diff --git a/.gitattributes b/.gitattributes index 9f21ec7595270247b105abcd90acbc9f0004a891..680e7f4b0c98fa6ef6f6c2d73b95cc462e5a7fec 100644 --- a/.gitattributes +++ b/.gitattributes @@ -61,3 +61,4 @@ node_modules/bare-url/prebuilds/win32-arm64/bare-url.bare filter=lfs diff=lfs me node_modules/bare-url/prebuilds/win32-x64/bare-url.bare filter=lfs diff=lfs merge=lfs -text node_modules/better-sqlite3/build/Release/better_sqlite3.node filter=lfs diff=lfs merge=lfs -text node_modules/concurrently/docs/demo.gif filter=lfs diff=lfs merge=lfs -text +node_modules/exif-parser/test/starfish.jpg filter=lfs diff=lfs merge=lfs -text diff --git a/node_modules/eslint-config-flat-gitignore/LICENSE b/node_modules/eslint-config-flat-gitignore/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7d71216f2ad255a3862e62dd83b3065ed79dd04f --- /dev/null +++ b/node_modules/eslint-config-flat-gitignore/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Anthony Fu + +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. diff --git a/node_modules/eslint-config-flat-gitignore/README.md b/node_modules/eslint-config-flat-gitignore/README.md new file mode 100644 index 0000000000000000000000000000000000000000..302e3727a37a03c958940364f91ebd6006a77ffe --- /dev/null +++ b/node_modules/eslint-config-flat-gitignore/README.md @@ -0,0 +1,113 @@ +# eslint-config-flat-gitignore + +[![npm version][npm-version-src]][npm-version-href] +[![npm downloads][npm-downloads-src]][npm-downloads-href] +[![bundle][bundle-src]][bundle-href] +[![JSDocs][jsdocs-src]][jsdocs-href] +[![License][license-src]][license-href] + +`.gitignore` support for [ESLint Flat Config](https://eslint.org/docs/latest/use/configure/configuration-files-new). + +## Usage + +```bash +npm i -D eslint-config-flat-gitignore +``` + +```js +// eslint.config.js +import gitignore from 'eslint-config-flat-gitignore' + +export default [ + // recommended putting it at the first + gitignore(), + // your other configs here +] +``` + +By default it will only looks for `.gitignore` but NOT `.eslintignore`, as we would recommended move away from `.eslintignore` to declare directly in `eslint.config.js` for single source of truth. If you still want it, you can pass the `files` option to specify the files to look for. + +```js +gitignore({ + files: [ + '.gitignore', + '.eslintignore', + ] +}) +``` + +By default, this plugin throws if any of the ignore files are missing. This can be disabled by passing setting the `strict` option to `false`. + +```js +gitignore({ + files: [ + '.gitignore', + '.eslintignore', + ], + strict: false, +}) +``` + +By default, this plugin will try to look up the directory tree and match the first `.gitignore` file. You can disable this by setting the `root` option to `true`, or specify the `files` option to a specific path. + +```js +gitignore({ + root: true +}) +``` + +If you want to include recursive `.gitignore` files (for example in monorepos), enable the `recursive` option. + +```js +gitignore({ + recursive: true, +}) +``` + +If you want recursive discovery but need to skip specific directory names, pass an object to `recursive` with `skipDirs`. + +```js +gitignore({ + recursive: { + // Skip any directory with this name at any depth + skipDirs: ['dist', 'coverage'], + }, +}) +``` + +`skipDirs` matches directory names (not paths) and applies in addition to the built-in skipped directories: `.git` and `node_modules`. + +This plugin will also automatically detect git submodule file `.gitmodules` and ignore all files under the submodule dirs. If you want to disable or customize this behavior, you can pass the `filesGitModules` option. + + +```js +gitignore({ + filesGitModules: [], // disable + filesGitModules: ['path/to/.gitmodules'], // customize +}) +``` + +## Sponsors + +

+ + Sponsors + +

+ +## License + +[MIT](./LICENSE) License © 2023-PRESENT [Anthony Fu](https://github.com/antfu) + + + +[npm-version-src]: https://img.shields.io/npm/v/eslint-config-flat-gitignore?style=flat&colorA=080f12&colorB=1fa669 +[npm-version-href]: https://npmjs.com/package/eslint-config-flat-gitignore +[npm-downloads-src]: https://img.shields.io/npm/dm/eslint-config-flat-gitignore?style=flat&colorA=080f12&colorB=1fa669 +[npm-downloads-href]: https://npmjs.com/package/eslint-config-flat-gitignore +[bundle-src]: https://img.shields.io/bundlephobia/minzip/eslint-config-flat-gitignore?style=flat&colorA=080f12&colorB=1fa669&label=minzip +[bundle-href]: https://bundlephobia.com/result?p=eslint-config-flat-gitignore +[license-src]: https://img.shields.io/github/license/antfu/eslint-config-flat-gitignore.svg?style=flat&colorA=080f12&colorB=1fa669 +[license-href]: https://github.com/antfu/eslint-config-flat-gitignore/blob/main/LICENSE +[jsdocs-src]: https://img.shields.io/badge/jsdocs-reference-080f12?style=flat&colorA=080f12&colorB=1fa669 +[jsdocs-href]: https://www.jsdocs.io/package/eslint-config-flat-gitignore diff --git a/node_modules/eslint-config-flat-gitignore/package.json b/node_modules/eslint-config-flat-gitignore/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c3566143724bb8d095f82ba9cc859ecec80125ae --- /dev/null +++ b/node_modules/eslint-config-flat-gitignore/package.json @@ -0,0 +1,67 @@ +{ + "name": "eslint-config-flat-gitignore", + "type": "module", + "version": "2.3.0", + "description": ".gitignore support for ESLint Flat Config", + "author": "Anthony Fu ", + "license": "MIT", + "funding": "https://github.com/sponsors/antfu", + "homepage": "https://github.com/antfu/eslint-config-flat-gitignore#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/antfu/eslint-config-flat-gitignore.git" + }, + "bugs": "https://github.com/antfu/eslint-config-flat-gitignore/issues", + "keywords": [ + "eslint-config", + "eslint-flat-config" + ], + "sideEffects": false, + "exports": { + ".": "./dist/index.mjs" + }, + "main": "./dist/index.mjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.mts", + "files": [ + "dist" + ], + "peerDependencies": { + "eslint": "^9.5.0 || ^10.0.0" + }, + "dependencies": { + "@eslint/compat": "^2.0.3" + }, + "devDependencies": { + "@antfu/eslint-config": "^7.7.3", + "@antfu/ni": "^30.0.0", + "@antfu/utils": "^9.3.0", + "@types/node": "^25.5.0", + "bumpp": "^11.0.1", + "eslint": "^10.1.0", + "find-up-simple": "^1.0.1", + "lint-staged": "^16.4.0", + "pnpm": "^10.32.1", + "simple-git-hooks": "^2.13.1", + "tsx": "^4.21.0", + "typescript": "^5.9.3", + "unbuild": "^3.6.1", + "vite": "^8.0.2", + "vitest": "^4.1.1" + }, + "simple-git-hooks": { + "pre-commit": "pnpm lint-staged" + }, + "lint-staged": { + "*": "eslint --fix" + }, + "scripts": { + "build": "unbuild", + "dev": "unbuild --stub", + "lint": "eslint .", + "release": "bumpp", + "start": "tsx src/index.ts", + "test": "vitest --pool=forks", + "typecheck": "tsc --noEmit" + } +} \ No newline at end of file diff --git a/node_modules/eslint-config-prettier/LICENSE b/node_modules/eslint-config-prettier/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4b17469e8038a832051611418c2bf8d569f88c44 --- /dev/null +++ b/node_modules/eslint-config-prettier/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/eslint-config-prettier/README.md b/node_modules/eslint-config-prettier/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2bdb30c30ebc4ec51c2108ed1c6b5256af412b6c --- /dev/null +++ b/node_modules/eslint-config-prettier/README.md @@ -0,0 +1,928 @@ +# eslint-config-prettier + +Turns off all rules that are unnecessary or might conflict with [Prettier]. + +This lets you use your favorite shareable config without letting its stylistic choices get in the way when using Prettier. + +Note that this config _only_ turns rules _off,_ so it only makes sense using it together with some other config. + +[prettier]: https://github.com/prettier/prettier + +## Installation + +1. Install eslint-config-prettier: + + ```shell + npm i -D eslint-config-prettier + ``` + + ```shell + yarn add -D eslint-config-prettier + ``` + + ```shell + pnpm add -D eslint-config-prettier + ``` + + ```shell + bun add -D eslint-config-prettier + ``` + +2. Add eslint-config-prettier to your ESLint configuration – either to [eslintrc] or to [eslint.config.js (flat config)]. + + - eslintrc: Add `"prettier"` to the "extends" array in your `.eslintrc.*` file. Make sure to put it **last,** so it gets the chance to override other configs. + + + ```json + { + "extends": [ + "some-other-config-you-use", + "prettier" + ] + } + ``` + + - eslint.config.js (flat config): Import eslint-config-prettier, and put it in the configuration array – **after** other configs that you want to override. + + + ```js + import someConfig from "some-other-config-you-use"; + // Note the `/flat` suffix here, the difference from default entry is that + // `/flat` added `name` property to the exported object to improve + // [config-inspector](https://eslint.org/blog/2024/04/eslint-config-inspector/) experience. + import eslintConfigPrettier from "eslint-config-prettier/flat"; + + export default [ + someConfig, + eslintConfigPrettier, + ]; + ``` + +3. Finally, run the [CLI helper tool](#cli-helper-tool) to find problems in the `"rules"` sections of your config. + +> 👉 Using [eslint-plugin-prettier]? Check out [eslint-plugin-prettier’s recommended config][eslint-plugin-prettier-recommended]. + +### Plugins + +eslint-config-prettier not only turns off _core_ rules, but also some from these plugins automatically: + +- [@babel/eslint-plugin] +- [@stylistic/eslint-plugin] +- [@typescript-eslint/eslint-plugin] +- [eslint-plugin-babel] +- [eslint-plugin-flowtype] +- [eslint-plugin-react] +- [eslint-plugin-standard] +- [eslint-plugin-unicorn] +- [eslint-plugin-vue] + +> ℹ️ Note: You might find guides on the Internet saying you should also extend stuff like `"prettier/react"`. Since version 8.0.0 of eslint-config-prettier, all you need to extend is `"prettier"`! That includes all plugins. + +#### eslint.config.js (flat config) plugin caveat + +With flat config, _you_ get to decide the plugin name! For example: + +```js +import typescriptEslint from "@typescript-eslint/eslint-plugin"; +import eslintConfigPrettier from "eslint-config-prettier/flat"; + +export default [ + { + plugins: { + // You’d typically use one of the following two: + // typescriptEslint: typescriptEslint, + // typescriptEslint, + // But in this example we give it another name. + // It might be tempting to use something shorter like “ts”: + ts: typescriptEslint, // 🚨 Don’t do this! + }, + rules: { + // With eslintrc, this is _always_ called: + // @typescript-eslint/indent + // But in eslint.config.js (flat config), the name chosen above in `plugins` is used. + "ts/indent": "error", // 🚨 Don’t do this! + }, + }, + eslintConfigPrettier, +]; +``` + +You might expect eslint-config-prettier to turn off `ts/indent`, but it won’t! Because eslint-config-prettier only turns off `@typescript-eslint/indent`. It cannot know what you chose to call the plugin. Same thing for the CLI helper tool. + +Simply stick to the official plugin names and you’ll be all good. + +If you encounter a shared _config_ that uses a non-standard plugin name, please ask them to use the standard name instead. + +### Excluding deprecated rules + +Some of the rules that eslint-config-prettier turns off may be deprecated, or even removed from ESLint. **This is perfectly fine,** but if you really need to omit the deprecated and removed rules, you can do so by setting the `ESLINT_CONFIG_PRETTIER_NO_DEPRECATED` environment variable to a non-empty value. For example: + +``` +env ESLINT_CONFIG_PRETTIER_NO_DEPRECATED=true npx eslint-find-rules --deprecated index.js +``` + +## CLI helper tool + +eslint-config-prettier also ships with a little CLI tool to help you check if your configuration contains any rules that are unnecessary or conflict with Prettier. Here’s how to run it: + +``` +npx eslint-config-prettier path/to/main.js +``` + +(Change `path/to/main.js` to a file that exists in your project.) + +### What and why + +Now, let’s have a look at what it does and why you might want to use it. + +🚨 This eslintrc example has a **conflicting rule** `"indent"` enabled: + + +```json +{ + "extends": [ + "some-other-config-you-use", + "prettier" + ], + "rules": { + "indent": "error" + } +} +``` + +For eslintrc, while the `"prettier"` config can disable problematic rules in `"some-other-config-you-use"`, it cannot touch `"rules"`! (That’s how ESLint works – it lets you override configs you extend.) The CLI helper tool reports that `"indent"` conflicts with Prettier, so you can remove it. (Which is nice – simplifying your config!) + +🚨 This eslint.config.js (flat config) example also has a **conflicting rule** `"indent"` enabled: + +```js +import someConfig from "some-other-config-you-use"; +import eslintConfigPrettier from "eslint-config-prettier/flat"; + +export default [ + someConfig, + eslintConfigPrettier, + { + rules: { + indent: "error", + }, + }, +]; +``` + +With the new ESLint “flat config” format, you can control what things override what yourself. One way of solving the above conflict is to reorder the config objects so that eslint-config-prettier is last: + +```js +import someConfig from "some-other-config-you-use"; +import eslintConfigPrettier from "eslint-config-prettier/flat"; + +export default [ + someConfig, + { + rules: { + indent: "error", + }, + }, + eslintConfigPrettier, // eslint-config-prettier last +]; +``` + +However, looking at the above config might feel confusing. It looks like we enable the `indent` rule, but in reality it’s disabled thanks to the `eslintConfigPrettier` line below it. Instead you might want to actually have your own rules _after_ eslint-config-prettier and run the CLI helper tool to find out about problems, so you can remove conflicting rules from the config file altogether (simplifying your config). + +### Checking multiple files + +In theory you need to run the tool for every single file in your project to be 100% sure that there are no conflicting rules, because ESLint supports having different rules for different files. Usually you’ll have about the same rules for all files, so it is good enough to run the command on one file. But if you use [multiple configuration files] or [overrides], you can provide several files to check: + +``` +npx eslint-config-prettier index.js test/index.js legacy/main.js +``` + +### Exit codes + +- 0: No problems found. +- 1: Unexpected error. +- 2: Conflicting rules found. + +### ESLINT_USE_FLAT_CONFIG environment variable + +Just like ESLint itself, you can control the eslint-config-prettier CLI helper tool using the `ESLINT_USE_FLAT_CONFIG` environment variable: + +- `ESLINT_USE_FLAT_CONFIG=true`: Only use eslint.config.js (flat config). +- `ESLINT_USE_FLAT_CONFIG=false`: Only use eslintrc files. +- Unset or any other value: First try eslint.config.js, then eslintrc. + +> **Warning** +> For eslint.config.js (flat config), the CLI helper tool imports `eslint/use-at-your-own-risk` which may break at any time. + +### Legacy + +eslint-config-prettier versions before 7.0.0 had a slightly different CLI tool that was run in a different way. For example: + +``` +npx eslint --print-config index.js | npx eslint-config-prettier-check +``` + +If you find something like that in a tutorial, this is what the command looks like in 7.0.0 or later: + +``` +npx eslint-config-prettier index.js +``` + +## Special rules + +There a few rules that eslint-config-prettier disables that actually can be enabled in some cases. + +- Some require certain options. The CLI helper tool validates this. +- Some require special attention when writing code. The CLI helper tool warns you if any of those rules are enabled, but can’t tell if anything is problematic. +- Some can cause problems if using [eslint-plugin-prettier] and `--fix`. + +For maximum ease of use, the special rules are disabled by default (provided that you include all needed things in `"extends"`). If you want them, you need to explicitly specify them in your ESLint config. + +### [arrow-body-style] and [prefer-arrow-callback] + +**These rules might cause problems if using [eslint-plugin-prettier] and `--fix`.** + +See the [`arrow-body-style` and `prefer-arrow-callback` issue][eslint-plugin-prettier-autofix-issue] for details. + +There are a couple of ways to turn these rules off: + +- Put `"plugin:prettier/recommended"` in your `"extends"`. That’s [eslint-plugin-prettier’s recommended config][eslint-plugin-prettier-recommended]. +- Put `"prettier/prettier"` in your `"extends"`. (Yes, there’s both a _rule_ called `"prettier/prettier"` and a _config_ called `"prettier/prettier"`.) +- Remove them from your config or turn them off manually. + +It doesn’t matter which approach you use. `"plugin:prettier/recommended"` is probably the easiest. + +Note: The CLI tool only reports these as problematic if the `"prettier/prettier"` _rule_ is enabled for the same file. + +These rules are safe to use if you don’t use [eslint-plugin-prettier]. In other words, if you run `eslint --fix` and `prettier --write` as separate steps. + +### [curly] + +**This rule requires certain options.** + +If a block (for example after `if`, `else`, `for` or `while`) contains only one statement, JavaScript allows omitting the curly braces around that statement. This rule enforces if or when those optional curly braces should be omitted. + +If you use the `"multi-line"` or `"multi-or-nest"` option, the rule can conflict with Prettier. + +For example, the `"multi-line"` option allows this line: + + +```js +if (cart.items && cart.items[0] && cart.items[0].quantity === 0) updateCart(cart); +``` + +However, Prettier might consider the line too long and turn it into the following, which the `"multi-line"` option does _not_ allow: + + +```js +if (cart.items && cart.items[0] && cart.items[0].quantity === 0) + updateCart(cart); +``` + +If you like this rule, it can be used just fine with Prettier as long as you don’t use the `"multi-line"` or `"multi-or-nest"` option. + +Example ESLint configuration: + + +```json +{ + "rules": { + "curly": ["error", "all"] + } +} +``` + +### [lines-around-comment] \(deprecated) + +(The following applies to [@stylistic/lines-around-comment], [@stylistic/js/lines-around-comment], [@stylistic/ts/lines-around-comment], and [@typescript-eslint/lines-around-comment] as well.) + +**This rule can be used with certain options.** + +This rule requires empty lines before and/or after comments. Prettier preserves blank lines, with two exceptions: + +- Several blank lines in a row are collapsed into a single blank line. This is fine. +- Blank lines at the beginning and end of blocks, objects and arrays are always removed. This may lead to conflicts. + +By default, ESLint requires a blank line above the comment is this case: + + +```js +if (result) { + + /* comment */ + return result; +} +``` + +However, Prettier removes the blank line: + + +```js +if (result) { + /* comment */ + return result; +} +``` + +If you like this rule, it can be used just fine with Prettier as long as you add some extra configuration to allow comments at the start and end of blocks, objects and arrays. + +Example ESLint configuration: + + +```json +{ + "rules": { + "lines-around-comment": [ + "error", + { + "beforeBlockComment": true, + "afterBlockComment": true, + "beforeLineComment": true, + "afterLineComment": true, + "allowBlockStart": true, + "allowBlockEnd": true, + "allowObjectStart": true, + "allowObjectEnd": true, + "allowArrayStart": true, + "allowArrayEnd": true + } + ] + } +} +``` + +### [max-len] \(deprecated) + +(The following applies to [@stylistic/max-len], [@stylistic/js/max-len], and [vue/max-len] as well.) + +**This rule requires special attention when writing code.** + +Usually, Prettier takes care of following a maximum line length automatically. However, there are cases where Prettier can’t do anything, such as for long strings, regular expressions and comments. Those need to be split up by a human. + +If you’d like to enforce an even stricter maximum line length policy than Prettier can provide automatically, you can enable this rule. Just remember to keep `max-len`’s options and Prettier’s `printWidth` option in sync. + +Keep in mind that you might have to refactor code slightly if Prettier formats lines in a way that the `max-len` rule does not approve of. + +Example ESLint configuration: + + +```json +{ + "rules": { + "max-len": ["error", {"code": 80, "ignoreUrls": true}] + } +} +``` + +### [no-confusing-arrow] \(deprecated) + +(The following applies to [@stylistic/no-confusing-arrow] and [@stylistic/js/no-confusing-arrow] as well.) + +**This rule requires certain options.** + +For example, the rule could warn about this line: + + +```js +var x = a => 1 ? 2 : 3; +``` + +With `{allowParens: true}` (the default since ESLint 6.0.0), adding parentheses is considered a valid way to avoid the arrow confusion: + + +```js +var x = a => (1 ? 2 : 3); +``` + +While Prettier keeps those parentheses, it removes them if the line is long enough to introduce a line break: + + +```js +EnterpriseCalculator.prototype.calculateImportantNumbers = inputNumber => + 1 ? 2 : 3; +``` + +With `{allowParens: false}`, ESLint instead suggests switching to an explicit return: + + +```js +var x = a => { return 1 ? 2 : 3; }; +``` + +That causes no problems with Prettier. + +If you like this rule, it can be used just fine with Prettier as long as the `allowParens` option is off. + +Example ESLint configuration: + + +```json +{ + "rules": { + "no-confusing-arrow": ["error", { "allowParens": false }] + } +} +``` + +(Note: The CLI helper tool considers `{allowParens: true}` to be the default, which is the case since ESLint 6.0.0. The tool will produce a warning if you use the default even if you use an older version of ESLint. It doesn’t hurt to explicitly set `{allowParens: false}` even though it is technically redundant. This way you are prepared for a future ESLint upgrade and the CLI tool can be kept simple.) + +### [no-mixed-operators] \(deprecated) + +(The following applies to [@stylistic/no-mixed-operators] and [@stylistic/js/no-mixed-operators] as well.) + +**This rule requires special attention when writing code.** + +This rule forbids mixing certain operators, such as `&&` and `||`. + +For example, the rule could warn about this line: + + +```js +var foo = a + b * c; +``` + +The rule suggests adding parentheses, like this: + + +```js +var foo = a + (b * c); +``` + +However, Prettier removes many “unnecessary” parentheses, turning it back to: + + +```js +var foo = a + b * c; +``` + +If you want to use this rule with Prettier, you need to split the expression into another variable: + + +```js +var bar = b * c; +var foo = a + bar; +``` + +Keep in mind that Prettier prints _some_ “unnecessary” parentheses, though: + + +```js +var foo = (a && b) || c; +``` + +Example ESLint configuration: + + +```json +{ + "rules": { + "no-mixed-operators": "error" + } +} +``` + +### [no-tabs] \(deprecated) + +(The following applies to [@stylistic/no-tabs] and [@stylistic/js/no-tabs] as well.) + +**This rule requires certain options.** + +This rule disallows the use of tab characters. By default the rule forbids _all_ tab characters. That can be used just fine with Prettier as long as you don’t configure Prettier to indent using tabs. + +Luckily, it’s possible to configure the rule so that it works regardless of whether Prettier uses spaces or tabs: Set `allowIndentationTabs` to `true`. This way Prettier takes care of your indentation, while the `no-tabs` takes care of potential tab characters anywhere else in your code. + +Example ESLint configuration: + + +```json +{ + "rules": { + "no-tabs": ["error", {"allowIndentationTabs": true}] + } +} +``` + +### [no-unexpected-multiline] + +**This rule requires special attention when writing code.** + +This rule disallows confusing multiline expressions where a newline looks like it is ending a statement, but is not. + +For example, the rule could warn about this: + + +```js +var hello = "world" +[1, 2, 3].forEach(addNumber) +``` + +Prettier usually formats this in a way that makes it obvious that a semicolon was missing: + + +```js +var hello = "world"[(1, 2, 3)].forEach(addNumber); +``` + +However, there are cases where Prettier breaks things into several lines such that the `no-unexpected-multiline` conflicts. + + +```js +const value = text.trim().split("\n")[position].toLowerCase(); +``` + +Prettier breaks it up into several lines, though, causing a conflict: + + +```js +const value = text + .trim() + .split("\n") + [position].toLowerCase(); +``` + +If you like this rule, it can usually be used with Prettier without problems, but occasionally you might need to either temporarily disable the rule or refactor your code. + + +```js +const value = text + .trim() + .split("\n") + // eslint-disable-next-line no-unexpected-multiline + [position].toLowerCase(); + +// Or: + +const lines = text.trim().split("\n"); +const value = lines[position].toLowerCase(); +``` + +**Note:** If you _do_ enable this rule, you have to run ESLint and Prettier as two separate steps (and ESLint first) in order to get any value out of it. Otherwise Prettier might reformat your code in such a way that ESLint never gets a chance to report anything (as seen in the first example). + +Example configuration: + + +```json +{ + "rules": { + "no-unexpected-multiline": "error" + } +} +``` + +### [quotes] \(deprecated) + +(The following applies to [babel/quotes], [@stylistic/quotes], [@stylistic/js/quotes], [@stylistic/ts/quotes], and [@typescript-eslint/quotes] as well.) + +**This rule requires certain options and certain Prettier options.** + +Usually, you don’t need this rule at all. But there are two cases where it could be useful: + +- To enforce the use of backticks rather than single or double quotes for strings. +- To forbid backticks where regular strings could have been used. + +#### Enforce backticks + +If you’d like all strings to use backticks (never quotes), enable the `"backtick"` option. + +Example ESLint configuration: + + +```json +{ + "rules": { + "quotes": ["error", "backtick"] + } +} +``` + +#### Forbid unnecessary backticks + +In the following example, the first array item could have been written with quotes instead of backticks. + + +```js +const strings = [ + `could have been a regular string`, + ` + multiple + lines + `, + `uses ${interpolation}`, + String.raw`\tagged/`, +]; +``` + +If you’d like ESLint to enforce `` `could have been a regular string` `` being written as either `"could have been a regular string"` or `'could have been a regular string'`, you need to use some specific configuration. The `quotes` rule has two options, a string option and an object option. + +- The first (string) option needs to be set to `"single"` or `"double"` and be kept in sync with Prettier’s [singleQuote] option. +- The second (object) option needs the following properties: + - `"avoidEscape": true` to follow Prettier’s [string formatting rules]. + - `"allowTemplateLiterals": false` to disallow unnecessary backticks. + +##### Example double quote configuration + +ESLint: + + +```json +{ + "rules": { + "quotes": [ + "error", + "double", + { "avoidEscape": true, "allowTemplateLiterals": false } + ] + } +} +``` + +Prettier (this is the default, so adding this is not required): + + +```json +{ + "singleQuote": false +} +``` + +##### Example single quote configuration + +ESLint: + + +```json +{ + "rules": { + "quotes": [ + "error", + "single", + { "avoidEscape": true, "allowTemplateLiterals": false } + ] + } +} +``` + +Prettier: + + +```json +{ + "singleQuote": true +} +``` + +### [unicorn/template-indent] + +**This rule can be used with certain options.** + +This rule will automatically fix the indentation of multiline string templates, to keep them in alignment with the code they are found in. A configurable whitelist is used to ensure no whitespace-sensitive strings are edited. + +Prettier deals with: + +- HTML +- CSS +- GraphQL +- markdown + +Using various tags, functions and comments. + +`unicorn/template-indent` by default formats some of the same tagged templates, which can cause conflicts. For example, the rule and Prettier disagree about indentation in ternaries: + +```js +condition + ? null + : html` +

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in dui + mauris. +

+ `; +``` + +If you like this rule, it can be used just fine with Prettier as long as you configure the rule to not deal with the same templates as Prettier. + +Example ESLint configuration: + + +```json +{ + "rules": { + "unicorn/template-indent": [ + "error", + { + "tags": [ + "outdent", + "dedent", + "sql", + "styled" + ], + "functions": [ + "dedent", + "stripIndent" + ], + "selectors": [], + "comments": [ + "indent" + ] + } + ] + } +} +``` + +Note: If you use `"selectors"`, the CLI helper tool cannot detect if your selectors might cause conflicts. + +### [vue/html-self-closing] + +**This rule requires certain options.** + +This rule enforces whether elements should be self-closing or not. + +Prettier generally preserves the way you wrote your elements: + + +```vue +
+
+ + + + +``` + +But for known _void_ HTML elements, Prettier always uses the self-closing style. For example, `` is turned into ``. + +If you like this rule, it can be used just fine with Prettier as long as you set `html.void` to `"any"`. + +Example ESLint configuration: + + +```json +{ + "rules": { + "vue/html-self-closing": [ + "error", + { + "html": { + "void": "any" + } + } + ] + } +} +``` + +## Other rules worth mentioning + +These rules don’t conflict with Prettier, but have some gotchas when used with Prettier. + +### [no-sequences] + +This rule forbids using JavaScript’s confusing comma operator (sequence expressions). This piece of code is not doing what it looks like: + + +```js +matrix[4, 7]; +``` + +Prettier adds parentheses to the above to make it clear that a sequence expression is used: + + +```js +matrix[(4, 7)]; +``` + +However, the `no-sequences` rule allows comma operators if the expression sequence is explicitly wrapped in parentheses. Since Prettier automatically wraps them in parentheses, you might never see any warnings from ESLint about comma operators. + +Ending up with an accidental sequence expression can easily happen while refactoring. If you want ESLint to catch such mistakes, it is recommended to forbid sequence expressions entirely using [no-restricted-syntax] \([as mentioned in the `no-sequences` documentation][no-sequences-full]): + + +```json +{ + "rules": { + "no-restricted-syntax": ["error", "SequenceExpression"] + } +} +``` + +If you still need to use the comma operator for some edge case, you can place an `// eslint-disable-next-line no-restricted-syntax` comment on the line above the expression. `no-sequences` can safely be disabled if you use the `no-restricted-syntax` approach. + +You can also supply a custom message if you want: + + +```json +{ + "rules": { + "no-restricted-syntax": [ + "error", + { + "selector": "SequenceExpression", + "message": "The comma operator is confusing and a common mistake. Don’t use it!" + } + ] + } +} +``` + +## Contributing + +See [package.json] for the exact versions of ESLint, Prettier and ESLint plugins that eslint-config-prettier has been tested with. + +Have new rules been added since those versions? Have we missed any rules? Is there a plugin you would like to see exclusions for? Open an issue or a pull request! + +If you’d like to add support for eslint-plugin-foobar, this is how you’d go about it: + +First, add rules to `index.js`: + + +```js +"foobar/some-rule": "off" +``` + +Then, create `test-lint/foobar.js`: + + +```js +/* eslint-disable quotes */ +"use strict"; + +// Prettier does not want spaces before the parentheses, but +// `plugin:foobar/recommended` wants one. +console.log(); +``` + +`test-lint/foobar.js` must fail when used with eslint-plugin-foobar and eslint-plugin-prettier at the same time – until eslint-config-prettier is added to the ESLint config. The file should be formatted according to Prettier, and that formatting should disagree with the plugin. + +Finally, you need to mention the plugin in several places: + +- Add eslint-plugin-foobar to the "devDependencies" field in `package.json`. +- Make sure that at least one rule from eslint-plugin-foobar gets used in `.eslintrc.base.js` and `eslint.base.config.js`. +- Add it to the lists of supported plugins in this `README.md`. + +When you’re done, run `npm test` to verify that you got it all right. It runs several other npm scripts: + +- `"test:prettier"` checks that Prettier has been run on all files. +- `"test:eslint"` makes sure that the files in `test-lint/` pass ESLint when the exclusions from eslint-config-prettier are used. It also lints the code of eslint-config-prettier itself. +- `"test:lint-verify-fail"` is run by a test in `test/lint-verify-fail.test.js`. +- `"test:lint-rules"` is run by a test in `test/rules.test.js`. +- `"test:jest"` runs unit tests that check a number of things: + - That eslint-plugin-foobar is mentioned in all the places shown above. + - That no unknown rules are turned off. This helps catching typos, for example. + - That the CLI works. +- `"test:cli-sanity"` and `"test:cli-sanity-warning"` are sanity checks for the CLI. + +## License + +[MIT](LICENSE). + +[@babel/eslint-plugin]: https://github.com/babel/babel/tree/main/eslint/babel-eslint-plugin +[@stylistic/eslint-plugin]: https://github.com/eslint-stylistic/eslint-stylistic +[@stylistic/lines-around-comment]: https://eslint.style/rules/default/lines-around-comment +[@stylistic/js/lines-around-comment]: https://eslint.style/rules/js/lines-around-comment +[@stylistic/ts/lines-around-comment]: https://eslint.style/rules/ts/lines-around-comment +[@stylistic/max-len]: https://eslint.style/rules/default/max-len +[@stylistic/js/max-len]: https://eslint.style/rules/js/max-len +[@stylistic/no-confusing-arrow]: https://eslint.style/rules/default/no-confusing-arrow +[@stylistic/js/no-confusing-arrow]: https://eslint.style/rules/js/no-confusing-arrow +[@stylistic/no-mixed-operators]: https://eslint.style/rules/default/no-mixed-operators +[@stylistic/js/no-mixed-operators]: https://eslint.style/rules/js/no-mixed-operators +[@stylistic/no-tabs]: https://eslint.style/rules/default/no-tabs +[@stylistic/js/no-tabs]: https://eslint.style/rules/js/no-tabs +[@stylistic/quotes]: https://eslint.style/rules/default/quotes +[@stylistic/js/quotes]: https://eslint.style/rules/js/quotes +[@stylistic/ts/quotes]: https://eslint.style/rules/ts/quotes +[@typescript-eslint/eslint-plugin]: https://github.com/typescript-eslint/typescript-eslint +[@typescript-eslint/lines-around-comment]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/lines-around-comment.md +[@typescript-eslint/quotes]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/quotes.md +[arrow-body-style]: https://eslint.org/docs/rules/arrow-body-style +[babel/quotes]: https://github.com/babel/eslint-plugin-babel#rules +[curly]: https://eslint.org/docs/rules/curly +[eslint-plugin-babel]: https://github.com/babel/eslint-plugin-babel +[eslint-plugin-flowtype]: https://github.com/gajus/eslint-plugin-flowtype +[eslint-plugin-prettier-autofix-issue]: https://github.com/prettier/eslint-plugin-prettier#arrow-body-style-and-prefer-arrow-callback-issue +[eslint-plugin-prettier-recommended]: https://github.com/prettier/eslint-plugin-prettier#recommended-configuration +[eslint-plugin-prettier]: https://github.com/prettier/eslint-plugin-prettier +[eslint-plugin-react]: https://github.com/yannickcr/eslint-plugin-react +[eslint-plugin-standard]: https://github.com/xjamundx/eslint-plugin-standard +[eslint-plugin-unicorn]: https://github.com/sindresorhus/eslint-plugin-unicorn +[eslint-plugin-vue]: https://github.com/vuejs/eslint-plugin-vue +[eslint.config.js (flat config)]: https://eslint.org/docs/latest/use/configure/configuration-files-new +[eslintrc]: https://eslint.org/docs/latest/use/configure/configuration-files +[lines-around-comment]: https://eslint.org/docs/rules/lines-around-comment +[max-len]: https://eslint.org/docs/rules/max-len +[multiple configuration files]: https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy +[no-confusing-arrow]: https://eslint.org/docs/rules/no-confusing-arrow +[no-mixed-operators]: https://eslint.org/docs/rules/no-mixed-operators +[no-restricted-syntax]: https://eslint.org/docs/rules/no-restricted-syntax +[no-sequences-full]: https://eslint.org/docs/rules/no-sequences#when-not-to-use-it +[no-sequences]: https://eslint.org/docs/rules/no-sequences +[no-tabs]: https://eslint.org/docs/rules/no-tabs +[no-unexpected-multiline]: https://eslint.org/docs/rules/no-unexpected-multiline +[overrides]: https://eslint.org/docs/user-guide/configuring#configuration-based-on-glob-patterns +[package.json]: https://github.com/prettier/eslint-config-prettier/blob/main/package.json +[prefer-arrow-callback]: https://eslint.org/docs/rules/prefer-arrow-callback +[quotes]: https://eslint.org/docs/rules/quotes +[singlequote]: https://prettier.io/docs/en/options.html#quotes +[string formatting rules]: https://prettier.io/docs/en/rationale.html#strings +[unicorn/template-indent]: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/template-indent.md +[vue/html-self-closing]: https://github.com/vuejs/eslint-plugin-vue/blob/master/docs/rules/html-self-closing.md +[vue/max-len]: https://github.com/vuejs/eslint-plugin-vue/blob/master/docs/rules/max-len.md diff --git a/node_modules/eslint-config-prettier/bin/cli.js b/node_modules/eslint-config-prettier/bin/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..da85433640340258448a748ac62b830855f8a668 --- /dev/null +++ b/node_modules/eslint-config-prettier/bin/cli.js @@ -0,0 +1,240 @@ +#!/usr/bin/env node + +"use strict"; + +const validators = require("./validators"); +const config = require(".."); +const prettier = require("../prettier"); + +// Require locally installed eslint, for `npx eslint-config-prettier` support +// with no local eslint-config-prettier installation. +const localRequire = (request) => + require( + require.resolve(request, { + paths: [process.cwd(), ...require.resolve.paths("eslint")], + }) + ); + +let experimentalApi = {}; +try { + experimentalApi = localRequire("eslint/use-at-your-own-risk"); +} catch (_error) {} + +const { ESLint, FlatESLint = experimentalApi.FlatESLint } = + localRequire("eslint"); + +const SPECIAL_RULES_URL = + "https://github.com/prettier/eslint-config-prettier#special-rules"; + +const PRETTIER_RULES_URL = + "https://github.com/prettier/eslint-config-prettier#arrow-body-style-and-prefer-arrow-callback"; + +if (module === require.main) { + const args = process.argv.slice(2); + + if (args.length === 0) { + console.error(help()); + process.exit(1); + } + + const eslint = new ESLint(); + const flatESLint = FlatESLint === undefined ? undefined : new FlatESLint(); + + Promise.all( + args.map((file) => { + switch (process.env.ESLINT_USE_FLAT_CONFIG) { + case "true": { + return flatESLint.calculateConfigForFile(file); + } + case "false": { + return eslint.calculateConfigForFile(file); + } + default: { + // This turns synchronous errors (such as `.calculateConfigForFile` not existing) + // and turns them into promise rejections. + return Promise.resolve() + .then(() => flatESLint.calculateConfigForFile(file)) + .catch(() => eslint.calculateConfigForFile(file)); + } + } + }) + ) + .then((configs) => { + const rules = configs.flatMap( + ( + // Initializing config and rules for files that aren't included in the flat config, + // which is a very unlikely scenario, but should still be treated as a success + { rules = {} } = {}, + index + ) => Object.entries(rules).map((entry) => [...entry, args[index]]) + ); + const result = processRules(rules); + if (result.stderr) { + console.error(result.stderr); + } + if (result.stdout) { + console.error(result.stdout); + } + process.exit(result.code); + }) + .catch((error) => { + console.error(error.message); + process.exit(1); + }); +} + +function help() { + return ` +Usage: npx eslint-config-prettier FILE... + +Resolves an ESLint configuration for every given FILE and checks if they +contain rules that are unnecessary or conflict with Prettier. Example: + + npx eslint-config-prettier index.js test/index.js other/file/to/check.js + +Exit codes: + +0: No automatically detectable problems found. +1: General error. +2: Conflicting rules found. + +For more information, see: +https://github.com/prettier/eslint-config-prettier#cli-helper-tool + `.trim(); +} + +function processRules(configRules) { + const regularRules = filterRules(config.rules, (_, value) => value === "off"); + const optionsRules = filterRules( + config.rules, + (ruleName, value) => value === 0 && ruleName in validators + ); + const specialRules = filterRules( + config.rules, + (ruleName, value) => value === 0 && !(ruleName in validators) + ); + + const enabledRules = configRules + .map(([ruleName, value, source]) => { + const arrayValue = Array.isArray(value) ? value : [value]; + const [level, ...options] = arrayValue; + const isOff = level === "off" || level === 0; + return isOff ? null : { ruleName, options, source }; + }) + .filter(Boolean); + + const flaggedRules = enabledRules.filter( + ({ ruleName }) => ruleName in config.rules + ); + + const regularFlaggedRuleNames = filterRuleNames( + flaggedRules, + ({ ruleName }) => ruleName in regularRules + ); + const optionsFlaggedRuleNames = filterRuleNames( + flaggedRules, + ({ ruleName, ...rule }) => + ruleName in optionsRules && !validators[ruleName](rule) + ); + const specialFlaggedRuleNames = filterRuleNames( + flaggedRules, + ({ ruleName }) => ruleName in specialRules + ); + const prettierFlaggedRuleNames = filterRuleNames( + enabledRules, + ({ ruleName, source }) => + ruleName in prettier.rules && + enabledRules.some( + (rule) => + rule.ruleName === "prettier/prettier" && rule.source === source + ) + ); + + const regularMessage = [ + "The following rules are unnecessary or might conflict with Prettier:", + "", + printRuleNames(regularFlaggedRuleNames), + ].join("\n"); + + const optionsMessage = [ + "The following rules are enabled with config that might conflict with Prettier. See:", + SPECIAL_RULES_URL, + "", + printRuleNames(optionsFlaggedRuleNames), + ].join("\n"); + + const specialMessage = [ + "The following rules are enabled but cannot be automatically checked. See:", + SPECIAL_RULES_URL, + "", + printRuleNames(specialFlaggedRuleNames), + ].join("\n"); + + const prettierMessage = [ + "The following rules can cause issues when using eslint-plugin-prettier at the same time.", + "Only enable them if you know what you are doing! See:", + PRETTIER_RULES_URL, + "", + printRuleNames(prettierFlaggedRuleNames), + ].join("\n"); + + if ( + regularFlaggedRuleNames.length === 0 && + optionsFlaggedRuleNames.length === 0 + ) { + const message = + specialFlaggedRuleNames.length === 0 && + prettierFlaggedRuleNames.length === 0 + ? "No rules that are unnecessary or conflict with Prettier were found." + : [ + specialFlaggedRuleNames.length === 0 ? null : specialMessage, + prettierFlaggedRuleNames.length === 0 ? null : prettierMessage, + "Other than that, no rules that are unnecessary or conflict with Prettier were found.", + ] + .filter(Boolean) + .join("\n\n"); + + return { + stdout: message, + code: 0, + }; + } + + const message = [ + regularFlaggedRuleNames.length === 0 ? null : regularMessage, + optionsFlaggedRuleNames.length === 0 ? null : optionsMessage, + specialFlaggedRuleNames.length === 0 ? null : specialMessage, + prettierFlaggedRuleNames.length === 0 ? null : prettierMessage, + ] + .filter(Boolean) + .join("\n\n"); + + return { + stdout: message, + code: 2, + }; +} + +function filterRules(rules, fn) { + return Object.fromEntries( + Object.entries(rules) + .filter(([ruleName, value]) => fn(ruleName, value)) + .map(([ruleName]) => [ruleName, true]) + ); +} + +function filterRuleNames(rules, fn) { + return [ + ...new Set(rules.filter((rule) => fn(rule)).map((rule) => rule.ruleName)), + ]; +} + +function printRuleNames(ruleNames) { + return ruleNames + .slice() + .sort() + .map((ruleName) => `- ${ruleName}`) + .join("\n"); +} + +exports.processRules = processRules; diff --git a/node_modules/eslint-config-prettier/bin/validators.js b/node_modules/eslint-config-prettier/bin/validators.js new file mode 100644 index 0000000000000000000000000000000000000000..175d67a11196bef9cd0e4d8834fb5fa656d9d016 --- /dev/null +++ b/node_modules/eslint-config-prettier/bin/validators.js @@ -0,0 +1,86 @@ +"use strict"; + +// These validator functions answer the question “Is the config valid?” – return +// `false` if the options DO conflict with Prettier, and `true` if they don’t. + +module.exports = { + "curly"({ options }) { + if (options.length === 0) { + return true; + } + + const firstOption = options[0]; + return firstOption !== "multi-line" && firstOption !== "multi-or-nest"; + }, + + "lines-around-comment"({ options }) { + if (options.length === 0) { + return false; + } + + const firstOption = options[0]; + return Boolean( + firstOption && + firstOption.allowBlockStart && + firstOption.allowBlockEnd && + firstOption.allowObjectStart && + firstOption.allowObjectEnd && + firstOption.allowArrayStart && + firstOption.allowArrayEnd + ); + }, + + "no-confusing-arrow"({ options }) { + if (options.length === 0) { + return false; + } + + const firstOption = options[0]; + return firstOption ? firstOption.allowParens === false : false; + }, + + "no-tabs"({ options }) { + if (options.length === 0) { + return false; + } + + const firstOption = options[0]; + return Boolean(firstOption && firstOption.allowIndentationTabs); + }, + + "unicorn/template-indent"({ options }) { + if (options.length === 0) { + return false; + } + + const { comments = [], tags = [] } = options[0] || {}; + + return ( + Array.isArray(comments) && + Array.isArray(tags) && + !( + comments.includes("GraphQL") || + comments.includes("HTML") || + tags.includes("css") || + tags.includes("graphql") || + tags.includes("gql") || + tags.includes("html") || + tags.includes("markdown") || + tags.includes("md") + ) + ); + }, + + "vue/html-self-closing"({ options }) { + if (options.length === 0) { + return false; + } + + const firstOption = options[0]; + return Boolean( + firstOption && firstOption.html && firstOption.html.void === "any" + // Enable when Prettier supports SVG: https://github.com/prettier/prettier/issues/5322 + // && firstOption.svg === "any" + ); + }, +}; diff --git a/node_modules/eslint-config-prettier/flat.d.ts b/node_modules/eslint-config-prettier/flat.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..980b69e6c23d917c1d52be4eb10539fcdd73e73f --- /dev/null +++ b/node_modules/eslint-config-prettier/flat.d.ts @@ -0,0 +1,7 @@ +import eslintConfigPrettier from "./index.js"; + +declare const eslintConfigPrettierFlat: typeof eslintConfigPrettier & { + name: "config-prettier"; +}; + +export = eslintConfigPrettierFlat; diff --git a/node_modules/eslint-config-prettier/flat.js b/node_modules/eslint-config-prettier/flat.js new file mode 100644 index 0000000000000000000000000000000000000000..adf9deec17c58f2c6e1036f3b5264467dad54f2b --- /dev/null +++ b/node_modules/eslint-config-prettier/flat.js @@ -0,0 +1,6 @@ +"use strict"; + +const { rules } = require("./index.js"); + +exports.name = "config-prettier"; +exports.rules = rules; diff --git a/node_modules/eslint-config-prettier/index.d.ts b/node_modules/eslint-config-prettier/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3548ea38c54adba1db6b1c818b9bb0ab7d95affb --- /dev/null +++ b/node_modules/eslint-config-prettier/index.d.ts @@ -0,0 +1,5 @@ +declare const eslintConfigPrettier: { + rules: Record; +}; + +export = eslintConfigPrettier; diff --git a/node_modules/eslint-config-prettier/index.js b/node_modules/eslint-config-prettier/index.js new file mode 100644 index 0000000000000000000000000000000000000000..dc39bee2999f3de532c56f16734d24a3e678d956 --- /dev/null +++ b/node_modules/eslint-config-prettier/index.js @@ -0,0 +1,395 @@ +"use strict"; + +const includeDeprecated = !process.env.ESLINT_CONFIG_PRETTIER_NO_DEPRECATED; + +const specialRule = 0; + +exports.rules = { + // The following rules can be used in some cases. See the README for more + // information. These are marked with `0` instead of `"off"` so that a + // script can distinguish them. Note that there are a few more of these + // in the deprecated section below. + "curly": specialRule, + "no-unexpected-multiline": specialRule, + "@stylistic/lines-around-comment": specialRule, + "@stylistic/max-len": specialRule, + "@stylistic/no-confusing-arrow": specialRule, + "@stylistic/no-mixed-operators": specialRule, + "@stylistic/no-tabs": specialRule, + "@stylistic/quotes": specialRule, + "@stylistic/js/lines-around-comment": specialRule, + "@stylistic/js/max-len": specialRule, + "@stylistic/js/no-confusing-arrow": specialRule, + "@stylistic/js/no-mixed-operators": specialRule, + "@stylistic/js/no-tabs": specialRule, + "@stylistic/js/quotes": specialRule, + "@stylistic/ts/lines-around-comment": specialRule, + "@stylistic/ts/quotes": specialRule, + "@typescript-eslint/lines-around-comment": specialRule, + "@typescript-eslint/quotes": specialRule, + "babel/quotes": specialRule, + "unicorn/template-indent": specialRule, + "vue/html-self-closing": specialRule, + "vue/max-len": specialRule, + + // The rest are rules that you never need to enable when using Prettier. + "@babel/object-curly-spacing": "off", + "@babel/semi": "off", + "@stylistic/array-bracket-newline": "off", + "@stylistic/array-bracket-spacing": "off", + "@stylistic/array-element-newline": "off", + "@stylistic/arrow-parens": "off", + "@stylistic/arrow-spacing": "off", + "@stylistic/block-spacing": "off", + "@stylistic/brace-style": "off", + "@stylistic/comma-dangle": "off", + "@stylistic/comma-spacing": "off", + "@stylistic/comma-style": "off", + "@stylistic/computed-property-spacing": "off", + "@stylistic/dot-location": "off", + "@stylistic/eol-last": "off", + "@stylistic/func-call-spacing": "off", + "@stylistic/function-call-argument-newline": "off", + "@stylistic/function-call-spacing": "off", + "@stylistic/function-paren-newline": "off", + "@stylistic/generator-star-spacing": "off", + "@stylistic/implicit-arrow-linebreak": "off", + "@stylistic/indent": "off", + "@stylistic/jsx-quotes": "off", + "@stylistic/key-spacing": "off", + "@stylistic/keyword-spacing": "off", + "@stylistic/linebreak-style": "off", + "@stylistic/max-statements-per-line": "off", + "@stylistic/multiline-ternary": "off", + "@stylistic/new-parens": "off", + "@stylistic/newline-per-chained-call": "off", + "@stylistic/no-extra-parens": "off", + "@stylistic/no-extra-semi": "off", + "@stylistic/no-floating-decimal": "off", + "@stylistic/no-mixed-spaces-and-tabs": "off", + "@stylistic/no-multi-spaces": "off", + "@stylistic/no-multiple-empty-lines": "off", + "@stylistic/no-trailing-spaces": "off", + "@stylistic/no-whitespace-before-property": "off", + "@stylistic/nonblock-statement-body-position": "off", + "@stylistic/object-curly-newline": "off", + "@stylistic/object-curly-spacing": "off", + "@stylistic/object-property-newline": "off", + "@stylistic/one-var-declaration-per-line": "off", + "@stylistic/operator-linebreak": "off", + "@stylistic/padded-blocks": "off", + "@stylistic/quote-props": "off", + "@stylistic/rest-spread-spacing": "off", + "@stylistic/semi": "off", + "@stylistic/semi-spacing": "off", + "@stylistic/semi-style": "off", + "@stylistic/space-before-blocks": "off", + "@stylistic/space-before-function-paren": "off", + "@stylistic/space-in-parens": "off", + "@stylistic/space-infix-ops": "off", + "@stylistic/space-unary-ops": "off", + "@stylistic/switch-colon-spacing": "off", + "@stylistic/template-curly-spacing": "off", + "@stylistic/template-tag-spacing": "off", + "@stylistic/wrap-iife": "off", + "@stylistic/wrap-regex": "off", + "@stylistic/yield-star-spacing": "off", + "@stylistic/member-delimiter-style": "off", + "@stylistic/type-annotation-spacing": "off", + "@stylistic/jsx-child-element-spacing": "off", + "@stylistic/jsx-closing-bracket-location": "off", + "@stylistic/jsx-closing-tag-location": "off", + "@stylistic/jsx-curly-newline": "off", + "@stylistic/jsx-curly-spacing": "off", + "@stylistic/jsx-equals-spacing": "off", + "@stylistic/jsx-first-prop-new-line": "off", + "@stylistic/jsx-indent": "off", + "@stylistic/jsx-indent-props": "off", + "@stylistic/jsx-max-props-per-line": "off", + "@stylistic/jsx-newline": "off", + "@stylistic/jsx-one-expression-per-line": "off", + "@stylistic/jsx-props-no-multi-spaces": "off", + "@stylistic/jsx-tag-spacing": "off", + "@stylistic/jsx-wrap-multilines": "off", + "@stylistic/indent-binary-ops": "off", + "@stylistic/type-generic-spacing": "off", + "@stylistic/type-named-tuple-spacing": "off", + "@stylistic/js/array-bracket-newline": "off", + "@stylistic/js/array-bracket-spacing": "off", + "@stylistic/js/array-element-newline": "off", + "@stylistic/js/arrow-parens": "off", + "@stylistic/js/arrow-spacing": "off", + "@stylistic/js/block-spacing": "off", + "@stylistic/js/brace-style": "off", + "@stylistic/js/comma-dangle": "off", + "@stylistic/js/comma-spacing": "off", + "@stylistic/js/comma-style": "off", + "@stylistic/js/computed-property-spacing": "off", + "@stylistic/js/dot-location": "off", + "@stylistic/js/eol-last": "off", + "@stylistic/js/func-call-spacing": "off", + "@stylistic/js/function-call-argument-newline": "off", + "@stylistic/js/function-call-spacing": "off", + "@stylistic/js/function-paren-newline": "off", + "@stylistic/js/generator-star-spacing": "off", + "@stylistic/js/implicit-arrow-linebreak": "off", + "@stylistic/js/indent": "off", + "@stylistic/js/jsx-quotes": "off", + "@stylistic/js/key-spacing": "off", + "@stylistic/js/keyword-spacing": "off", + "@stylistic/js/linebreak-style": "off", + "@stylistic/js/max-statements-per-line": "off", + "@stylistic/js/multiline-ternary": "off", + "@stylistic/js/new-parens": "off", + "@stylistic/js/newline-per-chained-call": "off", + "@stylistic/js/no-extra-parens": "off", + "@stylistic/js/no-extra-semi": "off", + "@stylistic/js/no-floating-decimal": "off", + "@stylistic/js/no-mixed-spaces-and-tabs": "off", + "@stylistic/js/no-multi-spaces": "off", + "@stylistic/js/no-multiple-empty-lines": "off", + "@stylistic/js/no-trailing-spaces": "off", + "@stylistic/js/no-whitespace-before-property": "off", + "@stylistic/js/nonblock-statement-body-position": "off", + "@stylistic/js/object-curly-newline": "off", + "@stylistic/js/object-curly-spacing": "off", + "@stylistic/js/object-property-newline": "off", + "@stylistic/js/one-var-declaration-per-line": "off", + "@stylistic/js/operator-linebreak": "off", + "@stylistic/js/padded-blocks": "off", + "@stylistic/js/quote-props": "off", + "@stylistic/js/rest-spread-spacing": "off", + "@stylistic/js/semi": "off", + "@stylistic/js/semi-spacing": "off", + "@stylistic/js/semi-style": "off", + "@stylistic/js/space-before-blocks": "off", + "@stylistic/js/space-before-function-paren": "off", + "@stylistic/js/space-in-parens": "off", + "@stylistic/js/space-infix-ops": "off", + "@stylistic/js/space-unary-ops": "off", + "@stylistic/js/switch-colon-spacing": "off", + "@stylistic/js/template-curly-spacing": "off", + "@stylistic/js/template-tag-spacing": "off", + "@stylistic/js/wrap-iife": "off", + "@stylistic/js/wrap-regex": "off", + "@stylistic/js/yield-star-spacing": "off", + "@stylistic/ts/block-spacing": "off", + "@stylistic/ts/brace-style": "off", + "@stylistic/ts/comma-dangle": "off", + "@stylistic/ts/comma-spacing": "off", + "@stylistic/ts/func-call-spacing": "off", + "@stylistic/ts/function-call-spacing": "off", + "@stylistic/ts/indent": "off", + "@stylistic/ts/key-spacing": "off", + "@stylistic/ts/keyword-spacing": "off", + "@stylistic/ts/member-delimiter-style": "off", + "@stylistic/ts/no-extra-parens": "off", + "@stylistic/ts/no-extra-semi": "off", + "@stylistic/ts/object-curly-spacing": "off", + "@stylistic/ts/semi": "off", + "@stylistic/ts/space-before-blocks": "off", + "@stylistic/ts/space-before-function-paren": "off", + "@stylistic/ts/space-infix-ops": "off", + "@stylistic/ts/type-annotation-spacing": "off", + "@stylistic/jsx/jsx-child-element-spacing": "off", + "@stylistic/jsx/jsx-closing-bracket-location": "off", + "@stylistic/jsx/jsx-closing-tag-location": "off", + "@stylistic/jsx/jsx-curly-newline": "off", + "@stylistic/jsx/jsx-curly-spacing": "off", + "@stylistic/jsx/jsx-equals-spacing": "off", + "@stylistic/jsx/jsx-first-prop-new-line": "off", + "@stylistic/jsx/jsx-indent": "off", + "@stylistic/jsx/jsx-indent-props": "off", + "@stylistic/jsx/jsx-max-props-per-line": "off", + "@typescript-eslint/block-spacing": "off", + "@typescript-eslint/brace-style": "off", + "@typescript-eslint/comma-dangle": "off", + "@typescript-eslint/comma-spacing": "off", + "@typescript-eslint/func-call-spacing": "off", + "@typescript-eslint/indent": "off", + "@typescript-eslint/key-spacing": "off", + "@typescript-eslint/keyword-spacing": "off", + "@typescript-eslint/member-delimiter-style": "off", + "@typescript-eslint/no-extra-parens": "off", + "@typescript-eslint/no-extra-semi": "off", + "@typescript-eslint/object-curly-spacing": "off", + "@typescript-eslint/semi": "off", + "@typescript-eslint/space-before-blocks": "off", + "@typescript-eslint/space-before-function-paren": "off", + "@typescript-eslint/space-infix-ops": "off", + "@typescript-eslint/type-annotation-spacing": "off", + "babel/object-curly-spacing": "off", + "babel/semi": "off", + "flowtype/boolean-style": "off", + "flowtype/delimiter-dangle": "off", + "flowtype/generic-spacing": "off", + "flowtype/object-type-curly-spacing": "off", + "flowtype/object-type-delimiter": "off", + "flowtype/quotes": "off", + "flowtype/semi": "off", + "flowtype/space-after-type-colon": "off", + "flowtype/space-before-generic-bracket": "off", + "flowtype/space-before-type-colon": "off", + "flowtype/union-intersection-spacing": "off", + "react/jsx-child-element-spacing": "off", + "react/jsx-closing-bracket-location": "off", + "react/jsx-closing-tag-location": "off", + "react/jsx-curly-newline": "off", + "react/jsx-curly-spacing": "off", + "react/jsx-equals-spacing": "off", + "react/jsx-first-prop-new-line": "off", + "react/jsx-indent": "off", + "react/jsx-indent-props": "off", + "react/jsx-max-props-per-line": "off", + "react/jsx-newline": "off", + "react/jsx-one-expression-per-line": "off", + "react/jsx-props-no-multi-spaces": "off", + "react/jsx-tag-spacing": "off", + "react/jsx-wrap-multilines": "off", + "standard/array-bracket-even-spacing": "off", + "standard/computed-property-even-spacing": "off", + "standard/object-curly-even-spacing": "off", + "unicorn/empty-brace-spaces": "off", + "unicorn/no-nested-ternary": "off", + "unicorn/number-literal-case": "off", + "vue/array-bracket-newline": "off", + "vue/array-bracket-spacing": "off", + "vue/array-element-newline": "off", + "vue/arrow-spacing": "off", + "vue/block-spacing": "off", + "vue/block-tag-newline": "off", + "vue/brace-style": "off", + "vue/comma-dangle": "off", + "vue/comma-spacing": "off", + "vue/comma-style": "off", + "vue/dot-location": "off", + "vue/func-call-spacing": "off", + "vue/html-closing-bracket-newline": "off", + "vue/html-closing-bracket-spacing": "off", + "vue/html-end-tags": "off", + "vue/html-indent": "off", + "vue/html-quotes": "off", + "vue/key-spacing": "off", + "vue/keyword-spacing": "off", + "vue/max-attributes-per-line": "off", + "vue/multiline-html-element-content-newline": "off", + "vue/multiline-ternary": "off", + "vue/mustache-interpolation-spacing": "off", + "vue/no-extra-parens": "off", + "vue/no-multi-spaces": "off", + "vue/no-spaces-around-equal-signs-in-attribute": "off", + "vue/object-curly-newline": "off", + "vue/object-curly-spacing": "off", + "vue/object-property-newline": "off", + "vue/operator-linebreak": "off", + "vue/quote-props": "off", + "vue/script-indent": "off", + "vue/singleline-html-element-content-newline": "off", + "vue/space-in-parens": "off", + "vue/space-infix-ops": "off", + "vue/space-unary-ops": "off", + "vue/template-curly-spacing": "off", + + ...(includeDeprecated && { + // Removed in version 0.10.0. + // https://eslint.org/docs/latest/rules/space-unary-word-ops + "space-unary-word-ops": "off", + + // Removed in version 1.0.0. + // https://github.com/eslint/eslint/issues/1898 + "generator-star": "off", + "no-comma-dangle": "off", + "no-reserved-keys": "off", + "no-space-before-semi": "off", + "no-wrap-func": "off", + "space-after-function-name": "off", + "space-before-function-parentheses": "off", + "space-in-brackets": "off", + + // Removed in version 2.0.0. + // https://github.com/eslint/eslint/issues/5032 + "no-arrow-condition": "off", + "space-after-keywords": "off", + "space-before-keywords": "off", + "space-return-throw-case": "off", + + // Deprecated since version 3.3.0. + // https://eslint.org/docs/rules/no-spaced-func + "no-spaced-func": "off", + + // Deprecated since version 4.0.0. + // https://github.com/eslint/eslint/pull/8286 + "indent-legacy": "off", + + // Deprecated since version 8.53.0. + // https://eslint.org/blog/2023/10/deprecating-formatting-rules/ + "array-bracket-newline": "off", + "array-bracket-spacing": "off", + "array-element-newline": "off", + "arrow-parens": "off", + "arrow-spacing": "off", + "block-spacing": "off", + "brace-style": "off", + "comma-dangle": "off", + "comma-spacing": "off", + "comma-style": "off", + "computed-property-spacing": "off", + "dot-location": "off", + "eol-last": "off", + "func-call-spacing": "off", + "function-call-argument-newline": "off", + "function-paren-newline": "off", + "generator-star-spacing": "off", + "implicit-arrow-linebreak": "off", + "indent": "off", + "jsx-quotes": "off", + "key-spacing": "off", + "keyword-spacing": "off", + "linebreak-style": "off", + "lines-around-comment": specialRule, + "max-len": specialRule, + "max-statements-per-line": "off", + "multiline-ternary": "off", + "new-parens": "off", + "newline-per-chained-call": "off", + "no-confusing-arrow": specialRule, + "no-extra-parens": "off", + "no-extra-semi": "off", + "no-floating-decimal": "off", + "no-mixed-operators": specialRule, + "no-mixed-spaces-and-tabs": "off", + "no-multi-spaces": "off", + "no-multiple-empty-lines": "off", + "no-tabs": specialRule, + "no-trailing-spaces": "off", + "no-whitespace-before-property": "off", + "nonblock-statement-body-position": "off", + "object-curly-newline": "off", + "object-curly-spacing": "off", + "object-property-newline": "off", + "one-var-declaration-per-line": "off", + "operator-linebreak": "off", + "padded-blocks": "off", + "quote-props": "off", + "quotes": specialRule, + "rest-spread-spacing": "off", + "semi": "off", + "semi-spacing": "off", + "semi-style": "off", + "space-before-blocks": "off", + "space-before-function-paren": "off", + "space-in-parens": "off", + "space-infix-ops": "off", + "space-unary-ops": "off", + "switch-colon-spacing": "off", + "template-curly-spacing": "off", + "template-tag-spacing": "off", + "wrap-iife": "off", + "wrap-regex": "off", + "yield-star-spacing": "off", + + // Deprecated since version 7.0.0. + // https://github.com/yannickcr/eslint-plugin-react/blob/master/CHANGELOG.md#700---2017-05-06 + "react/jsx-space-before-closing": "off", + }), +}; diff --git a/node_modules/eslint-config-prettier/package.json b/node_modules/eslint-config-prettier/package.json new file mode 100644 index 0000000000000000000000000000000000000000..20fd2b8b336f8c75916b0e74fd2edd53ebeb177d --- /dev/null +++ b/node_modules/eslint-config-prettier/package.json @@ -0,0 +1,51 @@ +{ + "name": "eslint-config-prettier", + "version": "10.1.8", + "type": "commonjs", + "description": "Turns off all rules that are unnecessary or might conflict with Prettier.", + "repository": "prettier/eslint-config-prettier", + "homepage": "https://github.com/prettier/eslint-config-prettier#readme", + "author": "Simon Lydell", + "maintainers": [ + "JounQin (https://www.1stG.me) " + ], + "funding": "https://opencollective.com/eslint-config-prettier", + "license": "MIT", + "bin": "bin/cli.js", + "main": "index.js", + "types": "index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "./flat": { + "types": "./flat.d.ts", + "default": "./flat.js" + }, + "./prettier": { + "types": "./prettier.d.ts", + "default": "./prettier.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "bin", + "flat.d.ts", + "flat.js", + "index.d.ts", + "index.js", + "prettier.d.ts", + "prettier.js" + ], + "keywords": [ + "eslint", + "eslintconfig", + "eslint-config", + "eslint-prettier", + "prettier" + ], + "peerDependencies": { + "eslint": ">=7.0.0" + } +} \ No newline at end of file diff --git a/node_modules/eslint-config-prettier/prettier.d.ts b/node_modules/eslint-config-prettier/prettier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..19b02c2c60c906ce45be1d95c9ec8313278ebd59 --- /dev/null +++ b/node_modules/eslint-config-prettier/prettier.d.ts @@ -0,0 +1 @@ +export const rules: Record; diff --git a/node_modules/eslint-config-prettier/prettier.js b/node_modules/eslint-config-prettier/prettier.js new file mode 100644 index 0000000000000000000000000000000000000000..b9ec0f73602cde3ea57d72c475b1ada105899331 --- /dev/null +++ b/node_modules/eslint-config-prettier/prettier.js @@ -0,0 +1,10 @@ +"use strict"; + +exports.rules = { + // These are safe to use as long as the `"prettier/prettier"` rule from + // eslint-plugin-prettier isn’t enabled. + // These are also included in `"plugin:prettier/recommended"`: + // https://github.com/prettier/eslint-plugin-prettier#recommended-configuration + "arrow-body-style": 0, + "prefer-arrow-callback": 0, +}; diff --git a/node_modules/eslint-plugin-prettier/LICENSE.md b/node_modules/eslint-plugin-prettier/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..26864ebf2b104771fe669f7d2559bdb1a7c5859b --- /dev/null +++ b/node_modules/eslint-plugin-prettier/LICENSE.md @@ -0,0 +1,24 @@ +# The MIT License (MIT) + +Copyright © 2017 Andres Suarez and Teddy Katz + +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. diff --git a/node_modules/eslint-plugin-prettier/README.md b/node_modules/eslint-plugin-prettier/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6bc12623d1b69a98af0ca80fc457abd838eb8151 --- /dev/null +++ b/node_modules/eslint-plugin-prettier/README.md @@ -0,0 +1,199 @@ +# eslint-plugin-prettier [![Build Status](https://github.com/prettier/eslint-plugin-prettier/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/prettier/eslint-plugin-prettier/actions?query=workflow%3ACI+branch%3Amain) + +Runs [Prettier](https://github.com/prettier/prettier) as an [ESLint](https://eslint.org) rule and reports differences as individual ESLint issues. + +If your desired formatting does not match Prettier’s output, you should use a different tool such as [prettier-eslint](https://github.com/prettier/prettier-eslint) instead. + +Please read [Integrating with linters](https://prettier.io/docs/en/integrating-with-linters.html) before installing. + +## TOC + +- [Sample](#sample) +- [Installation](#installation) +- [Configuration (legacy: `.eslintrc*`)](#configuration-legacy-eslintrc) +- [Configuration (new: `eslint.config.js`)](#configuration-new-eslintconfigjs) +- [`Svelte` support](#svelte-support) +- [`arrow-body-style` and `prefer-arrow-callback` issue](#arrow-body-style-and-prefer-arrow-callback-issue) +- [Options](#options) +- [Sponsors](#sponsors) +- [Backers](#backers) +- [Contributing](#contributing) +- [Changelog](#changelog) +- [License](#license) + +## Sample + +```js +error: Insert `,` (prettier/prettier) at pkg/commons-atom/ActiveEditorRegistry.js:22:25: + 20 | import { + 21 | observeActiveEditorsDebounced, +> 22 | editorChangesDebounced + | ^ + 23 | } from './debounced';; + 24 | + 25 | import {observableFromSubscribeFunction} from '../commons-node/event'; + + +error: Delete `;` (prettier/prettier) at pkg/commons-atom/ActiveEditorRegistry.js:23:21: + 21 | observeActiveEditorsDebounced, + 22 | editorChangesDebounced +> 23 | } from './debounced';; + | ^ + 24 | + 25 | import {observableFromSubscribeFunction} from '../commons-node/event'; + 26 | import {cacheWhileSubscribed} from '../commons-node/observable'; + + +2 errors found. +``` + +> `./node_modules/.bin/eslint --format codeframe pkg/commons-atom/ActiveEditorRegistry.js` (code from [nuclide](https://github.com/facebook/nuclide)). + +## Installation + +```sh +npm install --save-dev eslint-plugin-prettier eslint-config-prettier +npm install --save-dev --save-exact prettier +``` + +**_`eslint-plugin-prettier` does not install Prettier or ESLint for you._** _You must install these yourself._ + +This plugin works best if you disable all other ESLint rules relating to code formatting, and only enable rules that detect potential bugs. If another active ESLint rule disagrees with `prettier` about how code should be formatted, it will be impossible to avoid lint errors. Our recommended configuration automatically enables [`eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier) to disable all formatting-related ESLint rules. + +## Configuration (legacy: `.eslintrc*`) + +For [legacy configuration](https://eslint.org/docs/latest/use/configure/configuration-files-deprecated), this plugin ships with a `plugin:prettier/recommended` config that sets up both `eslint-plugin-prettier` and [`eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier) in one go. + +Add `plugin:prettier/recommended` as the _last_ item in the extends array in your `.eslintrc*` config file, so that `eslint-config-prettier` has the opportunity to override other configs: + +```json +{ + "extends": ["plugin:prettier/recommended"] +} +``` + +This will: + +- Enable the `prettier/prettier` rule. +- Disable the `arrow-body-style` and `prefer-arrow-callback` rules which are problematic with this plugin - see the below for why. +- Enable the `eslint-config-prettier` config which will turn off ESLint rules that conflict with Prettier. + +## Configuration (new: `eslint.config.js`) + +For [flat configuration](https://eslint.org/docs/latest/use/configure/configuration-files-new), this plugin ships with an `eslint-plugin-prettier/recommended` config that sets up both `eslint-plugin-prettier` and [`eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier) in one go. + +Import `eslint-plugin-prettier/recommended` and add it as the _last_ item in the configuration array in your `eslint.config.js` file so that `eslint-config-prettier` has the opportunity to override other configs: + +```js +const eslintPluginPrettierRecommended = require('eslint-plugin-prettier/recommended'); + +module.exports = [ + // Any other config imports go at the top + eslintPluginPrettierRecommended, +]; +``` + +This will: + +- Enable the `prettier/prettier` rule. +- Disable the `arrow-body-style` and `prefer-arrow-callback` rules which are problematic with this plugin - see the below for why. +- Enable the `eslint-config-prettier` config which will turn off ESLint rules that conflict with Prettier. + +## `Svelte` support + +We recommend to use [`eslint-plugin-svelte`](https://github.com/ota-meshi/eslint-plugin-svelte) instead of [`eslint-plugin-svelte3`](https://github.com/sveltejs/eslint-plugin-svelte3) because `eslint-plugin-svelte` has a correct [`eslint-svelte-parser`](https://github.com/ota-meshi/svelte-eslint-parser) instead of hacking. + +When use with `eslint-plugin-svelte3`, `eslint-plugin-prettier` will just ignore the text passed by `eslint-plugin-svelte3`, because the text has been modified. + +If you still decide to use `eslint-plugin-svelte3`, you'll need to run `prettier --write *.svelte` manually. + +## `arrow-body-style` and `prefer-arrow-callback` issue + +If you use [arrow-body-style](https://eslint.org/docs/rules/arrow-body-style) or [prefer-arrow-callback](https://eslint.org/docs/rules/prefer-arrow-callback) together with the `prettier/prettier` rule from this plugin, you can in some cases end up with invalid code due to a bug in ESLint’s autofix – see [issue #65](https://github.com/prettier/eslint-plugin-prettier/issues/65). + +For this reason, it’s recommended to turn off these rules. The `plugin:prettier/recommended` config does that for you. + +You _can_ still use these rules together with this plugin if you want, because the bug does not occur _all the time._ But if you do, you need to keep in mind that you might end up with invalid code, where you manually have to insert a missing closing parenthesis to get going again. + +If you’re fixing large of amounts of previously unformatted code, consider temporarily disabling the `prettier/prettier` rule and running `eslint --fix` and `prettier --write` separately. + +## Options + +> Note: While it is possible to pass options to Prettier via your ESLint configuration file, it is not recommended because editor extensions such as `prettier-atom` and `prettier-vscode` **will** read [`.prettierrc`](https://prettier.io/docs/en/configuration.html), but **won't** read settings from ESLint, which can lead to an inconsistent experience. + +- The first option: + - An object representing [options](https://prettier.io/docs/en/options.html) that will be passed into prettier. Example: + + ```json + { + "prettier/prettier": [ + "error", + { + "singleQuote": true, + "parser": "flow" + } + ] + } + ``` + + NB: This option will merge and override any config set with `.prettierrc` files + +- The second option: + - An object with the following options + - `usePrettierrc`: Enables loading of the Prettier configuration file, (default: `true`). May be useful if you are using multiple tools that conflict with each other, or do not wish to mix your ESLint settings with your Prettier configuration. And also, it is possible to run prettier without loading the prettierrc config file [via the CLI's --no-config option](https://prettier.io/docs/en/cli.html#--no-config) or through the API by [calling prettier.format() without passing through the options generated by calling resolveConfig](https://prettier.io/docs/en/api.html#prettierresolveconfigfilepath--options). + + ```json + { + "prettier/prettier": [ + "error", + {}, + { + "usePrettierrc": false + } + ] + } + ``` + + - `fileInfoOptions`: Options that are passed to [prettier.getFileInfo](https://prettier.io/docs/en/api.html#prettiergetfileinfofilepath--options) to decide whether a file needs to be formatted. Can be used for example to opt-out from ignoring files located in `node_modules` directories. + + ```json + { + "prettier/prettier": [ + "error", + {}, + { + "fileInfoOptions": { + "withNodeModules": true + } + } + ] + } + ``` + +- The rule is auto fixable -- if you run `eslint` with the `--fix` flag, your code will be formatted according to `prettier` style. + +--- + +## Sponsors + +| @prettier/plugin-eslint | eslint-config-prettier | eslint-plugin-prettier | prettier-eslint | prettier-eslint-cli | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [![@prettier/plugin-eslint Open Collective sponsors](https://opencollective.com/prettier-plugin-eslint/tiers/sponsors.svg)](https://opencollective.com/prettier-plugin-eslint) | [![eslint-config-prettier Open Collective backers](https://opencollective.com/eslint-config-prettier/tiers/sponsors.svg)](https://opencollective.com/eslint-config-prettier) | [![eslint-plugin-prettier Open Collective backers](https://opencollective.com/eslint-plugin-prettier/tiers/sponsors.svg)](https://opencollective.com/rxts) | [![prettier-eslint Open Collective sponsors](https://opencollective.com/prettier-eslint/tiers/sponsors.svg)](https://opencollective.com/prettier-eslint) | [![prettier-eslint-cli Open Collective backers](https://opencollective.com/prettier-eslint-cli/tiers/sponsors.svg)](https://opencollective.com/prettier-eslint-cli) | + +## Backers + +| @prettier/plugin-eslint | eslint-config-prettier | eslint-plugin-prettier | prettier-eslint | prettier-eslint-cli | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| [![@prettier/plugin-eslint Open Collective backers](https://opencollective.com/prettier-plugin-eslint/tiers/backers.svg)](https://opencollective.com/prettier-plugin-eslint) | [![eslint-config-prettier Open Collective backers](https://opencollective.com/eslint-config-prettier/tiers/backers.svg)](https://opencollective.com/eslint-config-prettier) | [![eslint-plugin-prettier Open Collective backers](https://opencollective.com/eslint-plugin-prettier/tiers/backers.svg)](https://opencollective.com/rxts) | [![prettier-eslint Open Collective backers](https://opencollective.com/prettier-eslint/tiers/backers.svg)](https://opencollective.com/prettier-eslint) | [![prettier-eslint-cli Open Collective backers](https://opencollective.com/prettier-eslint-cli/tiers/backers.svg)](https://opencollective.com/prettier-eslint-cli) | + +## Contributing + +See [CONTRIBUTING.md](https://github.com/prettier/eslint-plugin-prettier/blob/main/CONTRIBUTING.md) + +## Changelog + +Detailed changes for each release are documented in [CHANGELOG.md](./CHANGELOG.md). + +## License + +[MIT](http://opensource.org/licenses/MIT) diff --git a/node_modules/eslint-plugin-prettier/eslint-plugin-prettier.d.ts b/node_modules/eslint-plugin-prettier/eslint-plugin-prettier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eafdb4a18e8b260aae8ddfa122a48d60cea65f83 --- /dev/null +++ b/node_modules/eslint-plugin-prettier/eslint-plugin-prettier.d.ts @@ -0,0 +1,5 @@ +import { ESLint } from 'eslint'; + +declare const eslintPluginPrettier: ESLint.Plugin; + +export = eslintPluginPrettier; diff --git a/node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js b/node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js new file mode 100644 index 0000000000000000000000000000000000000000..7a6ecedaf60013f14308f636dfc031e0647fe099 --- /dev/null +++ b/node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js @@ -0,0 +1,306 @@ +/** + * @file Runs `prettier` as an ESLint rule. + * @author Andres Suarez + */ + +// @ts-check + +/** + * @import {AST, ESLint, Linter, Rule, SourceCode} from 'eslint' + * @import {Position} from 'estree' + * @import {FileInfoOptions, Options as PrettierOptions} from 'prettier' + * @import {Difference} from 'prettier-linter-helpers' + */ + +/** + * @typedef {PrettierOptions & { + * onDiskFilepath: string; + * parserMeta?: ESLint.ObjectMetaProperties['meta']; + * parserPath?: string; + * usePrettierrc?: boolean; + * }} Options + * + * + * @typedef {( + * source: string, + * options: Options, + * fileInfoOptions: FileInfoOptions, + * ) => string} PrettierFormat + */ + +'use strict'; + +// ------------------------------------------------------------------------------ +// Requirements +// ------------------------------------------------------------------------------ + +const { + showInvisibles, + generateDifferences, +} = require('prettier-linter-helpers'); +const { name, version } = require('./package.json'); + +// ------------------------------------------------------------------------------ +// Constants +// ------------------------------------------------------------------------------ + +const { INSERT, DELETE, REPLACE } = generateDifferences; + +// ------------------------------------------------------------------------------ +// Privates +// ------------------------------------------------------------------------------ + +// Lazily-loaded Prettier. +/** @type {PrettierFormat} */ +let prettierFormat; + +// ------------------------------------------------------------------------------ +// Rule Definition +// ------------------------------------------------------------------------------ + +/** @type {WeakMap} */ +const lineIndexesCache = new WeakMap(); + +/** + * Ponyfill `sourceCode.getLocFromIndex` when it's unavailable. + * + * See also `getLocFromIndex` in `@eslint/js`. + * + * @param {SourceCode} sourceCode + * @param {number} index + * @returns {Position} + */ +function getLocFromIndex(sourceCode, index) { + if (typeof sourceCode.getLocFromIndex === 'function') { + return sourceCode.getLocFromIndex(index); + } + + let lineIndexes = lineIndexesCache.get(sourceCode); + if (!lineIndexes) { + lineIndexes = [...sourceCode.text.matchAll(/\r?\n/g)].map( + match => match.index, + ); + // first line in the file starts at byte offset 0 + lineIndexes.unshift(0); + lineIndexesCache.set(sourceCode, lineIndexes); + } + + let line = 0; + while (line + 1 < lineIndexes.length && lineIndexes[line + 1] < index) { + line += 1; + } + const column = index - lineIndexes[line]; + + return { line: line + 1, column }; +} + +/** + * Reports a difference. + * + * @param {Rule.RuleContext} context - The ESLint rule context. + * @param {Difference} difference - The difference object. + * @returns {void} + */ +function reportDifference(context, difference) { + const { operation, offset } = difference; + const insertText = 'insertText' in difference ? difference.insertText : ''; + const deleteText = 'deleteText' in difference ? difference.deleteText : ''; + /** @type {AST.Range} */ + const range = [offset, offset + deleteText.length]; + // `context.getSourceCode()` was deprecated in ESLint v8.40.0 and replaced + // with the `sourceCode` property. + // TODO: Only use property when our eslint peerDependency is >=8.40.0. + const sourceCode = context.sourceCode ?? context.getSourceCode(); + + const [start, end] = range.map(index => getLocFromIndex(sourceCode, index)); + + context.report({ + messageId: operation, + data: { + deleteText: showInvisibles(deleteText), + insertText: showInvisibles(insertText), + }, + loc: { start, end }, + fix: fixer => fixer.replaceTextRange(range, insertText), + }); +} + +// ------------------------------------------------------------------------------ +// Module Definition +// ------------------------------------------------------------------------------ + +/** @type {ESLint.Plugin} */ +const eslintPluginPrettier = { + meta: { name, version }, + configs: { + recommended: { + extends: ['prettier'], + plugins: ['prettier'], + rules: { + 'prettier/prettier': 'error', + 'arrow-body-style': 'off', + 'prefer-arrow-callback': 'off', + }, + }, + }, + rules: { + prettier: { + meta: { + docs: { + url: 'https://github.com/prettier/eslint-plugin-prettier#options', + }, + type: 'layout', + fixable: 'code', + schema: [ + // Prettier options: + { + type: 'object', + properties: {}, + additionalProperties: true, + }, + { + type: 'object', + properties: { + usePrettierrc: { type: 'boolean' }, + fileInfoOptions: { + type: 'object', + properties: {}, + additionalProperties: true, + }, + }, + additionalProperties: false, + }, + ], + messages: { + [INSERT]: 'Insert `{{ insertText }}`', + [DELETE]: 'Delete `{{ deleteText }}`', + [REPLACE]: 'Replace `{{ deleteText }}` with `{{ insertText }}`', + }, + }, + create(context) { + const options = /** @type {Options | undefined} */ (context.options[1]); + const usePrettierrc = !options || options.usePrettierrc !== false; + /** @type {FileInfoOptions} */ + const fileInfoOptions = options?.fileInfoOptions || {}; + + // `context.getSourceCode()` was deprecated in ESLint v8.40.0 and replaced + // with the `sourceCode` property. + // TODO: Only use property when our eslint peerDependency is >=8.40.0. + const sourceCode = /** @type {SourceCode} */ ( + context.sourceCode ?? context.getSourceCode() + ); + // `context.getFilename()` was deprecated in ESLint v8.40.0 and replaced + // with the `filename` property. + // TODO: Only use property when our eslint peerDependency is >=8.40.0. + const filepath = context.filename ?? context.getFilename(); + + // Processors that extract content from a file, such as the markdown + // plugin extracting fenced code blocks may choose to specify virtual + // file paths. If this is the case then we need to resolve prettier + // config and file info using the on-disk path instead of the virtual + // path. + // `context.getPhysicalFilename()` was deprecated in ESLint v8.40.0 and replaced + // with the `physicalFilename` property. + // TODO: Only use property when our eslint peerDependency is >=8.40.0. + const onDiskFilepath = + context.physicalFilename ?? context.getPhysicalFilename(); + const source = sourceCode.text; + + return { + /** @param {unknown} node */ + [sourceCode.ast.type](node) { + if (!prettierFormat) { + // Prettier is expensive to load, so only load it if needed. + prettierFormat = /** @type {PrettierFormat} */ ( + require('synckit').createSyncFn(require.resolve('./worker.mjs')) + ); + } + + /** @type {PrettierOptions} */ + const eslintPrettierOptions = context.options[0] || {}; + + const parser = /** @type {Linter.Parser | undefined} */ ( + context.languageOptions?.parser + ); + + // prettier.format() may throw a SyntaxError if it cannot parse the + // source code it is given. Usually for JS files this isn't a + // problem as ESLint will report invalid syntax before trying to + // pass it to the prettier plugin. However this might be a problem + // for non-JS languages that are handled by a plugin. Notably Vue + // files throw an error if they contain unclosed elements, such as + // `. In this case report an error at the + // point at which parsing failed. + /** @type {string} */ + let prettierSource; + try { + prettierSource = prettierFormat( + source, + { + ...eslintPrettierOptions, + filepath, + onDiskFilepath, + parserMeta: + parser && + (parser.meta ?? { + name: parser.name, + version: parser.version, + }), + parserPath: context.parserPath, + usePrettierrc, + }, + fileInfoOptions, + ); + } catch (err) { + if (!(err instanceof SyntaxError)) { + throw err; + } + + let message = 'Parsing error: ' + err.message; + + const error = /** + * @type {SyntaxError & { + * codeFrame: string; + * loc?: AST.SourceLocation; + * }} + */ (err); + + // Prettier's message contains a codeframe style preview of the + // invalid code and the line/column at which the error occurred. + // ESLint shows those pieces of information elsewhere already so + // remove them from the message + if (error.codeFrame) { + message = message.replace(`\n${error.codeFrame}`, ''); + } + if (error.loc) { + message = message.replace(/ \(\d+:\d+\)$/, ''); + context.report({ message, loc: error.loc }); + } else { + context.report({ message, node }); + } + + return; + } + + if (prettierSource == null) { + return; + } + + if (source !== prettierSource) { + const differences = generateDifferences(source, prettierSource); + + for (const difference of differences) { + reportDifference( + /** @type {Rule.RuleContext} */ (context), + difference, + ); + } + } + }, + }; + }, + }, + }, +}; + +module.exports = eslintPluginPrettier; diff --git a/node_modules/eslint-plugin-prettier/package.json b/node_modules/eslint-plugin-prettier/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0f08af9c7fd3db3ebcab6ea6ded0a78aab2b170e --- /dev/null +++ b/node_modules/eslint-plugin-prettier/package.json @@ -0,0 +1,60 @@ +{ + "name": "eslint-plugin-prettier", + "version": "5.5.6", + "description": "Runs prettier as an eslint rule", + "repository": "https://github.com/prettier/eslint-plugin-prettier.git", + "homepage": "https://github.com/prettier/eslint-plugin-prettier#readme", + "author": "Teddy Katz", + "maintainers": [ + "JounQin (https://github.com/JounQin)" + ], + "funding": "https://opencollective.com/eslint-plugin-prettier", + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "main": "eslint-plugin-prettier.js", + "types": "eslint-plugin-prettier.d.ts", + "exports": { + ".": { + "types": "./eslint-plugin-prettier.d.ts", + "default": "./eslint-plugin-prettier.js" + }, + "./recommended": { + "types": "./recommended.d.ts", + "default": "./recommended.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "eslint-plugin-prettier.d.ts", + "eslint-plugin-prettier.js", + "recommended.d.ts", + "recommended.js", + "worker.mjs" + ], + "keywords": [ + "eslint", + "eslintplugin", + "eslint-plugin", + "prettier" + ], + "peerDependencies": { + "@types/eslint": ">=8.0.0", + "eslint": ">=8.0.0", + "eslint-config-prettier": ">= 7.0.0 <10.0.0 || >=10.1.0", + "prettier": ">=3.0.0" + }, + "peerDependenciesMeta": { + "@types/eslint": { + "optional": true + }, + "eslint-config-prettier": { + "optional": true + } + }, + "dependencies": { + "prettier-linter-helpers": "^1.0.1", + "synckit": "^0.11.13" + } +} \ No newline at end of file diff --git a/node_modules/eslint-plugin-prettier/recommended.d.ts b/node_modules/eslint-plugin-prettier/recommended.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..434147a1c4f45f6d5aa5a527eb84b93628cf3438 --- /dev/null +++ b/node_modules/eslint-plugin-prettier/recommended.d.ts @@ -0,0 +1,12 @@ +import { Linter } from 'eslint'; + +// prettier-ignore +type IfEqual = + (() => G extends A & G | G ? 1 : 2) extends + (() => G extends B & G | G ? 1 : 2) + ? X + : Y; + +declare const recommendedConfig: IfEqual; + +export = recommendedConfig; diff --git a/node_modules/eslint-plugin-prettier/recommended.js b/node_modules/eslint-plugin-prettier/recommended.js new file mode 100644 index 0000000000000000000000000000000000000000..cce31b08c1ba9bde73e97cda8f16c7f1d090d491 --- /dev/null +++ b/node_modules/eslint-plugin-prettier/recommended.js @@ -0,0 +1,18 @@ +const { rules: configPrettierRules } = require('eslint-config-prettier'); +const { + rules: configPrettierOverridesRules, +} = require('eslint-config-prettier/prettier'); +const eslintPluginPrettier = require('./eslint-plugin-prettier'); + +// Merge the contents of eslint-config-prettier into config +module.exports = { + name: 'eslint-plugin-prettier/recommended', + plugins: { + prettier: eslintPluginPrettier, + }, + rules: { + ...configPrettierRules, + ...configPrettierOverridesRules, + 'prettier/prettier': 'error', + }, +}; diff --git a/node_modules/eslint-plugin-prettier/worker.mjs b/node_modules/eslint-plugin-prettier/worker.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1451209f44b626ef3e6f0b8c3e719db99fb791f8 --- /dev/null +++ b/node_modules/eslint-plugin-prettier/worker.mjs @@ -0,0 +1,187 @@ +// @ts-check + +/** + * @typedef {PrettierOptions & { + * onDiskFilepath: string; + * parserMeta?: ESLint.ObjectMetaProperties['meta']; + * parserPath?: string; + * usePrettierrc?: boolean; + * }} Options + * @import {FileInfoOptions, Options as PrettierOptions} from 'prettier' + * @import {ESLint} from 'eslint' + */ + +import prettier from 'prettier'; +import { runAsWorker } from 'synckit'; + +runAsWorker( + /** + * @param {string} source - The source code to format. + * @param {Options} options - The prettier options. + * @param {FileInfoOptions} eslintFileInfoOptions - The file info options. + * @returns {Promise} The formatted source code. + */ + async ( + source, + { + filepath, + onDiskFilepath, + parserMeta, + parserPath, + usePrettierrc, + ...eslintPrettierOptions + }, + eslintFileInfoOptions, + ) => { + const prettierRcOptions = usePrettierrc + ? await prettier.resolveConfig(onDiskFilepath, { + editorconfig: true, + }) + : null; + + const { ignored, inferredParser } = await prettier.getFileInfo( + onDiskFilepath, + { + resolveConfig: false, + withNodeModules: false, + ignorePath: '.prettierignore', + ...prettierRcOptions, + ...eslintFileInfoOptions, + }, + ); + + // Skip if file is ignored using a .prettierignore file + if (ignored) { + return; + } + + const initialOptions = { parser: inferredParser ?? 'babel' }; + + // ESLint supports processors that let you extract and lint JS + // fragments within a non-JS language. In the cases where prettier + // supports the same language as a processor, we want to process + // the provided source code as javascript (as ESLint provides the + // rules with fragments of JS) instead of guessing the parser + // based off the filename. Otherwise, for instance, on a .md file we + // end up trying to run prettier over a fragment of JS using the + // markdown parser, which throws an error. + // Processors may set virtual filenames for these extracted blocks. + // If they do so then we want to trust the file extension they + // provide, and no override is needed. + // If the processor does not set any virtual filename (signified by + // `filepath` and `onDiskFilepath` being equal) AND we can't + // infer the parser from the filename, either because no filename + // was provided or because there is no parser found for the + // filename, use javascript. + // This is added to the options first, so that + // prettierRcOptions and eslintPrettierOptions can still override + // the parser. + // + // `parserBlocklist` should contain the list of prettier parser + // names for file types where: + // * Prettier supports parsing the file type + // * There is an ESLint processor that extracts JavaScript snippets + // from the file type. + if (filepath === onDiskFilepath) { + // The following list means the plugin process source into js content + // but with same filename, so we need to change the parser to `babel` + // by default. + // Related ESLint plugins are: + // 1. `eslint-plugin-graphql` (replacement: `@graphql-eslint/eslint-plugin`) + // 2. `eslint-plugin-html` + // 3. `eslint-plugin-markdown@1` (replacement: `eslint-plugin-markdown@2+`) + // 4. `eslint-plugin-svelte3` (replacement: `eslint-plugin-svelte@2+`) + let inferParserToBabel = false; + + switch (inferredParser) { + // it could be processed by `@graphql-eslint/eslint-plugin` or `eslint-plugin-graphql` + case 'graphql': { + if ( + // for `eslint-plugin-graphql`, see https://github.com/apollographql/eslint-plugin-graphql/blob/64c524cd6607358803d5fcb7cead0a383a125ccb/src/index.js#L416 + source.startsWith('ESLintPluginGraphQLFile`') + ) { + inferParserToBabel = true; + } + break; + } + case 'html': { + // it could be processed by `eslint-plugin-html` or correctly parsed by `@html-eslint/parser` + if ( + (typeof parserMeta !== 'undefined' && + parserMeta.name !== '@html-eslint/parser') || + (typeof parserPath === 'string' && + !/([\\/])@html-eslint\1parser\1/.test(parserPath)) + ) { + inferParserToBabel = true; + } + break; + } + case 'markdown': { + // it could be processed by `eslint-plugin-markdown@1` or correctly parsed by `eslint-mdx` + if ( + (typeof parserMeta !== 'undefined' && + parserMeta.name !== 'eslint-mdx') || + (typeof parserPath === 'string' && + !/([\\/])eslint-mdx\1/.test(parserPath)) + ) { + inferParserToBabel = true; + } + break; + } + // it could be processed by `@ota-meshi/eslint-plugin-svelte`, `eslint-plugin-svelte` or `eslint-plugin-svelte3` + case 'svelte': { + // The `source` would be modified by `eslint-plugin-svelte3` + if ( + typeof parserPath === 'string' && + !/([\\/])svelte-eslint-parser\1/.test(parserPath) + ) { + // We do not support `eslint-plugin-svelte3`, + // the users should run `prettier` on `.svelte` files manually + return; + } + } + } + + if (inferParserToBabel) { + initialOptions.parser = 'babel'; + } + } else { + // Similar to https://github.com/prettier/stylelint-prettier/pull/22 + // In all of the following cases ESLint extracts a part of a file to + // be formatted and there exists a prettier parser for the whole file. + // If you're interested in prettier you'll want a fully formatted file so + // you're about to run prettier over the whole file anyway. + // Therefore running prettier over just the style section is wasteful, so + // skip it. + const parserBlocklist = [ + 'babel', + 'babylon', + 'flow', + 'typescript', + 'vue', + 'markdown', + 'html', + 'mdx', + 'angular', + 'svelte', + 'pug', + 'oxc', + 'oxc-ts', + 'hermes', + ]; + if (parserBlocklist.includes(/** @type {string} */ (inferredParser))) { + return; + } + } + + /** @type {PrettierOptions} */ + const prettierOptions = { + ...initialOptions, + ...prettierRcOptions, + ...eslintPrettierOptions, + filepath, + }; + + return prettier.format(source, prettierOptions); + }, +); diff --git a/node_modules/eslint-plugin-react-hooks/LICENSE b/node_modules/eslint-plugin-react-hooks/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b93be90515ccd0b9daedaa589e42bf5929693f1f --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/LICENSE @@ -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. diff --git a/node_modules/eslint-plugin-react-hooks/README.md b/node_modules/eslint-plugin-react-hooks/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b0a4491c99e07ac948ea25be2946ab653b2f93ca --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/README.md @@ -0,0 +1,150 @@ +# `eslint-plugin-react-hooks` + +The official ESLint plugin for [React](https://react.dev) which enforces the [Rules of React](https://react.dev/reference/eslint-plugin-react-hooks) and other best practices. + +## Installation + +Assuming you already have ESLint installed, run: + +```sh +# npm +npm install eslint-plugin-react-hooks --save-dev + +# yarn +yarn add eslint-plugin-react-hooks --dev +``` + +### Flat Config (eslint.config.js|ts) + +Add the `recommended` config for all recommended rules: + +```js +// eslint.config.js +import reactHooks from 'eslint-plugin-react-hooks'; +import { defineConfig } from 'eslint/config'; + +export default defineConfig([ + reactHooks.configs.flat.recommended, +]); +``` + +If you want to try bleeding edge experimental compiler rules, use `recommended-latest`. + +```js +// eslint.config.js +import reactHooks from 'eslint-plugin-react-hooks'; +import { defineConfig } from 'eslint/config'; + +export default defineConfig([ + reactHooks.configs.flat['recommended-latest'], +]); +``` + +### Legacy Config (.eslintrc) + +If you are still using ESLint below 9.0.0, the `recommended` preset can also be used to enable all recommended rules. + +```js +{ + "extends": ["plugin:react-hooks/recommended"], + // ... +} + +``` + +### Custom Configuration + +If you want more fine-grained configuration, you can instead choose to enable specific rules. However, we strongly encourage using the recommended presets — see above — so that you will automatically receive new recommended rules as we add them in future versions of the plugin. + +#### Flat Config (eslint.config.js|ts) + +```js +import reactHooks from 'eslint-plugin-react-hooks'; + +export default [ + { + files: ['**/*.{js,jsx}'], + plugins: { 'react-hooks': reactHooks }, + // ... + rules: { + // Core hooks rules + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'warn', + + // React Compiler rules + 'react-hooks/config': 'error', + 'react-hooks/error-boundaries': 'error', + 'react-hooks/gating': 'error', + 'react-hooks/globals': 'error', + 'react-hooks/immutability': 'error', + 'react-hooks/preserve-manual-memoization': 'error', + 'react-hooks/purity': 'error', + 'react-hooks/refs': 'error', + 'react-hooks/set-state-in-effect': 'error', + 'react-hooks/set-state-in-render': 'error', + 'react-hooks/static-components': 'error', + 'react-hooks/unsupported-syntax': 'warn', + 'react-hooks/use-memo': 'error', + 'react-hooks/incompatible-library': 'warn', + } + }, +]; +``` + +#### Legacy Config (.eslintrc) +```js +{ + "plugins": [ + // ... + "react-hooks" + ], + "rules": { + // ... + // Core hooks rules + "react-hooks/rules-of-hooks": "error", + "react-hooks/exhaustive-deps": "warn", + + // React Compiler rules + "react-hooks/config": "error", + "react-hooks/error-boundaries": "error", + "react-hooks/gating": "error", + "react-hooks/globals": "error", + "react-hooks/immutability": "error", + "react-hooks/preserve-manual-memoization": "error", + "react-hooks/purity": "error", + "react-hooks/refs": "error", + "react-hooks/set-state-in-effect": "error", + "react-hooks/set-state-in-render": "error", + "react-hooks/static-components": "error", + "react-hooks/unsupported-syntax": "warn", + "react-hooks/use-memo": "error", + "react-hooks/incompatible-library": "warn" + } +} +``` + +## Advanced Configuration + +`exhaustive-deps` can be configured to validate dependencies of custom Hooks with the `additionalHooks` option. +This option accepts a regex to match the names of custom Hooks that have dependencies. + +```js +{ + rules: { + // ... + "react-hooks/exhaustive-deps": ["warn", { + additionalHooks: "(useMyCustomHook|useMyOtherCustomHook)" + }] + } +} +``` + +We suggest to use this option **very sparingly, if at all**. Generally saying, we recommend most custom Hooks to not use the dependencies argument, and instead provide a higher-level API that is more focused around a specific use case. + +## Valid and Invalid Examples + +Please refer to the [Rules of Hooks](https://react.dev/reference/rules/rules-of-hooks) documentation to learn more about this rule. + +## License + +MIT diff --git a/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.d.ts b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..50c98c5a74af20ec75b1e7302fa0437eebfbb7e0 --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.d.ts @@ -0,0 +1,101 @@ +import * as estree from 'estree'; +import { Rule, Linter } from 'eslint'; + +type ReactHooksFlatConfig = { + plugins: { + react: any; + }; + rules: Linter.RulesRecord; +}; +declare const plugin: { + meta: { + name: string; + version: string; + }; + rules: { + 'component-hook-factories': Rule.RuleModule; + 'exhaustive-deps': { + meta: { + type: "suggestion"; + docs: { + description: string; + recommended: true; + url: string; + }; + fixable: "code"; + hasSuggestions: true; + schema: { + type: "object"; + additionalProperties: false; + enableDangerousAutofixThisMayCauseInfiniteLoops: boolean; + properties: { + additionalHooks: { + type: "string"; + }; + enableDangerousAutofixThisMayCauseInfiniteLoops: { + type: "boolean"; + }; + experimental_autoDependenciesHooks: { + type: "array"; + items: { + type: "string"; + }; + }; + requireExplicitEffectDeps: { + type: "boolean"; + }; + }; + }[]; + }; + create(context: Rule.RuleContext): { + CallExpression: (node: estree.CallExpression) => void; + }; + }; + 'rules-of-hooks': { + meta: { + type: "problem"; + docs: { + description: string; + recommended: true; + url: string; + }; + schema: { + type: "object"; + additionalProperties: false; + properties: { + additionalHooks: { + type: "string"; + }; + }; + }[]; + }; + create(context: Rule.RuleContext): { + '*'(node: any): void; + '*:exit'(node: any): void; + CallExpression(node: estree.CallExpression & Rule.NodeParentExtension): void; + Identifier(node: estree.Identifier & Rule.NodeParentExtension): void; + 'CallExpression:exit'(node: estree.CallExpression & Rule.NodeParentExtension): void; + FunctionDeclaration(node: estree.FunctionDeclaration & Rule.NodeParentExtension): void; + ArrowFunctionExpression(node: estree.ArrowFunctionExpression & Rule.NodeParentExtension): void; + ComponentDeclaration(node: any): void; + HookDeclaration(node: any): void; + }; + }; + }; + configs: { + recommended: { + plugins: string[]; + rules: Linter.RulesRecord; + }; + 'recommended-latest': { + plugins: string[]; + rules: Linter.RulesRecord; + }; + flat: { + recommended: ReactHooksFlatConfig; + "recommended-latest": ReactHooksFlatConfig; + }; + }; +}; + +export { plugin as default }; diff --git a/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.development.js b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.development.js new file mode 100644 index 0000000000000000000000000000000000000000..7b02d8e88471334ee23ec70e53b84f79429e1bbe --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.development.js @@ -0,0 +1,55466 @@ +/** + * @license React + * eslint-plugin-react-hooks.development.js + * + * 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. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +var core$1 = require('@babel/core'); +var BabelParser = require('@babel/parser'); +var v4 = require('zod/v4'); +var v4$1 = require('zod-validation-error/v4'); +var crypto = require('crypto'); +var HermesParser = require('hermes-parser'); +var util = require('util'); + +const SETTINGS_KEY = 'react-hooks'; +const SETTINGS_ADDITIONAL_EFFECT_HOOKS_KEY = 'additionalEffectHooks'; +function getAdditionalEffectHooksFromSettings(settings) { + var _a; + const additionalHooks = (_a = settings[SETTINGS_KEY]) === null || _a === void 0 ? void 0 : _a[SETTINGS_ADDITIONAL_EFFECT_HOOKS_KEY]; + if (additionalHooks != null && typeof additionalHooks === 'string') { + return new RegExp(additionalHooks); + } + return undefined; +} + +const rule$1 = { + meta: { + type: 'suggestion', + docs: { + description: 'verifies the list of dependencies for Hooks like useEffect and similar', + recommended: true, + url: 'https://github.com/facebook/react/issues/14920', + }, + fixable: 'code', + hasSuggestions: true, + schema: [ + { + type: 'object', + additionalProperties: false, + enableDangerousAutofixThisMayCauseInfiniteLoops: false, + properties: { + additionalHooks: { + type: 'string', + }, + enableDangerousAutofixThisMayCauseInfiniteLoops: { + type: 'boolean', + }, + experimental_autoDependenciesHooks: { + type: 'array', + items: { + type: 'string', + }, + }, + requireExplicitEffectDeps: { + type: 'boolean', + }, + }, + }, + ], + }, + create(context) { + const rawOptions = context.options && context.options[0]; + const settings = context.settings || {}; + const additionalHooks = rawOptions && rawOptions.additionalHooks + ? new RegExp(rawOptions.additionalHooks) + : getAdditionalEffectHooksFromSettings(settings); + const enableDangerousAutofixThisMayCauseInfiniteLoops = (rawOptions && + rawOptions.enableDangerousAutofixThisMayCauseInfiniteLoops) || + false; + const experimental_autoDependenciesHooks = rawOptions && Array.isArray(rawOptions.experimental_autoDependenciesHooks) + ? rawOptions.experimental_autoDependenciesHooks + : []; + const requireExplicitEffectDeps = (rawOptions && rawOptions.requireExplicitEffectDeps) || false; + const options = { + additionalHooks, + experimental_autoDependenciesHooks, + enableDangerousAutofixThisMayCauseInfiniteLoops, + requireExplicitEffectDeps, + }; + function reportProblem(problem) { + if (enableDangerousAutofixThisMayCauseInfiniteLoops) { + if (Array.isArray(problem.suggest) && + problem.suggest.length > 0 && + problem.suggest[0]) { + problem.fix = problem.suggest[0].fix; + } + } + context.report(problem); + } + const getSourceCode = typeof context.getSourceCode === 'function' + ? () => { + return context.getSourceCode(); + } + : () => { + return context.sourceCode; + }; + const getScope = typeof context.getScope === 'function' + ? () => { + return context.getScope(); + } + : (node) => { + return context.sourceCode.getScope(node); + }; + const scopeManager = getSourceCode().scopeManager; + const setStateCallSites = new WeakMap(); + const stateVariables = new WeakSet(); + const stableKnownValueCache = new WeakMap(); + const functionWithoutCapturedValueCache = new WeakMap(); + const useEffectEventVariables = new WeakSet(); + function memoizeWithWeakMap(fn, map) { + return function (arg) { + if (map.has(arg)) { + return map.get(arg); + } + const result = fn(arg); + map.set(arg, result); + return result; + }; + } + function visitFunctionWithDependencies(node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook) { + if (isEffect && node.async) { + reportProblem({ + node: node, + message: `Effect callbacks are synchronous to prevent race conditions. ` + + `Put the async function inside:\n\n` + + 'useEffect(() => {\n' + + ' async function fetchData() {\n' + + ' // You can await here\n' + + ' const response = await MyAPI.getData(someId);\n' + + ' // ...\n' + + ' }\n' + + ' fetchData();\n' + + `}, [someId]); // Or [] if effect doesn't need props or state\n\n` + + 'Learn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching', + }); + } + const scope = scopeManager.acquire(node); + if (!scope) { + throw new Error('Unable to acquire scope for the current node. This is a bug in eslint-plugin-react-hooks, please file an issue.'); + } + const pureScopes = new Set(); + let componentScope = null; + { + let currentScope = scope.upper; + while (currentScope) { + pureScopes.add(currentScope); + if (currentScope.type === 'function' || + currentScope.type === 'hook' || + currentScope.type === 'component') { + break; + } + currentScope = currentScope.upper; + } + if (!currentScope) { + return; + } + componentScope = currentScope; + } + const isArray = Array.isArray; + function isStableKnownHookValue(resolved) { + if (!isArray(resolved.defs)) { + return false; + } + const def = resolved.defs[0]; + if (def == null) { + return false; + } + const defNode = def.node; + if (defNode.type !== 'VariableDeclarator') { + return false; + } + let init = defNode.init; + if (init == null) { + return false; + } + while (init.type === 'TSAsExpression' || init.type === 'AsExpression') { + init = init.expression; + } + let declaration = defNode.parent; + if (declaration == null && componentScope != null) { + fastFindReferenceWithParent(componentScope.block, def.node.id); + declaration = def.node.parent; + if (declaration == null) { + return false; + } + } + if (declaration != null && + 'kind' in declaration && + declaration.kind === 'const' && + init.type === 'Literal' && + (typeof init.value === 'string' || + typeof init.value === 'number' || + init.value === null)) { + return true; + } + if (init.type !== 'CallExpression') { + return false; + } + let callee = init.callee; + if (callee.type === 'MemberExpression' && + 'name' in callee.object && + callee.object.name === 'React' && + callee.property != null && + !callee.computed) { + callee = callee.property; + } + if (callee.type !== 'Identifier') { + return false; + } + const definitionNode = def.node; + const id = definitionNode.id; + const { name } = callee; + if (name === 'useRef' && id.type === 'Identifier') { + return true; + } + else if (isUseEffectEventIdentifier$1(callee) && + id.type === 'Identifier') { + for (const ref of resolved.references) { + if (ref !== id) { + useEffectEventVariables.add(ref.identifier); + } + } + return true; + } + else if (name === 'useState' || + name === 'useReducer' || + name === 'useActionState') { + if (id.type === 'ArrayPattern' && + id.elements.length === 2 && + isArray(resolved.identifiers)) { + if (id.elements[1] === resolved.identifiers[0]) { + if (name === 'useState') { + const references = resolved.references; + let writeCount = 0; + for (const reference of references) { + if (reference.isWrite()) { + writeCount++; + } + if (writeCount > 1) { + return false; + } + setStateCallSites.set(reference.identifier, id.elements[0]); + } + } + return true; + } + else if (id.elements[0] === resolved.identifiers[0]) { + if (name === 'useState') { + const references = resolved.references; + for (const reference of references) { + stateVariables.add(reference.identifier); + } + } + return false; + } + } + } + else if (name === 'useTransition') { + if (id.type === 'ArrayPattern' && + id.elements.length === 2 && + Array.isArray(resolved.identifiers)) { + if (id.elements[1] === resolved.identifiers[0]) { + return true; + } + } + } + return false; + } + function isFunctionWithoutCapturedValues(resolved) { + if (!isArray(resolved.defs)) { + return false; + } + const def = resolved.defs[0]; + if (def == null) { + return false; + } + if (def.node == null || def.node.id == null) { + return false; + } + const fnNode = def.node; + const childScopes = (componentScope === null || componentScope === void 0 ? void 0 : componentScope.childScopes) || []; + let fnScope = null; + for (const childScope of childScopes) { + const childScopeBlock = childScope.block; + if ((fnNode.type === 'FunctionDeclaration' && + childScopeBlock === fnNode) || + (fnNode.type === 'VariableDeclarator' && + childScopeBlock.parent === fnNode)) { + fnScope = childScope; + break; + } + } + if (fnScope == null) { + return false; + } + for (const ref of fnScope.through) { + if (ref.resolved == null) { + continue; + } + if (pureScopes.has(ref.resolved.scope) && + !memoizedIsStableKnownHookValue(ref.resolved)) { + return false; + } + } + return true; + } + const memoizedIsStableKnownHookValue = memoizeWithWeakMap(isStableKnownHookValue, stableKnownValueCache); + const memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache); + const currentRefsInEffectCleanup = new Map(); + function isInsideEffectCleanup(reference) { + let curScope = reference.from; + let isInReturnedFunction = false; + while (curScope != null && curScope.block !== node) { + if (curScope.type === 'function') { + isInReturnedFunction = + curScope.block.parent != null && + curScope.block.parent.type === 'ReturnStatement'; + } + curScope = curScope.upper; + } + return isInReturnedFunction; + } + const dependencies = new Map(); + const optionalChains = new Map(); + gatherDependenciesRecursively(scope); + function gatherDependenciesRecursively(currentScope) { + var _a, _b, _c, _d, _e, _f; + for (const reference of currentScope.references) { + if (!reference.resolved) { + continue; + } + if (!pureScopes.has(reference.resolved.scope)) { + continue; + } + const referenceNode = fastFindReferenceWithParent(node, reference.identifier); + if (referenceNode == null) { + continue; + } + const dependencyNode = getDependency(referenceNode); + const dependency = analyzePropertyChain(dependencyNode, optionalChains); + if (isEffect && + dependencyNode.type === 'Identifier' && + (((_a = dependencyNode.parent) === null || _a === void 0 ? void 0 : _a.type) === 'MemberExpression' || + ((_b = dependencyNode.parent) === null || _b === void 0 ? void 0 : _b.type) === 'OptionalMemberExpression') && + !dependencyNode.parent.computed && + dependencyNode.parent.property.type === 'Identifier' && + dependencyNode.parent.property.name === 'current' && + isInsideEffectCleanup(reference)) { + currentRefsInEffectCleanup.set(dependency, { + reference, + dependencyNode, + }); + } + if (((_c = dependencyNode.parent) === null || _c === void 0 ? void 0 : _c.type) === 'TSTypeQuery' || + ((_d = dependencyNode.parent) === null || _d === void 0 ? void 0 : _d.type) === 'TSTypeReference') { + continue; + } + const def = reference.resolved.defs[0]; + if (def == null) { + continue; + } + if (def.node != null && def.node.init === node.parent) { + continue; + } + if (def.type === 'TypeParameter' || + ((_e = dependencyNode.parent) === null || _e === void 0 ? void 0 : _e.type) === 'GenericTypeAnnotation') { + continue; + } + if (!dependencies.has(dependency)) { + const resolved = reference.resolved; + const isStable = memoizedIsStableKnownHookValue(resolved) || + memoizedIsFunctionWithoutCapturedValues(resolved); + dependencies.set(dependency, { + isStable, + references: [reference], + }); + } + else { + (_f = dependencies.get(dependency)) === null || _f === void 0 ? void 0 : _f.references.push(reference); + } + } + for (const childScope of currentScope.childScopes) { + gatherDependenciesRecursively(childScope); + } + } + currentRefsInEffectCleanup.forEach(({ reference, dependencyNode }, dependency) => { + var _a, _b; + const references = ((_a = reference.resolved) === null || _a === void 0 ? void 0 : _a.references) || []; + let foundCurrentAssignment = false; + for (const ref of references) { + const { identifier } = ref; + const { parent } = identifier; + if (parent != null && + parent.type === 'MemberExpression' && + !parent.computed && + parent.property.type === 'Identifier' && + parent.property.name === 'current' && + ((_b = parent.parent) === null || _b === void 0 ? void 0 : _b.type) === 'AssignmentExpression' && + parent.parent.left === parent) { + foundCurrentAssignment = true; + break; + } + } + if (foundCurrentAssignment) { + return; + } + reportProblem({ + node: dependencyNode.parent.property, + message: `The ref value '${dependency}.current' will likely have ` + + `changed by the time this effect cleanup function runs. If ` + + `this ref points to a node rendered by React, copy ` + + `'${dependency}.current' to a variable inside the effect, and ` + + `use that variable in the cleanup function.`, + }); + }); + const staleAssignments = new Set(); + function reportStaleAssignment(writeExpr, key) { + if (staleAssignments.has(key)) { + return; + } + staleAssignments.add(key); + reportProblem({ + node: writeExpr, + message: `Assignments to the '${key}' variable from inside React Hook ` + + `${getSourceCode().getText(reactiveHook)} will be lost after each ` + + `render. To preserve the value over time, store it in a useRef ` + + `Hook and keep the mutable value in the '.current' property. ` + + `Otherwise, you can move this variable directly inside ` + + `${getSourceCode().getText(reactiveHook)}.`, + }); + } + const stableDependencies = new Set(); + dependencies.forEach(({ isStable, references }, key) => { + if (isStable) { + stableDependencies.add(key); + } + references.forEach(reference => { + if (reference.writeExpr) { + reportStaleAssignment(reference.writeExpr, key); + } + }); + }); + if (staleAssignments.size > 0) { + return; + } + if (!declaredDependenciesNode) { + if (isAutoDepsHook) { + return; + } + let setStateInsideEffectWithoutDeps = null; + dependencies.forEach(({ references }, key) => { + if (setStateInsideEffectWithoutDeps) { + return; + } + references.forEach(reference => { + if (setStateInsideEffectWithoutDeps) { + return; + } + const id = reference.identifier; + const isSetState = setStateCallSites.has(id); + if (!isSetState) { + return; + } + let fnScope = reference.from; + while (fnScope != null && fnScope.type !== 'function') { + fnScope = fnScope.upper; + } + const isDirectlyInsideEffect = (fnScope === null || fnScope === void 0 ? void 0 : fnScope.block) === node; + if (isDirectlyInsideEffect) { + setStateInsideEffectWithoutDeps = key; + } + }); + }); + if (setStateInsideEffectWithoutDeps) { + const { suggestedDependencies } = collectRecommendations({ + dependencies, + declaredDependencies: [], + stableDependencies, + externalDependencies: new Set(), + isEffect: true, + }); + reportProblem({ + node: reactiveHook, + message: `React Hook ${reactiveHookName} contains a call to '${setStateInsideEffectWithoutDeps}'. ` + + `Without a list of dependencies, this can lead to an infinite chain of updates. ` + + `To fix this, pass [` + + suggestedDependencies.join(', ') + + `] as a second argument to the ${reactiveHookName} Hook.`, + suggest: [ + { + desc: `Add dependencies array: [${suggestedDependencies.join(', ')}]`, + fix(fixer) { + return fixer.insertTextAfter(node, `, [${suggestedDependencies.join(', ')}]`); + }, + }, + ], + }); + } + return; + } + if (isAutoDepsHook && + declaredDependenciesNode.type === 'Literal' && + declaredDependenciesNode.value === null) { + return; + } + const declaredDependencies = []; + const externalDependencies = new Set(); + const isArrayExpression = declaredDependenciesNode.type === 'ArrayExpression'; + const isTSAsArrayExpression = declaredDependenciesNode.type === 'TSAsExpression' && + declaredDependenciesNode.expression.type === 'ArrayExpression'; + if (!isArrayExpression && !isTSAsArrayExpression) { + reportProblem({ + node: declaredDependenciesNode, + message: `React Hook ${getSourceCode().getText(reactiveHook)} was passed a ` + + 'dependency list that is not an array literal. This means we ' + + "can't statically verify whether you've passed the correct " + + 'dependencies.', + }); + } + else { + const arrayExpression = isTSAsArrayExpression + ? declaredDependenciesNode.expression + : declaredDependenciesNode; + arrayExpression.elements.forEach(declaredDependencyNode => { + if (declaredDependencyNode === null) { + return; + } + if (declaredDependencyNode.type === 'SpreadElement') { + reportProblem({ + node: declaredDependencyNode, + message: `React Hook ${getSourceCode().getText(reactiveHook)} has a spread ` + + "element in its dependency array. This means we can't " + + "statically verify whether you've passed the " + + 'correct dependencies.', + }); + return; + } + if (useEffectEventVariables.has(declaredDependencyNode)) { + reportProblem({ + node: declaredDependencyNode, + message: 'Functions returned from `useEffectEvent` must not be included in the dependency array. ' + + `Remove \`${getSourceCode().getText(declaredDependencyNode)}\` from the list.`, + suggest: [ + { + desc: `Remove the dependency \`${getSourceCode().getText(declaredDependencyNode)}\``, + fix(fixer) { + return fixer.removeRange(declaredDependencyNode.range); + }, + }, + ], + }); + } + let declaredDependency; + try { + declaredDependency = analyzePropertyChain(declaredDependencyNode, null); + } + catch (error) { + if (error instanceof Error && + /Unsupported node type/.test(error.message)) { + if (declaredDependencyNode.type === 'Literal') { + if (declaredDependencyNode.value && + dependencies.has(declaredDependencyNode.value)) { + reportProblem({ + node: declaredDependencyNode, + message: `The ${declaredDependencyNode.raw} literal is not a valid dependency ` + + `because it never changes. ` + + `Did you mean to include ${declaredDependencyNode.value} in the array instead?`, + }); + } + else { + reportProblem({ + node: declaredDependencyNode, + message: `The ${declaredDependencyNode.raw} literal is not a valid dependency ` + + 'because it never changes. You can safely remove it.', + }); + } + } + else { + reportProblem({ + node: declaredDependencyNode, + message: `React Hook ${getSourceCode().getText(reactiveHook)} has a ` + + `complex expression in the dependency array. ` + + 'Extract it to a separate variable so it can be statically checked.', + }); + } + return; + } + else { + throw error; + } + } + let maybeID = declaredDependencyNode; + while (maybeID.type === 'MemberExpression' || + maybeID.type === 'OptionalMemberExpression' || + maybeID.type === 'ChainExpression') { + maybeID = maybeID.object || maybeID.expression.object; + } + const isDeclaredInComponent = !componentScope.through.some(ref => ref.identifier === maybeID); + declaredDependencies.push({ + key: declaredDependency, + node: declaredDependencyNode, + }); + if (!isDeclaredInComponent) { + externalDependencies.add(declaredDependency); + } + }); + } + const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies, } = collectRecommendations({ + dependencies, + declaredDependencies, + stableDependencies, + externalDependencies, + isEffect, + }); + let suggestedDeps = suggestedDependencies; + const problemCount = duplicateDependencies.size + + missingDependencies.size + + unnecessaryDependencies.size; + if (problemCount === 0) { + const constructions = scanForConstructions({ + declaredDependencies, + declaredDependenciesNode, + componentScope, + scope, + }); + constructions.forEach(({ construction, isUsedOutsideOfHook, depType }) => { + var _a; + const wrapperHook = depType === 'function' ? 'useCallback' : 'useMemo'; + const constructionType = depType === 'function' ? 'definition' : 'initialization'; + const defaultAdvice = `wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`; + const advice = isUsedOutsideOfHook + ? `To fix this, ${defaultAdvice}` + : `Move it inside the ${reactiveHookName} callback. Alternatively, ${defaultAdvice}`; + const causation = depType === 'conditional' || depType === 'logical expression' + ? 'could make' + : 'makes'; + const message = `The '${construction.name.name}' ${depType} ${causation} the dependencies of ` + + `${reactiveHookName} Hook (at line ${(_a = declaredDependenciesNode.loc) === null || _a === void 0 ? void 0 : _a.start.line}) ` + + `change on every render. ${advice}`; + let suggest; + if (isUsedOutsideOfHook && + construction.type === 'Variable' && + depType === 'function') { + suggest = [ + { + desc: `Wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`, + fix(fixer) { + const [before, after] = wrapperHook === 'useMemo' + ? [`useMemo(() => { return `, '; })'] + : ['useCallback(', ')']; + return [ + fixer.insertTextBefore(construction.node.init, before), + fixer.insertTextAfter(construction.node.init, after), + ]; + }, + }, + ]; + } + reportProblem({ + node: construction.node, + message, + suggest, + }); + }); + return; + } + if (!isEffect && missingDependencies.size > 0) { + suggestedDeps = collectRecommendations({ + dependencies, + declaredDependencies: [], + stableDependencies, + externalDependencies, + isEffect, + }).suggestedDependencies; + } + function areDeclaredDepsAlphabetized() { + if (declaredDependencies.length === 0) { + return true; + } + const declaredDepKeys = declaredDependencies.map(dep => dep.key); + const sortedDeclaredDepKeys = declaredDepKeys.slice().sort(); + return declaredDepKeys.join(',') === sortedDeclaredDepKeys.join(','); + } + if (areDeclaredDepsAlphabetized()) { + suggestedDeps.sort(); + } + function formatDependency(path) { + const members = path.split('.'); + let finalPath = ''; + for (let i = 0; i < members.length; i++) { + if (i !== 0) { + const pathSoFar = members.slice(0, i + 1).join('.'); + const isOptional = optionalChains.get(pathSoFar) === true; + finalPath += isOptional ? '?.' : '.'; + } + finalPath += members[i]; + } + return finalPath; + } + function getWarningMessage(deps, singlePrefix, label, fixVerb) { + if (deps.size === 0) { + return null; + } + return ((deps.size > 1 ? '' : singlePrefix + ' ') + + label + + ' ' + + (deps.size > 1 ? 'dependencies' : 'dependency') + + ': ' + + joinEnglish(Array.from(deps) + .sort() + .map(name => "'" + formatDependency(name) + "'")) + + `. Either ${fixVerb} ${deps.size > 1 ? 'them' : 'it'} or remove the dependency array.`); + } + let extraWarning = ''; + if (unnecessaryDependencies.size > 0) { + let badRef = null; + Array.from(unnecessaryDependencies.keys()).forEach(key => { + if (badRef !== null) { + return; + } + if (key.endsWith('.current')) { + badRef = key; + } + }); + if (badRef !== null) { + extraWarning = + ` Mutable values like '${badRef}' aren't valid dependencies ` + + "because mutating them doesn't re-render the component."; + } + else if (externalDependencies.size > 0) { + const dep = Array.from(externalDependencies)[0]; + if (!scope.set.has(dep)) { + extraWarning = + ` Outer scope values like '${dep}' aren't valid dependencies ` + + `because mutating them doesn't re-render the component.`; + } + } + } + if (!extraWarning && missingDependencies.has('props')) { + const propDep = dependencies.get('props'); + if (propDep == null) { + return; + } + const refs = propDep.references; + if (!Array.isArray(refs)) { + return; + } + let isPropsOnlyUsedInMembers = true; + for (const ref of refs) { + const id = fastFindReferenceWithParent(componentScope.block, ref.identifier); + if (!id) { + isPropsOnlyUsedInMembers = false; + break; + } + const parent = id.parent; + if (parent == null) { + isPropsOnlyUsedInMembers = false; + break; + } + if (parent.type !== 'MemberExpression' && + parent.type !== 'OptionalMemberExpression') { + isPropsOnlyUsedInMembers = false; + break; + } + } + if (isPropsOnlyUsedInMembers) { + extraWarning = + ` However, 'props' will change when *any* prop changes, so the ` + + `preferred fix is to destructure the 'props' object outside of ` + + `the ${reactiveHookName} call and refer to those specific props ` + + `inside ${getSourceCode().getText(reactiveHook)}.`; + } + } + if (!extraWarning && missingDependencies.size > 0) { + let missingCallbackDep = null; + missingDependencies.forEach(missingDep => { + var _a; + if (missingCallbackDep) { + return; + } + const topScopeRef = componentScope.set.get(missingDep); + const usedDep = dependencies.get(missingDep); + if (!(usedDep === null || usedDep === void 0 ? void 0 : usedDep.references) || + ((_a = usedDep === null || usedDep === void 0 ? void 0 : usedDep.references[0]) === null || _a === void 0 ? void 0 : _a.resolved) !== topScopeRef) { + return; + } + const def = topScopeRef === null || topScopeRef === void 0 ? void 0 : topScopeRef.defs[0]; + if (def == null || def.name == null || def.type !== 'Parameter') { + return; + } + let isFunctionCall = false; + let id; + for (const reference of usedDep.references) { + id = reference.identifier; + if (id != null && + id.parent != null && + (id.parent.type === 'CallExpression' || + id.parent.type === 'OptionalCallExpression') && + id.parent.callee === id) { + isFunctionCall = true; + break; + } + } + if (!isFunctionCall) { + return; + } + missingCallbackDep = missingDep; + }); + if (missingCallbackDep !== null) { + extraWarning = + ` If '${missingCallbackDep}' changes too often, ` + + `find the parent component that defines it ` + + `and wrap that definition in useCallback.`; + } + } + if (!extraWarning && missingDependencies.size > 0) { + let setStateRecommendation = null; + for (const missingDep of missingDependencies) { + if (setStateRecommendation !== null) { + break; + } + const usedDep = dependencies.get(missingDep); + const references = usedDep.references; + let id; + let maybeCall; + for (const reference of references) { + id = reference.identifier; + maybeCall = id.parent; + while (maybeCall != null && maybeCall !== componentScope.block) { + if (maybeCall.type === 'CallExpression') { + const correspondingStateVariable = setStateCallSites.get(maybeCall.callee); + if (correspondingStateVariable != null) { + if ('name' in correspondingStateVariable && + correspondingStateVariable.name === missingDep) { + setStateRecommendation = { + missingDep, + setter: 'name' in maybeCall.callee ? maybeCall.callee.name : '', + form: 'updater', + }; + } + else if (stateVariables.has(id)) { + setStateRecommendation = { + missingDep, + setter: 'name' in maybeCall.callee ? maybeCall.callee.name : '', + form: 'reducer', + }; + } + else { + const resolved = reference.resolved; + if (resolved != null) { + const def = resolved.defs[0]; + if (def != null && def.type === 'Parameter') { + setStateRecommendation = { + missingDep, + setter: 'name' in maybeCall.callee + ? maybeCall.callee.name + : '', + form: 'inlineReducer', + }; + } + } + } + break; + } + } + maybeCall = maybeCall.parent; + } + if (setStateRecommendation !== null) { + break; + } + } + } + if (setStateRecommendation !== null) { + switch (setStateRecommendation.form) { + case 'reducer': + extraWarning = + ` You can also replace multiple useState variables with useReducer ` + + `if '${setStateRecommendation.setter}' needs the ` + + `current value of '${setStateRecommendation.missingDep}'.`; + break; + case 'inlineReducer': + extraWarning = + ` If '${setStateRecommendation.setter}' needs the ` + + `current value of '${setStateRecommendation.missingDep}', ` + + `you can also switch to useReducer instead of useState and ` + + `read '${setStateRecommendation.missingDep}' in the reducer.`; + break; + case 'updater': + extraWarning = + ` You can also do a functional update '${setStateRecommendation.setter}(${setStateRecommendation.missingDep.slice(0, 1)} => ...)' if you only need '${setStateRecommendation.missingDep}'` + ` in the '${setStateRecommendation.setter}' call.`; + break; + default: + throw new Error('Unknown case.'); + } + } + } + reportProblem({ + node: declaredDependenciesNode, + message: `React Hook ${getSourceCode().getText(reactiveHook)} has ` + + (getWarningMessage(missingDependencies, 'a', 'missing', 'include') || + getWarningMessage(unnecessaryDependencies, 'an', 'unnecessary', 'exclude') || + getWarningMessage(duplicateDependencies, 'a', 'duplicate', 'omit')) + + extraWarning, + suggest: [ + { + desc: `Update the dependencies array to be: [${suggestedDeps + .map(formatDependency) + .join(', ')}]`, + fix(fixer) { + return fixer.replaceText(declaredDependenciesNode, `[${suggestedDeps.map(formatDependency).join(', ')}]`); + }, + }, + ], + }); + } + function visitCallExpression(node) { + const callbackIndex = getReactiveHookCallbackIndex(node.callee, options); + if (callbackIndex === -1) { + return; + } + let callback = node.arguments[callbackIndex]; + const reactiveHook = node.callee; + const nodeWithoutNamespace = getNodeWithoutReactNamespace$1(reactiveHook); + const reactiveHookName = 'name' in nodeWithoutNamespace ? nodeWithoutNamespace.name : ''; + const maybeNode = node.arguments[callbackIndex + 1]; + const declaredDependenciesNode = maybeNode && + !(maybeNode.type === 'Identifier' && maybeNode.name === 'undefined') + ? maybeNode + : undefined; + const isEffect = /Effect($|[^a-z])/g.test(reactiveHookName); + if (!callback) { + reportProblem({ + node: reactiveHook, + message: `React Hook ${reactiveHookName} requires an effect callback. ` + + `Did you forget to pass a callback to the hook?`, + }); + return; + } + if (!maybeNode && isEffect && options.requireExplicitEffectDeps) { + reportProblem({ + node: reactiveHook, + message: `React Hook ${reactiveHookName} always requires dependencies. ` + + `Please add a dependency array or an explicit \`undefined\``, + }); + } + const isAutoDepsHook = options.experimental_autoDependenciesHooks.includes(reactiveHookName); + if ((!declaredDependenciesNode || + (isAutoDepsHook && + declaredDependenciesNode.type === 'Literal' && + declaredDependenciesNode.value === null)) && + !isEffect) { + if (reactiveHookName === 'useMemo' || + reactiveHookName === 'useCallback') { + reportProblem({ + node: reactiveHook, + message: `React Hook ${reactiveHookName} does nothing when called with ` + + `only one argument. Did you forget to pass an array of ` + + `dependencies?`, + }); + } + return; + } + while (callback.type === 'TSAsExpression' || + callback.type === 'AsExpression') { + callback = callback.expression; + } + switch (callback.type) { + case 'FunctionExpression': + case 'ArrowFunctionExpression': + visitFunctionWithDependencies(callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook); + return; + case 'Identifier': + if (!declaredDependenciesNode || + (isAutoDepsHook && + declaredDependenciesNode.type === 'Literal' && + declaredDependenciesNode.value === null)) { + return; + } + if ('elements' in declaredDependenciesNode && + declaredDependenciesNode.elements && + declaredDependenciesNode.elements.some(el => el && el.type === 'Identifier' && el.name === callback.name)) { + return; + } + const variable = getScope(callback).set.get(callback.name); + if (variable == null || variable.defs == null) { + return; + } + const def = variable.defs[0]; + if (!def || !def.node) { + break; + } + if (def.type === 'Parameter') { + reportProblem({ + node: reactiveHook, + message: getUnknownDependenciesMessage(reactiveHookName), + }); + return; + } + if (def.type !== 'Variable' && def.type !== 'FunctionName') { + break; + } + switch (def.node.type) { + case 'FunctionDeclaration': + visitFunctionWithDependencies(def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook); + return; + case 'VariableDeclarator': + const init = def.node.init; + if (!init) { + break; + } + switch (init.type) { + case 'ArrowFunctionExpression': + case 'FunctionExpression': + visitFunctionWithDependencies(init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook); + return; + } + break; + } + break; + default: + reportProblem({ + node: reactiveHook, + message: getUnknownDependenciesMessage(reactiveHookName), + }); + return; + } + reportProblem({ + node: reactiveHook, + message: `React Hook ${reactiveHookName} has a missing dependency: '${callback.name}'. ` + + `Either include it or remove the dependency array.`, + suggest: [ + { + desc: `Update the dependencies array to be: [${callback.name}]`, + fix(fixer) { + return fixer.replaceText(declaredDependenciesNode, `[${callback.name}]`); + }, + }, + ], + }); + } + return { + CallExpression: visitCallExpression, + }; + }, +}; +function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect, }) { + const depTree = createDepTree(); + function createDepTree() { + return { + isUsed: false, + isSatisfiedRecursively: false, + isSubtreeUsed: false, + children: new Map(), + }; + } + dependencies.forEach((_, key) => { + const node = getOrCreateNodeByPath(depTree, key); + node.isUsed = true; + markAllParentsByPath(depTree, key, parent => { + parent.isSubtreeUsed = true; + }); + }); + declaredDependencies.forEach(({ key }) => { + const node = getOrCreateNodeByPath(depTree, key); + node.isSatisfiedRecursively = true; + }); + stableDependencies.forEach(key => { + const node = getOrCreateNodeByPath(depTree, key); + node.isSatisfiedRecursively = true; + }); + function getOrCreateNodeByPath(rootNode, path) { + const keys = path.split('.'); + let node = rootNode; + for (const key of keys) { + let child = node.children.get(key); + if (!child) { + child = createDepTree(); + node.children.set(key, child); + } + node = child; + } + return node; + } + function markAllParentsByPath(rootNode, path, fn) { + const keys = path.split('.'); + let node = rootNode; + for (const key of keys) { + const child = node.children.get(key); + if (!child) { + return; + } + fn(child); + node = child; + } + } + const missingDependencies = new Set(); + const satisfyingDependencies = new Set(); + scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, key => key); + function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) { + node.children.forEach((child, key) => { + const path = keyToPath(key); + if (child.isSatisfiedRecursively) { + if (child.isSubtreeUsed) { + satisfyingPaths.add(path); + } + return; + } + if (child.isUsed) { + missingPaths.add(path); + return; + } + scanTreeRecursively(child, missingPaths, satisfyingPaths, childKey => path + '.' + childKey); + }); + } + const suggestedDependencies = []; + const unnecessaryDependencies = new Set(); + const duplicateDependencies = new Set(); + declaredDependencies.forEach(({ key }) => { + if (satisfyingDependencies.has(key)) { + if (suggestedDependencies.indexOf(key) === -1) { + suggestedDependencies.push(key); + } + else { + duplicateDependencies.add(key); + } + } + else { + if (isEffect && + !key.endsWith('.current') && + !externalDependencies.has(key)) { + if (suggestedDependencies.indexOf(key) === -1) { + suggestedDependencies.push(key); + } + } + else { + unnecessaryDependencies.add(key); + } + } + }); + missingDependencies.forEach(key => { + suggestedDependencies.push(key); + }); + return { + suggestedDependencies, + unnecessaryDependencies, + duplicateDependencies, + missingDependencies, + }; +} +function getConstructionExpressionType(node) { + switch (node.type) { + case 'ObjectExpression': + return 'object'; + case 'ArrayExpression': + return 'array'; + case 'ArrowFunctionExpression': + case 'FunctionExpression': + return 'function'; + case 'ClassExpression': + return 'class'; + case 'ConditionalExpression': + if (getConstructionExpressionType(node.consequent) != null || + getConstructionExpressionType(node.alternate) != null) { + return 'conditional'; + } + return null; + case 'LogicalExpression': + if (getConstructionExpressionType(node.left) != null || + getConstructionExpressionType(node.right) != null) { + return 'logical expression'; + } + return null; + case 'JSXFragment': + return 'JSX fragment'; + case 'JSXElement': + return 'JSX element'; + case 'AssignmentExpression': + if (getConstructionExpressionType(node.right) != null) { + return 'assignment expression'; + } + return null; + case 'NewExpression': + return 'object construction'; + case 'Literal': + if (node.value instanceof RegExp) { + return 'regular expression'; + } + return null; + case 'TypeCastExpression': + case 'AsExpression': + case 'TSAsExpression': + return getConstructionExpressionType(node.expression); + } + return null; +} +function scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope, }) { + const constructions = declaredDependencies + .map(({ key }) => { + const ref = componentScope.variables.find(v => v.name === key); + if (ref == null) { + return null; + } + const node = ref.defs[0]; + if (node == null) { + return null; + } + if (node.type === 'Variable' && + node.node.type === 'VariableDeclarator' && + node.node.id.type === 'Identifier' && + node.node.init != null) { + const constantExpressionType = getConstructionExpressionType(node.node.init); + if (constantExpressionType) { + return [ref, constantExpressionType]; + } + } + if (node.type === 'FunctionName' && + node.node.type === 'FunctionDeclaration') { + return [ref, 'function']; + } + if (node.type === 'ClassName' && node.node.type === 'ClassDeclaration') { + return [ref, 'class']; + } + return null; + }) + .filter(Boolean); + function isUsedOutsideOfHook(ref) { + let foundWriteExpr = false; + for (const reference of ref.references) { + if (reference.writeExpr) { + if (foundWriteExpr) { + return true; + } + else { + foundWriteExpr = true; + continue; + } + } + let currentScope = reference.from; + while (currentScope !== scope && currentScope != null) { + currentScope = currentScope.upper; + } + if (currentScope !== scope) { + if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) { + return true; + } + } + } + return false; + } + return constructions.map(([ref, depType]) => ({ + construction: ref.defs[0], + depType, + isUsedOutsideOfHook: isUsedOutsideOfHook(ref), + })); +} +function getDependency(node) { + if (node.parent && + (node.parent.type === 'MemberExpression' || + node.parent.type === 'OptionalMemberExpression') && + node.parent.object === node && + 'name' in node.parent.property && + node.parent.property.name !== 'current' && + !node.parent.computed && + !(node.parent.parent != null && + (node.parent.parent.type === 'CallExpression' || + node.parent.parent.type === 'OptionalCallExpression') && + node.parent.parent.callee === node.parent)) { + return getDependency(node.parent); + } + else if (node.type === 'MemberExpression' && + node.parent && + node.parent.type === 'AssignmentExpression' && + node.parent.left === node) { + return node.object; + } + else { + return node; + } +} +function markNode(node, optionalChains, result) { + if (optionalChains) { + if ('optional' in node && node.optional) { + if (!optionalChains.has(result)) { + optionalChains.set(result, true); + } + } + else { + optionalChains.set(result, false); + } + } +} +function analyzePropertyChain(node, optionalChains) { + if (node.type === 'Identifier' || node.type === 'JSXIdentifier') { + const result = node.name; + if (optionalChains) { + optionalChains.set(result, false); + } + return result; + } + else if (node.type === 'MemberExpression' && !node.computed) { + const object = analyzePropertyChain(node.object, optionalChains); + const property = analyzePropertyChain(node.property, null); + const result = `${object}.${property}`; + markNode(node, optionalChains, result); + return result; + } + else if (node.type === 'OptionalMemberExpression' && !node.computed) { + const object = analyzePropertyChain(node.object, optionalChains); + const property = analyzePropertyChain(node.property, null); + const result = `${object}.${property}`; + markNode(node, optionalChains, result); + return result; + } + else if (node.type === 'ChainExpression' && + (!('computed' in node) || !node.computed)) { + const expression = node.expression; + if (expression.type === 'CallExpression') { + throw new Error(`Unsupported node type: ${expression.type}`); + } + const object = analyzePropertyChain(expression.object, optionalChains); + const property = analyzePropertyChain(expression.property, null); + const result = `${object}.${property}`; + markNode(expression, optionalChains, result); + return result; + } + else { + throw new Error(`Unsupported node type: ${node.type}`); + } +} +function getNodeWithoutReactNamespace$1(node) { + if (node.type === 'MemberExpression' && + node.object.type === 'Identifier' && + node.object.name === 'React' && + node.property.type === 'Identifier' && + !node.computed) { + return node.property; + } + return node; +} +function getReactiveHookCallbackIndex(calleeNode, options) { + const node = getNodeWithoutReactNamespace$1(calleeNode); + if (node.type !== 'Identifier') { + return -1; + } + switch (node.name) { + case 'useEffect': + case 'useLayoutEffect': + case 'useCallback': + case 'useMemo': + return 0; + case 'useImperativeHandle': + return 1; + default: + if (node === calleeNode && options && options.additionalHooks) { + let name; + try { + name = analyzePropertyChain(node, null); + } + catch (error) { + if (error instanceof Error && + /Unsupported node type/.test(error.message)) { + return 0; + } + else { + throw error; + } + } + return options.additionalHooks.test(name) ? 0 : -1; + } + else { + return -1; + } + } +} +function fastFindReferenceWithParent(start, target) { + const queue = [start]; + let item; + while (queue.length) { + item = queue.shift(); + if (isSameIdentifier(item, target)) { + return item; + } + if (!isAncestorNodeOf(item, target)) { + continue; + } + for (const [key, value] of Object.entries(item)) { + if (key === 'parent') { + continue; + } + if (isNodeLike(value)) { + value.parent = item; + queue.push(value); + } + else if (Array.isArray(value)) { + value.forEach(val => { + if (isNodeLike(val)) { + val.parent = item; + queue.push(val); + } + }); + } + } + } + return null; +} +function joinEnglish(arr) { + let s = ''; + for (let i = 0; i < arr.length; i++) { + s += arr[i]; + if (i === 0 && arr.length === 2) { + s += ' and '; + } + else if (i === arr.length - 2 && arr.length > 2) { + s += ', and '; + } + else if (i < arr.length - 1) { + s += ', '; + } + } + return s; +} +function isNodeLike(val) { + return (typeof val === 'object' && + val !== null && + !Array.isArray(val) && + 'type' in val && + typeof val.type === 'string'); +} +function isSameIdentifier(a, b) { + return ((a.type === 'Identifier' || a.type === 'JSXIdentifier') && + a.type === b.type && + a.name === b.name && + !!a.range && + !!b.range && + a.range[0] === b.range[0] && + a.range[1] === b.range[1]); +} +function isAncestorNodeOf(a, b) { + return (!!a.range && + !!b.range && + a.range[0] <= b.range[0] && + a.range[1] >= b.range[1]); +} +function isUseEffectEventIdentifier$1(node) { + return node.type === 'Identifier' && node.name === 'useEffectEvent'; +} +function getUnknownDependenciesMessage(reactiveHookName) { + return (`React Hook ${reactiveHookName} received a function whose dependencies ` + + `are unknown. Pass an inline function instead.`); +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var invariant_1; +var hasRequiredInvariant; + +function requireInvariant () { + if (hasRequiredInvariant) return invariant_1; + hasRequiredInvariant = 1; + + var invariant = function(condition, format, a, b, c, d, e, f) { + { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + invariant_1 = invariant; + return invariant_1; +} + +var invariantExports = requireInvariant(); +var invariant = /*@__PURE__*/getDefaultExportFromCjs(invariantExports); + +var lib$3 = {}; + +var isReactComponent = {}; + +var buildMatchMemberExpression = {}; + +var matchesPattern = {}; + +var generated$3 = {}; + +var shallowEqual = {}; + +var hasRequiredShallowEqual; + +function requireShallowEqual () { + if (hasRequiredShallowEqual) return shallowEqual; + hasRequiredShallowEqual = 1; + + Object.defineProperty(shallowEqual, "__esModule", { + value: true + }); + shallowEqual.default = shallowEqual$1; + function shallowEqual$1(actual, expected) { + const keys = Object.keys(expected); + for (const key of keys) { + if (actual[key] !== expected[key]) { + return false; + } + } + return true; + } + + + return shallowEqual; +} + +var deprecationWarning = {}; + +var hasRequiredDeprecationWarning; + +function requireDeprecationWarning () { + if (hasRequiredDeprecationWarning) return deprecationWarning; + hasRequiredDeprecationWarning = 1; + + Object.defineProperty(deprecationWarning, "__esModule", { + value: true + }); + deprecationWarning.default = deprecationWarning$1; + const warnings = new Set(); + function deprecationWarning$1(oldName, newName, prefix = "") { + if (warnings.has(oldName)) return; + warnings.add(oldName); + const { + internal, + trace + } = captureShortStackTrace(1, 2); + if (internal) { + return; + } + console.warn(`${prefix}\`${oldName}\` has been deprecated, please migrate to \`${newName}\`\n${trace}`); + } + function captureShortStackTrace(skip, length) { + const { + stackTraceLimit, + prepareStackTrace + } = Error; + let stackTrace; + Error.stackTraceLimit = 1 + skip + length; + Error.prepareStackTrace = function (err, stack) { + stackTrace = stack; + }; + Error.stackTraceLimit = stackTraceLimit; + Error.prepareStackTrace = prepareStackTrace; + if (!stackTrace) return { + internal: false, + trace: "" + }; + const shortStackTrace = stackTrace.slice(1 + skip, 1 + skip + length); + return { + internal: /[\\/]@babel[\\/]/.test(shortStackTrace[1].getFileName()), + trace: shortStackTrace.map(frame => ` at ${frame}`).join("\n") + }; + } + + + return deprecationWarning; +} + +var hasRequiredGenerated$3; + +function requireGenerated$3 () { + if (hasRequiredGenerated$3) return generated$3; + hasRequiredGenerated$3 = 1; + + Object.defineProperty(generated$3, "__esModule", { + value: true + }); + generated$3.isAccessor = isAccessor; + generated$3.isAnyTypeAnnotation = isAnyTypeAnnotation; + generated$3.isArgumentPlaceholder = isArgumentPlaceholder; + generated$3.isArrayExpression = isArrayExpression; + generated$3.isArrayPattern = isArrayPattern; + generated$3.isArrayTypeAnnotation = isArrayTypeAnnotation; + generated$3.isArrowFunctionExpression = isArrowFunctionExpression; + generated$3.isAssignmentExpression = isAssignmentExpression; + generated$3.isAssignmentPattern = isAssignmentPattern; + generated$3.isAwaitExpression = isAwaitExpression; + generated$3.isBigIntLiteral = isBigIntLiteral; + generated$3.isBinary = isBinary; + generated$3.isBinaryExpression = isBinaryExpression; + generated$3.isBindExpression = isBindExpression; + generated$3.isBlock = isBlock; + generated$3.isBlockParent = isBlockParent; + generated$3.isBlockStatement = isBlockStatement; + generated$3.isBooleanLiteral = isBooleanLiteral; + generated$3.isBooleanLiteralTypeAnnotation = isBooleanLiteralTypeAnnotation; + generated$3.isBooleanTypeAnnotation = isBooleanTypeAnnotation; + generated$3.isBreakStatement = isBreakStatement; + generated$3.isCallExpression = isCallExpression; + generated$3.isCatchClause = isCatchClause; + generated$3.isClass = isClass; + generated$3.isClassAccessorProperty = isClassAccessorProperty; + generated$3.isClassBody = isClassBody; + generated$3.isClassDeclaration = isClassDeclaration; + generated$3.isClassExpression = isClassExpression; + generated$3.isClassImplements = isClassImplements; + generated$3.isClassMethod = isClassMethod; + generated$3.isClassPrivateMethod = isClassPrivateMethod; + generated$3.isClassPrivateProperty = isClassPrivateProperty; + generated$3.isClassProperty = isClassProperty; + generated$3.isCompletionStatement = isCompletionStatement; + generated$3.isConditional = isConditional; + generated$3.isConditionalExpression = isConditionalExpression; + generated$3.isContinueStatement = isContinueStatement; + generated$3.isDebuggerStatement = isDebuggerStatement; + generated$3.isDecimalLiteral = isDecimalLiteral; + generated$3.isDeclaration = isDeclaration; + generated$3.isDeclareClass = isDeclareClass; + generated$3.isDeclareExportAllDeclaration = isDeclareExportAllDeclaration; + generated$3.isDeclareExportDeclaration = isDeclareExportDeclaration; + generated$3.isDeclareFunction = isDeclareFunction; + generated$3.isDeclareInterface = isDeclareInterface; + generated$3.isDeclareModule = isDeclareModule; + generated$3.isDeclareModuleExports = isDeclareModuleExports; + generated$3.isDeclareOpaqueType = isDeclareOpaqueType; + generated$3.isDeclareTypeAlias = isDeclareTypeAlias; + generated$3.isDeclareVariable = isDeclareVariable; + generated$3.isDeclaredPredicate = isDeclaredPredicate; + generated$3.isDecorator = isDecorator; + generated$3.isDirective = isDirective; + generated$3.isDirectiveLiteral = isDirectiveLiteral; + generated$3.isDoExpression = isDoExpression; + generated$3.isDoWhileStatement = isDoWhileStatement; + generated$3.isEmptyStatement = isEmptyStatement; + generated$3.isEmptyTypeAnnotation = isEmptyTypeAnnotation; + generated$3.isEnumBody = isEnumBody; + generated$3.isEnumBooleanBody = isEnumBooleanBody; + generated$3.isEnumBooleanMember = isEnumBooleanMember; + generated$3.isEnumDeclaration = isEnumDeclaration; + generated$3.isEnumDefaultedMember = isEnumDefaultedMember; + generated$3.isEnumMember = isEnumMember; + generated$3.isEnumNumberBody = isEnumNumberBody; + generated$3.isEnumNumberMember = isEnumNumberMember; + generated$3.isEnumStringBody = isEnumStringBody; + generated$3.isEnumStringMember = isEnumStringMember; + generated$3.isEnumSymbolBody = isEnumSymbolBody; + generated$3.isExistsTypeAnnotation = isExistsTypeAnnotation; + generated$3.isExportAllDeclaration = isExportAllDeclaration; + generated$3.isExportDeclaration = isExportDeclaration; + generated$3.isExportDefaultDeclaration = isExportDefaultDeclaration; + generated$3.isExportDefaultSpecifier = isExportDefaultSpecifier; + generated$3.isExportNamedDeclaration = isExportNamedDeclaration; + generated$3.isExportNamespaceSpecifier = isExportNamespaceSpecifier; + generated$3.isExportSpecifier = isExportSpecifier; + generated$3.isExpression = isExpression; + generated$3.isExpressionStatement = isExpressionStatement; + generated$3.isExpressionWrapper = isExpressionWrapper; + generated$3.isFile = isFile; + generated$3.isFlow = isFlow; + generated$3.isFlowBaseAnnotation = isFlowBaseAnnotation; + generated$3.isFlowDeclaration = isFlowDeclaration; + generated$3.isFlowPredicate = isFlowPredicate; + generated$3.isFlowType = isFlowType; + generated$3.isFor = isFor; + generated$3.isForInStatement = isForInStatement; + generated$3.isForOfStatement = isForOfStatement; + generated$3.isForStatement = isForStatement; + generated$3.isForXStatement = isForXStatement; + generated$3.isFunction = isFunction; + generated$3.isFunctionDeclaration = isFunctionDeclaration; + generated$3.isFunctionExpression = isFunctionExpression; + generated$3.isFunctionParent = isFunctionParent; + generated$3.isFunctionTypeAnnotation = isFunctionTypeAnnotation; + generated$3.isFunctionTypeParam = isFunctionTypeParam; + generated$3.isGenericTypeAnnotation = isGenericTypeAnnotation; + generated$3.isIdentifier = isIdentifier; + generated$3.isIfStatement = isIfStatement; + generated$3.isImmutable = isImmutable; + generated$3.isImport = isImport; + generated$3.isImportAttribute = isImportAttribute; + generated$3.isImportDeclaration = isImportDeclaration; + generated$3.isImportDefaultSpecifier = isImportDefaultSpecifier; + generated$3.isImportExpression = isImportExpression; + generated$3.isImportNamespaceSpecifier = isImportNamespaceSpecifier; + generated$3.isImportOrExportDeclaration = isImportOrExportDeclaration; + generated$3.isImportSpecifier = isImportSpecifier; + generated$3.isIndexedAccessType = isIndexedAccessType; + generated$3.isInferredPredicate = isInferredPredicate; + generated$3.isInterfaceDeclaration = isInterfaceDeclaration; + generated$3.isInterfaceExtends = isInterfaceExtends; + generated$3.isInterfaceTypeAnnotation = isInterfaceTypeAnnotation; + generated$3.isInterpreterDirective = isInterpreterDirective; + generated$3.isIntersectionTypeAnnotation = isIntersectionTypeAnnotation; + generated$3.isJSX = isJSX; + generated$3.isJSXAttribute = isJSXAttribute; + generated$3.isJSXClosingElement = isJSXClosingElement; + generated$3.isJSXClosingFragment = isJSXClosingFragment; + generated$3.isJSXElement = isJSXElement; + generated$3.isJSXEmptyExpression = isJSXEmptyExpression; + generated$3.isJSXExpressionContainer = isJSXExpressionContainer; + generated$3.isJSXFragment = isJSXFragment; + generated$3.isJSXIdentifier = isJSXIdentifier; + generated$3.isJSXMemberExpression = isJSXMemberExpression; + generated$3.isJSXNamespacedName = isJSXNamespacedName; + generated$3.isJSXOpeningElement = isJSXOpeningElement; + generated$3.isJSXOpeningFragment = isJSXOpeningFragment; + generated$3.isJSXSpreadAttribute = isJSXSpreadAttribute; + generated$3.isJSXSpreadChild = isJSXSpreadChild; + generated$3.isJSXText = isJSXText; + generated$3.isLVal = isLVal; + generated$3.isLabeledStatement = isLabeledStatement; + generated$3.isLiteral = isLiteral; + generated$3.isLogicalExpression = isLogicalExpression; + generated$3.isLoop = isLoop; + generated$3.isMemberExpression = isMemberExpression; + generated$3.isMetaProperty = isMetaProperty; + generated$3.isMethod = isMethod; + generated$3.isMiscellaneous = isMiscellaneous; + generated$3.isMixedTypeAnnotation = isMixedTypeAnnotation; + generated$3.isModuleDeclaration = isModuleDeclaration; + generated$3.isModuleExpression = isModuleExpression; + generated$3.isModuleSpecifier = isModuleSpecifier; + generated$3.isNewExpression = isNewExpression; + generated$3.isNoop = isNoop; + generated$3.isNullLiteral = isNullLiteral; + generated$3.isNullLiteralTypeAnnotation = isNullLiteralTypeAnnotation; + generated$3.isNullableTypeAnnotation = isNullableTypeAnnotation; + generated$3.isNumberLiteral = isNumberLiteral; + generated$3.isNumberLiteralTypeAnnotation = isNumberLiteralTypeAnnotation; + generated$3.isNumberTypeAnnotation = isNumberTypeAnnotation; + generated$3.isNumericLiteral = isNumericLiteral; + generated$3.isObjectExpression = isObjectExpression; + generated$3.isObjectMember = isObjectMember; + generated$3.isObjectMethod = isObjectMethod; + generated$3.isObjectPattern = isObjectPattern; + generated$3.isObjectProperty = isObjectProperty; + generated$3.isObjectTypeAnnotation = isObjectTypeAnnotation; + generated$3.isObjectTypeCallProperty = isObjectTypeCallProperty; + generated$3.isObjectTypeIndexer = isObjectTypeIndexer; + generated$3.isObjectTypeInternalSlot = isObjectTypeInternalSlot; + generated$3.isObjectTypeProperty = isObjectTypeProperty; + generated$3.isObjectTypeSpreadProperty = isObjectTypeSpreadProperty; + generated$3.isOpaqueType = isOpaqueType; + generated$3.isOptionalCallExpression = isOptionalCallExpression; + generated$3.isOptionalIndexedAccessType = isOptionalIndexedAccessType; + generated$3.isOptionalMemberExpression = isOptionalMemberExpression; + generated$3.isParenthesizedExpression = isParenthesizedExpression; + generated$3.isPattern = isPattern; + generated$3.isPatternLike = isPatternLike; + generated$3.isPipelineBareFunction = isPipelineBareFunction; + generated$3.isPipelinePrimaryTopicReference = isPipelinePrimaryTopicReference; + generated$3.isPipelineTopicExpression = isPipelineTopicExpression; + generated$3.isPlaceholder = isPlaceholder; + generated$3.isPrivate = isPrivate; + generated$3.isPrivateName = isPrivateName; + generated$3.isProgram = isProgram; + generated$3.isProperty = isProperty; + generated$3.isPureish = isPureish; + generated$3.isQualifiedTypeIdentifier = isQualifiedTypeIdentifier; + generated$3.isRecordExpression = isRecordExpression; + generated$3.isRegExpLiteral = isRegExpLiteral; + generated$3.isRegexLiteral = isRegexLiteral; + generated$3.isRestElement = isRestElement; + generated$3.isRestProperty = isRestProperty; + generated$3.isReturnStatement = isReturnStatement; + generated$3.isScopable = isScopable; + generated$3.isSequenceExpression = isSequenceExpression; + generated$3.isSpreadElement = isSpreadElement; + generated$3.isSpreadProperty = isSpreadProperty; + generated$3.isStandardized = isStandardized; + generated$3.isStatement = isStatement; + generated$3.isStaticBlock = isStaticBlock; + generated$3.isStringLiteral = isStringLiteral; + generated$3.isStringLiteralTypeAnnotation = isStringLiteralTypeAnnotation; + generated$3.isStringTypeAnnotation = isStringTypeAnnotation; + generated$3.isSuper = isSuper; + generated$3.isSwitchCase = isSwitchCase; + generated$3.isSwitchStatement = isSwitchStatement; + generated$3.isSymbolTypeAnnotation = isSymbolTypeAnnotation; + generated$3.isTSAnyKeyword = isTSAnyKeyword; + generated$3.isTSArrayType = isTSArrayType; + generated$3.isTSAsExpression = isTSAsExpression; + generated$3.isTSBaseType = isTSBaseType; + generated$3.isTSBigIntKeyword = isTSBigIntKeyword; + generated$3.isTSBooleanKeyword = isTSBooleanKeyword; + generated$3.isTSCallSignatureDeclaration = isTSCallSignatureDeclaration; + generated$3.isTSConditionalType = isTSConditionalType; + generated$3.isTSConstructSignatureDeclaration = isTSConstructSignatureDeclaration; + generated$3.isTSConstructorType = isTSConstructorType; + generated$3.isTSDeclareFunction = isTSDeclareFunction; + generated$3.isTSDeclareMethod = isTSDeclareMethod; + generated$3.isTSEntityName = isTSEntityName; + generated$3.isTSEnumDeclaration = isTSEnumDeclaration; + generated$3.isTSEnumMember = isTSEnumMember; + generated$3.isTSExportAssignment = isTSExportAssignment; + generated$3.isTSExpressionWithTypeArguments = isTSExpressionWithTypeArguments; + generated$3.isTSExternalModuleReference = isTSExternalModuleReference; + generated$3.isTSFunctionType = isTSFunctionType; + generated$3.isTSImportEqualsDeclaration = isTSImportEqualsDeclaration; + generated$3.isTSImportType = isTSImportType; + generated$3.isTSIndexSignature = isTSIndexSignature; + generated$3.isTSIndexedAccessType = isTSIndexedAccessType; + generated$3.isTSInferType = isTSInferType; + generated$3.isTSInstantiationExpression = isTSInstantiationExpression; + generated$3.isTSInterfaceBody = isTSInterfaceBody; + generated$3.isTSInterfaceDeclaration = isTSInterfaceDeclaration; + generated$3.isTSIntersectionType = isTSIntersectionType; + generated$3.isTSIntrinsicKeyword = isTSIntrinsicKeyword; + generated$3.isTSLiteralType = isTSLiteralType; + generated$3.isTSMappedType = isTSMappedType; + generated$3.isTSMethodSignature = isTSMethodSignature; + generated$3.isTSModuleBlock = isTSModuleBlock; + generated$3.isTSModuleDeclaration = isTSModuleDeclaration; + generated$3.isTSNamedTupleMember = isTSNamedTupleMember; + generated$3.isTSNamespaceExportDeclaration = isTSNamespaceExportDeclaration; + generated$3.isTSNeverKeyword = isTSNeverKeyword; + generated$3.isTSNonNullExpression = isTSNonNullExpression; + generated$3.isTSNullKeyword = isTSNullKeyword; + generated$3.isTSNumberKeyword = isTSNumberKeyword; + generated$3.isTSObjectKeyword = isTSObjectKeyword; + generated$3.isTSOptionalType = isTSOptionalType; + generated$3.isTSParameterProperty = isTSParameterProperty; + generated$3.isTSParenthesizedType = isTSParenthesizedType; + generated$3.isTSPropertySignature = isTSPropertySignature; + generated$3.isTSQualifiedName = isTSQualifiedName; + generated$3.isTSRestType = isTSRestType; + generated$3.isTSSatisfiesExpression = isTSSatisfiesExpression; + generated$3.isTSStringKeyword = isTSStringKeyword; + generated$3.isTSSymbolKeyword = isTSSymbolKeyword; + generated$3.isTSThisType = isTSThisType; + generated$3.isTSTupleType = isTSTupleType; + generated$3.isTSType = isTSType; + generated$3.isTSTypeAliasDeclaration = isTSTypeAliasDeclaration; + generated$3.isTSTypeAnnotation = isTSTypeAnnotation; + generated$3.isTSTypeAssertion = isTSTypeAssertion; + generated$3.isTSTypeElement = isTSTypeElement; + generated$3.isTSTypeLiteral = isTSTypeLiteral; + generated$3.isTSTypeOperator = isTSTypeOperator; + generated$3.isTSTypeParameter = isTSTypeParameter; + generated$3.isTSTypeParameterDeclaration = isTSTypeParameterDeclaration; + generated$3.isTSTypeParameterInstantiation = isTSTypeParameterInstantiation; + generated$3.isTSTypePredicate = isTSTypePredicate; + generated$3.isTSTypeQuery = isTSTypeQuery; + generated$3.isTSTypeReference = isTSTypeReference; + generated$3.isTSUndefinedKeyword = isTSUndefinedKeyword; + generated$3.isTSUnionType = isTSUnionType; + generated$3.isTSUnknownKeyword = isTSUnknownKeyword; + generated$3.isTSVoidKeyword = isTSVoidKeyword; + generated$3.isTaggedTemplateExpression = isTaggedTemplateExpression; + generated$3.isTemplateElement = isTemplateElement; + generated$3.isTemplateLiteral = isTemplateLiteral; + generated$3.isTerminatorless = isTerminatorless; + generated$3.isThisExpression = isThisExpression; + generated$3.isThisTypeAnnotation = isThisTypeAnnotation; + generated$3.isThrowStatement = isThrowStatement; + generated$3.isTopicReference = isTopicReference; + generated$3.isTryStatement = isTryStatement; + generated$3.isTupleExpression = isTupleExpression; + generated$3.isTupleTypeAnnotation = isTupleTypeAnnotation; + generated$3.isTypeAlias = isTypeAlias; + generated$3.isTypeAnnotation = isTypeAnnotation; + generated$3.isTypeCastExpression = isTypeCastExpression; + generated$3.isTypeParameter = isTypeParameter; + generated$3.isTypeParameterDeclaration = isTypeParameterDeclaration; + generated$3.isTypeParameterInstantiation = isTypeParameterInstantiation; + generated$3.isTypeScript = isTypeScript; + generated$3.isTypeofTypeAnnotation = isTypeofTypeAnnotation; + generated$3.isUnaryExpression = isUnaryExpression; + generated$3.isUnaryLike = isUnaryLike; + generated$3.isUnionTypeAnnotation = isUnionTypeAnnotation; + generated$3.isUpdateExpression = isUpdateExpression; + generated$3.isUserWhitespacable = isUserWhitespacable; + generated$3.isV8IntrinsicIdentifier = isV8IntrinsicIdentifier; + generated$3.isVariableDeclaration = isVariableDeclaration; + generated$3.isVariableDeclarator = isVariableDeclarator; + generated$3.isVariance = isVariance; + generated$3.isVoidTypeAnnotation = isVoidTypeAnnotation; + generated$3.isWhile = isWhile; + generated$3.isWhileStatement = isWhileStatement; + generated$3.isWithStatement = isWithStatement; + generated$3.isYieldExpression = isYieldExpression; + var _shallowEqual = requireShallowEqual(); + var _deprecationWarning = requireDeprecationWarning(); + function isArrayExpression(node, opts) { + if (!node) return false; + if (node.type !== "ArrayExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isAssignmentExpression(node, opts) { + if (!node) return false; + if (node.type !== "AssignmentExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBinaryExpression(node, opts) { + if (!node) return false; + if (node.type !== "BinaryExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isInterpreterDirective(node, opts) { + if (!node) return false; + if (node.type !== "InterpreterDirective") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDirective(node, opts) { + if (!node) return false; + if (node.type !== "Directive") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDirectiveLiteral(node, opts) { + if (!node) return false; + if (node.type !== "DirectiveLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBlockStatement(node, opts) { + if (!node) return false; + if (node.type !== "BlockStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBreakStatement(node, opts) { + if (!node) return false; + if (node.type !== "BreakStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isCallExpression(node, opts) { + if (!node) return false; + if (node.type !== "CallExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isCatchClause(node, opts) { + if (!node) return false; + if (node.type !== "CatchClause") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isConditionalExpression(node, opts) { + if (!node) return false; + if (node.type !== "ConditionalExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isContinueStatement(node, opts) { + if (!node) return false; + if (node.type !== "ContinueStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDebuggerStatement(node, opts) { + if (!node) return false; + if (node.type !== "DebuggerStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDoWhileStatement(node, opts) { + if (!node) return false; + if (node.type !== "DoWhileStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEmptyStatement(node, opts) { + if (!node) return false; + if (node.type !== "EmptyStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExpressionStatement(node, opts) { + if (!node) return false; + if (node.type !== "ExpressionStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFile(node, opts) { + if (!node) return false; + if (node.type !== "File") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isForInStatement(node, opts) { + if (!node) return false; + if (node.type !== "ForInStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isForStatement(node, opts) { + if (!node) return false; + if (node.type !== "ForStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunctionDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "FunctionDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunctionExpression(node, opts) { + if (!node) return false; + if (node.type !== "FunctionExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isIdentifier(node, opts) { + if (!node) return false; + if (node.type !== "Identifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isIfStatement(node, opts) { + if (!node) return false; + if (node.type !== "IfStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isLabeledStatement(node, opts) { + if (!node) return false; + if (node.type !== "LabeledStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStringLiteral(node, opts) { + if (!node) return false; + if (node.type !== "StringLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNumericLiteral(node, opts) { + if (!node) return false; + if (node.type !== "NumericLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNullLiteral(node, opts) { + if (!node) return false; + if (node.type !== "NullLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBooleanLiteral(node, opts) { + if (!node) return false; + if (node.type !== "BooleanLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isRegExpLiteral(node, opts) { + if (!node) return false; + if (node.type !== "RegExpLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isLogicalExpression(node, opts) { + if (!node) return false; + if (node.type !== "LogicalExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isMemberExpression(node, opts) { + if (!node) return false; + if (node.type !== "MemberExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNewExpression(node, opts) { + if (!node) return false; + if (node.type !== "NewExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isProgram(node, opts) { + if (!node) return false; + if (node.type !== "Program") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectExpression(node, opts) { + if (!node) return false; + if (node.type !== "ObjectExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectMethod(node, opts) { + if (!node) return false; + if (node.type !== "ObjectMethod") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectProperty(node, opts) { + if (!node) return false; + if (node.type !== "ObjectProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isRestElement(node, opts) { + if (!node) return false; + if (node.type !== "RestElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isReturnStatement(node, opts) { + if (!node) return false; + if (node.type !== "ReturnStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSequenceExpression(node, opts) { + if (!node) return false; + if (node.type !== "SequenceExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isParenthesizedExpression(node, opts) { + if (!node) return false; + if (node.type !== "ParenthesizedExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSwitchCase(node, opts) { + if (!node) return false; + if (node.type !== "SwitchCase") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSwitchStatement(node, opts) { + if (!node) return false; + if (node.type !== "SwitchStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isThisExpression(node, opts) { + if (!node) return false; + if (node.type !== "ThisExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isThrowStatement(node, opts) { + if (!node) return false; + if (node.type !== "ThrowStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTryStatement(node, opts) { + if (!node) return false; + if (node.type !== "TryStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isUnaryExpression(node, opts) { + if (!node) return false; + if (node.type !== "UnaryExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isUpdateExpression(node, opts) { + if (!node) return false; + if (node.type !== "UpdateExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isVariableDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "VariableDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isVariableDeclarator(node, opts) { + if (!node) return false; + if (node.type !== "VariableDeclarator") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isWhileStatement(node, opts) { + if (!node) return false; + if (node.type !== "WhileStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isWithStatement(node, opts) { + if (!node) return false; + if (node.type !== "WithStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isAssignmentPattern(node, opts) { + if (!node) return false; + if (node.type !== "AssignmentPattern") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isArrayPattern(node, opts) { + if (!node) return false; + if (node.type !== "ArrayPattern") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isArrowFunctionExpression(node, opts) { + if (!node) return false; + if (node.type !== "ArrowFunctionExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassBody(node, opts) { + if (!node) return false; + if (node.type !== "ClassBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassExpression(node, opts) { + if (!node) return false; + if (node.type !== "ClassExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "ClassDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportAllDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "ExportAllDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportDefaultDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "ExportDefaultDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportNamedDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "ExportNamedDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ExportSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isForOfStatement(node, opts) { + if (!node) return false; + if (node.type !== "ForOfStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "ImportDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportDefaultSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ImportDefaultSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportNamespaceSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ImportNamespaceSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ImportSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportExpression(node, opts) { + if (!node) return false; + if (node.type !== "ImportExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isMetaProperty(node, opts) { + if (!node) return false; + if (node.type !== "MetaProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassMethod(node, opts) { + if (!node) return false; + if (node.type !== "ClassMethod") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectPattern(node, opts) { + if (!node) return false; + if (node.type !== "ObjectPattern") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSpreadElement(node, opts) { + if (!node) return false; + if (node.type !== "SpreadElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSuper(node, opts) { + if (!node) return false; + if (node.type !== "Super") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTaggedTemplateExpression(node, opts) { + if (!node) return false; + if (node.type !== "TaggedTemplateExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTemplateElement(node, opts) { + if (!node) return false; + if (node.type !== "TemplateElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTemplateLiteral(node, opts) { + if (!node) return false; + if (node.type !== "TemplateLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isYieldExpression(node, opts) { + if (!node) return false; + if (node.type !== "YieldExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isAwaitExpression(node, opts) { + if (!node) return false; + if (node.type !== "AwaitExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImport(node, opts) { + if (!node) return false; + if (node.type !== "Import") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBigIntLiteral(node, opts) { + if (!node) return false; + if (node.type !== "BigIntLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportNamespaceSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ExportNamespaceSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isOptionalMemberExpression(node, opts) { + if (!node) return false; + if (node.type !== "OptionalMemberExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isOptionalCallExpression(node, opts) { + if (!node) return false; + if (node.type !== "OptionalCallExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassProperty(node, opts) { + if (!node) return false; + if (node.type !== "ClassProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassAccessorProperty(node, opts) { + if (!node) return false; + if (node.type !== "ClassAccessorProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassPrivateProperty(node, opts) { + if (!node) return false; + if (node.type !== "ClassPrivateProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassPrivateMethod(node, opts) { + if (!node) return false; + if (node.type !== "ClassPrivateMethod") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPrivateName(node, opts) { + if (!node) return false; + if (node.type !== "PrivateName") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStaticBlock(node, opts) { + if (!node) return false; + if (node.type !== "StaticBlock") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isAnyTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "AnyTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isArrayTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "ArrayTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBooleanTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "BooleanTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBooleanLiteralTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "BooleanLiteralTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNullLiteralTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "NullLiteralTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassImplements(node, opts) { + if (!node) return false; + if (node.type !== "ClassImplements") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareClass(node, opts) { + if (!node) return false; + if (node.type !== "DeclareClass") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareFunction(node, opts) { + if (!node) return false; + if (node.type !== "DeclareFunction") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareInterface(node, opts) { + if (!node) return false; + if (node.type !== "DeclareInterface") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareModule(node, opts) { + if (!node) return false; + if (node.type !== "DeclareModule") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareModuleExports(node, opts) { + if (!node) return false; + if (node.type !== "DeclareModuleExports") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareTypeAlias(node, opts) { + if (!node) return false; + if (node.type !== "DeclareTypeAlias") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareOpaqueType(node, opts) { + if (!node) return false; + if (node.type !== "DeclareOpaqueType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareVariable(node, opts) { + if (!node) return false; + if (node.type !== "DeclareVariable") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareExportDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "DeclareExportDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareExportAllDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "DeclareExportAllDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclaredPredicate(node, opts) { + if (!node) return false; + if (node.type !== "DeclaredPredicate") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExistsTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "ExistsTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunctionTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "FunctionTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunctionTypeParam(node, opts) { + if (!node) return false; + if (node.type !== "FunctionTypeParam") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isGenericTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "GenericTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isInferredPredicate(node, opts) { + if (!node) return false; + if (node.type !== "InferredPredicate") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isInterfaceExtends(node, opts) { + if (!node) return false; + if (node.type !== "InterfaceExtends") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isInterfaceDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "InterfaceDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isInterfaceTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "InterfaceTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isIntersectionTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "IntersectionTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isMixedTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "MixedTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEmptyTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "EmptyTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNullableTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "NullableTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNumberLiteralTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "NumberLiteralTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNumberTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "NumberTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeInternalSlot(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeInternalSlot") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeCallProperty(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeCallProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeIndexer(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeIndexer") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeProperty(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeSpreadProperty(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeSpreadProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isOpaqueType(node, opts) { + if (!node) return false; + if (node.type !== "OpaqueType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isQualifiedTypeIdentifier(node, opts) { + if (!node) return false; + if (node.type !== "QualifiedTypeIdentifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStringLiteralTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "StringLiteralTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStringTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "StringTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSymbolTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "SymbolTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isThisTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "ThisTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTupleTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "TupleTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeofTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "TypeofTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeAlias(node, opts) { + if (!node) return false; + if (node.type !== "TypeAlias") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "TypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeCastExpression(node, opts) { + if (!node) return false; + if (node.type !== "TypeCastExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeParameter(node, opts) { + if (!node) return false; + if (node.type !== "TypeParameter") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeParameterDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TypeParameterDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeParameterInstantiation(node, opts) { + if (!node) return false; + if (node.type !== "TypeParameterInstantiation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isUnionTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "UnionTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isVariance(node, opts) { + if (!node) return false; + if (node.type !== "Variance") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isVoidTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "VoidTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "EnumDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumBooleanBody(node, opts) { + if (!node) return false; + if (node.type !== "EnumBooleanBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumNumberBody(node, opts) { + if (!node) return false; + if (node.type !== "EnumNumberBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumStringBody(node, opts) { + if (!node) return false; + if (node.type !== "EnumStringBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumSymbolBody(node, opts) { + if (!node) return false; + if (node.type !== "EnumSymbolBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumBooleanMember(node, opts) { + if (!node) return false; + if (node.type !== "EnumBooleanMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumNumberMember(node, opts) { + if (!node) return false; + if (node.type !== "EnumNumberMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumStringMember(node, opts) { + if (!node) return false; + if (node.type !== "EnumStringMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumDefaultedMember(node, opts) { + if (!node) return false; + if (node.type !== "EnumDefaultedMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isIndexedAccessType(node, opts) { + if (!node) return false; + if (node.type !== "IndexedAccessType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isOptionalIndexedAccessType(node, opts) { + if (!node) return false; + if (node.type !== "OptionalIndexedAccessType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXAttribute(node, opts) { + if (!node) return false; + if (node.type !== "JSXAttribute") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXClosingElement(node, opts) { + if (!node) return false; + if (node.type !== "JSXClosingElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXElement(node, opts) { + if (!node) return false; + if (node.type !== "JSXElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXEmptyExpression(node, opts) { + if (!node) return false; + if (node.type !== "JSXEmptyExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXExpressionContainer(node, opts) { + if (!node) return false; + if (node.type !== "JSXExpressionContainer") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXSpreadChild(node, opts) { + if (!node) return false; + if (node.type !== "JSXSpreadChild") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXIdentifier(node, opts) { + if (!node) return false; + if (node.type !== "JSXIdentifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXMemberExpression(node, opts) { + if (!node) return false; + if (node.type !== "JSXMemberExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXNamespacedName(node, opts) { + if (!node) return false; + if (node.type !== "JSXNamespacedName") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXOpeningElement(node, opts) { + if (!node) return false; + if (node.type !== "JSXOpeningElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXSpreadAttribute(node, opts) { + if (!node) return false; + if (node.type !== "JSXSpreadAttribute") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXText(node, opts) { + if (!node) return false; + if (node.type !== "JSXText") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXFragment(node, opts) { + if (!node) return false; + if (node.type !== "JSXFragment") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXOpeningFragment(node, opts) { + if (!node) return false; + if (node.type !== "JSXOpeningFragment") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXClosingFragment(node, opts) { + if (!node) return false; + if (node.type !== "JSXClosingFragment") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNoop(node, opts) { + if (!node) return false; + if (node.type !== "Noop") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPlaceholder(node, opts) { + if (!node) return false; + if (node.type !== "Placeholder") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isV8IntrinsicIdentifier(node, opts) { + if (!node) return false; + if (node.type !== "V8IntrinsicIdentifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isArgumentPlaceholder(node, opts) { + if (!node) return false; + if (node.type !== "ArgumentPlaceholder") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBindExpression(node, opts) { + if (!node) return false; + if (node.type !== "BindExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportAttribute(node, opts) { + if (!node) return false; + if (node.type !== "ImportAttribute") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDecorator(node, opts) { + if (!node) return false; + if (node.type !== "Decorator") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDoExpression(node, opts) { + if (!node) return false; + if (node.type !== "DoExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportDefaultSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ExportDefaultSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isRecordExpression(node, opts) { + if (!node) return false; + if (node.type !== "RecordExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTupleExpression(node, opts) { + if (!node) return false; + if (node.type !== "TupleExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDecimalLiteral(node, opts) { + if (!node) return false; + if (node.type !== "DecimalLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isModuleExpression(node, opts) { + if (!node) return false; + if (node.type !== "ModuleExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTopicReference(node, opts) { + if (!node) return false; + if (node.type !== "TopicReference") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPipelineTopicExpression(node, opts) { + if (!node) return false; + if (node.type !== "PipelineTopicExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPipelineBareFunction(node, opts) { + if (!node) return false; + if (node.type !== "PipelineBareFunction") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPipelinePrimaryTopicReference(node, opts) { + if (!node) return false; + if (node.type !== "PipelinePrimaryTopicReference") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSParameterProperty(node, opts) { + if (!node) return false; + if (node.type !== "TSParameterProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSDeclareFunction(node, opts) { + if (!node) return false; + if (node.type !== "TSDeclareFunction") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSDeclareMethod(node, opts) { + if (!node) return false; + if (node.type !== "TSDeclareMethod") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSQualifiedName(node, opts) { + if (!node) return false; + if (node.type !== "TSQualifiedName") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSCallSignatureDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSCallSignatureDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSConstructSignatureDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSConstructSignatureDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSPropertySignature(node, opts) { + if (!node) return false; + if (node.type !== "TSPropertySignature") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSMethodSignature(node, opts) { + if (!node) return false; + if (node.type !== "TSMethodSignature") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSIndexSignature(node, opts) { + if (!node) return false; + if (node.type !== "TSIndexSignature") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSAnyKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSAnyKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSBooleanKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSBooleanKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSBigIntKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSBigIntKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSIntrinsicKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSIntrinsicKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNeverKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSNeverKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNullKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSNullKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNumberKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSNumberKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSObjectKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSObjectKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSStringKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSStringKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSSymbolKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSSymbolKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSUndefinedKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSUndefinedKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSUnknownKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSUnknownKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSVoidKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSVoidKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSThisType(node, opts) { + if (!node) return false; + if (node.type !== "TSThisType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSFunctionType(node, opts) { + if (!node) return false; + if (node.type !== "TSFunctionType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSConstructorType(node, opts) { + if (!node) return false; + if (node.type !== "TSConstructorType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeReference(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeReference") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypePredicate(node, opts) { + if (!node) return false; + if (node.type !== "TSTypePredicate") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeQuery(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeQuery") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeLiteral(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSArrayType(node, opts) { + if (!node) return false; + if (node.type !== "TSArrayType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTupleType(node, opts) { + if (!node) return false; + if (node.type !== "TSTupleType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSOptionalType(node, opts) { + if (!node) return false; + if (node.type !== "TSOptionalType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSRestType(node, opts) { + if (!node) return false; + if (node.type !== "TSRestType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNamedTupleMember(node, opts) { + if (!node) return false; + if (node.type !== "TSNamedTupleMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSUnionType(node, opts) { + if (!node) return false; + if (node.type !== "TSUnionType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSIntersectionType(node, opts) { + if (!node) return false; + if (node.type !== "TSIntersectionType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSConditionalType(node, opts) { + if (!node) return false; + if (node.type !== "TSConditionalType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSInferType(node, opts) { + if (!node) return false; + if (node.type !== "TSInferType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSParenthesizedType(node, opts) { + if (!node) return false; + if (node.type !== "TSParenthesizedType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeOperator(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeOperator") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSIndexedAccessType(node, opts) { + if (!node) return false; + if (node.type !== "TSIndexedAccessType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSMappedType(node, opts) { + if (!node) return false; + if (node.type !== "TSMappedType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSLiteralType(node, opts) { + if (!node) return false; + if (node.type !== "TSLiteralType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSExpressionWithTypeArguments(node, opts) { + if (!node) return false; + if (node.type !== "TSExpressionWithTypeArguments") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSInterfaceDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSInterfaceDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSInterfaceBody(node, opts) { + if (!node) return false; + if (node.type !== "TSInterfaceBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeAliasDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeAliasDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSInstantiationExpression(node, opts) { + if (!node) return false; + if (node.type !== "TSInstantiationExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSAsExpression(node, opts) { + if (!node) return false; + if (node.type !== "TSAsExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSSatisfiesExpression(node, opts) { + if (!node) return false; + if (node.type !== "TSSatisfiesExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeAssertion(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeAssertion") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSEnumDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSEnumDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSEnumMember(node, opts) { + if (!node) return false; + if (node.type !== "TSEnumMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSModuleDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSModuleDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSModuleBlock(node, opts) { + if (!node) return false; + if (node.type !== "TSModuleBlock") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSImportType(node, opts) { + if (!node) return false; + if (node.type !== "TSImportType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSImportEqualsDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSImportEqualsDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSExternalModuleReference(node, opts) { + if (!node) return false; + if (node.type !== "TSExternalModuleReference") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNonNullExpression(node, opts) { + if (!node) return false; + if (node.type !== "TSNonNullExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSExportAssignment(node, opts) { + if (!node) return false; + if (node.type !== "TSExportAssignment") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNamespaceExportDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSNamespaceExportDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeParameterInstantiation(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeParameterInstantiation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeParameterDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeParameterDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeParameter(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeParameter") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStandardized(node, opts) { + if (!node) return false; + switch (node.type) { + case "ArrayExpression": + case "AssignmentExpression": + case "BinaryExpression": + case "InterpreterDirective": + case "Directive": + case "DirectiveLiteral": + case "BlockStatement": + case "BreakStatement": + case "CallExpression": + case "CatchClause": + case "ConditionalExpression": + case "ContinueStatement": + case "DebuggerStatement": + case "DoWhileStatement": + case "EmptyStatement": + case "ExpressionStatement": + case "File": + case "ForInStatement": + case "ForStatement": + case "FunctionDeclaration": + case "FunctionExpression": + case "Identifier": + case "IfStatement": + case "LabeledStatement": + case "StringLiteral": + case "NumericLiteral": + case "NullLiteral": + case "BooleanLiteral": + case "RegExpLiteral": + case "LogicalExpression": + case "MemberExpression": + case "NewExpression": + case "Program": + case "ObjectExpression": + case "ObjectMethod": + case "ObjectProperty": + case "RestElement": + case "ReturnStatement": + case "SequenceExpression": + case "ParenthesizedExpression": + case "SwitchCase": + case "SwitchStatement": + case "ThisExpression": + case "ThrowStatement": + case "TryStatement": + case "UnaryExpression": + case "UpdateExpression": + case "VariableDeclaration": + case "VariableDeclarator": + case "WhileStatement": + case "WithStatement": + case "AssignmentPattern": + case "ArrayPattern": + case "ArrowFunctionExpression": + case "ClassBody": + case "ClassExpression": + case "ClassDeclaration": + case "ExportAllDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + case "ExportSpecifier": + case "ForOfStatement": + case "ImportDeclaration": + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "ImportSpecifier": + case "ImportExpression": + case "MetaProperty": + case "ClassMethod": + case "ObjectPattern": + case "SpreadElement": + case "Super": + case "TaggedTemplateExpression": + case "TemplateElement": + case "TemplateLiteral": + case "YieldExpression": + case "AwaitExpression": + case "Import": + case "BigIntLiteral": + case "ExportNamespaceSpecifier": + case "OptionalMemberExpression": + case "OptionalCallExpression": + case "ClassProperty": + case "ClassAccessorProperty": + case "ClassPrivateProperty": + case "ClassPrivateMethod": + case "PrivateName": + case "StaticBlock": + break; + case "Placeholder": + switch (node.expectedNode) { + case "Identifier": + case "StringLiteral": + case "BlockStatement": + case "ClassBody": + break; + default: + return false; + } + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExpression(node, opts) { + if (!node) return false; + switch (node.type) { + case "ArrayExpression": + case "AssignmentExpression": + case "BinaryExpression": + case "CallExpression": + case "ConditionalExpression": + case "FunctionExpression": + case "Identifier": + case "StringLiteral": + case "NumericLiteral": + case "NullLiteral": + case "BooleanLiteral": + case "RegExpLiteral": + case "LogicalExpression": + case "MemberExpression": + case "NewExpression": + case "ObjectExpression": + case "SequenceExpression": + case "ParenthesizedExpression": + case "ThisExpression": + case "UnaryExpression": + case "UpdateExpression": + case "ArrowFunctionExpression": + case "ClassExpression": + case "ImportExpression": + case "MetaProperty": + case "Super": + case "TaggedTemplateExpression": + case "TemplateLiteral": + case "YieldExpression": + case "AwaitExpression": + case "Import": + case "BigIntLiteral": + case "OptionalMemberExpression": + case "OptionalCallExpression": + case "TypeCastExpression": + case "JSXElement": + case "JSXFragment": + case "BindExpression": + case "DoExpression": + case "RecordExpression": + case "TupleExpression": + case "DecimalLiteral": + case "ModuleExpression": + case "TopicReference": + case "PipelineTopicExpression": + case "PipelineBareFunction": + case "PipelinePrimaryTopicReference": + case "TSInstantiationExpression": + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + break; + case "Placeholder": + switch (node.expectedNode) { + case "Expression": + case "Identifier": + case "StringLiteral": + break; + default: + return false; + } + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBinary(node, opts) { + if (!node) return false; + switch (node.type) { + case "BinaryExpression": + case "LogicalExpression": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isScopable(node, opts) { + if (!node) return false; + switch (node.type) { + case "BlockStatement": + case "CatchClause": + case "DoWhileStatement": + case "ForInStatement": + case "ForStatement": + case "FunctionDeclaration": + case "FunctionExpression": + case "Program": + case "ObjectMethod": + case "SwitchStatement": + case "WhileStatement": + case "ArrowFunctionExpression": + case "ClassExpression": + case "ClassDeclaration": + case "ForOfStatement": + case "ClassMethod": + case "ClassPrivateMethod": + case "StaticBlock": + case "TSModuleBlock": + break; + case "Placeholder": + if (node.expectedNode === "BlockStatement") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBlockParent(node, opts) { + if (!node) return false; + switch (node.type) { + case "BlockStatement": + case "CatchClause": + case "DoWhileStatement": + case "ForInStatement": + case "ForStatement": + case "FunctionDeclaration": + case "FunctionExpression": + case "Program": + case "ObjectMethod": + case "SwitchStatement": + case "WhileStatement": + case "ArrowFunctionExpression": + case "ForOfStatement": + case "ClassMethod": + case "ClassPrivateMethod": + case "StaticBlock": + case "TSModuleBlock": + break; + case "Placeholder": + if (node.expectedNode === "BlockStatement") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBlock(node, opts) { + if (!node) return false; + switch (node.type) { + case "BlockStatement": + case "Program": + case "TSModuleBlock": + break; + case "Placeholder": + if (node.expectedNode === "BlockStatement") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStatement(node, opts) { + if (!node) return false; + switch (node.type) { + case "BlockStatement": + case "BreakStatement": + case "ContinueStatement": + case "DebuggerStatement": + case "DoWhileStatement": + case "EmptyStatement": + case "ExpressionStatement": + case "ForInStatement": + case "ForStatement": + case "FunctionDeclaration": + case "IfStatement": + case "LabeledStatement": + case "ReturnStatement": + case "SwitchStatement": + case "ThrowStatement": + case "TryStatement": + case "VariableDeclaration": + case "WhileStatement": + case "WithStatement": + case "ClassDeclaration": + case "ExportAllDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + case "ForOfStatement": + case "ImportDeclaration": + case "DeclareClass": + case "DeclareFunction": + case "DeclareInterface": + case "DeclareModule": + case "DeclareModuleExports": + case "DeclareTypeAlias": + case "DeclareOpaqueType": + case "DeclareVariable": + case "DeclareExportDeclaration": + case "DeclareExportAllDeclaration": + case "InterfaceDeclaration": + case "OpaqueType": + case "TypeAlias": + case "EnumDeclaration": + case "TSDeclareFunction": + case "TSInterfaceDeclaration": + case "TSTypeAliasDeclaration": + case "TSEnumDeclaration": + case "TSModuleDeclaration": + case "TSImportEqualsDeclaration": + case "TSExportAssignment": + case "TSNamespaceExportDeclaration": + break; + case "Placeholder": + switch (node.expectedNode) { + case "Statement": + case "Declaration": + case "BlockStatement": + break; + default: + return false; + } + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTerminatorless(node, opts) { + if (!node) return false; + switch (node.type) { + case "BreakStatement": + case "ContinueStatement": + case "ReturnStatement": + case "ThrowStatement": + case "YieldExpression": + case "AwaitExpression": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isCompletionStatement(node, opts) { + if (!node) return false; + switch (node.type) { + case "BreakStatement": + case "ContinueStatement": + case "ReturnStatement": + case "ThrowStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isConditional(node, opts) { + if (!node) return false; + switch (node.type) { + case "ConditionalExpression": + case "IfStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isLoop(node, opts) { + if (!node) return false; + switch (node.type) { + case "DoWhileStatement": + case "ForInStatement": + case "ForStatement": + case "WhileStatement": + case "ForOfStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isWhile(node, opts) { + if (!node) return false; + switch (node.type) { + case "DoWhileStatement": + case "WhileStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExpressionWrapper(node, opts) { + if (!node) return false; + switch (node.type) { + case "ExpressionStatement": + case "ParenthesizedExpression": + case "TypeCastExpression": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFor(node, opts) { + if (!node) return false; + switch (node.type) { + case "ForInStatement": + case "ForStatement": + case "ForOfStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isForXStatement(node, opts) { + if (!node) return false; + switch (node.type) { + case "ForInStatement": + case "ForOfStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunction(node, opts) { + if (!node) return false; + switch (node.type) { + case "FunctionDeclaration": + case "FunctionExpression": + case "ObjectMethod": + case "ArrowFunctionExpression": + case "ClassMethod": + case "ClassPrivateMethod": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunctionParent(node, opts) { + if (!node) return false; + switch (node.type) { + case "FunctionDeclaration": + case "FunctionExpression": + case "ObjectMethod": + case "ArrowFunctionExpression": + case "ClassMethod": + case "ClassPrivateMethod": + case "StaticBlock": + case "TSModuleBlock": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPureish(node, opts) { + if (!node) return false; + switch (node.type) { + case "FunctionDeclaration": + case "FunctionExpression": + case "StringLiteral": + case "NumericLiteral": + case "NullLiteral": + case "BooleanLiteral": + case "RegExpLiteral": + case "ArrowFunctionExpression": + case "BigIntLiteral": + case "DecimalLiteral": + break; + case "Placeholder": + if (node.expectedNode === "StringLiteral") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclaration(node, opts) { + if (!node) return false; + switch (node.type) { + case "FunctionDeclaration": + case "VariableDeclaration": + case "ClassDeclaration": + case "ExportAllDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + case "ImportDeclaration": + case "DeclareClass": + case "DeclareFunction": + case "DeclareInterface": + case "DeclareModule": + case "DeclareModuleExports": + case "DeclareTypeAlias": + case "DeclareOpaqueType": + case "DeclareVariable": + case "DeclareExportDeclaration": + case "DeclareExportAllDeclaration": + case "InterfaceDeclaration": + case "OpaqueType": + case "TypeAlias": + case "EnumDeclaration": + case "TSDeclareFunction": + case "TSInterfaceDeclaration": + case "TSTypeAliasDeclaration": + case "TSEnumDeclaration": + case "TSModuleDeclaration": + break; + case "Placeholder": + if (node.expectedNode === "Declaration") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPatternLike(node, opts) { + if (!node) return false; + switch (node.type) { + case "Identifier": + case "RestElement": + case "AssignmentPattern": + case "ArrayPattern": + case "ObjectPattern": + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + break; + case "Placeholder": + switch (node.expectedNode) { + case "Pattern": + case "Identifier": + break; + default: + return false; + } + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isLVal(node, opts) { + if (!node) return false; + switch (node.type) { + case "Identifier": + case "MemberExpression": + case "RestElement": + case "AssignmentPattern": + case "ArrayPattern": + case "ObjectPattern": + case "TSParameterProperty": + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + break; + case "Placeholder": + switch (node.expectedNode) { + case "Pattern": + case "Identifier": + break; + default: + return false; + } + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSEntityName(node, opts) { + if (!node) return false; + switch (node.type) { + case "Identifier": + case "TSQualifiedName": + break; + case "Placeholder": + if (node.expectedNode === "Identifier") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isLiteral(node, opts) { + if (!node) return false; + switch (node.type) { + case "StringLiteral": + case "NumericLiteral": + case "NullLiteral": + case "BooleanLiteral": + case "RegExpLiteral": + case "TemplateLiteral": + case "BigIntLiteral": + case "DecimalLiteral": + break; + case "Placeholder": + if (node.expectedNode === "StringLiteral") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImmutable(node, opts) { + if (!node) return false; + switch (node.type) { + case "StringLiteral": + case "NumericLiteral": + case "NullLiteral": + case "BooleanLiteral": + case "BigIntLiteral": + case "JSXAttribute": + case "JSXClosingElement": + case "JSXElement": + case "JSXExpressionContainer": + case "JSXSpreadChild": + case "JSXOpeningElement": + case "JSXText": + case "JSXFragment": + case "JSXOpeningFragment": + case "JSXClosingFragment": + case "DecimalLiteral": + break; + case "Placeholder": + if (node.expectedNode === "StringLiteral") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isUserWhitespacable(node, opts) { + if (!node) return false; + switch (node.type) { + case "ObjectMethod": + case "ObjectProperty": + case "ObjectTypeInternalSlot": + case "ObjectTypeCallProperty": + case "ObjectTypeIndexer": + case "ObjectTypeProperty": + case "ObjectTypeSpreadProperty": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isMethod(node, opts) { + if (!node) return false; + switch (node.type) { + case "ObjectMethod": + case "ClassMethod": + case "ClassPrivateMethod": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectMember(node, opts) { + if (!node) return false; + switch (node.type) { + case "ObjectMethod": + case "ObjectProperty": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isProperty(node, opts) { + if (!node) return false; + switch (node.type) { + case "ObjectProperty": + case "ClassProperty": + case "ClassAccessorProperty": + case "ClassPrivateProperty": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isUnaryLike(node, opts) { + if (!node) return false; + switch (node.type) { + case "UnaryExpression": + case "SpreadElement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPattern(node, opts) { + if (!node) return false; + switch (node.type) { + case "AssignmentPattern": + case "ArrayPattern": + case "ObjectPattern": + break; + case "Placeholder": + if (node.expectedNode === "Pattern") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClass(node, opts) { + if (!node) return false; + switch (node.type) { + case "ClassExpression": + case "ClassDeclaration": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportOrExportDeclaration(node, opts) { + if (!node) return false; + switch (node.type) { + case "ExportAllDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + case "ImportDeclaration": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportDeclaration(node, opts) { + if (!node) return false; + switch (node.type) { + case "ExportAllDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isModuleSpecifier(node, opts) { + if (!node) return false; + switch (node.type) { + case "ExportSpecifier": + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "ImportSpecifier": + case "ExportNamespaceSpecifier": + case "ExportDefaultSpecifier": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isAccessor(node, opts) { + if (!node) return false; + switch (node.type) { + case "ClassAccessorProperty": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPrivate(node, opts) { + if (!node) return false; + switch (node.type) { + case "ClassPrivateProperty": + case "ClassPrivateMethod": + case "PrivateName": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFlow(node, opts) { + if (!node) return false; + switch (node.type) { + case "AnyTypeAnnotation": + case "ArrayTypeAnnotation": + case "BooleanTypeAnnotation": + case "BooleanLiteralTypeAnnotation": + case "NullLiteralTypeAnnotation": + case "ClassImplements": + case "DeclareClass": + case "DeclareFunction": + case "DeclareInterface": + case "DeclareModule": + case "DeclareModuleExports": + case "DeclareTypeAlias": + case "DeclareOpaqueType": + case "DeclareVariable": + case "DeclareExportDeclaration": + case "DeclareExportAllDeclaration": + case "DeclaredPredicate": + case "ExistsTypeAnnotation": + case "FunctionTypeAnnotation": + case "FunctionTypeParam": + case "GenericTypeAnnotation": + case "InferredPredicate": + case "InterfaceExtends": + case "InterfaceDeclaration": + case "InterfaceTypeAnnotation": + case "IntersectionTypeAnnotation": + case "MixedTypeAnnotation": + case "EmptyTypeAnnotation": + case "NullableTypeAnnotation": + case "NumberLiteralTypeAnnotation": + case "NumberTypeAnnotation": + case "ObjectTypeAnnotation": + case "ObjectTypeInternalSlot": + case "ObjectTypeCallProperty": + case "ObjectTypeIndexer": + case "ObjectTypeProperty": + case "ObjectTypeSpreadProperty": + case "OpaqueType": + case "QualifiedTypeIdentifier": + case "StringLiteralTypeAnnotation": + case "StringTypeAnnotation": + case "SymbolTypeAnnotation": + case "ThisTypeAnnotation": + case "TupleTypeAnnotation": + case "TypeofTypeAnnotation": + case "TypeAlias": + case "TypeAnnotation": + case "TypeCastExpression": + case "TypeParameter": + case "TypeParameterDeclaration": + case "TypeParameterInstantiation": + case "UnionTypeAnnotation": + case "Variance": + case "VoidTypeAnnotation": + case "EnumDeclaration": + case "EnumBooleanBody": + case "EnumNumberBody": + case "EnumStringBody": + case "EnumSymbolBody": + case "EnumBooleanMember": + case "EnumNumberMember": + case "EnumStringMember": + case "EnumDefaultedMember": + case "IndexedAccessType": + case "OptionalIndexedAccessType": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFlowType(node, opts) { + if (!node) return false; + switch (node.type) { + case "AnyTypeAnnotation": + case "ArrayTypeAnnotation": + case "BooleanTypeAnnotation": + case "BooleanLiteralTypeAnnotation": + case "NullLiteralTypeAnnotation": + case "ExistsTypeAnnotation": + case "FunctionTypeAnnotation": + case "GenericTypeAnnotation": + case "InterfaceTypeAnnotation": + case "IntersectionTypeAnnotation": + case "MixedTypeAnnotation": + case "EmptyTypeAnnotation": + case "NullableTypeAnnotation": + case "NumberLiteralTypeAnnotation": + case "NumberTypeAnnotation": + case "ObjectTypeAnnotation": + case "StringLiteralTypeAnnotation": + case "StringTypeAnnotation": + case "SymbolTypeAnnotation": + case "ThisTypeAnnotation": + case "TupleTypeAnnotation": + case "TypeofTypeAnnotation": + case "UnionTypeAnnotation": + case "VoidTypeAnnotation": + case "IndexedAccessType": + case "OptionalIndexedAccessType": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFlowBaseAnnotation(node, opts) { + if (!node) return false; + switch (node.type) { + case "AnyTypeAnnotation": + case "BooleanTypeAnnotation": + case "NullLiteralTypeAnnotation": + case "MixedTypeAnnotation": + case "EmptyTypeAnnotation": + case "NumberTypeAnnotation": + case "StringTypeAnnotation": + case "SymbolTypeAnnotation": + case "ThisTypeAnnotation": + case "VoidTypeAnnotation": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFlowDeclaration(node, opts) { + if (!node) return false; + switch (node.type) { + case "DeclareClass": + case "DeclareFunction": + case "DeclareInterface": + case "DeclareModule": + case "DeclareModuleExports": + case "DeclareTypeAlias": + case "DeclareOpaqueType": + case "DeclareVariable": + case "DeclareExportDeclaration": + case "DeclareExportAllDeclaration": + case "InterfaceDeclaration": + case "OpaqueType": + case "TypeAlias": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFlowPredicate(node, opts) { + if (!node) return false; + switch (node.type) { + case "DeclaredPredicate": + case "InferredPredicate": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumBody(node, opts) { + if (!node) return false; + switch (node.type) { + case "EnumBooleanBody": + case "EnumNumberBody": + case "EnumStringBody": + case "EnumSymbolBody": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumMember(node, opts) { + if (!node) return false; + switch (node.type) { + case "EnumBooleanMember": + case "EnumNumberMember": + case "EnumStringMember": + case "EnumDefaultedMember": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSX(node, opts) { + if (!node) return false; + switch (node.type) { + case "JSXAttribute": + case "JSXClosingElement": + case "JSXElement": + case "JSXEmptyExpression": + case "JSXExpressionContainer": + case "JSXSpreadChild": + case "JSXIdentifier": + case "JSXMemberExpression": + case "JSXNamespacedName": + case "JSXOpeningElement": + case "JSXSpreadAttribute": + case "JSXText": + case "JSXFragment": + case "JSXOpeningFragment": + case "JSXClosingFragment": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isMiscellaneous(node, opts) { + if (!node) return false; + switch (node.type) { + case "Noop": + case "Placeholder": + case "V8IntrinsicIdentifier": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeScript(node, opts) { + if (!node) return false; + switch (node.type) { + case "TSParameterProperty": + case "TSDeclareFunction": + case "TSDeclareMethod": + case "TSQualifiedName": + case "TSCallSignatureDeclaration": + case "TSConstructSignatureDeclaration": + case "TSPropertySignature": + case "TSMethodSignature": + case "TSIndexSignature": + case "TSAnyKeyword": + case "TSBooleanKeyword": + case "TSBigIntKeyword": + case "TSIntrinsicKeyword": + case "TSNeverKeyword": + case "TSNullKeyword": + case "TSNumberKeyword": + case "TSObjectKeyword": + case "TSStringKeyword": + case "TSSymbolKeyword": + case "TSUndefinedKeyword": + case "TSUnknownKeyword": + case "TSVoidKeyword": + case "TSThisType": + case "TSFunctionType": + case "TSConstructorType": + case "TSTypeReference": + case "TSTypePredicate": + case "TSTypeQuery": + case "TSTypeLiteral": + case "TSArrayType": + case "TSTupleType": + case "TSOptionalType": + case "TSRestType": + case "TSNamedTupleMember": + case "TSUnionType": + case "TSIntersectionType": + case "TSConditionalType": + case "TSInferType": + case "TSParenthesizedType": + case "TSTypeOperator": + case "TSIndexedAccessType": + case "TSMappedType": + case "TSLiteralType": + case "TSExpressionWithTypeArguments": + case "TSInterfaceDeclaration": + case "TSInterfaceBody": + case "TSTypeAliasDeclaration": + case "TSInstantiationExpression": + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSEnumDeclaration": + case "TSEnumMember": + case "TSModuleDeclaration": + case "TSModuleBlock": + case "TSImportType": + case "TSImportEqualsDeclaration": + case "TSExternalModuleReference": + case "TSNonNullExpression": + case "TSExportAssignment": + case "TSNamespaceExportDeclaration": + case "TSTypeAnnotation": + case "TSTypeParameterInstantiation": + case "TSTypeParameterDeclaration": + case "TSTypeParameter": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeElement(node, opts) { + if (!node) return false; + switch (node.type) { + case "TSCallSignatureDeclaration": + case "TSConstructSignatureDeclaration": + case "TSPropertySignature": + case "TSMethodSignature": + case "TSIndexSignature": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSType(node, opts) { + if (!node) return false; + switch (node.type) { + case "TSAnyKeyword": + case "TSBooleanKeyword": + case "TSBigIntKeyword": + case "TSIntrinsicKeyword": + case "TSNeverKeyword": + case "TSNullKeyword": + case "TSNumberKeyword": + case "TSObjectKeyword": + case "TSStringKeyword": + case "TSSymbolKeyword": + case "TSUndefinedKeyword": + case "TSUnknownKeyword": + case "TSVoidKeyword": + case "TSThisType": + case "TSFunctionType": + case "TSConstructorType": + case "TSTypeReference": + case "TSTypePredicate": + case "TSTypeQuery": + case "TSTypeLiteral": + case "TSArrayType": + case "TSTupleType": + case "TSOptionalType": + case "TSRestType": + case "TSUnionType": + case "TSIntersectionType": + case "TSConditionalType": + case "TSInferType": + case "TSParenthesizedType": + case "TSTypeOperator": + case "TSIndexedAccessType": + case "TSMappedType": + case "TSLiteralType": + case "TSExpressionWithTypeArguments": + case "TSImportType": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSBaseType(node, opts) { + if (!node) return false; + switch (node.type) { + case "TSAnyKeyword": + case "TSBooleanKeyword": + case "TSBigIntKeyword": + case "TSIntrinsicKeyword": + case "TSNeverKeyword": + case "TSNullKeyword": + case "TSNumberKeyword": + case "TSObjectKeyword": + case "TSStringKeyword": + case "TSSymbolKeyword": + case "TSUndefinedKeyword": + case "TSUnknownKeyword": + case "TSVoidKeyword": + case "TSThisType": + case "TSLiteralType": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNumberLiteral(node, opts) { + (0, _deprecationWarning.default)("isNumberLiteral", "isNumericLiteral"); + if (!node) return false; + if (node.type !== "NumberLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isRegexLiteral(node, opts) { + (0, _deprecationWarning.default)("isRegexLiteral", "isRegExpLiteral"); + if (!node) return false; + if (node.type !== "RegexLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isRestProperty(node, opts) { + (0, _deprecationWarning.default)("isRestProperty", "isRestElement"); + if (!node) return false; + if (node.type !== "RestProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSpreadProperty(node, opts) { + (0, _deprecationWarning.default)("isSpreadProperty", "isSpreadElement"); + if (!node) return false; + if (node.type !== "SpreadProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isModuleDeclaration(node, opts) { + (0, _deprecationWarning.default)("isModuleDeclaration", "isImportOrExportDeclaration"); + return isImportOrExportDeclaration(node, opts); + } + + + return generated$3; +} + +var hasRequiredMatchesPattern; + +function requireMatchesPattern () { + if (hasRequiredMatchesPattern) return matchesPattern; + hasRequiredMatchesPattern = 1; + + Object.defineProperty(matchesPattern, "__esModule", { + value: true + }); + matchesPattern.default = matchesPattern$1; + var _index = requireGenerated$3(); + function matchesPattern$1(member, match, allowPartial) { + if (!(0, _index.isMemberExpression)(member)) return false; + const parts = Array.isArray(match) ? match : match.split("."); + const nodes = []; + let node; + for (node = member; (0, _index.isMemberExpression)(node); node = node.object) { + nodes.push(node.property); + } + nodes.push(node); + if (nodes.length < parts.length) return false; + if (!allowPartial && nodes.length > parts.length) return false; + for (let i = 0, j = nodes.length - 1; i < parts.length; i++, j--) { + const node = nodes[j]; + let value; + if ((0, _index.isIdentifier)(node)) { + value = node.name; + } else if ((0, _index.isStringLiteral)(node)) { + value = node.value; + } else if ((0, _index.isThisExpression)(node)) { + value = "this"; + } else { + return false; + } + if (parts[i] !== value) return false; + } + return true; + } + + + return matchesPattern; +} + +var hasRequiredBuildMatchMemberExpression; + +function requireBuildMatchMemberExpression () { + if (hasRequiredBuildMatchMemberExpression) return buildMatchMemberExpression; + hasRequiredBuildMatchMemberExpression = 1; + + Object.defineProperty(buildMatchMemberExpression, "__esModule", { + value: true + }); + buildMatchMemberExpression.default = buildMatchMemberExpression$1; + var _matchesPattern = requireMatchesPattern(); + function buildMatchMemberExpression$1(match, allowPartial) { + const parts = match.split("."); + return member => (0, _matchesPattern.default)(member, parts, allowPartial); + } + + + return buildMatchMemberExpression; +} + +var hasRequiredIsReactComponent; + +function requireIsReactComponent () { + if (hasRequiredIsReactComponent) return isReactComponent; + hasRequiredIsReactComponent = 1; + + Object.defineProperty(isReactComponent, "__esModule", { + value: true + }); + isReactComponent.default = void 0; + var _buildMatchMemberExpression = requireBuildMatchMemberExpression(); + const isReactComponent$1 = (0, _buildMatchMemberExpression.default)("React.Component"); + isReactComponent.default = isReactComponent$1; + + + return isReactComponent; +} + +var isCompatTag = {}; + +var hasRequiredIsCompatTag; + +function requireIsCompatTag () { + if (hasRequiredIsCompatTag) return isCompatTag; + hasRequiredIsCompatTag = 1; + + Object.defineProperty(isCompatTag, "__esModule", { + value: true + }); + isCompatTag.default = isCompatTag$1; + function isCompatTag$1(tagName) { + return !!tagName && /^[a-z]/.test(tagName); + } + + + return isCompatTag; +} + +var buildChildren = {}; + +var cleanJSXElementLiteralChild = {}; + +var generated$2 = {}; + +var validate$1 = {}; + +var definitions = {}; + +var core = {}; + +var is = {}; + +var isType = {}; + +var hasRequiredIsType; + +function requireIsType () { + if (hasRequiredIsType) return isType; + hasRequiredIsType = 1; + + Object.defineProperty(isType, "__esModule", { + value: true + }); + isType.default = isType$1; + var _index = requireDefinitions(); + function isType$1(nodeType, targetType) { + if (nodeType === targetType) return true; + if (nodeType == null) return false; + if (_index.ALIAS_KEYS[targetType]) return false; + const aliases = _index.FLIPPED_ALIAS_KEYS[targetType]; + if (aliases) { + if (aliases[0] === nodeType) return true; + for (const alias of aliases) { + if (nodeType === alias) return true; + } + } + return false; + } + + + return isType; +} + +var isPlaceholderType = {}; + +var hasRequiredIsPlaceholderType; + +function requireIsPlaceholderType () { + if (hasRequiredIsPlaceholderType) return isPlaceholderType; + hasRequiredIsPlaceholderType = 1; + + Object.defineProperty(isPlaceholderType, "__esModule", { + value: true + }); + isPlaceholderType.default = isPlaceholderType$1; + var _index = requireDefinitions(); + function isPlaceholderType$1(placeholderType, targetType) { + if (placeholderType === targetType) return true; + const aliases = _index.PLACEHOLDERS_ALIAS[placeholderType]; + if (aliases) { + for (const alias of aliases) { + if (targetType === alias) return true; + } + } + return false; + } + + + return isPlaceholderType; +} + +var hasRequiredIs; + +function requireIs () { + if (hasRequiredIs) return is; + hasRequiredIs = 1; + + Object.defineProperty(is, "__esModule", { + value: true + }); + is.default = is$1; + var _shallowEqual = requireShallowEqual(); + var _isType = requireIsType(); + var _isPlaceholderType = requireIsPlaceholderType(); + var _index = requireDefinitions(); + function is$1(type, node, opts) { + if (!node) return false; + const matches = (0, _isType.default)(node.type, type); + if (!matches) { + if (!opts && node.type === "Placeholder" && type in _index.FLIPPED_ALIAS_KEYS) { + return (0, _isPlaceholderType.default)(node.expectedNode, type); + } + return false; + } + if (opts === undefined) { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + + return is; +} + +var isValidIdentifier = {}; + +var lib$2 = {}; + +var identifier = {}; + +var hasRequiredIdentifier; + +function requireIdentifier () { + if (hasRequiredIdentifier) return identifier; + hasRequiredIdentifier = 1; + + Object.defineProperty(identifier, "__esModule", { + value: true + }); + identifier.isIdentifierChar = isIdentifierChar; + identifier.isIdentifierName = isIdentifierName; + identifier.isIdentifierStart = isIdentifierStart; + let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + let nonASCIIidentifierChars = "\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65"; + const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 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, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; + const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + function isInAstralSet(code, set) { + let pos = 0x10000; + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + return false; + } + function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes); + } + function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); + } + function isIdentifierName(name) { + let isFirst = true; + for (let i = 0; i < name.length; i++) { + let cp = name.charCodeAt(i); + if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) { + const trail = name.charCodeAt(++i); + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + if (isFirst) { + isFirst = false; + if (!isIdentifierStart(cp)) { + return false; + } + } else if (!isIdentifierChar(cp)) { + return false; + } + } + return !isFirst; + } + + + return identifier; +} + +var keyword = {}; + +var hasRequiredKeyword; + +function requireKeyword () { + if (hasRequiredKeyword) return keyword; + hasRequiredKeyword = 1; + + Object.defineProperty(keyword, "__esModule", { + value: true + }); + keyword.isKeyword = isKeyword; + keyword.isReservedWord = isReservedWord; + keyword.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; + keyword.isStrictBindReservedWord = isStrictBindReservedWord; + keyword.isStrictReservedWord = isStrictReservedWord; + const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] + }; + const keywords = new Set(reservedWords.keyword); + const reservedWordsStrictSet = new Set(reservedWords.strict); + const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); + function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; + } + function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); + } + function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); + } + function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); + } + function isKeyword(word) { + return keywords.has(word); + } + + + return keyword; +} + +var hasRequiredLib$3; + +function requireLib$3 () { + if (hasRequiredLib$3) return lib$2; + hasRequiredLib$3 = 1; + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "isIdentifierChar", { + enumerable: true, + get: function () { + return _identifier.isIdentifierChar; + } + }); + Object.defineProperty(exports, "isIdentifierName", { + enumerable: true, + get: function () { + return _identifier.isIdentifierName; + } + }); + Object.defineProperty(exports, "isIdentifierStart", { + enumerable: true, + get: function () { + return _identifier.isIdentifierStart; + } + }); + Object.defineProperty(exports, "isKeyword", { + enumerable: true, + get: function () { + return _keyword.isKeyword; + } + }); + Object.defineProperty(exports, "isReservedWord", { + enumerable: true, + get: function () { + return _keyword.isReservedWord; + } + }); + Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindOnlyReservedWord; + } + }); + Object.defineProperty(exports, "isStrictBindReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindReservedWord; + } + }); + Object.defineProperty(exports, "isStrictReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictReservedWord; + } + }); + var _identifier = requireIdentifier(); + var _keyword = requireKeyword(); + + +} (lib$2)); + return lib$2; +} + +var hasRequiredIsValidIdentifier; + +function requireIsValidIdentifier () { + if (hasRequiredIsValidIdentifier) return isValidIdentifier; + hasRequiredIsValidIdentifier = 1; + + Object.defineProperty(isValidIdentifier, "__esModule", { + value: true + }); + isValidIdentifier.default = isValidIdentifier$1; + var _helperValidatorIdentifier = requireLib$3(); + function isValidIdentifier$1(name, reserved = true) { + if (typeof name !== "string") return false; + if (reserved) { + if ((0, _helperValidatorIdentifier.isKeyword)(name) || (0, _helperValidatorIdentifier.isStrictReservedWord)(name, true)) { + return false; + } + } + return (0, _helperValidatorIdentifier.isIdentifierName)(name); + } + + + return isValidIdentifier; +} + +var lib$1 = {}; + +var hasRequiredLib$2; + +function requireLib$2 () { + if (hasRequiredLib$2) return lib$1; + hasRequiredLib$2 = 1; + + Object.defineProperty(lib$1, "__esModule", { + value: true + }); + lib$1.readCodePoint = readCodePoint; + lib$1.readInt = readInt; + lib$1.readStringContents = readStringContents; + var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; + }; + const forbiddenNumericSeparatorSiblings = { + decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]), + hex: new Set([46, 88, 95, 120]) + }; + const isAllowedNumericSeparatorSibling = { + bin: ch => ch === 48 || ch === 49, + oct: ch => ch >= 48 && ch <= 55, + dec: ch => ch >= 48 && ch <= 57, + hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 + }; + function readStringContents(type, input, pos, lineStart, curLine, errors) { + const initialPos = pos; + const initialLineStart = lineStart; + const initialCurLine = curLine; + let out = ""; + let firstInvalidLoc = null; + let chunkStart = pos; + const { + length + } = input; + for (;;) { + if (pos >= length) { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + out += input.slice(chunkStart, pos); + break; + } + const ch = input.charCodeAt(pos); + if (isStringEnd(type, ch, input, pos)) { + out += input.slice(chunkStart, pos); + break; + } + if (ch === 92) { + out += input.slice(chunkStart, pos); + const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors); + if (res.ch === null && !firstInvalidLoc) { + firstInvalidLoc = { + pos, + lineStart, + curLine + }; + } else { + out += res.ch; + } + ({ + pos, + lineStart, + curLine + } = res); + chunkStart = pos; + } else if (ch === 8232 || ch === 8233) { + ++pos; + ++curLine; + lineStart = pos; + } else if (ch === 10 || ch === 13) { + if (type === "template") { + out += input.slice(chunkStart, pos) + "\n"; + ++pos; + if (ch === 13 && input.charCodeAt(pos) === 10) { + ++pos; + } + ++curLine; + chunkStart = lineStart = pos; + } else { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + } + } else { + ++pos; + } + } + return { + pos, + str: out, + firstInvalidLoc, + lineStart, + curLine, + containsInvalid: !!firstInvalidLoc + }; + } + function isStringEnd(type, ch, input, pos) { + if (type === "template") { + return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; + } + return ch === (type === "double" ? 34 : 39); + } + function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { + const throwOnInvalid = !inTemplate; + pos++; + const res = ch => ({ + pos, + ch, + lineStart, + curLine + }); + const ch = input.charCodeAt(pos++); + switch (ch) { + case 110: + return res("\n"); + case 114: + return res("\r"); + case 120: + { + let code; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCharCode(code)); + } + case 117: + { + let code; + ({ + code, + pos + } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCodePoint(code)); + } + case 116: + return res("\t"); + case 98: + return res("\b"); + case 118: + return res("\u000b"); + case 102: + return res("\f"); + case 13: + if (input.charCodeAt(pos) === 10) { + ++pos; + } + case 10: + lineStart = pos; + ++curLine; + case 8232: + case 8233: + return res(""); + case 56: + case 57: + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(pos - 1, lineStart, curLine); + } + default: + if (ch >= 48 && ch <= 55) { + const startPos = pos - 1; + const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2)); + let octalStr = match[0]; + let octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + pos += octalStr.length - 1; + const next = input.charCodeAt(pos); + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(startPos, lineStart, curLine); + } + } + return res(String.fromCharCode(octal)); + } + return res(String.fromCharCode(ch)); + } + } + function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { + const initialPos = pos; + let n; + ({ + n, + pos + } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid)); + if (n === null) { + if (throwOnInvalid) { + errors.invalidEscapeSequence(initialPos, lineStart, curLine); + } else { + pos = initialPos - 1; + } + } + return { + code: n, + pos + }; + } + function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) { + const start = pos; + const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; + let invalid = false; + let total = 0; + for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { + const code = input.charCodeAt(pos); + let val; + if (code === 95 && allowNumSeparator !== "bail") { + const prev = input.charCodeAt(pos - 1); + const next = input.charCodeAt(pos + 1); + if (!allowNumSeparator) { + if (bailOnError) return { + n: null, + pos + }; + errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); + } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { + if (bailOnError) return { + n: null, + pos + }; + errors.unexpectedNumericSeparator(pos, lineStart, curLine); + } + ++pos; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + if (val <= 9 && bailOnError) { + return { + n: null, + pos + }; + } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { + val = 0; + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } + } + ++pos; + total = total * radix + val; + } + if (pos === start || len != null && pos - start !== len || invalid) { + return { + n: null, + pos + }; + } + return { + n: total, + pos + }; + } + function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { + const ch = input.charCodeAt(pos); + let code; + if (ch === 123) { + ++pos; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); + ++pos; + if (code !== null && code > 0x10ffff) { + if (throwOnInvalid) { + errors.invalidCodePoint(pos, lineStart, curLine); + } else { + return { + code: null, + pos + }; + } + } + } else { + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); + } + return { + code, + pos + }; + } + + + return lib$1; +} + +var constants = {}; + +var hasRequiredConstants; + +function requireConstants () { + if (hasRequiredConstants) return constants; + hasRequiredConstants = 1; + + Object.defineProperty(constants, "__esModule", { + value: true + }); + constants.UPDATE_OPERATORS = constants.UNARY_OPERATORS = constants.STRING_UNARY_OPERATORS = constants.STATEMENT_OR_BLOCK_KEYS = constants.NUMBER_UNARY_OPERATORS = constants.NUMBER_BINARY_OPERATORS = constants.NOT_LOCAL_BINDING = constants.LOGICAL_OPERATORS = constants.INHERIT_KEYS = constants.FOR_INIT_KEYS = constants.FLATTENABLE_KEYS = constants.EQUALITY_BINARY_OPERATORS = constants.COMPARISON_BINARY_OPERATORS = constants.COMMENT_KEYS = constants.BOOLEAN_UNARY_OPERATORS = constants.BOOLEAN_NUMBER_BINARY_OPERATORS = constants.BOOLEAN_BINARY_OPERATORS = constants.BLOCK_SCOPED_SYMBOL = constants.BINARY_OPERATORS = constants.ASSIGNMENT_OPERATORS = void 0; + constants.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; + constants.FLATTENABLE_KEYS = ["body", "expressions"]; + constants.FOR_INIT_KEYS = ["left", "init"]; + constants.COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; + const LOGICAL_OPERATORS = constants.LOGICAL_OPERATORS = ["||", "&&", "??"]; + constants.UPDATE_OPERATORS = ["++", "--"]; + const BOOLEAN_NUMBER_BINARY_OPERATORS = constants.BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; + const EQUALITY_BINARY_OPERATORS = constants.EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; + const COMPARISON_BINARY_OPERATORS = constants.COMPARISON_BINARY_OPERATORS = [...EQUALITY_BINARY_OPERATORS, "in", "instanceof"]; + const BOOLEAN_BINARY_OPERATORS = constants.BOOLEAN_BINARY_OPERATORS = [...COMPARISON_BINARY_OPERATORS, ...BOOLEAN_NUMBER_BINARY_OPERATORS]; + const NUMBER_BINARY_OPERATORS = constants.NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; + constants.BINARY_OPERATORS = ["+", ...NUMBER_BINARY_OPERATORS, ...BOOLEAN_BINARY_OPERATORS, "|>"]; + constants.ASSIGNMENT_OPERATORS = ["=", "+=", ...NUMBER_BINARY_OPERATORS.map(op => op + "="), ...LOGICAL_OPERATORS.map(op => op + "=")]; + const BOOLEAN_UNARY_OPERATORS = constants.BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; + const NUMBER_UNARY_OPERATORS = constants.NUMBER_UNARY_OPERATORS = ["+", "-", "~"]; + const STRING_UNARY_OPERATORS = constants.STRING_UNARY_OPERATORS = ["typeof"]; + constants.UNARY_OPERATORS = ["void", "throw", ...BOOLEAN_UNARY_OPERATORS, ...NUMBER_UNARY_OPERATORS, ...STRING_UNARY_OPERATORS]; + constants.INHERIT_KEYS = { + optional: ["typeAnnotation", "typeParameters", "returnType"], + force: ["start", "loc", "end"] + }; + constants.BLOCK_SCOPED_SYMBOL = Symbol.for("var used to be block scoped"); + constants.NOT_LOCAL_BINDING = Symbol.for("should not be considered a local binding"); + + + return constants; +} + +var utils = {}; + +var hasRequiredUtils; + +function requireUtils () { + if (hasRequiredUtils) return utils; + hasRequiredUtils = 1; + + Object.defineProperty(utils, "__esModule", { + value: true + }); + utils.VISITOR_KEYS = utils.NODE_PARENT_VALIDATIONS = utils.NODE_FIELDS = utils.FLIPPED_ALIAS_KEYS = utils.DEPRECATED_KEYS = utils.BUILDER_KEYS = utils.ALIAS_KEYS = void 0; + utils.arrayOf = arrayOf; + utils.arrayOfType = arrayOfType; + utils.assertEach = assertEach; + utils.assertNodeOrValueType = assertNodeOrValueType; + utils.assertNodeType = assertNodeType; + utils.assertOneOf = assertOneOf; + utils.assertOptionalChainStart = assertOptionalChainStart; + utils.assertShape = assertShape; + utils.assertValueType = assertValueType; + utils.chain = chain; + utils.default = defineType; + utils.defineAliasedType = defineAliasedType; + utils.validate = validate; + utils.validateArrayOfType = validateArrayOfType; + utils.validateOptional = validateOptional; + utils.validateOptionalType = validateOptionalType; + utils.validateType = validateType; + var _is = requireIs(); + var _validate = requireValidate(); + const VISITOR_KEYS = utils.VISITOR_KEYS = {}; + const ALIAS_KEYS = utils.ALIAS_KEYS = {}; + const FLIPPED_ALIAS_KEYS = utils.FLIPPED_ALIAS_KEYS = {}; + const NODE_FIELDS = utils.NODE_FIELDS = {}; + const BUILDER_KEYS = utils.BUILDER_KEYS = {}; + const DEPRECATED_KEYS = utils.DEPRECATED_KEYS = {}; + const NODE_PARENT_VALIDATIONS = utils.NODE_PARENT_VALIDATIONS = {}; + function getType(val) { + if (Array.isArray(val)) { + return "array"; + } else if (val === null) { + return "null"; + } else { + return typeof val; + } + } + function validate(validate) { + return { + validate + }; + } + function validateType(...typeNames) { + return validate(assertNodeType(...typeNames)); + } + function validateOptional(validate) { + return { + validate, + optional: true + }; + } + function validateOptionalType(...typeNames) { + return { + validate: assertNodeType(...typeNames), + optional: true + }; + } + function arrayOf(elementType) { + return chain(assertValueType("array"), assertEach(elementType)); + } + function arrayOfType(...typeNames) { + return arrayOf(assertNodeType(...typeNames)); + } + function validateArrayOfType(...typeNames) { + return validate(arrayOfType(...typeNames)); + } + function assertEach(callback) { + const childValidator = process.env.BABEL_TYPES_8_BREAKING ? _validate.validateChild : () => {}; + function validator(node, key, val) { + if (!Array.isArray(val)) return; + for (let i = 0; i < val.length; i++) { + const subkey = `${key}[${i}]`; + const v = val[i]; + callback(node, subkey, v); + childValidator(node, subkey, v); + } + } + validator.each = callback; + return validator; + } + function assertOneOf(...values) { + function validate(node, key, val) { + if (!values.includes(val)) { + throw new TypeError(`Property ${key} expected value to be one of ${JSON.stringify(values)} but got ${JSON.stringify(val)}`); + } + } + validate.oneOf = values; + return validate; + } + function assertNodeType(...types) { + function validate(node, key, val) { + for (const type of types) { + if ((0, _is.default)(type, val)) { + (0, _validate.validateChild)(node, key, val); + return; + } + } + throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val == null ? void 0 : val.type)}`); + } + validate.oneOfNodeTypes = types; + return validate; + } + function assertNodeOrValueType(...types) { + function validate(node, key, val) { + for (const type of types) { + if (getType(val) === type || (0, _is.default)(type, val)) { + (0, _validate.validateChild)(node, key, val); + return; + } + } + throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val == null ? void 0 : val.type)}`); + } + validate.oneOfNodeOrValueTypes = types; + return validate; + } + function assertValueType(type) { + function validate(node, key, val) { + const valid = getType(val) === type; + if (!valid) { + throw new TypeError(`Property ${key} expected type of ${type} but got ${getType(val)}`); + } + } + validate.type = type; + return validate; + } + function assertShape(shape) { + function validate(node, key, val) { + const errors = []; + for (const property of Object.keys(shape)) { + try { + (0, _validate.validateField)(node, property, val[property], shape[property]); + } catch (error) { + if (error instanceof TypeError) { + errors.push(error.message); + continue; + } + throw error; + } + } + if (errors.length) { + throw new TypeError(`Property ${key} of ${node.type} expected to have the following:\n${errors.join("\n")}`); + } + } + validate.shapeOf = shape; + return validate; + } + function assertOptionalChainStart() { + function validate(node) { + var _current; + let current = node; + while (node) { + const { + type + } = current; + if (type === "OptionalCallExpression") { + if (current.optional) return; + current = current.callee; + continue; + } + if (type === "OptionalMemberExpression") { + if (current.optional) return; + current = current.object; + continue; + } + break; + } + throw new TypeError(`Non-optional ${node.type} must chain from an optional OptionalMemberExpression or OptionalCallExpression. Found chain from ${(_current = current) == null ? void 0 : _current.type}`); + } + return validate; + } + function chain(...fns) { + function validate(...args) { + for (const fn of fns) { + fn(...args); + } + } + validate.chainOf = fns; + if (fns.length >= 2 && "type" in fns[0] && fns[0].type === "array" && !("each" in fns[1])) { + throw new Error(`An assertValueType("array") validator can only be followed by an assertEach(...) validator.`); + } + return validate; + } + const validTypeOpts = new Set(["aliases", "builder", "deprecatedAlias", "fields", "inherits", "visitor", "validate"]); + const validFieldKeys = new Set(["default", "optional", "deprecated", "validate"]); + const store = {}; + function defineAliasedType(...aliases) { + return (type, opts = {}) => { + let defined = opts.aliases; + if (!defined) { + var _store$opts$inherits$, _defined; + if (opts.inherits) defined = (_store$opts$inherits$ = store[opts.inherits].aliases) == null ? void 0 : _store$opts$inherits$.slice(); + (_defined = defined) != null ? _defined : defined = []; + opts.aliases = defined; + } + const additional = aliases.filter(a => !defined.includes(a)); + defined.unshift(...additional); + defineType(type, opts); + }; + } + function defineType(type, opts = {}) { + const inherits = opts.inherits && store[opts.inherits] || {}; + let fields = opts.fields; + if (!fields) { + fields = {}; + if (inherits.fields) { + const keys = Object.getOwnPropertyNames(inherits.fields); + for (const key of keys) { + const field = inherits.fields[key]; + const def = field.default; + if (Array.isArray(def) ? def.length > 0 : def && typeof def === "object") { + throw new Error("field defaults can only be primitives or empty arrays currently"); + } + fields[key] = { + default: Array.isArray(def) ? [] : def, + optional: field.optional, + deprecated: field.deprecated, + validate: field.validate + }; + } + } + } + const visitor = opts.visitor || inherits.visitor || []; + const aliases = opts.aliases || inherits.aliases || []; + const builder = opts.builder || inherits.builder || opts.visitor || []; + for (const k of Object.keys(opts)) { + if (!validTypeOpts.has(k)) { + throw new Error(`Unknown type option "${k}" on ${type}`); + } + } + if (opts.deprecatedAlias) { + DEPRECATED_KEYS[opts.deprecatedAlias] = type; + } + for (const key of visitor.concat(builder)) { + fields[key] = fields[key] || {}; + } + for (const key of Object.keys(fields)) { + const field = fields[key]; + if (field.default !== undefined && !builder.includes(key)) { + field.optional = true; + } + if (field.default === undefined) { + field.default = null; + } else if (!field.validate && field.default != null) { + field.validate = assertValueType(getType(field.default)); + } + for (const k of Object.keys(field)) { + if (!validFieldKeys.has(k)) { + throw new Error(`Unknown field key "${k}" on ${type}.${key}`); + } + } + } + VISITOR_KEYS[type] = opts.visitor = visitor; + BUILDER_KEYS[type] = opts.builder = builder; + NODE_FIELDS[type] = opts.fields = fields; + ALIAS_KEYS[type] = opts.aliases = aliases; + aliases.forEach(alias => { + FLIPPED_ALIAS_KEYS[alias] = FLIPPED_ALIAS_KEYS[alias] || []; + FLIPPED_ALIAS_KEYS[alias].push(type); + }); + if (opts.validate) { + NODE_PARENT_VALIDATIONS[type] = opts.validate; + } + store[type] = opts; + } + + + return utils; +} + +var hasRequiredCore; + +function requireCore () { + if (hasRequiredCore) return core; + hasRequiredCore = 1; + + Object.defineProperty(core, "__esModule", { + value: true + }); + core.patternLikeCommon = core.importAttributes = core.functionTypeAnnotationCommon = core.functionDeclarationCommon = core.functionCommon = core.classMethodOrPropertyCommon = core.classMethodOrDeclareMethodCommon = void 0; + var _is = requireIs(); + var _isValidIdentifier = requireIsValidIdentifier(); + var _helperValidatorIdentifier = requireLib$3(); + var _helperStringParser = requireLib$2(); + var _index = requireConstants(); + var _utils = requireUtils(); + const defineType = (0, _utils.defineAliasedType)("Standardized"); + defineType("ArrayExpression", { + fields: { + elements: { + validate: (0, _utils.arrayOf)((0, _utils.assertNodeOrValueType)("null", "Expression", "SpreadElement")), + default: !process.env.BABEL_TYPES_8_BREAKING ? [] : undefined + } + }, + visitor: ["elements"], + aliases: ["Expression"] + }); + defineType("AssignmentExpression", { + fields: { + operator: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertValueType)("string") : Object.assign(function () { + const identifier = (0, _utils.assertOneOf)(..._index.ASSIGNMENT_OPERATORS); + const pattern = (0, _utils.assertOneOf)("="); + return function (node, key, val) { + const validator = (0, _is.default)("Pattern", node.left) ? pattern : identifier; + validator(node, key, val); + }; + }(), { + type: "string" + }) + }, + left: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal", "OptionalMemberExpression") : (0, _utils.assertNodeType)("Identifier", "MemberExpression", "OptionalMemberExpression", "ArrayPattern", "ObjectPattern", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + builder: ["operator", "left", "right"], + visitor: ["left", "right"], + aliases: ["Expression"] + }); + defineType("BinaryExpression", { + builder: ["operator", "left", "right"], + fields: { + operator: { + validate: (0, _utils.assertOneOf)(..._index.BINARY_OPERATORS) + }, + left: { + validate: function () { + const expression = (0, _utils.assertNodeType)("Expression"); + const inOp = (0, _utils.assertNodeType)("Expression", "PrivateName"); + const validator = Object.assign(function (node, key, val) { + const validator = node.operator === "in" ? inOp : expression; + validator(node, key, val); + }, { + oneOfNodeTypes: ["Expression", "PrivateName"] + }); + return validator; + }() + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + visitor: ["left", "right"], + aliases: ["Binary", "Expression"] + }); + defineType("InterpreterDirective", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + defineType("Directive", { + visitor: ["value"], + fields: { + value: { + validate: (0, _utils.assertNodeType)("DirectiveLiteral") + } + } + }); + defineType("DirectiveLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + defineType("BlockStatement", { + builder: ["body", "directives"], + visitor: ["directives", "body"], + fields: { + directives: { + validate: (0, _utils.arrayOfType)("Directive"), + default: [] + }, + body: (0, _utils.validateArrayOfType)("Statement") + }, + aliases: ["Scopable", "BlockParent", "Block", "Statement"] + }); + defineType("BreakStatement", { + visitor: ["label"], + fields: { + label: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + } + }, + aliases: ["Statement", "Terminatorless", "CompletionStatement"] + }); + defineType("CallExpression", { + visitor: ["callee", "arguments", "typeParameters", "typeArguments"], + builder: ["callee", "arguments"], + aliases: ["Expression"], + fields: Object.assign({ + callee: { + validate: (0, _utils.assertNodeType)("Expression", "Super", "V8IntrinsicIdentifier") + }, + arguments: (0, _utils.validateArrayOfType)("Expression", "SpreadElement", "ArgumentPlaceholder") + }, !process.env.BABEL_TYPES_8_BREAKING ? { + optional: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + } : {}, { + typeArguments: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TSTypeParameterInstantiation"), + optional: true + } + }) + }); + defineType("CatchClause", { + visitor: ["param", "body"], + fields: { + param: { + validate: (0, _utils.assertNodeType)("Identifier", "ArrayPattern", "ObjectPattern"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }, + aliases: ["Scopable", "BlockParent"] + }); + defineType("ConditionalExpression", { + visitor: ["test", "consequent", "alternate"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + consequent: { + validate: (0, _utils.assertNodeType)("Expression") + }, + alternate: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + aliases: ["Expression", "Conditional"] + }); + defineType("ContinueStatement", { + visitor: ["label"], + fields: { + label: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + } + }, + aliases: ["Statement", "Terminatorless", "CompletionStatement"] + }); + defineType("DebuggerStatement", { + aliases: ["Statement"] + }); + defineType("DoWhileStatement", { + builder: ["test", "body"], + visitor: ["body", "test"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + }, + aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"] + }); + defineType("EmptyStatement", { + aliases: ["Statement"] + }); + defineType("ExpressionStatement", { + visitor: ["expression"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + aliases: ["Statement", "ExpressionWrapper"] + }); + defineType("File", { + builder: ["program", "comments", "tokens"], + visitor: ["program"], + fields: { + program: { + validate: (0, _utils.assertNodeType)("Program") + }, + comments: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? Object.assign(() => {}, { + each: { + oneOfNodeTypes: ["CommentBlock", "CommentLine"] + } + }) : (0, _utils.assertEach)((0, _utils.assertNodeType)("CommentBlock", "CommentLine")), + optional: true + }, + tokens: { + validate: (0, _utils.assertEach)(Object.assign(() => {}, { + type: "any" + })), + optional: true + } + } + }); + defineType("ForInStatement", { + visitor: ["left", "right", "body"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], + fields: { + left: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("VariableDeclaration", "LVal") : (0, _utils.assertNodeType)("VariableDeclaration", "Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + defineType("ForStatement", { + visitor: ["init", "test", "update", "body"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"], + fields: { + init: { + validate: (0, _utils.assertNodeType)("VariableDeclaration", "Expression"), + optional: true + }, + test: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + update: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + const functionCommon = () => ({ + params: (0, _utils.validateArrayOfType)("Identifier", "Pattern", "RestElement"), + generator: { + default: false + }, + async: { + default: false + } + }); + core.functionCommon = functionCommon; + const functionTypeAnnotationCommon = () => ({ + returnType: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), + optional: true + } + }); + core.functionTypeAnnotationCommon = functionTypeAnnotationCommon; + const functionDeclarationCommon = () => Object.assign({}, functionCommon(), { + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + id: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + } + }); + core.functionDeclarationCommon = functionDeclarationCommon; + defineType("FunctionDeclaration", { + builder: ["id", "params", "body", "generator", "async"], + visitor: ["id", "typeParameters", "params", "returnType", "body"], + fields: Object.assign({}, functionDeclarationCommon(), functionTypeAnnotationCommon(), { + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + }, + predicate: { + validate: (0, _utils.assertNodeType)("DeclaredPredicate", "InferredPredicate"), + optional: true + } + }), + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"], + validate: !process.env.BABEL_TYPES_8_BREAKING ? undefined : function () { + const identifier = (0, _utils.assertNodeType)("Identifier"); + return function (parent, key, node) { + if (!(0, _is.default)("ExportDefaultDeclaration", parent)) { + identifier(node, "id", node.id); + } + }; + }() + }); + defineType("FunctionExpression", { + inherits: "FunctionDeclaration", + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], + fields: Object.assign({}, functionCommon(), functionTypeAnnotationCommon(), { + id: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + }, + predicate: { + validate: (0, _utils.assertNodeType)("DeclaredPredicate", "InferredPredicate"), + optional: true + } + }) + }); + const patternLikeCommon = () => ({ + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + optional: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + } + }); + core.patternLikeCommon = patternLikeCommon; + defineType("Identifier", { + builder: ["name"], + visitor: ["typeAnnotation", "decorators"], + aliases: ["Expression", "PatternLike", "LVal", "TSEntityName"], + fields: Object.assign({}, patternLikeCommon(), { + name: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertValueType)("string"), Object.assign(function (node, key, val) { + if (!(0, _isValidIdentifier.default)(val, false)) { + throw new TypeError(`"${val}" is not a valid identifier name`); + } + }, { + type: "string" + })) : (0, _utils.assertValueType)("string") + } + }), + validate: process.env.BABEL_TYPES_8_BREAKING ? function (parent, key, node) { + const match = /\.(\w+)$/.exec(key); + if (!match) return; + const [, parentKey] = match; + const nonComp = { + computed: false + }; + if (parentKey === "property") { + if ((0, _is.default)("MemberExpression", parent, nonComp)) return; + if ((0, _is.default)("OptionalMemberExpression", parent, nonComp)) return; + } else if (parentKey === "key") { + if ((0, _is.default)("Property", parent, nonComp)) return; + if ((0, _is.default)("Method", parent, nonComp)) return; + } else if (parentKey === "exported") { + if ((0, _is.default)("ExportSpecifier", parent)) return; + } else if (parentKey === "imported") { + if ((0, _is.default)("ImportSpecifier", parent, { + imported: node + })) return; + } else if (parentKey === "meta") { + if ((0, _is.default)("MetaProperty", parent, { + meta: node + })) return; + } + if (((0, _helperValidatorIdentifier.isKeyword)(node.name) || (0, _helperValidatorIdentifier.isReservedWord)(node.name, false)) && node.name !== "this") { + throw new TypeError(`"${node.name}" is not a valid identifier`); + } + } : undefined + }); + defineType("IfStatement", { + visitor: ["test", "consequent", "alternate"], + aliases: ["Statement", "Conditional"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + consequent: { + validate: (0, _utils.assertNodeType)("Statement") + }, + alternate: { + optional: true, + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + defineType("LabeledStatement", { + visitor: ["label", "body"], + aliases: ["Statement"], + fields: { + label: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + defineType("StringLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + defineType("NumericLiteral", { + builder: ["value"], + deprecatedAlias: "NumberLiteral", + fields: { + value: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("number"), Object.assign(function (node, key, val) { + }, { + type: "number" + })) + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + defineType("NullLiteral", { + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + defineType("BooleanLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("boolean") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + defineType("RegExpLiteral", { + builder: ["pattern", "flags"], + deprecatedAlias: "RegexLiteral", + aliases: ["Expression", "Pureish", "Literal"], + fields: { + pattern: { + validate: (0, _utils.assertValueType)("string") + }, + flags: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertValueType)("string"), Object.assign(function (node, key, val) { + const invalid = /[^gimsuy]/.exec(val); + if (invalid) { + throw new TypeError(`"${invalid[0]}" is not a valid RegExp flag`); + } + }, { + type: "string" + })) : (0, _utils.assertValueType)("string"), + default: "" + } + } + }); + defineType("LogicalExpression", { + builder: ["operator", "left", "right"], + visitor: ["left", "right"], + aliases: ["Binary", "Expression"], + fields: { + operator: { + validate: (0, _utils.assertOneOf)(..._index.LOGICAL_OPERATORS) + }, + left: { + validate: (0, _utils.assertNodeType)("Expression") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("MemberExpression", { + builder: ["object", "property", "computed", ...(!process.env.BABEL_TYPES_8_BREAKING ? ["optional"] : [])], + visitor: ["object", "property"], + aliases: ["Expression", "LVal"], + fields: Object.assign({ + object: { + validate: (0, _utils.assertNodeType)("Expression", "Super") + }, + property: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier", "PrivateName"); + const computed = (0, _utils.assertNodeType)("Expression"); + const validator = function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + validator.oneOfNodeTypes = ["Expression", "Identifier", "PrivateName"]; + return validator; + }() + }, + computed: { + default: false + } + }, !process.env.BABEL_TYPES_8_BREAKING ? { + optional: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + } : {}) + }); + defineType("NewExpression", { + inherits: "CallExpression" + }); + defineType("Program", { + visitor: ["directives", "body"], + builder: ["body", "directives", "sourceType", "interpreter"], + fields: { + sourceType: { + validate: (0, _utils.assertOneOf)("script", "module"), + default: "script" + }, + interpreter: { + validate: (0, _utils.assertNodeType)("InterpreterDirective"), + default: null, + optional: true + }, + directives: { + validate: (0, _utils.arrayOfType)("Directive"), + default: [] + }, + body: (0, _utils.validateArrayOfType)("Statement") + }, + aliases: ["Scopable", "BlockParent", "Block"] + }); + defineType("ObjectExpression", { + visitor: ["properties"], + aliases: ["Expression"], + fields: { + properties: (0, _utils.validateArrayOfType)("ObjectMethod", "ObjectProperty", "SpreadElement") + } + }); + defineType("ObjectMethod", { + builder: ["kind", "key", "params", "body", "computed", "generator", "async"], + visitor: ["decorators", "key", "typeParameters", "params", "returnType", "body"], + fields: Object.assign({}, functionCommon(), functionTypeAnnotationCommon(), { + kind: Object.assign({ + validate: (0, _utils.assertOneOf)("method", "get", "set") + }, !process.env.BABEL_TYPES_8_BREAKING ? { + default: "method" + } : {}), + computed: { + default: false + }, + key: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral"); + const computed = (0, _utils.assertNodeType)("Expression"); + const validator = function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + validator.oneOfNodeTypes = ["Expression", "Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral"]; + return validator; + }() + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }), + aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"] + }); + defineType("ObjectProperty", { + builder: ["key", "value", "computed", "shorthand", ...(!process.env.BABEL_TYPES_8_BREAKING ? ["decorators"] : [])], + fields: { + computed: { + default: false + }, + key: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "DecimalLiteral", "PrivateName"); + const computed = (0, _utils.assertNodeType)("Expression"); + const validator = Object.assign(function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }, { + oneOfNodeTypes: ["Expression", "Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "DecimalLiteral", "PrivateName"] + }); + return validator; + }() + }, + value: { + validate: (0, _utils.assertNodeType)("Expression", "PatternLike") + }, + shorthand: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertValueType)("boolean"), Object.assign(function (node, key, shorthand) { + if (!shorthand) return; + if (node.computed) { + throw new TypeError("Property shorthand of ObjectProperty cannot be true if computed is true"); + } + if (!(0, _is.default)("Identifier", node.key)) { + throw new TypeError("Property shorthand of ObjectProperty cannot be true if key is not an Identifier"); + } + }, { + type: "boolean" + })) : (0, _utils.assertValueType)("boolean"), + default: false + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + } + }, + visitor: ["key", "value", "decorators"], + aliases: ["UserWhitespacable", "Property", "ObjectMember"], + validate: !process.env.BABEL_TYPES_8_BREAKING ? undefined : function () { + const pattern = (0, _utils.assertNodeType)("Identifier", "Pattern", "TSAsExpression", "TSSatisfiesExpression", "TSNonNullExpression", "TSTypeAssertion"); + const expression = (0, _utils.assertNodeType)("Expression"); + return function (parent, key, node) { + const validator = (0, _is.default)("ObjectPattern", parent) ? pattern : expression; + validator(node, "value", node.value); + }; + }() + }); + defineType("RestElement", { + visitor: ["argument", "typeAnnotation"], + builder: ["argument"], + aliases: ["LVal", "PatternLike"], + deprecatedAlias: "RestProperty", + fields: Object.assign({}, patternLikeCommon(), { + argument: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal") : (0, _utils.assertNodeType)("Identifier", "ArrayPattern", "ObjectPattern", "MemberExpression", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression") + } + }), + validate: process.env.BABEL_TYPES_8_BREAKING ? function (parent, key) { + const match = /(\w+)\[(\d+)\]/.exec(key); + if (!match) throw new Error("Internal Babel error: malformed key."); + const [, listKey, index] = match; + if (parent[listKey].length > +index + 1) { + throw new TypeError(`RestElement must be last element of ${listKey}`); + } + } : undefined + }); + defineType("ReturnStatement", { + visitor: ["argument"], + aliases: ["Statement", "Terminatorless", "CompletionStatement"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + } + } + }); + defineType("SequenceExpression", { + visitor: ["expressions"], + fields: { + expressions: (0, _utils.validateArrayOfType)("Expression") + }, + aliases: ["Expression"] + }); + defineType("ParenthesizedExpression", { + visitor: ["expression"], + aliases: ["Expression", "ExpressionWrapper"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("SwitchCase", { + visitor: ["test", "consequent"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + consequent: (0, _utils.validateArrayOfType)("Statement") + } + }); + defineType("SwitchStatement", { + visitor: ["discriminant", "cases"], + aliases: ["Statement", "BlockParent", "Scopable"], + fields: { + discriminant: { + validate: (0, _utils.assertNodeType)("Expression") + }, + cases: (0, _utils.validateArrayOfType)("SwitchCase") + } + }); + defineType("ThisExpression", { + aliases: ["Expression"] + }); + defineType("ThrowStatement", { + visitor: ["argument"], + aliases: ["Statement", "Terminatorless", "CompletionStatement"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("TryStatement", { + visitor: ["block", "handler", "finalizer"], + aliases: ["Statement"], + fields: { + block: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertNodeType)("BlockStatement"), Object.assign(function (node) { + if (!node.handler && !node.finalizer) { + throw new TypeError("TryStatement expects either a handler or finalizer, or both"); + } + }, { + oneOfNodeTypes: ["BlockStatement"] + })) : (0, _utils.assertNodeType)("BlockStatement") + }, + handler: { + optional: true, + validate: (0, _utils.assertNodeType)("CatchClause") + }, + finalizer: { + optional: true, + validate: (0, _utils.assertNodeType)("BlockStatement") + } + } + }); + defineType("UnaryExpression", { + builder: ["operator", "argument", "prefix"], + fields: { + prefix: { + default: true + }, + argument: { + validate: (0, _utils.assertNodeType)("Expression") + }, + operator: { + validate: (0, _utils.assertOneOf)(..._index.UNARY_OPERATORS) + } + }, + visitor: ["argument"], + aliases: ["UnaryLike", "Expression"] + }); + defineType("UpdateExpression", { + builder: ["operator", "argument", "prefix"], + fields: { + prefix: { + default: false + }, + argument: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("Expression") : (0, _utils.assertNodeType)("Identifier", "MemberExpression") + }, + operator: { + validate: (0, _utils.assertOneOf)(..._index.UPDATE_OPERATORS) + } + }, + visitor: ["argument"], + aliases: ["Expression"] + }); + defineType("VariableDeclaration", { + builder: ["kind", "declarations"], + visitor: ["declarations"], + aliases: ["Statement", "Declaration"], + fields: { + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + kind: { + validate: (0, _utils.assertOneOf)("var", "let", "const", "using", "await using") + }, + declarations: (0, _utils.validateArrayOfType)("VariableDeclarator") + }, + validate: process.env.BABEL_TYPES_8_BREAKING ? (() => { + const withoutInit = (0, _utils.assertNodeType)("Identifier"); + return function (parent, key, node) { + if ((0, _is.default)("ForXStatement", parent, { + left: node + })) { + if (node.declarations.length !== 1) { + throw new TypeError(`Exactly one VariableDeclarator is required in the VariableDeclaration of a ${parent.type}`); + } + } else { + node.declarations.forEach(decl => { + if (!decl.init) withoutInit(decl, "id", decl.id); + }); + } + }; + })() : undefined + }); + defineType("VariableDeclarator", { + visitor: ["id", "init"], + fields: { + id: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal") : (0, _utils.assertNodeType)("Identifier", "ArrayPattern", "ObjectPattern") + }, + definite: { + optional: true, + validate: (0, _utils.assertValueType)("boolean") + }, + init: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("WhileStatement", { + visitor: ["test", "body"], + aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + defineType("WithStatement", { + visitor: ["object", "body"], + aliases: ["Statement"], + fields: { + object: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + defineType("AssignmentPattern", { + visitor: ["left", "right", "decorators"], + builder: ["left", "right"], + aliases: ["Pattern", "PatternLike", "LVal"], + fields: Object.assign({}, patternLikeCommon(), { + left: { + validate: (0, _utils.assertNodeType)("Identifier", "ObjectPattern", "ArrayPattern", "MemberExpression", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + } + }) + }); + defineType("ArrayPattern", { + visitor: ["elements", "typeAnnotation"], + builder: ["elements"], + aliases: ["Pattern", "PatternLike", "LVal"], + fields: Object.assign({}, patternLikeCommon(), { + elements: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeOrValueType)("null", "PatternLike", "LVal"))) + } + }) + }); + defineType("ArrowFunctionExpression", { + builder: ["params", "body", "async"], + visitor: ["typeParameters", "params", "returnType", "body"], + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], + fields: Object.assign({}, functionCommon(), functionTypeAnnotationCommon(), { + expression: { + validate: (0, _utils.assertValueType)("boolean") + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement", "Expression") + }, + predicate: { + validate: (0, _utils.assertNodeType)("DeclaredPredicate", "InferredPredicate"), + optional: true + } + }) + }); + defineType("ClassBody", { + visitor: ["body"], + fields: { + body: (0, _utils.validateArrayOfType)("ClassMethod", "ClassPrivateMethod", "ClassProperty", "ClassPrivateProperty", "ClassAccessorProperty", "TSDeclareMethod", "TSIndexSignature", "StaticBlock") + } + }); + defineType("ClassExpression", { + builder: ["id", "superClass", "body", "decorators"], + visitor: ["decorators", "id", "typeParameters", "superClass", "superTypeParameters", "mixins", "implements", "body"], + aliases: ["Scopable", "Class", "Expression"], + fields: { + id: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("ClassBody") + }, + superClass: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + }, + superTypeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + }, + implements: { + validate: (0, _utils.arrayOfType)("TSExpressionWithTypeArguments", "ClassImplements"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + mixins: { + validate: (0, _utils.assertNodeType)("InterfaceExtends"), + optional: true + } + } + }); + defineType("ClassDeclaration", { + inherits: "ClassExpression", + aliases: ["Scopable", "Class", "Statement", "Declaration"], + fields: { + id: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("ClassBody") + }, + superClass: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + }, + superTypeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + }, + implements: { + validate: (0, _utils.arrayOfType)("TSExpressionWithTypeArguments", "ClassImplements"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + mixins: { + validate: (0, _utils.assertNodeType)("InterfaceExtends"), + optional: true + }, + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + abstract: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + }, + validate: !process.env.BABEL_TYPES_8_BREAKING ? undefined : function () { + const identifier = (0, _utils.assertNodeType)("Identifier"); + return function (parent, key, node) { + if (!(0, _is.default)("ExportDefaultDeclaration", parent)) { + identifier(node, "id", node.id); + } + }; + }() + }); + const importAttributes = core.importAttributes = { + attributes: { + optional: true, + validate: (0, _utils.arrayOfType)("ImportAttribute") + }, + assertions: { + deprecated: true, + optional: true, + validate: (0, _utils.arrayOfType)("ImportAttribute") + } + }; + defineType("ExportAllDeclaration", { + builder: ["source"], + visitor: ["source", "attributes", "assertions"], + aliases: ["Statement", "Declaration", "ImportOrExportDeclaration", "ExportDeclaration"], + fields: Object.assign({ + source: { + validate: (0, _utils.assertNodeType)("StringLiteral") + }, + exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("type", "value")) + }, importAttributes) + }); + defineType("ExportDefaultDeclaration", { + visitor: ["declaration"], + aliases: ["Statement", "Declaration", "ImportOrExportDeclaration", "ExportDeclaration"], + fields: { + declaration: (0, _utils.validateType)("TSDeclareFunction", "FunctionDeclaration", "ClassDeclaration", "Expression"), + exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("value")) + } + }); + defineType("ExportNamedDeclaration", { + builder: ["declaration", "specifiers", "source"], + visitor: process.env ? ["declaration", "specifiers", "source", "attributes"] : ["declaration", "specifiers", "source", "attributes", "assertions"], + aliases: ["Statement", "Declaration", "ImportOrExportDeclaration", "ExportDeclaration"], + fields: Object.assign({ + declaration: { + optional: true, + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertNodeType)("Declaration"), Object.assign(function (node, key, val) { + if (val && node.specifiers.length) { + throw new TypeError("Only declaration or specifiers is allowed on ExportNamedDeclaration"); + } + if (val && node.source) { + throw new TypeError("Cannot export a declaration from a source"); + } + }, { + oneOfNodeTypes: ["Declaration"] + })) : (0, _utils.assertNodeType)("Declaration") + } + }, importAttributes, { + specifiers: { + default: [], + validate: (0, _utils.arrayOf)(function () { + const sourced = (0, _utils.assertNodeType)("ExportSpecifier", "ExportDefaultSpecifier", "ExportNamespaceSpecifier"); + const sourceless = (0, _utils.assertNodeType)("ExportSpecifier"); + if (!process.env.BABEL_TYPES_8_BREAKING) return sourced; + return Object.assign(function (node, key, val) { + const validator = node.source ? sourced : sourceless; + validator(node, key, val); + }, { + oneOfNodeTypes: ["ExportSpecifier", "ExportDefaultSpecifier", "ExportNamespaceSpecifier"] + }); + }()) + }, + source: { + validate: (0, _utils.assertNodeType)("StringLiteral"), + optional: true + }, + exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("type", "value")) + }) + }); + defineType("ExportSpecifier", { + visitor: ["local", "exported"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + exported: { + validate: (0, _utils.assertNodeType)("Identifier", "StringLiteral") + }, + exportKind: { + validate: (0, _utils.assertOneOf)("type", "value"), + optional: true + } + } + }); + defineType("ForOfStatement", { + visitor: ["left", "right", "body"], + builder: ["left", "right", "body", "await"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], + fields: { + left: { + validate: function () { + if (!process.env.BABEL_TYPES_8_BREAKING) { + return (0, _utils.assertNodeType)("VariableDeclaration", "LVal"); + } + const declaration = (0, _utils.assertNodeType)("VariableDeclaration"); + const lval = (0, _utils.assertNodeType)("Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression"); + return Object.assign(function (node, key, val) { + if ((0, _is.default)("VariableDeclaration", val)) { + declaration(node, key, val); + } else { + lval(node, key, val); + } + }, { + oneOfNodeTypes: ["VariableDeclaration", "Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression"] + }); + }() + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + }, + await: { + default: false + } + } + }); + defineType("ImportDeclaration", { + builder: ["specifiers", "source"], + visitor: ["specifiers", "source", "attributes", "assertions"], + aliases: ["Statement", "Declaration", "ImportOrExportDeclaration"], + fields: Object.assign({}, importAttributes, { + module: { + optional: true, + validate: (0, _utils.assertValueType)("boolean") + }, + phase: { + default: null, + validate: (0, _utils.assertOneOf)("source", "defer") + }, + specifiers: (0, _utils.validateArrayOfType)("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier"), + source: { + validate: (0, _utils.assertNodeType)("StringLiteral") + }, + importKind: { + validate: (0, _utils.assertOneOf)("type", "typeof", "value"), + optional: true + } + }) + }); + defineType("ImportDefaultSpecifier", { + visitor: ["local"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + defineType("ImportNamespaceSpecifier", { + visitor: ["local"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + defineType("ImportSpecifier", { + visitor: ["imported", "local"], + builder: ["local", "imported"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + imported: { + validate: (0, _utils.assertNodeType)("Identifier", "StringLiteral") + }, + importKind: { + validate: (0, _utils.assertOneOf)("type", "typeof", "value"), + optional: true + } + } + }); + defineType("ImportExpression", { + visitor: ["source", "options"], + aliases: ["Expression"], + fields: { + phase: { + default: null, + validate: (0, _utils.assertOneOf)("source", "defer") + }, + source: { + validate: (0, _utils.assertNodeType)("Expression") + }, + options: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + } + } + }); + defineType("MetaProperty", { + visitor: ["meta", "property"], + aliases: ["Expression"], + fields: { + meta: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertNodeType)("Identifier"), Object.assign(function (node, key, val) { + let property; + switch (val.name) { + case "function": + property = "sent"; + break; + case "new": + property = "target"; + break; + case "import": + property = "meta"; + break; + } + if (!(0, _is.default)("Identifier", node.property, { + name: property + })) { + throw new TypeError("Unrecognised MetaProperty"); + } + }, { + oneOfNodeTypes: ["Identifier"] + })) : (0, _utils.assertNodeType)("Identifier") + }, + property: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + const classMethodOrPropertyCommon = () => ({ + abstract: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + accessibility: { + validate: (0, _utils.assertOneOf)("public", "private", "protected"), + optional: true + }, + static: { + default: false + }, + override: { + default: false + }, + computed: { + default: false + }, + optional: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + key: { + validate: (0, _utils.chain)(function () { + const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral"); + const computed = (0, _utils.assertNodeType)("Expression"); + return function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + }(), (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "Expression")) + } + }); + core.classMethodOrPropertyCommon = classMethodOrPropertyCommon; + const classMethodOrDeclareMethodCommon = () => Object.assign({}, functionCommon(), classMethodOrPropertyCommon(), { + params: (0, _utils.validateArrayOfType)("Identifier", "Pattern", "RestElement", "TSParameterProperty"), + kind: { + validate: (0, _utils.assertOneOf)("get", "set", "method", "constructor"), + default: "method" + }, + access: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("public", "private", "protected")), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + } + }); + core.classMethodOrDeclareMethodCommon = classMethodOrDeclareMethodCommon; + defineType("ClassMethod", { + aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], + builder: ["kind", "key", "params", "body", "computed", "static", "generator", "async"], + visitor: ["decorators", "key", "typeParameters", "params", "returnType", "body"], + fields: Object.assign({}, classMethodOrDeclareMethodCommon(), functionTypeAnnotationCommon(), { + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }) + }); + defineType("ObjectPattern", { + visitor: ["properties", "typeAnnotation", "decorators"], + builder: ["properties"], + aliases: ["Pattern", "PatternLike", "LVal"], + fields: Object.assign({}, patternLikeCommon(), { + properties: (0, _utils.validateArrayOfType)("RestElement", "ObjectProperty") + }) + }); + defineType("SpreadElement", { + visitor: ["argument"], + aliases: ["UnaryLike"], + deprecatedAlias: "SpreadProperty", + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("Super", { + aliases: ["Expression"] + }); + defineType("TaggedTemplateExpression", { + visitor: ["tag", "typeParameters", "quasi"], + builder: ["tag", "quasi"], + aliases: ["Expression"], + fields: { + tag: { + validate: (0, _utils.assertNodeType)("Expression") + }, + quasi: { + validate: (0, _utils.assertNodeType)("TemplateLiteral") + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + } + } + }); + defineType("TemplateElement", { + builder: ["value", "tail"], + fields: { + value: { + validate: (0, _utils.chain)((0, _utils.assertShape)({ + raw: { + validate: (0, _utils.assertValueType)("string") + }, + cooked: { + validate: (0, _utils.assertValueType)("string"), + optional: true + } + }), function templateElementCookedValidator(node) { + const raw = node.value.raw; + let unterminatedCalled = false; + const error = () => { + throw new Error("Internal @babel/types error."); + }; + const { + str, + firstInvalidLoc + } = (0, _helperStringParser.readStringContents)("template", raw, 0, 0, 0, { + unterminated() { + unterminatedCalled = true; + }, + strictNumericEscape: error, + invalidEscapeSequence: error, + numericSeparatorInEscapeSequence: error, + unexpectedNumericSeparator: error, + invalidDigit: error, + invalidCodePoint: error + }); + if (!unterminatedCalled) throw new Error("Invalid raw"); + node.value.cooked = firstInvalidLoc ? null : str; + }) + }, + tail: { + default: false + } + } + }); + defineType("TemplateLiteral", { + visitor: ["quasis", "expressions"], + aliases: ["Expression", "Literal"], + fields: { + quasis: (0, _utils.validateArrayOfType)("TemplateElement"), + expressions: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "TSType")), function (node, key, val) { + if (node.quasis.length !== val.length + 1) { + throw new TypeError(`Number of ${node.type} quasis should be exactly one more than the number of expressions.\nExpected ${val.length + 1} quasis but got ${node.quasis.length}`); + } + }) + } + } + }); + defineType("YieldExpression", { + builder: ["argument", "delegate"], + visitor: ["argument"], + aliases: ["Expression", "Terminatorless"], + fields: { + delegate: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertValueType)("boolean"), Object.assign(function (node, key, val) { + if (val && !node.argument) { + throw new TypeError("Property delegate of YieldExpression cannot be true if there is no argument"); + } + }, { + type: "boolean" + })) : (0, _utils.assertValueType)("boolean"), + default: false + }, + argument: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("AwaitExpression", { + builder: ["argument"], + visitor: ["argument"], + aliases: ["Expression", "Terminatorless"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("Import", { + aliases: ["Expression"] + }); + defineType("BigIntLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + defineType("ExportNamespaceSpecifier", { + visitor: ["exported"], + aliases: ["ModuleSpecifier"], + fields: { + exported: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + defineType("OptionalMemberExpression", { + builder: ["object", "property", "computed", "optional"], + visitor: ["object", "property"], + aliases: ["Expression"], + fields: { + object: { + validate: (0, _utils.assertNodeType)("Expression") + }, + property: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier"); + const computed = (0, _utils.assertNodeType)("Expression"); + const validator = Object.assign(function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }, { + oneOfNodeTypes: ["Expression", "Identifier"] + }); + return validator; + }() + }, + computed: { + default: false + }, + optional: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertValueType)("boolean") : (0, _utils.chain)((0, _utils.assertValueType)("boolean"), (0, _utils.assertOptionalChainStart)()) + } + } + }); + defineType("OptionalCallExpression", { + visitor: ["callee", "arguments", "typeParameters", "typeArguments"], + builder: ["callee", "arguments", "optional"], + aliases: ["Expression"], + fields: { + callee: { + validate: (0, _utils.assertNodeType)("Expression") + }, + arguments: (0, _utils.validateArrayOfType)("Expression", "SpreadElement", "ArgumentPlaceholder"), + optional: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertValueType)("boolean") : (0, _utils.chain)((0, _utils.assertValueType)("boolean"), (0, _utils.assertOptionalChainStart)()) + }, + typeArguments: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TSTypeParameterInstantiation"), + optional: true + } + } + }); + defineType("ClassProperty", { + visitor: ["decorators", "key", "typeAnnotation", "value"], + builder: ["key", "value", "typeAnnotation", "decorators", "computed", "static"], + aliases: ["Property"], + fields: Object.assign({}, classMethodOrPropertyCommon(), { + value: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + definite: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + readonly: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + variance: { + validate: (0, _utils.assertNodeType)("Variance"), + optional: true + } + }) + }); + defineType("ClassAccessorProperty", { + visitor: ["decorators", "key", "typeAnnotation", "value"], + builder: ["key", "value", "typeAnnotation", "decorators", "computed", "static"], + aliases: ["Property", "Accessor"], + fields: Object.assign({}, classMethodOrPropertyCommon(), { + key: { + validate: (0, _utils.chain)(function () { + const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "PrivateName"); + const computed = (0, _utils.assertNodeType)("Expression"); + return function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + }(), (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "Expression", "PrivateName")) + }, + value: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + definite: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + readonly: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + variance: { + validate: (0, _utils.assertNodeType)("Variance"), + optional: true + } + }) + }); + defineType("ClassPrivateProperty", { + visitor: ["decorators", "key", "typeAnnotation", "value"], + builder: ["key", "value", "decorators", "static"], + aliases: ["Property", "Private"], + fields: { + key: { + validate: (0, _utils.assertNodeType)("PrivateName") + }, + value: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + static: { + validate: (0, _utils.assertValueType)("boolean"), + default: false + }, + readonly: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + definite: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + variance: { + validate: (0, _utils.assertNodeType)("Variance"), + optional: true + } + } + }); + defineType("ClassPrivateMethod", { + builder: ["kind", "key", "params", "body", "static"], + visitor: ["decorators", "key", "typeParameters", "params", "returnType", "body"], + aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method", "Private"], + fields: Object.assign({}, classMethodOrDeclareMethodCommon(), functionTypeAnnotationCommon(), { + kind: { + validate: (0, _utils.assertOneOf)("get", "set", "method"), + default: "method" + }, + key: { + validate: (0, _utils.assertNodeType)("PrivateName") + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }) + }); + defineType("PrivateName", { + visitor: ["id"], + aliases: ["Private"], + fields: { + id: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + defineType("StaticBlock", { + visitor: ["body"], + fields: { + body: (0, _utils.validateArrayOfType)("Statement") + }, + aliases: ["Scopable", "BlockParent", "FunctionParent"] + }); + + + return core; +} + +var flow = {}; + +var hasRequiredFlow; + +function requireFlow () { + if (hasRequiredFlow) return flow; + hasRequiredFlow = 1; + + var _core = requireCore(); + var _utils = requireUtils(); + const defineType = (0, _utils.defineAliasedType)("Flow"); + const defineInterfaceishType = name => { + const isDeclareClass = name === "DeclareClass"; + defineType(name, { + builder: ["id", "typeParameters", "extends", "body"], + visitor: ["id", "typeParameters", "extends", ...(isDeclareClass ? ["mixins", "implements"] : []), "body"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: Object.assign({ + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")) + }, isDeclareClass ? { + mixins: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")), + implements: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ClassImplements")) + } : {}, { + body: (0, _utils.validateType)("ObjectTypeAnnotation") + }) + }); + }; + defineType("AnyTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("ArrayTypeAnnotation", { + visitor: ["elementType"], + aliases: ["FlowType"], + fields: { + elementType: (0, _utils.validateType)("FlowType") + } + }); + defineType("BooleanTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("BooleanLiteralTypeAnnotation", { + builder: ["value"], + aliases: ["FlowType"], + fields: { + value: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("NullLiteralTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("ClassImplements", { + visitor: ["id", "typeParameters"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") + } + }); + defineInterfaceishType("DeclareClass"); + defineType("DeclareFunction", { + visitor: ["id"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + predicate: (0, _utils.validateOptionalType)("DeclaredPredicate") + } + }); + defineInterfaceishType("DeclareInterface"); + defineType("DeclareModule", { + builder: ["id", "body", "kind"], + visitor: ["id", "body"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier", "StringLiteral"), + body: (0, _utils.validateType)("BlockStatement"), + kind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("CommonJS", "ES")) + } + }); + defineType("DeclareModuleExports", { + visitor: ["typeAnnotation"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + typeAnnotation: (0, _utils.validateType)("TypeAnnotation") + } + }); + defineType("DeclareTypeAlias", { + visitor: ["id", "typeParameters", "right"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + right: (0, _utils.validateType)("FlowType") + } + }); + defineType("DeclareOpaqueType", { + visitor: ["id", "typeParameters", "supertype"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + supertype: (0, _utils.validateOptionalType)("FlowType"), + impltype: (0, _utils.validateOptionalType)("FlowType") + } + }); + defineType("DeclareVariable", { + visitor: ["id"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier") + } + }); + defineType("DeclareExportDeclaration", { + visitor: ["declaration", "specifiers", "source", "attributes"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: Object.assign({ + declaration: (0, _utils.validateOptionalType)("Flow"), + specifiers: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ExportSpecifier", "ExportNamespaceSpecifier")), + source: (0, _utils.validateOptionalType)("StringLiteral"), + default: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) + }, _core.importAttributes) + }); + defineType("DeclareExportAllDeclaration", { + visitor: ["source", "attributes"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: Object.assign({ + source: (0, _utils.validateType)("StringLiteral"), + exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("type", "value")) + }, _core.importAttributes) + }); + defineType("DeclaredPredicate", { + visitor: ["value"], + aliases: ["FlowPredicate"], + fields: { + value: (0, _utils.validateType)("Flow") + } + }); + defineType("ExistsTypeAnnotation", { + aliases: ["FlowType"] + }); + defineType("FunctionTypeAnnotation", { + visitor: ["typeParameters", "params", "rest", "returnType"], + aliases: ["FlowType"], + fields: { + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + params: (0, _utils.validateArrayOfType)("FunctionTypeParam"), + rest: (0, _utils.validateOptionalType)("FunctionTypeParam"), + this: (0, _utils.validateOptionalType)("FunctionTypeParam"), + returnType: (0, _utils.validateType)("FlowType") + } + }); + defineType("FunctionTypeParam", { + visitor: ["name", "typeAnnotation"], + fields: { + name: (0, _utils.validateOptionalType)("Identifier"), + typeAnnotation: (0, _utils.validateType)("FlowType"), + optional: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("GenericTypeAnnotation", { + visitor: ["id", "typeParameters"], + aliases: ["FlowType"], + fields: { + id: (0, _utils.validateType)("Identifier", "QualifiedTypeIdentifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") + } + }); + defineType("InferredPredicate", { + aliases: ["FlowPredicate"] + }); + defineType("InterfaceExtends", { + visitor: ["id", "typeParameters"], + fields: { + id: (0, _utils.validateType)("Identifier", "QualifiedTypeIdentifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") + } + }); + defineInterfaceishType("InterfaceDeclaration"); + defineType("InterfaceTypeAnnotation", { + visitor: ["extends", "body"], + aliases: ["FlowType"], + fields: { + extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")), + body: (0, _utils.validateType)("ObjectTypeAnnotation") + } + }); + defineType("IntersectionTypeAnnotation", { + visitor: ["types"], + aliases: ["FlowType"], + fields: { + types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + defineType("MixedTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("EmptyTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("NullableTypeAnnotation", { + visitor: ["typeAnnotation"], + aliases: ["FlowType"], + fields: { + typeAnnotation: (0, _utils.validateType)("FlowType") + } + }); + defineType("NumberLiteralTypeAnnotation", { + builder: ["value"], + aliases: ["FlowType"], + fields: { + value: (0, _utils.validate)((0, _utils.assertValueType)("number")) + } + }); + defineType("NumberTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("ObjectTypeAnnotation", { + visitor: ["properties", "indexers", "callProperties", "internalSlots"], + aliases: ["FlowType"], + builder: ["properties", "indexers", "callProperties", "internalSlots", "exact"], + fields: { + properties: (0, _utils.validate)((0, _utils.arrayOfType)("ObjectTypeProperty", "ObjectTypeSpreadProperty")), + indexers: { + validate: (0, _utils.arrayOfType)("ObjectTypeIndexer"), + optional: true, + default: [] + }, + callProperties: { + validate: (0, _utils.arrayOfType)("ObjectTypeCallProperty"), + optional: true, + default: [] + }, + internalSlots: { + validate: (0, _utils.arrayOfType)("ObjectTypeInternalSlot"), + optional: true, + default: [] + }, + exact: { + validate: (0, _utils.assertValueType)("boolean"), + default: false + }, + inexact: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("ObjectTypeInternalSlot", { + visitor: ["id", "value"], + builder: ["id", "value", "optional", "static", "method"], + aliases: ["UserWhitespacable"], + fields: { + id: (0, _utils.validateType)("Identifier"), + value: (0, _utils.validateType)("FlowType"), + optional: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + method: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("ObjectTypeCallProperty", { + visitor: ["value"], + aliases: ["UserWhitespacable"], + fields: { + value: (0, _utils.validateType)("FlowType"), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("ObjectTypeIndexer", { + visitor: ["variance", "id", "key", "value"], + builder: ["id", "key", "value", "variance"], + aliases: ["UserWhitespacable"], + fields: { + id: (0, _utils.validateOptionalType)("Identifier"), + key: (0, _utils.validateType)("FlowType"), + value: (0, _utils.validateType)("FlowType"), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + variance: (0, _utils.validateOptionalType)("Variance") + } + }); + defineType("ObjectTypeProperty", { + visitor: ["key", "value", "variance"], + aliases: ["UserWhitespacable"], + fields: { + key: (0, _utils.validateType)("Identifier", "StringLiteral"), + value: (0, _utils.validateType)("FlowType"), + kind: (0, _utils.validate)((0, _utils.assertOneOf)("init", "get", "set")), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + proto: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + optional: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + variance: (0, _utils.validateOptionalType)("Variance"), + method: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("ObjectTypeSpreadProperty", { + visitor: ["argument"], + aliases: ["UserWhitespacable"], + fields: { + argument: (0, _utils.validateType)("FlowType") + } + }); + defineType("OpaqueType", { + visitor: ["id", "typeParameters", "supertype", "impltype"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + supertype: (0, _utils.validateOptionalType)("FlowType"), + impltype: (0, _utils.validateType)("FlowType") + } + }); + defineType("QualifiedTypeIdentifier", { + visitor: ["qualification", "id"], + builder: ["id", "qualification"], + fields: { + id: (0, _utils.validateType)("Identifier"), + qualification: (0, _utils.validateType)("Identifier", "QualifiedTypeIdentifier") + } + }); + defineType("StringLiteralTypeAnnotation", { + builder: ["value"], + aliases: ["FlowType"], + fields: { + value: (0, _utils.validate)((0, _utils.assertValueType)("string")) + } + }); + defineType("StringTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("SymbolTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("ThisTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("TupleTypeAnnotation", { + visitor: ["types"], + aliases: ["FlowType"], + fields: { + types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + defineType("TypeofTypeAnnotation", { + visitor: ["argument"], + aliases: ["FlowType"], + fields: { + argument: (0, _utils.validateType)("FlowType") + } + }); + defineType("TypeAlias", { + visitor: ["id", "typeParameters", "right"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + right: (0, _utils.validateType)("FlowType") + } + }); + defineType("TypeAnnotation", { + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("FlowType") + } + }); + defineType("TypeCastExpression", { + visitor: ["expression", "typeAnnotation"], + aliases: ["ExpressionWrapper", "Expression"], + fields: { + expression: (0, _utils.validateType)("Expression"), + typeAnnotation: (0, _utils.validateType)("TypeAnnotation") + } + }); + defineType("TypeParameter", { + visitor: ["bound", "default", "variance"], + fields: { + name: (0, _utils.validate)((0, _utils.assertValueType)("string")), + bound: (0, _utils.validateOptionalType)("TypeAnnotation"), + default: (0, _utils.validateOptionalType)("FlowType"), + variance: (0, _utils.validateOptionalType)("Variance") + } + }); + defineType("TypeParameterDeclaration", { + visitor: ["params"], + fields: { + params: (0, _utils.validate)((0, _utils.arrayOfType)("TypeParameter")) + } + }); + defineType("TypeParameterInstantiation", { + visitor: ["params"], + fields: { + params: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + defineType("UnionTypeAnnotation", { + visitor: ["types"], + aliases: ["FlowType"], + fields: { + types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + defineType("Variance", { + builder: ["kind"], + fields: { + kind: (0, _utils.validate)((0, _utils.assertOneOf)("minus", "plus")) + } + }); + defineType("VoidTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("EnumDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "body"], + fields: { + id: (0, _utils.validateType)("Identifier"), + body: (0, _utils.validateType)("EnumBooleanBody", "EnumNumberBody", "EnumStringBody", "EnumSymbolBody") + } + }); + defineType("EnumBooleanBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + explicitType: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + members: (0, _utils.validateArrayOfType)("EnumBooleanMember"), + hasUnknownMembers: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("EnumNumberBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + explicitType: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + members: (0, _utils.validateArrayOfType)("EnumNumberMember"), + hasUnknownMembers: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("EnumStringBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + explicitType: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + members: (0, _utils.validateArrayOfType)("EnumStringMember", "EnumDefaultedMember"), + hasUnknownMembers: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("EnumSymbolBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + members: (0, _utils.validateArrayOfType)("EnumDefaultedMember"), + hasUnknownMembers: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("EnumBooleanMember", { + aliases: ["EnumMember"], + visitor: ["id"], + fields: { + id: (0, _utils.validateType)("Identifier"), + init: (0, _utils.validateType)("BooleanLiteral") + } + }); + defineType("EnumNumberMember", { + aliases: ["EnumMember"], + visitor: ["id", "init"], + fields: { + id: (0, _utils.validateType)("Identifier"), + init: (0, _utils.validateType)("NumericLiteral") + } + }); + defineType("EnumStringMember", { + aliases: ["EnumMember"], + visitor: ["id", "init"], + fields: { + id: (0, _utils.validateType)("Identifier"), + init: (0, _utils.validateType)("StringLiteral") + } + }); + defineType("EnumDefaultedMember", { + aliases: ["EnumMember"], + visitor: ["id"], + fields: { + id: (0, _utils.validateType)("Identifier") + } + }); + defineType("IndexedAccessType", { + visitor: ["objectType", "indexType"], + aliases: ["FlowType"], + fields: { + objectType: (0, _utils.validateType)("FlowType"), + indexType: (0, _utils.validateType)("FlowType") + } + }); + defineType("OptionalIndexedAccessType", { + visitor: ["objectType", "indexType"], + aliases: ["FlowType"], + fields: { + objectType: (0, _utils.validateType)("FlowType"), + indexType: (0, _utils.validateType)("FlowType"), + optional: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + + + return flow; +} + +var jsx = {}; + +var hasRequiredJsx; + +function requireJsx () { + if (hasRequiredJsx) return jsx; + hasRequiredJsx = 1; + + var _utils = requireUtils(); + const defineType = (0, _utils.defineAliasedType)("JSX"); + defineType("JSXAttribute", { + visitor: ["name", "value"], + aliases: ["Immutable"], + fields: { + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXNamespacedName") + }, + value: { + optional: true, + validate: (0, _utils.assertNodeType)("JSXElement", "JSXFragment", "StringLiteral", "JSXExpressionContainer") + } + } + }); + defineType("JSXClosingElement", { + visitor: ["name"], + aliases: ["Immutable"], + fields: { + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression", "JSXNamespacedName") + } + } + }); + defineType("JSXElement", { + builder: ["openingElement", "closingElement", "children", "selfClosing"], + visitor: ["openingElement", "children", "closingElement"], + aliases: ["Immutable", "Expression"], + fields: Object.assign({ + openingElement: { + validate: (0, _utils.assertNodeType)("JSXOpeningElement") + }, + closingElement: { + optional: true, + validate: (0, _utils.assertNodeType)("JSXClosingElement") + }, + children: (0, _utils.validateArrayOfType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment") + }, { + selfClosing: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + }) + }); + defineType("JSXEmptyExpression", {}); + defineType("JSXExpressionContainer", { + visitor: ["expression"], + aliases: ["Immutable"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression", "JSXEmptyExpression") + } + } + }); + defineType("JSXSpreadChild", { + visitor: ["expression"], + aliases: ["Immutable"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("JSXIdentifier", { + builder: ["name"], + fields: { + name: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + defineType("JSXMemberExpression", { + visitor: ["object", "property"], + fields: { + object: { + validate: (0, _utils.assertNodeType)("JSXMemberExpression", "JSXIdentifier") + }, + property: { + validate: (0, _utils.assertNodeType)("JSXIdentifier") + } + } + }); + defineType("JSXNamespacedName", { + visitor: ["namespace", "name"], + fields: { + namespace: { + validate: (0, _utils.assertNodeType)("JSXIdentifier") + }, + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier") + } + } + }); + defineType("JSXOpeningElement", { + builder: ["name", "attributes", "selfClosing"], + visitor: ["name", "attributes"], + aliases: ["Immutable"], + fields: { + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression", "JSXNamespacedName") + }, + selfClosing: { + default: false + }, + attributes: (0, _utils.validateArrayOfType)("JSXAttribute", "JSXSpreadAttribute"), + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + } + } + }); + defineType("JSXSpreadAttribute", { + visitor: ["argument"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("JSXText", { + aliases: ["Immutable"], + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + defineType("JSXFragment", { + builder: ["openingFragment", "closingFragment", "children"], + visitor: ["openingFragment", "children", "closingFragment"], + aliases: ["Immutable", "Expression"], + fields: { + openingFragment: { + validate: (0, _utils.assertNodeType)("JSXOpeningFragment") + }, + closingFragment: { + validate: (0, _utils.assertNodeType)("JSXClosingFragment") + }, + children: (0, _utils.validateArrayOfType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment") + } + }); + defineType("JSXOpeningFragment", { + aliases: ["Immutable"] + }); + defineType("JSXClosingFragment", { + aliases: ["Immutable"] + }); + + + return jsx; +} + +var misc = {}; + +var placeholders = {}; + +var hasRequiredPlaceholders; + +function requirePlaceholders () { + if (hasRequiredPlaceholders) return placeholders; + hasRequiredPlaceholders = 1; + + Object.defineProperty(placeholders, "__esModule", { + value: true + }); + placeholders.PLACEHOLDERS_FLIPPED_ALIAS = placeholders.PLACEHOLDERS_ALIAS = placeholders.PLACEHOLDERS = void 0; + var _utils = requireUtils(); + const PLACEHOLDERS = placeholders.PLACEHOLDERS = ["Identifier", "StringLiteral", "Expression", "Statement", "Declaration", "BlockStatement", "ClassBody", "Pattern"]; + const PLACEHOLDERS_ALIAS = placeholders.PLACEHOLDERS_ALIAS = { + Declaration: ["Statement"], + Pattern: ["PatternLike", "LVal"] + }; + for (const type of PLACEHOLDERS) { + const alias = _utils.ALIAS_KEYS[type]; + if (alias != null && alias.length) PLACEHOLDERS_ALIAS[type] = alias; + } + const PLACEHOLDERS_FLIPPED_ALIAS = placeholders.PLACEHOLDERS_FLIPPED_ALIAS = {}; + Object.keys(PLACEHOLDERS_ALIAS).forEach(type => { + PLACEHOLDERS_ALIAS[type].forEach(alias => { + if (!hasOwnProperty.call(PLACEHOLDERS_FLIPPED_ALIAS, alias)) { + PLACEHOLDERS_FLIPPED_ALIAS[alias] = []; + } + PLACEHOLDERS_FLIPPED_ALIAS[alias].push(type); + }); + }); + + + return placeholders; +} + +var hasRequiredMisc; + +function requireMisc () { + if (hasRequiredMisc) return misc; + hasRequiredMisc = 1; + + var _utils = requireUtils(); + var _placeholders = requirePlaceholders(); + var _core = requireCore(); + const defineType = (0, _utils.defineAliasedType)("Miscellaneous"); + { + defineType("Noop", { + visitor: [] + }); + } + defineType("Placeholder", { + visitor: [], + builder: ["expectedNode", "name"], + fields: Object.assign({ + name: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + expectedNode: { + validate: (0, _utils.assertOneOf)(..._placeholders.PLACEHOLDERS) + } + }, (0, _core.patternLikeCommon)()) + }); + defineType("V8IntrinsicIdentifier", { + builder: ["name"], + fields: { + name: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + + + return misc; +} + +var experimental = {}; + +var hasRequiredExperimental; + +function requireExperimental () { + if (hasRequiredExperimental) return experimental; + hasRequiredExperimental = 1; + + var _utils = requireUtils(); + (0, _utils.default)("ArgumentPlaceholder", {}); + (0, _utils.default)("BindExpression", { + visitor: ["object", "callee"], + aliases: ["Expression"], + fields: !process.env.BABEL_TYPES_8_BREAKING ? { + object: { + validate: Object.assign(() => {}, { + oneOfNodeTypes: ["Expression"] + }) + }, + callee: { + validate: Object.assign(() => {}, { + oneOfNodeTypes: ["Expression"] + }) + } + } : { + object: { + validate: (0, _utils.assertNodeType)("Expression") + }, + callee: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("ImportAttribute", { + visitor: ["key", "value"], + fields: { + key: { + validate: (0, _utils.assertNodeType)("Identifier", "StringLiteral") + }, + value: { + validate: (0, _utils.assertNodeType)("StringLiteral") + } + } + }); + (0, _utils.default)("Decorator", { + visitor: ["expression"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("DoExpression", { + visitor: ["body"], + builder: ["body", "async"], + aliases: ["Expression"], + fields: { + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + }, + async: { + validate: (0, _utils.assertValueType)("boolean"), + default: false + } + } + }); + (0, _utils.default)("ExportDefaultSpecifier", { + visitor: ["exported"], + aliases: ["ModuleSpecifier"], + fields: { + exported: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + (0, _utils.default)("RecordExpression", { + visitor: ["properties"], + aliases: ["Expression"], + fields: { + properties: (0, _utils.validateArrayOfType)("ObjectProperty", "SpreadElement") + } + }); + (0, _utils.default)("TupleExpression", { + fields: { + elements: { + validate: (0, _utils.arrayOfType)("Expression", "SpreadElement"), + default: [] + } + }, + visitor: ["elements"], + aliases: ["Expression"] + }); + { + (0, _utils.default)("DecimalLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + } + (0, _utils.default)("ModuleExpression", { + visitor: ["body"], + fields: { + body: { + validate: (0, _utils.assertNodeType)("Program") + } + }, + aliases: ["Expression"] + }); + (0, _utils.default)("TopicReference", { + aliases: ["Expression"] + }); + (0, _utils.default)("PipelineTopicExpression", { + builder: ["expression"], + visitor: ["expression"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + aliases: ["Expression"] + }); + (0, _utils.default)("PipelineBareFunction", { + builder: ["callee"], + visitor: ["callee"], + fields: { + callee: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + aliases: ["Expression"] + }); + (0, _utils.default)("PipelinePrimaryTopicReference", { + aliases: ["Expression"] + }); + + + return experimental; +} + +var typescript = {}; + +var hasRequiredTypescript; + +function requireTypescript () { + if (hasRequiredTypescript) return typescript; + hasRequiredTypescript = 1; + + var _utils = requireUtils(); + var _core = requireCore(); + var _is = requireIs(); + const defineType = (0, _utils.defineAliasedType)("TypeScript"); + const bool = (0, _utils.assertValueType)("boolean"); + const tSFunctionTypeAnnotationCommon = () => ({ + returnType: { + validate: (0, _utils.assertNodeType)("TSTypeAnnotation", "Noop"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TSTypeParameterDeclaration", "Noop"), + optional: true + } + }); + defineType("TSParameterProperty", { + aliases: ["LVal"], + visitor: ["parameter"], + fields: { + accessibility: { + validate: (0, _utils.assertOneOf)("public", "private", "protected"), + optional: true + }, + readonly: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + parameter: { + validate: (0, _utils.assertNodeType)("Identifier", "AssignmentPattern") + }, + override: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + } + } + }); + defineType("TSDeclareFunction", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "typeParameters", "params", "returnType"], + fields: Object.assign({}, (0, _core.functionDeclarationCommon)(), tSFunctionTypeAnnotationCommon()) + }); + defineType("TSDeclareMethod", { + visitor: ["decorators", "key", "typeParameters", "params", "returnType"], + fields: Object.assign({}, (0, _core.classMethodOrDeclareMethodCommon)(), tSFunctionTypeAnnotationCommon()) + }); + defineType("TSQualifiedName", { + aliases: ["TSEntityName"], + visitor: ["left", "right"], + fields: { + left: (0, _utils.validateType)("TSEntityName"), + right: (0, _utils.validateType)("Identifier") + } + }); + const signatureDeclarationCommon = () => ({ + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), + ["parameters"]: (0, _utils.validateArrayOfType)("ArrayPattern", "Identifier", "ObjectPattern", "RestElement"), + ["typeAnnotation"]: (0, _utils.validateOptionalType)("TSTypeAnnotation") + }); + const callConstructSignatureDeclaration = { + aliases: ["TSTypeElement"], + visitor: ["typeParameters", "parameters", "typeAnnotation"], + fields: signatureDeclarationCommon() + }; + defineType("TSCallSignatureDeclaration", callConstructSignatureDeclaration); + defineType("TSConstructSignatureDeclaration", callConstructSignatureDeclaration); + const namedTypeElementCommon = () => ({ + key: (0, _utils.validateType)("Expression"), + computed: { + default: false + }, + optional: (0, _utils.validateOptional)(bool) + }); + defineType("TSPropertySignature", { + aliases: ["TSTypeElement"], + visitor: ["key", "typeAnnotation"], + fields: Object.assign({}, namedTypeElementCommon(), { + readonly: (0, _utils.validateOptional)(bool), + typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation"), + kind: { + validate: (0, _utils.assertOneOf)("get", "set") + } + }) + }); + defineType("TSMethodSignature", { + aliases: ["TSTypeElement"], + visitor: ["key", "typeParameters", "parameters", "typeAnnotation"], + fields: Object.assign({}, signatureDeclarationCommon(), namedTypeElementCommon(), { + kind: { + validate: (0, _utils.assertOneOf)("method", "get", "set") + } + }) + }); + defineType("TSIndexSignature", { + aliases: ["TSTypeElement"], + visitor: ["parameters", "typeAnnotation"], + fields: { + readonly: (0, _utils.validateOptional)(bool), + static: (0, _utils.validateOptional)(bool), + parameters: (0, _utils.validateArrayOfType)("Identifier"), + typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation") + } + }); + const tsKeywordTypes = ["TSAnyKeyword", "TSBooleanKeyword", "TSBigIntKeyword", "TSIntrinsicKeyword", "TSNeverKeyword", "TSNullKeyword", "TSNumberKeyword", "TSObjectKeyword", "TSStringKeyword", "TSSymbolKeyword", "TSUndefinedKeyword", "TSUnknownKeyword", "TSVoidKeyword"]; + for (const type of tsKeywordTypes) { + defineType(type, { + aliases: ["TSType", "TSBaseType"], + visitor: [], + fields: {} + }); + } + defineType("TSThisType", { + aliases: ["TSType", "TSBaseType"], + visitor: [], + fields: {} + }); + const fnOrCtrBase = { + aliases: ["TSType"], + visitor: ["typeParameters", "parameters", "typeAnnotation"] + }; + defineType("TSFunctionType", Object.assign({}, fnOrCtrBase, { + fields: signatureDeclarationCommon() + })); + defineType("TSConstructorType", Object.assign({}, fnOrCtrBase, { + fields: Object.assign({}, signatureDeclarationCommon(), { + abstract: (0, _utils.validateOptional)(bool) + }) + })); + defineType("TSTypeReference", { + aliases: ["TSType"], + visitor: ["typeName", "typeParameters"], + fields: { + typeName: (0, _utils.validateType)("TSEntityName"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") + } + }); + defineType("TSTypePredicate", { + aliases: ["TSType"], + visitor: ["parameterName", "typeAnnotation"], + builder: ["parameterName", "typeAnnotation", "asserts"], + fields: { + parameterName: (0, _utils.validateType)("Identifier", "TSThisType"), + typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation"), + asserts: (0, _utils.validateOptional)(bool) + } + }); + defineType("TSTypeQuery", { + aliases: ["TSType"], + visitor: ["exprName", "typeParameters"], + fields: { + exprName: (0, _utils.validateType)("TSEntityName", "TSImportType"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") + } + }); + defineType("TSTypeLiteral", { + aliases: ["TSType"], + visitor: ["members"], + fields: { + members: (0, _utils.validateArrayOfType)("TSTypeElement") + } + }); + defineType("TSArrayType", { + aliases: ["TSType"], + visitor: ["elementType"], + fields: { + elementType: (0, _utils.validateType)("TSType") + } + }); + defineType("TSTupleType", { + aliases: ["TSType"], + visitor: ["elementTypes"], + fields: { + elementTypes: (0, _utils.validateArrayOfType)("TSType", "TSNamedTupleMember") + } + }); + defineType("TSOptionalType", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + defineType("TSRestType", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + defineType("TSNamedTupleMember", { + visitor: ["label", "elementType"], + builder: ["label", "elementType", "optional"], + fields: { + label: (0, _utils.validateType)("Identifier"), + optional: { + validate: bool, + default: false + }, + elementType: (0, _utils.validateType)("TSType") + } + }); + const unionOrIntersection = { + aliases: ["TSType"], + visitor: ["types"], + fields: { + types: (0, _utils.validateArrayOfType)("TSType") + } + }; + defineType("TSUnionType", unionOrIntersection); + defineType("TSIntersectionType", unionOrIntersection); + defineType("TSConditionalType", { + aliases: ["TSType"], + visitor: ["checkType", "extendsType", "trueType", "falseType"], + fields: { + checkType: (0, _utils.validateType)("TSType"), + extendsType: (0, _utils.validateType)("TSType"), + trueType: (0, _utils.validateType)("TSType"), + falseType: (0, _utils.validateType)("TSType") + } + }); + defineType("TSInferType", { + aliases: ["TSType"], + visitor: ["typeParameter"], + fields: { + typeParameter: (0, _utils.validateType)("TSTypeParameter") + } + }); + defineType("TSParenthesizedType", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + defineType("TSTypeOperator", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + operator: (0, _utils.validate)((0, _utils.assertValueType)("string")), + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + defineType("TSIndexedAccessType", { + aliases: ["TSType"], + visitor: ["objectType", "indexType"], + fields: { + objectType: (0, _utils.validateType)("TSType"), + indexType: (0, _utils.validateType)("TSType") + } + }); + defineType("TSMappedType", { + aliases: ["TSType"], + visitor: ["typeParameter", "nameType", "typeAnnotation"], + builder: ["typeParameter", "typeAnnotation", "nameType"], + fields: Object.assign({}, { + typeParameter: (0, _utils.validateType)("TSTypeParameter") + }, { + readonly: (0, _utils.validateOptional)((0, _utils.assertOneOf)(true, false, "+", "-")), + optional: (0, _utils.validateOptional)((0, _utils.assertOneOf)(true, false, "+", "-")), + typeAnnotation: (0, _utils.validateOptionalType)("TSType"), + nameType: (0, _utils.validateOptionalType)("TSType") + }) + }); + defineType("TSLiteralType", { + aliases: ["TSType", "TSBaseType"], + visitor: ["literal"], + fields: { + literal: { + validate: function () { + const unaryExpression = (0, _utils.assertNodeType)("NumericLiteral", "BigIntLiteral"); + const unaryOperator = (0, _utils.assertOneOf)("-"); + const literal = (0, _utils.assertNodeType)("NumericLiteral", "StringLiteral", "BooleanLiteral", "BigIntLiteral", "TemplateLiteral"); + function validator(parent, key, node) { + if ((0, _is.default)("UnaryExpression", node)) { + unaryOperator(node, "operator", node.operator); + unaryExpression(node, "argument", node.argument); + } else { + literal(parent, key, node); + } + } + validator.oneOfNodeTypes = ["NumericLiteral", "StringLiteral", "BooleanLiteral", "BigIntLiteral", "TemplateLiteral", "UnaryExpression"]; + return validator; + }() + } + } + }); + const expressionWithTypeArguments = { + aliases: ["TSType"], + visitor: ["expression", "typeParameters"], + fields: { + expression: (0, _utils.validateType)("TSEntityName"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") + } + }; + { + defineType("TSExpressionWithTypeArguments", expressionWithTypeArguments); + } + defineType("TSInterfaceDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "typeParameters", "extends", "body"], + fields: { + declare: (0, _utils.validateOptional)(bool), + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), + extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("TSExpressionWithTypeArguments")), + body: (0, _utils.validateType)("TSInterfaceBody") + } + }); + defineType("TSInterfaceBody", { + visitor: ["body"], + fields: { + body: (0, _utils.validateArrayOfType)("TSTypeElement") + } + }); + defineType("TSTypeAliasDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "typeParameters", "typeAnnotation"], + fields: { + declare: (0, _utils.validateOptional)(bool), + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + defineType("TSInstantiationExpression", { + aliases: ["Expression"], + visitor: ["expression", "typeParameters"], + fields: { + expression: (0, _utils.validateType)("Expression"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") + } + }); + const TSTypeExpression = { + aliases: ["Expression", "LVal", "PatternLike"], + visitor: ["expression", "typeAnnotation"], + fields: { + expression: (0, _utils.validateType)("Expression"), + typeAnnotation: (0, _utils.validateType)("TSType") + } + }; + defineType("TSAsExpression", TSTypeExpression); + defineType("TSSatisfiesExpression", TSTypeExpression); + defineType("TSTypeAssertion", { + aliases: ["Expression", "LVal", "PatternLike"], + visitor: ["typeAnnotation", "expression"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType"), + expression: (0, _utils.validateType)("Expression") + } + }); + defineType("TSEnumDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "members"], + fields: { + declare: (0, _utils.validateOptional)(bool), + const: (0, _utils.validateOptional)(bool), + id: (0, _utils.validateType)("Identifier"), + members: (0, _utils.validateArrayOfType)("TSEnumMember"), + initializer: (0, _utils.validateOptionalType)("Expression") + } + }); + defineType("TSEnumMember", { + visitor: ["id", "initializer"], + fields: { + id: (0, _utils.validateType)("Identifier", "StringLiteral"), + initializer: (0, _utils.validateOptionalType)("Expression") + } + }); + defineType("TSModuleDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "body"], + fields: Object.assign({ + kind: { + validate: (0, _utils.assertOneOf)("global", "module", "namespace") + }, + declare: (0, _utils.validateOptional)(bool) + }, { + global: (0, _utils.validateOptional)(bool) + }, { + id: (0, _utils.validateType)("Identifier", "StringLiteral"), + body: (0, _utils.validateType)("TSModuleBlock", "TSModuleDeclaration") + }) + }); + defineType("TSModuleBlock", { + aliases: ["Scopable", "Block", "BlockParent", "FunctionParent"], + visitor: ["body"], + fields: { + body: (0, _utils.validateArrayOfType)("Statement") + } + }); + defineType("TSImportType", { + aliases: ["TSType"], + visitor: ["argument", "qualifier", "typeParameters"], + fields: { + argument: (0, _utils.validateType)("StringLiteral"), + qualifier: (0, _utils.validateOptionalType)("TSEntityName"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation"), + options: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + } + } + }); + defineType("TSImportEqualsDeclaration", { + aliases: ["Statement"], + visitor: ["id", "moduleReference"], + fields: { + isExport: (0, _utils.validate)(bool), + id: (0, _utils.validateType)("Identifier"), + moduleReference: (0, _utils.validateType)("TSEntityName", "TSExternalModuleReference"), + importKind: { + validate: (0, _utils.assertOneOf)("type", "value"), + optional: true + } + } + }); + defineType("TSExternalModuleReference", { + visitor: ["expression"], + fields: { + expression: (0, _utils.validateType)("StringLiteral") + } + }); + defineType("TSNonNullExpression", { + aliases: ["Expression", "LVal", "PatternLike"], + visitor: ["expression"], + fields: { + expression: (0, _utils.validateType)("Expression") + } + }); + defineType("TSExportAssignment", { + aliases: ["Statement"], + visitor: ["expression"], + fields: { + expression: (0, _utils.validateType)("Expression") + } + }); + defineType("TSNamespaceExportDeclaration", { + aliases: ["Statement"], + visitor: ["id"], + fields: { + id: (0, _utils.validateType)("Identifier") + } + }); + defineType("TSTypeAnnotation", { + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TSType") + } + } + }); + defineType("TSTypeParameterInstantiation", { + visitor: ["params"], + fields: { + params: (0, _utils.validateArrayOfType)("TSType") + } + }); + defineType("TSTypeParameterDeclaration", { + visitor: ["params"], + fields: { + params: (0, _utils.validateArrayOfType)("TSTypeParameter") + } + }); + defineType("TSTypeParameter", { + builder: ["constraint", "default", "name"], + visitor: ["constraint", "default"], + fields: { + name: { + validate: (0, _utils.assertValueType)("string") + }, + in: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + out: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + const: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + constraint: { + validate: (0, _utils.assertNodeType)("TSType"), + optional: true + }, + default: { + validate: (0, _utils.assertNodeType)("TSType"), + optional: true + } + } + }); + + + return typescript; +} + +var deprecatedAliases = {}; + +var hasRequiredDeprecatedAliases; + +function requireDeprecatedAliases () { + if (hasRequiredDeprecatedAliases) return deprecatedAliases; + hasRequiredDeprecatedAliases = 1; + + Object.defineProperty(deprecatedAliases, "__esModule", { + value: true + }); + deprecatedAliases.DEPRECATED_ALIASES = void 0; + deprecatedAliases.DEPRECATED_ALIASES = { + ModuleDeclaration: "ImportOrExportDeclaration" + }; + + + return deprecatedAliases; +} + +var hasRequiredDefinitions; + +function requireDefinitions () { + if (hasRequiredDefinitions) return definitions; + hasRequiredDefinitions = 1; + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "ALIAS_KEYS", { + enumerable: true, + get: function () { + return _utils.ALIAS_KEYS; + } + }); + Object.defineProperty(exports, "BUILDER_KEYS", { + enumerable: true, + get: function () { + return _utils.BUILDER_KEYS; + } + }); + Object.defineProperty(exports, "DEPRECATED_ALIASES", { + enumerable: true, + get: function () { + return _deprecatedAliases.DEPRECATED_ALIASES; + } + }); + Object.defineProperty(exports, "DEPRECATED_KEYS", { + enumerable: true, + get: function () { + return _utils.DEPRECATED_KEYS; + } + }); + Object.defineProperty(exports, "FLIPPED_ALIAS_KEYS", { + enumerable: true, + get: function () { + return _utils.FLIPPED_ALIAS_KEYS; + } + }); + Object.defineProperty(exports, "NODE_FIELDS", { + enumerable: true, + get: function () { + return _utils.NODE_FIELDS; + } + }); + Object.defineProperty(exports, "NODE_PARENT_VALIDATIONS", { + enumerable: true, + get: function () { + return _utils.NODE_PARENT_VALIDATIONS; + } + }); + Object.defineProperty(exports, "PLACEHOLDERS", { + enumerable: true, + get: function () { + return _placeholders.PLACEHOLDERS; + } + }); + Object.defineProperty(exports, "PLACEHOLDERS_ALIAS", { + enumerable: true, + get: function () { + return _placeholders.PLACEHOLDERS_ALIAS; + } + }); + Object.defineProperty(exports, "PLACEHOLDERS_FLIPPED_ALIAS", { + enumerable: true, + get: function () { + return _placeholders.PLACEHOLDERS_FLIPPED_ALIAS; + } + }); + exports.TYPES = void 0; + Object.defineProperty(exports, "VISITOR_KEYS", { + enumerable: true, + get: function () { + return _utils.VISITOR_KEYS; + } + }); + requireCore(); + requireFlow(); + requireJsx(); + requireMisc(); + requireExperimental(); + requireTypescript(); + var _utils = requireUtils(); + var _placeholders = requirePlaceholders(); + var _deprecatedAliases = requireDeprecatedAliases(); + Object.keys(_deprecatedAliases.DEPRECATED_ALIASES).forEach(deprecatedAlias => { + _utils.FLIPPED_ALIAS_KEYS[deprecatedAlias] = _utils.FLIPPED_ALIAS_KEYS[_deprecatedAliases.DEPRECATED_ALIASES[deprecatedAlias]]; + }); + exports.TYPES = [].concat(Object.keys(_utils.VISITOR_KEYS), Object.keys(_utils.FLIPPED_ALIAS_KEYS), Object.keys(_utils.DEPRECATED_KEYS)); + + +} (definitions)); + return definitions; +} + +var hasRequiredValidate; + +function requireValidate () { + if (hasRequiredValidate) return validate$1; + hasRequiredValidate = 1; + + Object.defineProperty(validate$1, "__esModule", { + value: true + }); + validate$1.default = validate; + validate$1.validateChild = validateChild; + validate$1.validateField = validateField; + validate$1.validateInternal = validateInternal; + var _index = requireDefinitions(); + function validate(node, key, val) { + if (!node) return; + const fields = _index.NODE_FIELDS[node.type]; + if (!fields) return; + const field = fields[key]; + validateField(node, key, val, field); + validateChild(node, key, val); + } + function validateInternal(field, node, key, val, maybeNode) { + if (!(field != null && field.validate)) return; + if (field.optional && val == null) return; + field.validate(node, key, val); + if (maybeNode) { + var _NODE_PARENT_VALIDATI; + const type = val.type; + if (type == null) return; + (_NODE_PARENT_VALIDATI = _index.NODE_PARENT_VALIDATIONS[type]) == null || _NODE_PARENT_VALIDATI.call(_index.NODE_PARENT_VALIDATIONS, node, key, val); + } + } + function validateField(node, key, val, field) { + if (!(field != null && field.validate)) return; + if (field.optional && val == null) return; + field.validate(node, key, val); + } + function validateChild(node, key, val) { + var _NODE_PARENT_VALIDATI2; + const type = val == null ? void 0 : val.type; + if (type == null) return; + (_NODE_PARENT_VALIDATI2 = _index.NODE_PARENT_VALIDATIONS[type]) == null || _NODE_PARENT_VALIDATI2.call(_index.NODE_PARENT_VALIDATIONS, node, key, val); + } + + + return validate$1; +} + +var hasRequiredGenerated$2; + +function requireGenerated$2 () { + if (hasRequiredGenerated$2) return generated$2; + hasRequiredGenerated$2 = 1; + + Object.defineProperty(generated$2, "__esModule", { + value: true + }); + generated$2.anyTypeAnnotation = anyTypeAnnotation; + generated$2.argumentPlaceholder = argumentPlaceholder; + generated$2.arrayExpression = arrayExpression; + generated$2.arrayPattern = arrayPattern; + generated$2.arrayTypeAnnotation = arrayTypeAnnotation; + generated$2.arrowFunctionExpression = arrowFunctionExpression; + generated$2.assignmentExpression = assignmentExpression; + generated$2.assignmentPattern = assignmentPattern; + generated$2.awaitExpression = awaitExpression; + generated$2.bigIntLiteral = bigIntLiteral; + generated$2.binaryExpression = binaryExpression; + generated$2.bindExpression = bindExpression; + generated$2.blockStatement = blockStatement; + generated$2.booleanLiteral = booleanLiteral; + generated$2.booleanLiteralTypeAnnotation = booleanLiteralTypeAnnotation; + generated$2.booleanTypeAnnotation = booleanTypeAnnotation; + generated$2.breakStatement = breakStatement; + generated$2.callExpression = callExpression; + generated$2.catchClause = catchClause; + generated$2.classAccessorProperty = classAccessorProperty; + generated$2.classBody = classBody; + generated$2.classDeclaration = classDeclaration; + generated$2.classExpression = classExpression; + generated$2.classImplements = classImplements; + generated$2.classMethod = classMethod; + generated$2.classPrivateMethod = classPrivateMethod; + generated$2.classPrivateProperty = classPrivateProperty; + generated$2.classProperty = classProperty; + generated$2.conditionalExpression = conditionalExpression; + generated$2.continueStatement = continueStatement; + generated$2.debuggerStatement = debuggerStatement; + generated$2.decimalLiteral = decimalLiteral; + generated$2.declareClass = declareClass; + generated$2.declareExportAllDeclaration = declareExportAllDeclaration; + generated$2.declareExportDeclaration = declareExportDeclaration; + generated$2.declareFunction = declareFunction; + generated$2.declareInterface = declareInterface; + generated$2.declareModule = declareModule; + generated$2.declareModuleExports = declareModuleExports; + generated$2.declareOpaqueType = declareOpaqueType; + generated$2.declareTypeAlias = declareTypeAlias; + generated$2.declareVariable = declareVariable; + generated$2.declaredPredicate = declaredPredicate; + generated$2.decorator = decorator; + generated$2.directive = directive; + generated$2.directiveLiteral = directiveLiteral; + generated$2.doExpression = doExpression; + generated$2.doWhileStatement = doWhileStatement; + generated$2.emptyStatement = emptyStatement; + generated$2.emptyTypeAnnotation = emptyTypeAnnotation; + generated$2.enumBooleanBody = enumBooleanBody; + generated$2.enumBooleanMember = enumBooleanMember; + generated$2.enumDeclaration = enumDeclaration; + generated$2.enumDefaultedMember = enumDefaultedMember; + generated$2.enumNumberBody = enumNumberBody; + generated$2.enumNumberMember = enumNumberMember; + generated$2.enumStringBody = enumStringBody; + generated$2.enumStringMember = enumStringMember; + generated$2.enumSymbolBody = enumSymbolBody; + generated$2.existsTypeAnnotation = existsTypeAnnotation; + generated$2.exportAllDeclaration = exportAllDeclaration; + generated$2.exportDefaultDeclaration = exportDefaultDeclaration; + generated$2.exportDefaultSpecifier = exportDefaultSpecifier; + generated$2.exportNamedDeclaration = exportNamedDeclaration; + generated$2.exportNamespaceSpecifier = exportNamespaceSpecifier; + generated$2.exportSpecifier = exportSpecifier; + generated$2.expressionStatement = expressionStatement; + generated$2.file = file; + generated$2.forInStatement = forInStatement; + generated$2.forOfStatement = forOfStatement; + generated$2.forStatement = forStatement; + generated$2.functionDeclaration = functionDeclaration; + generated$2.functionExpression = functionExpression; + generated$2.functionTypeAnnotation = functionTypeAnnotation; + generated$2.functionTypeParam = functionTypeParam; + generated$2.genericTypeAnnotation = genericTypeAnnotation; + generated$2.identifier = identifier; + generated$2.ifStatement = ifStatement; + generated$2.import = _import; + generated$2.importAttribute = importAttribute; + generated$2.importDeclaration = importDeclaration; + generated$2.importDefaultSpecifier = importDefaultSpecifier; + generated$2.importExpression = importExpression; + generated$2.importNamespaceSpecifier = importNamespaceSpecifier; + generated$2.importSpecifier = importSpecifier; + generated$2.indexedAccessType = indexedAccessType; + generated$2.inferredPredicate = inferredPredicate; + generated$2.interfaceDeclaration = interfaceDeclaration; + generated$2.interfaceExtends = interfaceExtends; + generated$2.interfaceTypeAnnotation = interfaceTypeAnnotation; + generated$2.interpreterDirective = interpreterDirective; + generated$2.intersectionTypeAnnotation = intersectionTypeAnnotation; + generated$2.jSXAttribute = generated$2.jsxAttribute = jsxAttribute; + generated$2.jSXClosingElement = generated$2.jsxClosingElement = jsxClosingElement; + generated$2.jSXClosingFragment = generated$2.jsxClosingFragment = jsxClosingFragment; + generated$2.jSXElement = generated$2.jsxElement = jsxElement; + generated$2.jSXEmptyExpression = generated$2.jsxEmptyExpression = jsxEmptyExpression; + generated$2.jSXExpressionContainer = generated$2.jsxExpressionContainer = jsxExpressionContainer; + generated$2.jSXFragment = generated$2.jsxFragment = jsxFragment; + generated$2.jSXIdentifier = generated$2.jsxIdentifier = jsxIdentifier; + generated$2.jSXMemberExpression = generated$2.jsxMemberExpression = jsxMemberExpression; + generated$2.jSXNamespacedName = generated$2.jsxNamespacedName = jsxNamespacedName; + generated$2.jSXOpeningElement = generated$2.jsxOpeningElement = jsxOpeningElement; + generated$2.jSXOpeningFragment = generated$2.jsxOpeningFragment = jsxOpeningFragment; + generated$2.jSXSpreadAttribute = generated$2.jsxSpreadAttribute = jsxSpreadAttribute; + generated$2.jSXSpreadChild = generated$2.jsxSpreadChild = jsxSpreadChild; + generated$2.jSXText = generated$2.jsxText = jsxText; + generated$2.labeledStatement = labeledStatement; + generated$2.logicalExpression = logicalExpression; + generated$2.memberExpression = memberExpression; + generated$2.metaProperty = metaProperty; + generated$2.mixedTypeAnnotation = mixedTypeAnnotation; + generated$2.moduleExpression = moduleExpression; + generated$2.newExpression = newExpression; + generated$2.noop = noop; + generated$2.nullLiteral = nullLiteral; + generated$2.nullLiteralTypeAnnotation = nullLiteralTypeAnnotation; + generated$2.nullableTypeAnnotation = nullableTypeAnnotation; + generated$2.numberLiteral = NumberLiteral; + generated$2.numberLiteralTypeAnnotation = numberLiteralTypeAnnotation; + generated$2.numberTypeAnnotation = numberTypeAnnotation; + generated$2.numericLiteral = numericLiteral; + generated$2.objectExpression = objectExpression; + generated$2.objectMethod = objectMethod; + generated$2.objectPattern = objectPattern; + generated$2.objectProperty = objectProperty; + generated$2.objectTypeAnnotation = objectTypeAnnotation; + generated$2.objectTypeCallProperty = objectTypeCallProperty; + generated$2.objectTypeIndexer = objectTypeIndexer; + generated$2.objectTypeInternalSlot = objectTypeInternalSlot; + generated$2.objectTypeProperty = objectTypeProperty; + generated$2.objectTypeSpreadProperty = objectTypeSpreadProperty; + generated$2.opaqueType = opaqueType; + generated$2.optionalCallExpression = optionalCallExpression; + generated$2.optionalIndexedAccessType = optionalIndexedAccessType; + generated$2.optionalMemberExpression = optionalMemberExpression; + generated$2.parenthesizedExpression = parenthesizedExpression; + generated$2.pipelineBareFunction = pipelineBareFunction; + generated$2.pipelinePrimaryTopicReference = pipelinePrimaryTopicReference; + generated$2.pipelineTopicExpression = pipelineTopicExpression; + generated$2.placeholder = placeholder; + generated$2.privateName = privateName; + generated$2.program = program; + generated$2.qualifiedTypeIdentifier = qualifiedTypeIdentifier; + generated$2.recordExpression = recordExpression; + generated$2.regExpLiteral = regExpLiteral; + generated$2.regexLiteral = RegexLiteral; + generated$2.restElement = restElement; + generated$2.restProperty = RestProperty; + generated$2.returnStatement = returnStatement; + generated$2.sequenceExpression = sequenceExpression; + generated$2.spreadElement = spreadElement; + generated$2.spreadProperty = SpreadProperty; + generated$2.staticBlock = staticBlock; + generated$2.stringLiteral = stringLiteral; + generated$2.stringLiteralTypeAnnotation = stringLiteralTypeAnnotation; + generated$2.stringTypeAnnotation = stringTypeAnnotation; + generated$2.super = _super; + generated$2.switchCase = switchCase; + generated$2.switchStatement = switchStatement; + generated$2.symbolTypeAnnotation = symbolTypeAnnotation; + generated$2.taggedTemplateExpression = taggedTemplateExpression; + generated$2.templateElement = templateElement; + generated$2.templateLiteral = templateLiteral; + generated$2.thisExpression = thisExpression; + generated$2.thisTypeAnnotation = thisTypeAnnotation; + generated$2.throwStatement = throwStatement; + generated$2.topicReference = topicReference; + generated$2.tryStatement = tryStatement; + generated$2.tSAnyKeyword = generated$2.tsAnyKeyword = tsAnyKeyword; + generated$2.tSArrayType = generated$2.tsArrayType = tsArrayType; + generated$2.tSAsExpression = generated$2.tsAsExpression = tsAsExpression; + generated$2.tSBigIntKeyword = generated$2.tsBigIntKeyword = tsBigIntKeyword; + generated$2.tSBooleanKeyword = generated$2.tsBooleanKeyword = tsBooleanKeyword; + generated$2.tSCallSignatureDeclaration = generated$2.tsCallSignatureDeclaration = tsCallSignatureDeclaration; + generated$2.tSConditionalType = generated$2.tsConditionalType = tsConditionalType; + generated$2.tSConstructSignatureDeclaration = generated$2.tsConstructSignatureDeclaration = tsConstructSignatureDeclaration; + generated$2.tSConstructorType = generated$2.tsConstructorType = tsConstructorType; + generated$2.tSDeclareFunction = generated$2.tsDeclareFunction = tsDeclareFunction; + generated$2.tSDeclareMethod = generated$2.tsDeclareMethod = tsDeclareMethod; + generated$2.tSEnumDeclaration = generated$2.tsEnumDeclaration = tsEnumDeclaration; + generated$2.tSEnumMember = generated$2.tsEnumMember = tsEnumMember; + generated$2.tSExportAssignment = generated$2.tsExportAssignment = tsExportAssignment; + generated$2.tSExpressionWithTypeArguments = generated$2.tsExpressionWithTypeArguments = tsExpressionWithTypeArguments; + generated$2.tSExternalModuleReference = generated$2.tsExternalModuleReference = tsExternalModuleReference; + generated$2.tSFunctionType = generated$2.tsFunctionType = tsFunctionType; + generated$2.tSImportEqualsDeclaration = generated$2.tsImportEqualsDeclaration = tsImportEqualsDeclaration; + generated$2.tSImportType = generated$2.tsImportType = tsImportType; + generated$2.tSIndexSignature = generated$2.tsIndexSignature = tsIndexSignature; + generated$2.tSIndexedAccessType = generated$2.tsIndexedAccessType = tsIndexedAccessType; + generated$2.tSInferType = generated$2.tsInferType = tsInferType; + generated$2.tSInstantiationExpression = generated$2.tsInstantiationExpression = tsInstantiationExpression; + generated$2.tSInterfaceBody = generated$2.tsInterfaceBody = tsInterfaceBody; + generated$2.tSInterfaceDeclaration = generated$2.tsInterfaceDeclaration = tsInterfaceDeclaration; + generated$2.tSIntersectionType = generated$2.tsIntersectionType = tsIntersectionType; + generated$2.tSIntrinsicKeyword = generated$2.tsIntrinsicKeyword = tsIntrinsicKeyword; + generated$2.tSLiteralType = generated$2.tsLiteralType = tsLiteralType; + generated$2.tSMappedType = generated$2.tsMappedType = tsMappedType; + generated$2.tSMethodSignature = generated$2.tsMethodSignature = tsMethodSignature; + generated$2.tSModuleBlock = generated$2.tsModuleBlock = tsModuleBlock; + generated$2.tSModuleDeclaration = generated$2.tsModuleDeclaration = tsModuleDeclaration; + generated$2.tSNamedTupleMember = generated$2.tsNamedTupleMember = tsNamedTupleMember; + generated$2.tSNamespaceExportDeclaration = generated$2.tsNamespaceExportDeclaration = tsNamespaceExportDeclaration; + generated$2.tSNeverKeyword = generated$2.tsNeverKeyword = tsNeverKeyword; + generated$2.tSNonNullExpression = generated$2.tsNonNullExpression = tsNonNullExpression; + generated$2.tSNullKeyword = generated$2.tsNullKeyword = tsNullKeyword; + generated$2.tSNumberKeyword = generated$2.tsNumberKeyword = tsNumberKeyword; + generated$2.tSObjectKeyword = generated$2.tsObjectKeyword = tsObjectKeyword; + generated$2.tSOptionalType = generated$2.tsOptionalType = tsOptionalType; + generated$2.tSParameterProperty = generated$2.tsParameterProperty = tsParameterProperty; + generated$2.tSParenthesizedType = generated$2.tsParenthesizedType = tsParenthesizedType; + generated$2.tSPropertySignature = generated$2.tsPropertySignature = tsPropertySignature; + generated$2.tSQualifiedName = generated$2.tsQualifiedName = tsQualifiedName; + generated$2.tSRestType = generated$2.tsRestType = tsRestType; + generated$2.tSSatisfiesExpression = generated$2.tsSatisfiesExpression = tsSatisfiesExpression; + generated$2.tSStringKeyword = generated$2.tsStringKeyword = tsStringKeyword; + generated$2.tSSymbolKeyword = generated$2.tsSymbolKeyword = tsSymbolKeyword; + generated$2.tSThisType = generated$2.tsThisType = tsThisType; + generated$2.tSTupleType = generated$2.tsTupleType = tsTupleType; + generated$2.tSTypeAliasDeclaration = generated$2.tsTypeAliasDeclaration = tsTypeAliasDeclaration; + generated$2.tSTypeAnnotation = generated$2.tsTypeAnnotation = tsTypeAnnotation; + generated$2.tSTypeAssertion = generated$2.tsTypeAssertion = tsTypeAssertion; + generated$2.tSTypeLiteral = generated$2.tsTypeLiteral = tsTypeLiteral; + generated$2.tSTypeOperator = generated$2.tsTypeOperator = tsTypeOperator; + generated$2.tSTypeParameter = generated$2.tsTypeParameter = tsTypeParameter; + generated$2.tSTypeParameterDeclaration = generated$2.tsTypeParameterDeclaration = tsTypeParameterDeclaration; + generated$2.tSTypeParameterInstantiation = generated$2.tsTypeParameterInstantiation = tsTypeParameterInstantiation; + generated$2.tSTypePredicate = generated$2.tsTypePredicate = tsTypePredicate; + generated$2.tSTypeQuery = generated$2.tsTypeQuery = tsTypeQuery; + generated$2.tSTypeReference = generated$2.tsTypeReference = tsTypeReference; + generated$2.tSUndefinedKeyword = generated$2.tsUndefinedKeyword = tsUndefinedKeyword; + generated$2.tSUnionType = generated$2.tsUnionType = tsUnionType; + generated$2.tSUnknownKeyword = generated$2.tsUnknownKeyword = tsUnknownKeyword; + generated$2.tSVoidKeyword = generated$2.tsVoidKeyword = tsVoidKeyword; + generated$2.tupleExpression = tupleExpression; + generated$2.tupleTypeAnnotation = tupleTypeAnnotation; + generated$2.typeAlias = typeAlias; + generated$2.typeAnnotation = typeAnnotation; + generated$2.typeCastExpression = typeCastExpression; + generated$2.typeParameter = typeParameter; + generated$2.typeParameterDeclaration = typeParameterDeclaration; + generated$2.typeParameterInstantiation = typeParameterInstantiation; + generated$2.typeofTypeAnnotation = typeofTypeAnnotation; + generated$2.unaryExpression = unaryExpression; + generated$2.unionTypeAnnotation = unionTypeAnnotation; + generated$2.updateExpression = updateExpression; + generated$2.v8IntrinsicIdentifier = v8IntrinsicIdentifier; + generated$2.variableDeclaration = variableDeclaration; + generated$2.variableDeclarator = variableDeclarator; + generated$2.variance = variance; + generated$2.voidTypeAnnotation = voidTypeAnnotation; + generated$2.whileStatement = whileStatement; + generated$2.withStatement = withStatement; + generated$2.yieldExpression = yieldExpression; + var _validate = requireValidate(); + var _deprecationWarning = requireDeprecationWarning(); + var utils = requireUtils(); + const { + validateInternal: validate + } = _validate; + const { + NODE_FIELDS + } = utils; + function arrayExpression(elements = []) { + const node = { + type: "ArrayExpression", + elements + }; + const defs = NODE_FIELDS.ArrayExpression; + validate(defs.elements, node, "elements", elements, 1); + return node; + } + function assignmentExpression(operator, left, right) { + const node = { + type: "AssignmentExpression", + operator, + left, + right + }; + const defs = NODE_FIELDS.AssignmentExpression; + validate(defs.operator, node, "operator", operator); + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function binaryExpression(operator, left, right) { + const node = { + type: "BinaryExpression", + operator, + left, + right + }; + const defs = NODE_FIELDS.BinaryExpression; + validate(defs.operator, node, "operator", operator); + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function interpreterDirective(value) { + const node = { + type: "InterpreterDirective", + value + }; + const defs = NODE_FIELDS.InterpreterDirective; + validate(defs.value, node, "value", value); + return node; + } + function directive(value) { + const node = { + type: "Directive", + value + }; + const defs = NODE_FIELDS.Directive; + validate(defs.value, node, "value", value, 1); + return node; + } + function directiveLiteral(value) { + const node = { + type: "DirectiveLiteral", + value + }; + const defs = NODE_FIELDS.DirectiveLiteral; + validate(defs.value, node, "value", value); + return node; + } + function blockStatement(body, directives = []) { + const node = { + type: "BlockStatement", + body, + directives + }; + const defs = NODE_FIELDS.BlockStatement; + validate(defs.body, node, "body", body, 1); + validate(defs.directives, node, "directives", directives, 1); + return node; + } + function breakStatement(label = null) { + const node = { + type: "BreakStatement", + label + }; + const defs = NODE_FIELDS.BreakStatement; + validate(defs.label, node, "label", label, 1); + return node; + } + function callExpression(callee, _arguments) { + const node = { + type: "CallExpression", + callee, + arguments: _arguments + }; + const defs = NODE_FIELDS.CallExpression; + validate(defs.callee, node, "callee", callee, 1); + validate(defs.arguments, node, "arguments", _arguments, 1); + return node; + } + function catchClause(param = null, body) { + const node = { + type: "CatchClause", + param, + body + }; + const defs = NODE_FIELDS.CatchClause; + validate(defs.param, node, "param", param, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function conditionalExpression(test, consequent, alternate) { + const node = { + type: "ConditionalExpression", + test, + consequent, + alternate + }; + const defs = NODE_FIELDS.ConditionalExpression; + validate(defs.test, node, "test", test, 1); + validate(defs.consequent, node, "consequent", consequent, 1); + validate(defs.alternate, node, "alternate", alternate, 1); + return node; + } + function continueStatement(label = null) { + const node = { + type: "ContinueStatement", + label + }; + const defs = NODE_FIELDS.ContinueStatement; + validate(defs.label, node, "label", label, 1); + return node; + } + function debuggerStatement() { + return { + type: "DebuggerStatement" + }; + } + function doWhileStatement(test, body) { + const node = { + type: "DoWhileStatement", + test, + body + }; + const defs = NODE_FIELDS.DoWhileStatement; + validate(defs.test, node, "test", test, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function emptyStatement() { + return { + type: "EmptyStatement" + }; + } + function expressionStatement(expression) { + const node = { + type: "ExpressionStatement", + expression + }; + const defs = NODE_FIELDS.ExpressionStatement; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function file(program, comments = null, tokens = null) { + const node = { + type: "File", + program, + comments, + tokens + }; + const defs = NODE_FIELDS.File; + validate(defs.program, node, "program", program, 1); + validate(defs.comments, node, "comments", comments, 1); + validate(defs.tokens, node, "tokens", tokens); + return node; + } + function forInStatement(left, right, body) { + const node = { + type: "ForInStatement", + left, + right, + body + }; + const defs = NODE_FIELDS.ForInStatement; + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function forStatement(init = null, test = null, update = null, body) { + const node = { + type: "ForStatement", + init, + test, + update, + body + }; + const defs = NODE_FIELDS.ForStatement; + validate(defs.init, node, "init", init, 1); + validate(defs.test, node, "test", test, 1); + validate(defs.update, node, "update", update, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function functionDeclaration(id = null, params, body, generator = false, async = false) { + const node = { + type: "FunctionDeclaration", + id, + params, + body, + generator, + async + }; + const defs = NODE_FIELDS.FunctionDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.generator, node, "generator", generator); + validate(defs.async, node, "async", async); + return node; + } + function functionExpression(id = null, params, body, generator = false, async = false) { + const node = { + type: "FunctionExpression", + id, + params, + body, + generator, + async + }; + const defs = NODE_FIELDS.FunctionExpression; + validate(defs.id, node, "id", id, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.generator, node, "generator", generator); + validate(defs.async, node, "async", async); + return node; + } + function identifier(name) { + const node = { + type: "Identifier", + name + }; + const defs = NODE_FIELDS.Identifier; + validate(defs.name, node, "name", name); + return node; + } + function ifStatement(test, consequent, alternate = null) { + const node = { + type: "IfStatement", + test, + consequent, + alternate + }; + const defs = NODE_FIELDS.IfStatement; + validate(defs.test, node, "test", test, 1); + validate(defs.consequent, node, "consequent", consequent, 1); + validate(defs.alternate, node, "alternate", alternate, 1); + return node; + } + function labeledStatement(label, body) { + const node = { + type: "LabeledStatement", + label, + body + }; + const defs = NODE_FIELDS.LabeledStatement; + validate(defs.label, node, "label", label, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function stringLiteral(value) { + const node = { + type: "StringLiteral", + value + }; + const defs = NODE_FIELDS.StringLiteral; + validate(defs.value, node, "value", value); + return node; + } + function numericLiteral(value) { + const node = { + type: "NumericLiteral", + value + }; + const defs = NODE_FIELDS.NumericLiteral; + validate(defs.value, node, "value", value); + return node; + } + function nullLiteral() { + return { + type: "NullLiteral" + }; + } + function booleanLiteral(value) { + const node = { + type: "BooleanLiteral", + value + }; + const defs = NODE_FIELDS.BooleanLiteral; + validate(defs.value, node, "value", value); + return node; + } + function regExpLiteral(pattern, flags = "") { + const node = { + type: "RegExpLiteral", + pattern, + flags + }; + const defs = NODE_FIELDS.RegExpLiteral; + validate(defs.pattern, node, "pattern", pattern); + validate(defs.flags, node, "flags", flags); + return node; + } + function logicalExpression(operator, left, right) { + const node = { + type: "LogicalExpression", + operator, + left, + right + }; + const defs = NODE_FIELDS.LogicalExpression; + validate(defs.operator, node, "operator", operator); + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function memberExpression(object, property, computed = false, optional = null) { + const node = { + type: "MemberExpression", + object, + property, + computed, + optional + }; + const defs = NODE_FIELDS.MemberExpression; + validate(defs.object, node, "object", object, 1); + validate(defs.property, node, "property", property, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.optional, node, "optional", optional); + return node; + } + function newExpression(callee, _arguments) { + const node = { + type: "NewExpression", + callee, + arguments: _arguments + }; + const defs = NODE_FIELDS.NewExpression; + validate(defs.callee, node, "callee", callee, 1); + validate(defs.arguments, node, "arguments", _arguments, 1); + return node; + } + function program(body, directives = [], sourceType = "script", interpreter = null) { + const node = { + type: "Program", + body, + directives, + sourceType, + interpreter + }; + const defs = NODE_FIELDS.Program; + validate(defs.body, node, "body", body, 1); + validate(defs.directives, node, "directives", directives, 1); + validate(defs.sourceType, node, "sourceType", sourceType); + validate(defs.interpreter, node, "interpreter", interpreter, 1); + return node; + } + function objectExpression(properties) { + const node = { + type: "ObjectExpression", + properties + }; + const defs = NODE_FIELDS.ObjectExpression; + validate(defs.properties, node, "properties", properties, 1); + return node; + } + function objectMethod(kind = "method", key, params, body, computed = false, generator = false, async = false) { + const node = { + type: "ObjectMethod", + kind, + key, + params, + body, + computed, + generator, + async + }; + const defs = NODE_FIELDS.ObjectMethod; + validate(defs.kind, node, "kind", kind); + validate(defs.key, node, "key", key, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.generator, node, "generator", generator); + validate(defs.async, node, "async", async); + return node; + } + function objectProperty(key, value, computed = false, shorthand = false, decorators = null) { + const node = { + type: "ObjectProperty", + key, + value, + computed, + shorthand, + decorators + }; + const defs = NODE_FIELDS.ObjectProperty; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.shorthand, node, "shorthand", shorthand); + validate(defs.decorators, node, "decorators", decorators, 1); + return node; + } + function restElement(argument) { + const node = { + type: "RestElement", + argument + }; + const defs = NODE_FIELDS.RestElement; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function returnStatement(argument = null) { + const node = { + type: "ReturnStatement", + argument + }; + const defs = NODE_FIELDS.ReturnStatement; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function sequenceExpression(expressions) { + const node = { + type: "SequenceExpression", + expressions + }; + const defs = NODE_FIELDS.SequenceExpression; + validate(defs.expressions, node, "expressions", expressions, 1); + return node; + } + function parenthesizedExpression(expression) { + const node = { + type: "ParenthesizedExpression", + expression + }; + const defs = NODE_FIELDS.ParenthesizedExpression; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function switchCase(test = null, consequent) { + const node = { + type: "SwitchCase", + test, + consequent + }; + const defs = NODE_FIELDS.SwitchCase; + validate(defs.test, node, "test", test, 1); + validate(defs.consequent, node, "consequent", consequent, 1); + return node; + } + function switchStatement(discriminant, cases) { + const node = { + type: "SwitchStatement", + discriminant, + cases + }; + const defs = NODE_FIELDS.SwitchStatement; + validate(defs.discriminant, node, "discriminant", discriminant, 1); + validate(defs.cases, node, "cases", cases, 1); + return node; + } + function thisExpression() { + return { + type: "ThisExpression" + }; + } + function throwStatement(argument) { + const node = { + type: "ThrowStatement", + argument + }; + const defs = NODE_FIELDS.ThrowStatement; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function tryStatement(block, handler = null, finalizer = null) { + const node = { + type: "TryStatement", + block, + handler, + finalizer + }; + const defs = NODE_FIELDS.TryStatement; + validate(defs.block, node, "block", block, 1); + validate(defs.handler, node, "handler", handler, 1); + validate(defs.finalizer, node, "finalizer", finalizer, 1); + return node; + } + function unaryExpression(operator, argument, prefix = true) { + const node = { + type: "UnaryExpression", + operator, + argument, + prefix + }; + const defs = NODE_FIELDS.UnaryExpression; + validate(defs.operator, node, "operator", operator); + validate(defs.argument, node, "argument", argument, 1); + validate(defs.prefix, node, "prefix", prefix); + return node; + } + function updateExpression(operator, argument, prefix = false) { + const node = { + type: "UpdateExpression", + operator, + argument, + prefix + }; + const defs = NODE_FIELDS.UpdateExpression; + validate(defs.operator, node, "operator", operator); + validate(defs.argument, node, "argument", argument, 1); + validate(defs.prefix, node, "prefix", prefix); + return node; + } + function variableDeclaration(kind, declarations) { + const node = { + type: "VariableDeclaration", + kind, + declarations + }; + const defs = NODE_FIELDS.VariableDeclaration; + validate(defs.kind, node, "kind", kind); + validate(defs.declarations, node, "declarations", declarations, 1); + return node; + } + function variableDeclarator(id, init = null) { + const node = { + type: "VariableDeclarator", + id, + init + }; + const defs = NODE_FIELDS.VariableDeclarator; + validate(defs.id, node, "id", id, 1); + validate(defs.init, node, "init", init, 1); + return node; + } + function whileStatement(test, body) { + const node = { + type: "WhileStatement", + test, + body + }; + const defs = NODE_FIELDS.WhileStatement; + validate(defs.test, node, "test", test, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function withStatement(object, body) { + const node = { + type: "WithStatement", + object, + body + }; + const defs = NODE_FIELDS.WithStatement; + validate(defs.object, node, "object", object, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function assignmentPattern(left, right) { + const node = { + type: "AssignmentPattern", + left, + right + }; + const defs = NODE_FIELDS.AssignmentPattern; + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function arrayPattern(elements) { + const node = { + type: "ArrayPattern", + elements + }; + const defs = NODE_FIELDS.ArrayPattern; + validate(defs.elements, node, "elements", elements, 1); + return node; + } + function arrowFunctionExpression(params, body, async = false) { + const node = { + type: "ArrowFunctionExpression", + params, + body, + async, + expression: null + }; + const defs = NODE_FIELDS.ArrowFunctionExpression; + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.async, node, "async", async); + return node; + } + function classBody(body) { + const node = { + type: "ClassBody", + body + }; + const defs = NODE_FIELDS.ClassBody; + validate(defs.body, node, "body", body, 1); + return node; + } + function classExpression(id = null, superClass = null, body, decorators = null) { + const node = { + type: "ClassExpression", + id, + superClass, + body, + decorators + }; + const defs = NODE_FIELDS.ClassExpression; + validate(defs.id, node, "id", id, 1); + validate(defs.superClass, node, "superClass", superClass, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.decorators, node, "decorators", decorators, 1); + return node; + } + function classDeclaration(id = null, superClass = null, body, decorators = null) { + const node = { + type: "ClassDeclaration", + id, + superClass, + body, + decorators + }; + const defs = NODE_FIELDS.ClassDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.superClass, node, "superClass", superClass, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.decorators, node, "decorators", decorators, 1); + return node; + } + function exportAllDeclaration(source) { + const node = { + type: "ExportAllDeclaration", + source + }; + const defs = NODE_FIELDS.ExportAllDeclaration; + validate(defs.source, node, "source", source, 1); + return node; + } + function exportDefaultDeclaration(declaration) { + const node = { + type: "ExportDefaultDeclaration", + declaration + }; + const defs = NODE_FIELDS.ExportDefaultDeclaration; + validate(defs.declaration, node, "declaration", declaration, 1); + return node; + } + function exportNamedDeclaration(declaration = null, specifiers = [], source = null) { + const node = { + type: "ExportNamedDeclaration", + declaration, + specifiers, + source + }; + const defs = NODE_FIELDS.ExportNamedDeclaration; + validate(defs.declaration, node, "declaration", declaration, 1); + validate(defs.specifiers, node, "specifiers", specifiers, 1); + validate(defs.source, node, "source", source, 1); + return node; + } + function exportSpecifier(local, exported) { + const node = { + type: "ExportSpecifier", + local, + exported + }; + const defs = NODE_FIELDS.ExportSpecifier; + validate(defs.local, node, "local", local, 1); + validate(defs.exported, node, "exported", exported, 1); + return node; + } + function forOfStatement(left, right, body, _await = false) { + const node = { + type: "ForOfStatement", + left, + right, + body, + await: _await + }; + const defs = NODE_FIELDS.ForOfStatement; + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.await, node, "await", _await); + return node; + } + function importDeclaration(specifiers, source) { + const node = { + type: "ImportDeclaration", + specifiers, + source + }; + const defs = NODE_FIELDS.ImportDeclaration; + validate(defs.specifiers, node, "specifiers", specifiers, 1); + validate(defs.source, node, "source", source, 1); + return node; + } + function importDefaultSpecifier(local) { + const node = { + type: "ImportDefaultSpecifier", + local + }; + const defs = NODE_FIELDS.ImportDefaultSpecifier; + validate(defs.local, node, "local", local, 1); + return node; + } + function importNamespaceSpecifier(local) { + const node = { + type: "ImportNamespaceSpecifier", + local + }; + const defs = NODE_FIELDS.ImportNamespaceSpecifier; + validate(defs.local, node, "local", local, 1); + return node; + } + function importSpecifier(local, imported) { + const node = { + type: "ImportSpecifier", + local, + imported + }; + const defs = NODE_FIELDS.ImportSpecifier; + validate(defs.local, node, "local", local, 1); + validate(defs.imported, node, "imported", imported, 1); + return node; + } + function importExpression(source, options = null) { + const node = { + type: "ImportExpression", + source, + options + }; + const defs = NODE_FIELDS.ImportExpression; + validate(defs.source, node, "source", source, 1); + validate(defs.options, node, "options", options, 1); + return node; + } + function metaProperty(meta, property) { + const node = { + type: "MetaProperty", + meta, + property + }; + const defs = NODE_FIELDS.MetaProperty; + validate(defs.meta, node, "meta", meta, 1); + validate(defs.property, node, "property", property, 1); + return node; + } + function classMethod(kind = "method", key, params, body, computed = false, _static = false, generator = false, async = false) { + const node = { + type: "ClassMethod", + kind, + key, + params, + body, + computed, + static: _static, + generator, + async + }; + const defs = NODE_FIELDS.ClassMethod; + validate(defs.kind, node, "kind", kind); + validate(defs.key, node, "key", key, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.static, node, "static", _static); + validate(defs.generator, node, "generator", generator); + validate(defs.async, node, "async", async); + return node; + } + function objectPattern(properties) { + const node = { + type: "ObjectPattern", + properties + }; + const defs = NODE_FIELDS.ObjectPattern; + validate(defs.properties, node, "properties", properties, 1); + return node; + } + function spreadElement(argument) { + const node = { + type: "SpreadElement", + argument + }; + const defs = NODE_FIELDS.SpreadElement; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function _super() { + return { + type: "Super" + }; + } + function taggedTemplateExpression(tag, quasi) { + const node = { + type: "TaggedTemplateExpression", + tag, + quasi + }; + const defs = NODE_FIELDS.TaggedTemplateExpression; + validate(defs.tag, node, "tag", tag, 1); + validate(defs.quasi, node, "quasi", quasi, 1); + return node; + } + function templateElement(value, tail = false) { + const node = { + type: "TemplateElement", + value, + tail + }; + const defs = NODE_FIELDS.TemplateElement; + validate(defs.value, node, "value", value); + validate(defs.tail, node, "tail", tail); + return node; + } + function templateLiteral(quasis, expressions) { + const node = { + type: "TemplateLiteral", + quasis, + expressions + }; + const defs = NODE_FIELDS.TemplateLiteral; + validate(defs.quasis, node, "quasis", quasis, 1); + validate(defs.expressions, node, "expressions", expressions, 1); + return node; + } + function yieldExpression(argument = null, delegate = false) { + const node = { + type: "YieldExpression", + argument, + delegate + }; + const defs = NODE_FIELDS.YieldExpression; + validate(defs.argument, node, "argument", argument, 1); + validate(defs.delegate, node, "delegate", delegate); + return node; + } + function awaitExpression(argument) { + const node = { + type: "AwaitExpression", + argument + }; + const defs = NODE_FIELDS.AwaitExpression; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function _import() { + return { + type: "Import" + }; + } + function bigIntLiteral(value) { + const node = { + type: "BigIntLiteral", + value + }; + const defs = NODE_FIELDS.BigIntLiteral; + validate(defs.value, node, "value", value); + return node; + } + function exportNamespaceSpecifier(exported) { + const node = { + type: "ExportNamespaceSpecifier", + exported + }; + const defs = NODE_FIELDS.ExportNamespaceSpecifier; + validate(defs.exported, node, "exported", exported, 1); + return node; + } + function optionalMemberExpression(object, property, computed = false, optional) { + const node = { + type: "OptionalMemberExpression", + object, + property, + computed, + optional + }; + const defs = NODE_FIELDS.OptionalMemberExpression; + validate(defs.object, node, "object", object, 1); + validate(defs.property, node, "property", property, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.optional, node, "optional", optional); + return node; + } + function optionalCallExpression(callee, _arguments, optional) { + const node = { + type: "OptionalCallExpression", + callee, + arguments: _arguments, + optional + }; + const defs = NODE_FIELDS.OptionalCallExpression; + validate(defs.callee, node, "callee", callee, 1); + validate(defs.arguments, node, "arguments", _arguments, 1); + validate(defs.optional, node, "optional", optional); + return node; + } + function classProperty(key, value = null, typeAnnotation = null, decorators = null, computed = false, _static = false) { + const node = { + type: "ClassProperty", + key, + value, + typeAnnotation, + decorators, + computed, + static: _static + }; + const defs = NODE_FIELDS.ClassProperty; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + validate(defs.decorators, node, "decorators", decorators, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.static, node, "static", _static); + return node; + } + function classAccessorProperty(key, value = null, typeAnnotation = null, decorators = null, computed = false, _static = false) { + const node = { + type: "ClassAccessorProperty", + key, + value, + typeAnnotation, + decorators, + computed, + static: _static + }; + const defs = NODE_FIELDS.ClassAccessorProperty; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + validate(defs.decorators, node, "decorators", decorators, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.static, node, "static", _static); + return node; + } + function classPrivateProperty(key, value = null, decorators = null, _static = false) { + const node = { + type: "ClassPrivateProperty", + key, + value, + decorators, + static: _static + }; + const defs = NODE_FIELDS.ClassPrivateProperty; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.decorators, node, "decorators", decorators, 1); + validate(defs.static, node, "static", _static); + return node; + } + function classPrivateMethod(kind = "method", key, params, body, _static = false) { + const node = { + type: "ClassPrivateMethod", + kind, + key, + params, + body, + static: _static + }; + const defs = NODE_FIELDS.ClassPrivateMethod; + validate(defs.kind, node, "kind", kind); + validate(defs.key, node, "key", key, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.static, node, "static", _static); + return node; + } + function privateName(id) { + const node = { + type: "PrivateName", + id + }; + const defs = NODE_FIELDS.PrivateName; + validate(defs.id, node, "id", id, 1); + return node; + } + function staticBlock(body) { + const node = { + type: "StaticBlock", + body + }; + const defs = NODE_FIELDS.StaticBlock; + validate(defs.body, node, "body", body, 1); + return node; + } + function anyTypeAnnotation() { + return { + type: "AnyTypeAnnotation" + }; + } + function arrayTypeAnnotation(elementType) { + const node = { + type: "ArrayTypeAnnotation", + elementType + }; + const defs = NODE_FIELDS.ArrayTypeAnnotation; + validate(defs.elementType, node, "elementType", elementType, 1); + return node; + } + function booleanTypeAnnotation() { + return { + type: "BooleanTypeAnnotation" + }; + } + function booleanLiteralTypeAnnotation(value) { + const node = { + type: "BooleanLiteralTypeAnnotation", + value + }; + const defs = NODE_FIELDS.BooleanLiteralTypeAnnotation; + validate(defs.value, node, "value", value); + return node; + } + function nullLiteralTypeAnnotation() { + return { + type: "NullLiteralTypeAnnotation" + }; + } + function classImplements(id, typeParameters = null) { + const node = { + type: "ClassImplements", + id, + typeParameters + }; + const defs = NODE_FIELDS.ClassImplements; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function declareClass(id, typeParameters = null, _extends = null, body) { + const node = { + type: "DeclareClass", + id, + typeParameters, + extends: _extends, + body + }; + const defs = NODE_FIELDS.DeclareClass; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.extends, node, "extends", _extends, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function declareFunction(id) { + const node = { + type: "DeclareFunction", + id + }; + const defs = NODE_FIELDS.DeclareFunction; + validate(defs.id, node, "id", id, 1); + return node; + } + function declareInterface(id, typeParameters = null, _extends = null, body) { + const node = { + type: "DeclareInterface", + id, + typeParameters, + extends: _extends, + body + }; + const defs = NODE_FIELDS.DeclareInterface; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.extends, node, "extends", _extends, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function declareModule(id, body, kind = null) { + const node = { + type: "DeclareModule", + id, + body, + kind + }; + const defs = NODE_FIELDS.DeclareModule; + validate(defs.id, node, "id", id, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.kind, node, "kind", kind); + return node; + } + function declareModuleExports(typeAnnotation) { + const node = { + type: "DeclareModuleExports", + typeAnnotation + }; + const defs = NODE_FIELDS.DeclareModuleExports; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function declareTypeAlias(id, typeParameters = null, right) { + const node = { + type: "DeclareTypeAlias", + id, + typeParameters, + right + }; + const defs = NODE_FIELDS.DeclareTypeAlias; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function declareOpaqueType(id, typeParameters = null, supertype = null) { + const node = { + type: "DeclareOpaqueType", + id, + typeParameters, + supertype + }; + const defs = NODE_FIELDS.DeclareOpaqueType; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.supertype, node, "supertype", supertype, 1); + return node; + } + function declareVariable(id) { + const node = { + type: "DeclareVariable", + id + }; + const defs = NODE_FIELDS.DeclareVariable; + validate(defs.id, node, "id", id, 1); + return node; + } + function declareExportDeclaration(declaration = null, specifiers = null, source = null, attributes = null) { + const node = { + type: "DeclareExportDeclaration", + declaration, + specifiers, + source, + attributes + }; + const defs = NODE_FIELDS.DeclareExportDeclaration; + validate(defs.declaration, node, "declaration", declaration, 1); + validate(defs.specifiers, node, "specifiers", specifiers, 1); + validate(defs.source, node, "source", source, 1); + validate(defs.attributes, node, "attributes", attributes, 1); + return node; + } + function declareExportAllDeclaration(source, attributes = null) { + const node = { + type: "DeclareExportAllDeclaration", + source, + attributes + }; + const defs = NODE_FIELDS.DeclareExportAllDeclaration; + validate(defs.source, node, "source", source, 1); + validate(defs.attributes, node, "attributes", attributes, 1); + return node; + } + function declaredPredicate(value) { + const node = { + type: "DeclaredPredicate", + value + }; + const defs = NODE_FIELDS.DeclaredPredicate; + validate(defs.value, node, "value", value, 1); + return node; + } + function existsTypeAnnotation() { + return { + type: "ExistsTypeAnnotation" + }; + } + function functionTypeAnnotation(typeParameters = null, params, rest = null, returnType) { + const node = { + type: "FunctionTypeAnnotation", + typeParameters, + params, + rest, + returnType + }; + const defs = NODE_FIELDS.FunctionTypeAnnotation; + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.rest, node, "rest", rest, 1); + validate(defs.returnType, node, "returnType", returnType, 1); + return node; + } + function functionTypeParam(name = null, typeAnnotation) { + const node = { + type: "FunctionTypeParam", + name, + typeAnnotation + }; + const defs = NODE_FIELDS.FunctionTypeParam; + validate(defs.name, node, "name", name, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function genericTypeAnnotation(id, typeParameters = null) { + const node = { + type: "GenericTypeAnnotation", + id, + typeParameters + }; + const defs = NODE_FIELDS.GenericTypeAnnotation; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function inferredPredicate() { + return { + type: "InferredPredicate" + }; + } + function interfaceExtends(id, typeParameters = null) { + const node = { + type: "InterfaceExtends", + id, + typeParameters + }; + const defs = NODE_FIELDS.InterfaceExtends; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function interfaceDeclaration(id, typeParameters = null, _extends = null, body) { + const node = { + type: "InterfaceDeclaration", + id, + typeParameters, + extends: _extends, + body + }; + const defs = NODE_FIELDS.InterfaceDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.extends, node, "extends", _extends, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function interfaceTypeAnnotation(_extends = null, body) { + const node = { + type: "InterfaceTypeAnnotation", + extends: _extends, + body + }; + const defs = NODE_FIELDS.InterfaceTypeAnnotation; + validate(defs.extends, node, "extends", _extends, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function intersectionTypeAnnotation(types) { + const node = { + type: "IntersectionTypeAnnotation", + types + }; + const defs = NODE_FIELDS.IntersectionTypeAnnotation; + validate(defs.types, node, "types", types, 1); + return node; + } + function mixedTypeAnnotation() { + return { + type: "MixedTypeAnnotation" + }; + } + function emptyTypeAnnotation() { + return { + type: "EmptyTypeAnnotation" + }; + } + function nullableTypeAnnotation(typeAnnotation) { + const node = { + type: "NullableTypeAnnotation", + typeAnnotation + }; + const defs = NODE_FIELDS.NullableTypeAnnotation; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function numberLiteralTypeAnnotation(value) { + const node = { + type: "NumberLiteralTypeAnnotation", + value + }; + const defs = NODE_FIELDS.NumberLiteralTypeAnnotation; + validate(defs.value, node, "value", value); + return node; + } + function numberTypeAnnotation() { + return { + type: "NumberTypeAnnotation" + }; + } + function objectTypeAnnotation(properties, indexers = [], callProperties = [], internalSlots = [], exact = false) { + const node = { + type: "ObjectTypeAnnotation", + properties, + indexers, + callProperties, + internalSlots, + exact + }; + const defs = NODE_FIELDS.ObjectTypeAnnotation; + validate(defs.properties, node, "properties", properties, 1); + validate(defs.indexers, node, "indexers", indexers, 1); + validate(defs.callProperties, node, "callProperties", callProperties, 1); + validate(defs.internalSlots, node, "internalSlots", internalSlots, 1); + validate(defs.exact, node, "exact", exact); + return node; + } + function objectTypeInternalSlot(id, value, optional, _static, method) { + const node = { + type: "ObjectTypeInternalSlot", + id, + value, + optional, + static: _static, + method + }; + const defs = NODE_FIELDS.ObjectTypeInternalSlot; + validate(defs.id, node, "id", id, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.optional, node, "optional", optional); + validate(defs.static, node, "static", _static); + validate(defs.method, node, "method", method); + return node; + } + function objectTypeCallProperty(value) { + const node = { + type: "ObjectTypeCallProperty", + value, + static: null + }; + const defs = NODE_FIELDS.ObjectTypeCallProperty; + validate(defs.value, node, "value", value, 1); + return node; + } + function objectTypeIndexer(id = null, key, value, variance = null) { + const node = { + type: "ObjectTypeIndexer", + id, + key, + value, + variance, + static: null + }; + const defs = NODE_FIELDS.ObjectTypeIndexer; + validate(defs.id, node, "id", id, 1); + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.variance, node, "variance", variance, 1); + return node; + } + function objectTypeProperty(key, value, variance = null) { + const node = { + type: "ObjectTypeProperty", + key, + value, + variance, + kind: null, + method: null, + optional: null, + proto: null, + static: null + }; + const defs = NODE_FIELDS.ObjectTypeProperty; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.variance, node, "variance", variance, 1); + return node; + } + function objectTypeSpreadProperty(argument) { + const node = { + type: "ObjectTypeSpreadProperty", + argument + }; + const defs = NODE_FIELDS.ObjectTypeSpreadProperty; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function opaqueType(id, typeParameters = null, supertype = null, impltype) { + const node = { + type: "OpaqueType", + id, + typeParameters, + supertype, + impltype + }; + const defs = NODE_FIELDS.OpaqueType; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.supertype, node, "supertype", supertype, 1); + validate(defs.impltype, node, "impltype", impltype, 1); + return node; + } + function qualifiedTypeIdentifier(id, qualification) { + const node = { + type: "QualifiedTypeIdentifier", + id, + qualification + }; + const defs = NODE_FIELDS.QualifiedTypeIdentifier; + validate(defs.id, node, "id", id, 1); + validate(defs.qualification, node, "qualification", qualification, 1); + return node; + } + function stringLiteralTypeAnnotation(value) { + const node = { + type: "StringLiteralTypeAnnotation", + value + }; + const defs = NODE_FIELDS.StringLiteralTypeAnnotation; + validate(defs.value, node, "value", value); + return node; + } + function stringTypeAnnotation() { + return { + type: "StringTypeAnnotation" + }; + } + function symbolTypeAnnotation() { + return { + type: "SymbolTypeAnnotation" + }; + } + function thisTypeAnnotation() { + return { + type: "ThisTypeAnnotation" + }; + } + function tupleTypeAnnotation(types) { + const node = { + type: "TupleTypeAnnotation", + types + }; + const defs = NODE_FIELDS.TupleTypeAnnotation; + validate(defs.types, node, "types", types, 1); + return node; + } + function typeofTypeAnnotation(argument) { + const node = { + type: "TypeofTypeAnnotation", + argument + }; + const defs = NODE_FIELDS.TypeofTypeAnnotation; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function typeAlias(id, typeParameters = null, right) { + const node = { + type: "TypeAlias", + id, + typeParameters, + right + }; + const defs = NODE_FIELDS.TypeAlias; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function typeAnnotation(typeAnnotation) { + const node = { + type: "TypeAnnotation", + typeAnnotation + }; + const defs = NODE_FIELDS.TypeAnnotation; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function typeCastExpression(expression, typeAnnotation) { + const node = { + type: "TypeCastExpression", + expression, + typeAnnotation + }; + const defs = NODE_FIELDS.TypeCastExpression; + validate(defs.expression, node, "expression", expression, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function typeParameter(bound = null, _default = null, variance = null) { + const node = { + type: "TypeParameter", + bound, + default: _default, + variance, + name: null + }; + const defs = NODE_FIELDS.TypeParameter; + validate(defs.bound, node, "bound", bound, 1); + validate(defs.default, node, "default", _default, 1); + validate(defs.variance, node, "variance", variance, 1); + return node; + } + function typeParameterDeclaration(params) { + const node = { + type: "TypeParameterDeclaration", + params + }; + const defs = NODE_FIELDS.TypeParameterDeclaration; + validate(defs.params, node, "params", params, 1); + return node; + } + function typeParameterInstantiation(params) { + const node = { + type: "TypeParameterInstantiation", + params + }; + const defs = NODE_FIELDS.TypeParameterInstantiation; + validate(defs.params, node, "params", params, 1); + return node; + } + function unionTypeAnnotation(types) { + const node = { + type: "UnionTypeAnnotation", + types + }; + const defs = NODE_FIELDS.UnionTypeAnnotation; + validate(defs.types, node, "types", types, 1); + return node; + } + function variance(kind) { + const node = { + type: "Variance", + kind + }; + const defs = NODE_FIELDS.Variance; + validate(defs.kind, node, "kind", kind); + return node; + } + function voidTypeAnnotation() { + return { + type: "VoidTypeAnnotation" + }; + } + function enumDeclaration(id, body) { + const node = { + type: "EnumDeclaration", + id, + body + }; + const defs = NODE_FIELDS.EnumDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function enumBooleanBody(members) { + const node = { + type: "EnumBooleanBody", + members, + explicitType: null, + hasUnknownMembers: null + }; + const defs = NODE_FIELDS.EnumBooleanBody; + validate(defs.members, node, "members", members, 1); + return node; + } + function enumNumberBody(members) { + const node = { + type: "EnumNumberBody", + members, + explicitType: null, + hasUnknownMembers: null + }; + const defs = NODE_FIELDS.EnumNumberBody; + validate(defs.members, node, "members", members, 1); + return node; + } + function enumStringBody(members) { + const node = { + type: "EnumStringBody", + members, + explicitType: null, + hasUnknownMembers: null + }; + const defs = NODE_FIELDS.EnumStringBody; + validate(defs.members, node, "members", members, 1); + return node; + } + function enumSymbolBody(members) { + const node = { + type: "EnumSymbolBody", + members, + hasUnknownMembers: null + }; + const defs = NODE_FIELDS.EnumSymbolBody; + validate(defs.members, node, "members", members, 1); + return node; + } + function enumBooleanMember(id) { + const node = { + type: "EnumBooleanMember", + id, + init: null + }; + const defs = NODE_FIELDS.EnumBooleanMember; + validate(defs.id, node, "id", id, 1); + return node; + } + function enumNumberMember(id, init) { + const node = { + type: "EnumNumberMember", + id, + init + }; + const defs = NODE_FIELDS.EnumNumberMember; + validate(defs.id, node, "id", id, 1); + validate(defs.init, node, "init", init, 1); + return node; + } + function enumStringMember(id, init) { + const node = { + type: "EnumStringMember", + id, + init + }; + const defs = NODE_FIELDS.EnumStringMember; + validate(defs.id, node, "id", id, 1); + validate(defs.init, node, "init", init, 1); + return node; + } + function enumDefaultedMember(id) { + const node = { + type: "EnumDefaultedMember", + id + }; + const defs = NODE_FIELDS.EnumDefaultedMember; + validate(defs.id, node, "id", id, 1); + return node; + } + function indexedAccessType(objectType, indexType) { + const node = { + type: "IndexedAccessType", + objectType, + indexType + }; + const defs = NODE_FIELDS.IndexedAccessType; + validate(defs.objectType, node, "objectType", objectType, 1); + validate(defs.indexType, node, "indexType", indexType, 1); + return node; + } + function optionalIndexedAccessType(objectType, indexType) { + const node = { + type: "OptionalIndexedAccessType", + objectType, + indexType, + optional: null + }; + const defs = NODE_FIELDS.OptionalIndexedAccessType; + validate(defs.objectType, node, "objectType", objectType, 1); + validate(defs.indexType, node, "indexType", indexType, 1); + return node; + } + function jsxAttribute(name, value = null) { + const node = { + type: "JSXAttribute", + name, + value + }; + const defs = NODE_FIELDS.JSXAttribute; + validate(defs.name, node, "name", name, 1); + validate(defs.value, node, "value", value, 1); + return node; + } + function jsxClosingElement(name) { + const node = { + type: "JSXClosingElement", + name + }; + const defs = NODE_FIELDS.JSXClosingElement; + validate(defs.name, node, "name", name, 1); + return node; + } + function jsxElement(openingElement, closingElement = null, children, selfClosing = null) { + const node = { + type: "JSXElement", + openingElement, + closingElement, + children, + selfClosing + }; + const defs = NODE_FIELDS.JSXElement; + validate(defs.openingElement, node, "openingElement", openingElement, 1); + validate(defs.closingElement, node, "closingElement", closingElement, 1); + validate(defs.children, node, "children", children, 1); + validate(defs.selfClosing, node, "selfClosing", selfClosing); + return node; + } + function jsxEmptyExpression() { + return { + type: "JSXEmptyExpression" + }; + } + function jsxExpressionContainer(expression) { + const node = { + type: "JSXExpressionContainer", + expression + }; + const defs = NODE_FIELDS.JSXExpressionContainer; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function jsxSpreadChild(expression) { + const node = { + type: "JSXSpreadChild", + expression + }; + const defs = NODE_FIELDS.JSXSpreadChild; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function jsxIdentifier(name) { + const node = { + type: "JSXIdentifier", + name + }; + const defs = NODE_FIELDS.JSXIdentifier; + validate(defs.name, node, "name", name); + return node; + } + function jsxMemberExpression(object, property) { + const node = { + type: "JSXMemberExpression", + object, + property + }; + const defs = NODE_FIELDS.JSXMemberExpression; + validate(defs.object, node, "object", object, 1); + validate(defs.property, node, "property", property, 1); + return node; + } + function jsxNamespacedName(namespace, name) { + const node = { + type: "JSXNamespacedName", + namespace, + name + }; + const defs = NODE_FIELDS.JSXNamespacedName; + validate(defs.namespace, node, "namespace", namespace, 1); + validate(defs.name, node, "name", name, 1); + return node; + } + function jsxOpeningElement(name, attributes, selfClosing = false) { + const node = { + type: "JSXOpeningElement", + name, + attributes, + selfClosing + }; + const defs = NODE_FIELDS.JSXOpeningElement; + validate(defs.name, node, "name", name, 1); + validate(defs.attributes, node, "attributes", attributes, 1); + validate(defs.selfClosing, node, "selfClosing", selfClosing); + return node; + } + function jsxSpreadAttribute(argument) { + const node = { + type: "JSXSpreadAttribute", + argument + }; + const defs = NODE_FIELDS.JSXSpreadAttribute; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function jsxText(value) { + const node = { + type: "JSXText", + value + }; + const defs = NODE_FIELDS.JSXText; + validate(defs.value, node, "value", value); + return node; + } + function jsxFragment(openingFragment, closingFragment, children) { + const node = { + type: "JSXFragment", + openingFragment, + closingFragment, + children + }; + const defs = NODE_FIELDS.JSXFragment; + validate(defs.openingFragment, node, "openingFragment", openingFragment, 1); + validate(defs.closingFragment, node, "closingFragment", closingFragment, 1); + validate(defs.children, node, "children", children, 1); + return node; + } + function jsxOpeningFragment() { + return { + type: "JSXOpeningFragment" + }; + } + function jsxClosingFragment() { + return { + type: "JSXClosingFragment" + }; + } + function noop() { + return { + type: "Noop" + }; + } + function placeholder(expectedNode, name) { + const node = { + type: "Placeholder", + expectedNode, + name + }; + const defs = NODE_FIELDS.Placeholder; + validate(defs.expectedNode, node, "expectedNode", expectedNode); + validate(defs.name, node, "name", name, 1); + return node; + } + function v8IntrinsicIdentifier(name) { + const node = { + type: "V8IntrinsicIdentifier", + name + }; + const defs = NODE_FIELDS.V8IntrinsicIdentifier; + validate(defs.name, node, "name", name); + return node; + } + function argumentPlaceholder() { + return { + type: "ArgumentPlaceholder" + }; + } + function bindExpression(object, callee) { + const node = { + type: "BindExpression", + object, + callee + }; + const defs = NODE_FIELDS.BindExpression; + validate(defs.object, node, "object", object, 1); + validate(defs.callee, node, "callee", callee, 1); + return node; + } + function importAttribute(key, value) { + const node = { + type: "ImportAttribute", + key, + value + }; + const defs = NODE_FIELDS.ImportAttribute; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + return node; + } + function decorator(expression) { + const node = { + type: "Decorator", + expression + }; + const defs = NODE_FIELDS.Decorator; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function doExpression(body, async = false) { + const node = { + type: "DoExpression", + body, + async + }; + const defs = NODE_FIELDS.DoExpression; + validate(defs.body, node, "body", body, 1); + validate(defs.async, node, "async", async); + return node; + } + function exportDefaultSpecifier(exported) { + const node = { + type: "ExportDefaultSpecifier", + exported + }; + const defs = NODE_FIELDS.ExportDefaultSpecifier; + validate(defs.exported, node, "exported", exported, 1); + return node; + } + function recordExpression(properties) { + const node = { + type: "RecordExpression", + properties + }; + const defs = NODE_FIELDS.RecordExpression; + validate(defs.properties, node, "properties", properties, 1); + return node; + } + function tupleExpression(elements = []) { + const node = { + type: "TupleExpression", + elements + }; + const defs = NODE_FIELDS.TupleExpression; + validate(defs.elements, node, "elements", elements, 1); + return node; + } + function decimalLiteral(value) { + const node = { + type: "DecimalLiteral", + value + }; + const defs = NODE_FIELDS.DecimalLiteral; + validate(defs.value, node, "value", value); + return node; + } + function moduleExpression(body) { + const node = { + type: "ModuleExpression", + body + }; + const defs = NODE_FIELDS.ModuleExpression; + validate(defs.body, node, "body", body, 1); + return node; + } + function topicReference() { + return { + type: "TopicReference" + }; + } + function pipelineTopicExpression(expression) { + const node = { + type: "PipelineTopicExpression", + expression + }; + const defs = NODE_FIELDS.PipelineTopicExpression; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function pipelineBareFunction(callee) { + const node = { + type: "PipelineBareFunction", + callee + }; + const defs = NODE_FIELDS.PipelineBareFunction; + validate(defs.callee, node, "callee", callee, 1); + return node; + } + function pipelinePrimaryTopicReference() { + return { + type: "PipelinePrimaryTopicReference" + }; + } + function tsParameterProperty(parameter) { + const node = { + type: "TSParameterProperty", + parameter + }; + const defs = NODE_FIELDS.TSParameterProperty; + validate(defs.parameter, node, "parameter", parameter, 1); + return node; + } + function tsDeclareFunction(id = null, typeParameters = null, params, returnType = null) { + const node = { + type: "TSDeclareFunction", + id, + typeParameters, + params, + returnType + }; + const defs = NODE_FIELDS.TSDeclareFunction; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.returnType, node, "returnType", returnType, 1); + return node; + } + function tsDeclareMethod(decorators = null, key, typeParameters = null, params, returnType = null) { + const node = { + type: "TSDeclareMethod", + decorators, + key, + typeParameters, + params, + returnType + }; + const defs = NODE_FIELDS.TSDeclareMethod; + validate(defs.decorators, node, "decorators", decorators, 1); + validate(defs.key, node, "key", key, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.returnType, node, "returnType", returnType, 1); + return node; + } + function tsQualifiedName(left, right) { + const node = { + type: "TSQualifiedName", + left, + right + }; + const defs = NODE_FIELDS.TSQualifiedName; + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function tsCallSignatureDeclaration(typeParameters = null, parameters, typeAnnotation = null) { + const node = { + type: "TSCallSignatureDeclaration", + typeParameters, + parameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSCallSignatureDeclaration; + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsConstructSignatureDeclaration(typeParameters = null, parameters, typeAnnotation = null) { + const node = { + type: "TSConstructSignatureDeclaration", + typeParameters, + parameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSConstructSignatureDeclaration; + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsPropertySignature(key, typeAnnotation = null) { + const node = { + type: "TSPropertySignature", + key, + typeAnnotation, + kind: null + }; + const defs = NODE_FIELDS.TSPropertySignature; + validate(defs.key, node, "key", key, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsMethodSignature(key, typeParameters = null, parameters, typeAnnotation = null) { + const node = { + type: "TSMethodSignature", + key, + typeParameters, + parameters, + typeAnnotation, + kind: null + }; + const defs = NODE_FIELDS.TSMethodSignature; + validate(defs.key, node, "key", key, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsIndexSignature(parameters, typeAnnotation = null) { + const node = { + type: "TSIndexSignature", + parameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSIndexSignature; + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsAnyKeyword() { + return { + type: "TSAnyKeyword" + }; + } + function tsBooleanKeyword() { + return { + type: "TSBooleanKeyword" + }; + } + function tsBigIntKeyword() { + return { + type: "TSBigIntKeyword" + }; + } + function tsIntrinsicKeyword() { + return { + type: "TSIntrinsicKeyword" + }; + } + function tsNeverKeyword() { + return { + type: "TSNeverKeyword" + }; + } + function tsNullKeyword() { + return { + type: "TSNullKeyword" + }; + } + function tsNumberKeyword() { + return { + type: "TSNumberKeyword" + }; + } + function tsObjectKeyword() { + return { + type: "TSObjectKeyword" + }; + } + function tsStringKeyword() { + return { + type: "TSStringKeyword" + }; + } + function tsSymbolKeyword() { + return { + type: "TSSymbolKeyword" + }; + } + function tsUndefinedKeyword() { + return { + type: "TSUndefinedKeyword" + }; + } + function tsUnknownKeyword() { + return { + type: "TSUnknownKeyword" + }; + } + function tsVoidKeyword() { + return { + type: "TSVoidKeyword" + }; + } + function tsThisType() { + return { + type: "TSThisType" + }; + } + function tsFunctionType(typeParameters = null, parameters, typeAnnotation = null) { + const node = { + type: "TSFunctionType", + typeParameters, + parameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSFunctionType; + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsConstructorType(typeParameters = null, parameters, typeAnnotation = null) { + const node = { + type: "TSConstructorType", + typeParameters, + parameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSConstructorType; + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsTypeReference(typeName, typeParameters = null) { + const node = { + type: "TSTypeReference", + typeName, + typeParameters + }; + const defs = NODE_FIELDS.TSTypeReference; + validate(defs.typeName, node, "typeName", typeName, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function tsTypePredicate(parameterName, typeAnnotation = null, asserts = null) { + const node = { + type: "TSTypePredicate", + parameterName, + typeAnnotation, + asserts + }; + const defs = NODE_FIELDS.TSTypePredicate; + validate(defs.parameterName, node, "parameterName", parameterName, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + validate(defs.asserts, node, "asserts", asserts); + return node; + } + function tsTypeQuery(exprName, typeParameters = null) { + const node = { + type: "TSTypeQuery", + exprName, + typeParameters + }; + const defs = NODE_FIELDS.TSTypeQuery; + validate(defs.exprName, node, "exprName", exprName, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function tsTypeLiteral(members) { + const node = { + type: "TSTypeLiteral", + members + }; + const defs = NODE_FIELDS.TSTypeLiteral; + validate(defs.members, node, "members", members, 1); + return node; + } + function tsArrayType(elementType) { + const node = { + type: "TSArrayType", + elementType + }; + const defs = NODE_FIELDS.TSArrayType; + validate(defs.elementType, node, "elementType", elementType, 1); + return node; + } + function tsTupleType(elementTypes) { + const node = { + type: "TSTupleType", + elementTypes + }; + const defs = NODE_FIELDS.TSTupleType; + validate(defs.elementTypes, node, "elementTypes", elementTypes, 1); + return node; + } + function tsOptionalType(typeAnnotation) { + const node = { + type: "TSOptionalType", + typeAnnotation + }; + const defs = NODE_FIELDS.TSOptionalType; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsRestType(typeAnnotation) { + const node = { + type: "TSRestType", + typeAnnotation + }; + const defs = NODE_FIELDS.TSRestType; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsNamedTupleMember(label, elementType, optional = false) { + const node = { + type: "TSNamedTupleMember", + label, + elementType, + optional + }; + const defs = NODE_FIELDS.TSNamedTupleMember; + validate(defs.label, node, "label", label, 1); + validate(defs.elementType, node, "elementType", elementType, 1); + validate(defs.optional, node, "optional", optional); + return node; + } + function tsUnionType(types) { + const node = { + type: "TSUnionType", + types + }; + const defs = NODE_FIELDS.TSUnionType; + validate(defs.types, node, "types", types, 1); + return node; + } + function tsIntersectionType(types) { + const node = { + type: "TSIntersectionType", + types + }; + const defs = NODE_FIELDS.TSIntersectionType; + validate(defs.types, node, "types", types, 1); + return node; + } + function tsConditionalType(checkType, extendsType, trueType, falseType) { + const node = { + type: "TSConditionalType", + checkType, + extendsType, + trueType, + falseType + }; + const defs = NODE_FIELDS.TSConditionalType; + validate(defs.checkType, node, "checkType", checkType, 1); + validate(defs.extendsType, node, "extendsType", extendsType, 1); + validate(defs.trueType, node, "trueType", trueType, 1); + validate(defs.falseType, node, "falseType", falseType, 1); + return node; + } + function tsInferType(typeParameter) { + const node = { + type: "TSInferType", + typeParameter + }; + const defs = NODE_FIELDS.TSInferType; + validate(defs.typeParameter, node, "typeParameter", typeParameter, 1); + return node; + } + function tsParenthesizedType(typeAnnotation) { + const node = { + type: "TSParenthesizedType", + typeAnnotation + }; + const defs = NODE_FIELDS.TSParenthesizedType; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsTypeOperator(typeAnnotation) { + const node = { + type: "TSTypeOperator", + typeAnnotation, + operator: null + }; + const defs = NODE_FIELDS.TSTypeOperator; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsIndexedAccessType(objectType, indexType) { + const node = { + type: "TSIndexedAccessType", + objectType, + indexType + }; + const defs = NODE_FIELDS.TSIndexedAccessType; + validate(defs.objectType, node, "objectType", objectType, 1); + validate(defs.indexType, node, "indexType", indexType, 1); + return node; + } + function tsMappedType(typeParameter, typeAnnotation = null, nameType = null) { + const node = { + type: "TSMappedType", + typeParameter, + typeAnnotation, + nameType + }; + const defs = NODE_FIELDS.TSMappedType; + validate(defs.typeParameter, node, "typeParameter", typeParameter, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + validate(defs.nameType, node, "nameType", nameType, 1); + return node; + } + function tsLiteralType(literal) { + const node = { + type: "TSLiteralType", + literal + }; + const defs = NODE_FIELDS.TSLiteralType; + validate(defs.literal, node, "literal", literal, 1); + return node; + } + function tsExpressionWithTypeArguments(expression, typeParameters = null) { + const node = { + type: "TSExpressionWithTypeArguments", + expression, + typeParameters + }; + const defs = NODE_FIELDS.TSExpressionWithTypeArguments; + validate(defs.expression, node, "expression", expression, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function tsInterfaceDeclaration(id, typeParameters = null, _extends = null, body) { + const node = { + type: "TSInterfaceDeclaration", + id, + typeParameters, + extends: _extends, + body + }; + const defs = NODE_FIELDS.TSInterfaceDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.extends, node, "extends", _extends, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function tsInterfaceBody(body) { + const node = { + type: "TSInterfaceBody", + body + }; + const defs = NODE_FIELDS.TSInterfaceBody; + validate(defs.body, node, "body", body, 1); + return node; + } + function tsTypeAliasDeclaration(id, typeParameters = null, typeAnnotation) { + const node = { + type: "TSTypeAliasDeclaration", + id, + typeParameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSTypeAliasDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsInstantiationExpression(expression, typeParameters = null) { + const node = { + type: "TSInstantiationExpression", + expression, + typeParameters + }; + const defs = NODE_FIELDS.TSInstantiationExpression; + validate(defs.expression, node, "expression", expression, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function tsAsExpression(expression, typeAnnotation) { + const node = { + type: "TSAsExpression", + expression, + typeAnnotation + }; + const defs = NODE_FIELDS.TSAsExpression; + validate(defs.expression, node, "expression", expression, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsSatisfiesExpression(expression, typeAnnotation) { + const node = { + type: "TSSatisfiesExpression", + expression, + typeAnnotation + }; + const defs = NODE_FIELDS.TSSatisfiesExpression; + validate(defs.expression, node, "expression", expression, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsTypeAssertion(typeAnnotation, expression) { + const node = { + type: "TSTypeAssertion", + typeAnnotation, + expression + }; + const defs = NODE_FIELDS.TSTypeAssertion; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function tsEnumDeclaration(id, members) { + const node = { + type: "TSEnumDeclaration", + id, + members + }; + const defs = NODE_FIELDS.TSEnumDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.members, node, "members", members, 1); + return node; + } + function tsEnumMember(id, initializer = null) { + const node = { + type: "TSEnumMember", + id, + initializer + }; + const defs = NODE_FIELDS.TSEnumMember; + validate(defs.id, node, "id", id, 1); + validate(defs.initializer, node, "initializer", initializer, 1); + return node; + } + function tsModuleDeclaration(id, body) { + const node = { + type: "TSModuleDeclaration", + id, + body, + kind: null + }; + const defs = NODE_FIELDS.TSModuleDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function tsModuleBlock(body) { + const node = { + type: "TSModuleBlock", + body + }; + const defs = NODE_FIELDS.TSModuleBlock; + validate(defs.body, node, "body", body, 1); + return node; + } + function tsImportType(argument, qualifier = null, typeParameters = null) { + const node = { + type: "TSImportType", + argument, + qualifier, + typeParameters + }; + const defs = NODE_FIELDS.TSImportType; + validate(defs.argument, node, "argument", argument, 1); + validate(defs.qualifier, node, "qualifier", qualifier, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function tsImportEqualsDeclaration(id, moduleReference) { + const node = { + type: "TSImportEqualsDeclaration", + id, + moduleReference, + isExport: null + }; + const defs = NODE_FIELDS.TSImportEqualsDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.moduleReference, node, "moduleReference", moduleReference, 1); + return node; + } + function tsExternalModuleReference(expression) { + const node = { + type: "TSExternalModuleReference", + expression + }; + const defs = NODE_FIELDS.TSExternalModuleReference; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function tsNonNullExpression(expression) { + const node = { + type: "TSNonNullExpression", + expression + }; + const defs = NODE_FIELDS.TSNonNullExpression; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function tsExportAssignment(expression) { + const node = { + type: "TSExportAssignment", + expression + }; + const defs = NODE_FIELDS.TSExportAssignment; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function tsNamespaceExportDeclaration(id) { + const node = { + type: "TSNamespaceExportDeclaration", + id + }; + const defs = NODE_FIELDS.TSNamespaceExportDeclaration; + validate(defs.id, node, "id", id, 1); + return node; + } + function tsTypeAnnotation(typeAnnotation) { + const node = { + type: "TSTypeAnnotation", + typeAnnotation + }; + const defs = NODE_FIELDS.TSTypeAnnotation; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsTypeParameterInstantiation(params) { + const node = { + type: "TSTypeParameterInstantiation", + params + }; + const defs = NODE_FIELDS.TSTypeParameterInstantiation; + validate(defs.params, node, "params", params, 1); + return node; + } + function tsTypeParameterDeclaration(params) { + const node = { + type: "TSTypeParameterDeclaration", + params + }; + const defs = NODE_FIELDS.TSTypeParameterDeclaration; + validate(defs.params, node, "params", params, 1); + return node; + } + function tsTypeParameter(constraint = null, _default = null, name) { + const node = { + type: "TSTypeParameter", + constraint, + default: _default, + name + }; + const defs = NODE_FIELDS.TSTypeParameter; + validate(defs.constraint, node, "constraint", constraint, 1); + validate(defs.default, node, "default", _default, 1); + validate(defs.name, node, "name", name); + return node; + } + function NumberLiteral(value) { + (0, _deprecationWarning.default)("NumberLiteral", "NumericLiteral", "The node type "); + return numericLiteral(value); + } + function RegexLiteral(pattern, flags = "") { + (0, _deprecationWarning.default)("RegexLiteral", "RegExpLiteral", "The node type "); + return regExpLiteral(pattern, flags); + } + function RestProperty(argument) { + (0, _deprecationWarning.default)("RestProperty", "RestElement", "The node type "); + return restElement(argument); + } + function SpreadProperty(argument) { + (0, _deprecationWarning.default)("SpreadProperty", "SpreadElement", "The node type "); + return spreadElement(argument); + } + + + return generated$2; +} + +var hasRequiredCleanJSXElementLiteralChild; + +function requireCleanJSXElementLiteralChild () { + if (hasRequiredCleanJSXElementLiteralChild) return cleanJSXElementLiteralChild; + hasRequiredCleanJSXElementLiteralChild = 1; + + Object.defineProperty(cleanJSXElementLiteralChild, "__esModule", { + value: true + }); + cleanJSXElementLiteralChild.default = cleanJSXElementLiteralChild$1; + var _index = requireGenerated$2(); + var _index2 = requireLib$1(); + function cleanJSXElementLiteralChild$1(child, args) { + const lines = child.value.split(/\r\n|\n|\r/); + let lastNonEmptyLine = 0; + for (let i = 0; i < lines.length; i++) { + if (/[^ \t]/.exec(lines[i])) { + lastNonEmptyLine = i; + } + } + let str = ""; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const isFirstLine = i === 0; + const isLastLine = i === lines.length - 1; + const isLastNonEmptyLine = i === lastNonEmptyLine; + let trimmedLine = line.replace(/\t/g, " "); + if (!isFirstLine) { + trimmedLine = trimmedLine.replace(/^ +/, ""); + } + if (!isLastLine) { + trimmedLine = trimmedLine.replace(/ +$/, ""); + } + if (trimmedLine) { + if (!isLastNonEmptyLine) { + trimmedLine += " "; + } + str += trimmedLine; + } + } + if (str) args.push((0, _index2.inherits)((0, _index.stringLiteral)(str), child)); + } + + + return cleanJSXElementLiteralChild; +} + +var hasRequiredBuildChildren; + +function requireBuildChildren () { + if (hasRequiredBuildChildren) return buildChildren; + hasRequiredBuildChildren = 1; + + Object.defineProperty(buildChildren, "__esModule", { + value: true + }); + buildChildren.default = buildChildren$1; + var _index = requireGenerated$3(); + var _cleanJSXElementLiteralChild = requireCleanJSXElementLiteralChild(); + function buildChildren$1(node) { + const elements = []; + for (let i = 0; i < node.children.length; i++) { + let child = node.children[i]; + if ((0, _index.isJSXText)(child)) { + (0, _cleanJSXElementLiteralChild.default)(child, elements); + continue; + } + if ((0, _index.isJSXExpressionContainer)(child)) child = child.expression; + if ((0, _index.isJSXEmptyExpression)(child)) continue; + elements.push(child); + } + return elements; + } + + + return buildChildren; +} + +var assertNode = {}; + +var isNode = {}; + +var hasRequiredIsNode; + +function requireIsNode () { + if (hasRequiredIsNode) return isNode; + hasRequiredIsNode = 1; + + Object.defineProperty(isNode, "__esModule", { + value: true + }); + isNode.default = isNode$1; + var _index = requireDefinitions(); + function isNode$1(node) { + return !!(node && _index.VISITOR_KEYS[node.type]); + } + + + return isNode; +} + +var hasRequiredAssertNode; + +function requireAssertNode () { + if (hasRequiredAssertNode) return assertNode; + hasRequiredAssertNode = 1; + + Object.defineProperty(assertNode, "__esModule", { + value: true + }); + assertNode.default = assertNode$1; + var _isNode = requireIsNode(); + function assertNode$1(node) { + if (!(0, _isNode.default)(node)) { + var _node$type; + const type = (_node$type = node == null ? void 0 : node.type) != null ? _node$type : JSON.stringify(node); + throw new TypeError(`Not a valid node of type "${type}"`); + } + } + + + return assertNode; +} + +var generated$1 = {}; + +var hasRequiredGenerated$1; + +function requireGenerated$1 () { + if (hasRequiredGenerated$1) return generated$1; + hasRequiredGenerated$1 = 1; + + Object.defineProperty(generated$1, "__esModule", { + value: true + }); + generated$1.assertAccessor = assertAccessor; + generated$1.assertAnyTypeAnnotation = assertAnyTypeAnnotation; + generated$1.assertArgumentPlaceholder = assertArgumentPlaceholder; + generated$1.assertArrayExpression = assertArrayExpression; + generated$1.assertArrayPattern = assertArrayPattern; + generated$1.assertArrayTypeAnnotation = assertArrayTypeAnnotation; + generated$1.assertArrowFunctionExpression = assertArrowFunctionExpression; + generated$1.assertAssignmentExpression = assertAssignmentExpression; + generated$1.assertAssignmentPattern = assertAssignmentPattern; + generated$1.assertAwaitExpression = assertAwaitExpression; + generated$1.assertBigIntLiteral = assertBigIntLiteral; + generated$1.assertBinary = assertBinary; + generated$1.assertBinaryExpression = assertBinaryExpression; + generated$1.assertBindExpression = assertBindExpression; + generated$1.assertBlock = assertBlock; + generated$1.assertBlockParent = assertBlockParent; + generated$1.assertBlockStatement = assertBlockStatement; + generated$1.assertBooleanLiteral = assertBooleanLiteral; + generated$1.assertBooleanLiteralTypeAnnotation = assertBooleanLiteralTypeAnnotation; + generated$1.assertBooleanTypeAnnotation = assertBooleanTypeAnnotation; + generated$1.assertBreakStatement = assertBreakStatement; + generated$1.assertCallExpression = assertCallExpression; + generated$1.assertCatchClause = assertCatchClause; + generated$1.assertClass = assertClass; + generated$1.assertClassAccessorProperty = assertClassAccessorProperty; + generated$1.assertClassBody = assertClassBody; + generated$1.assertClassDeclaration = assertClassDeclaration; + generated$1.assertClassExpression = assertClassExpression; + generated$1.assertClassImplements = assertClassImplements; + generated$1.assertClassMethod = assertClassMethod; + generated$1.assertClassPrivateMethod = assertClassPrivateMethod; + generated$1.assertClassPrivateProperty = assertClassPrivateProperty; + generated$1.assertClassProperty = assertClassProperty; + generated$1.assertCompletionStatement = assertCompletionStatement; + generated$1.assertConditional = assertConditional; + generated$1.assertConditionalExpression = assertConditionalExpression; + generated$1.assertContinueStatement = assertContinueStatement; + generated$1.assertDebuggerStatement = assertDebuggerStatement; + generated$1.assertDecimalLiteral = assertDecimalLiteral; + generated$1.assertDeclaration = assertDeclaration; + generated$1.assertDeclareClass = assertDeclareClass; + generated$1.assertDeclareExportAllDeclaration = assertDeclareExportAllDeclaration; + generated$1.assertDeclareExportDeclaration = assertDeclareExportDeclaration; + generated$1.assertDeclareFunction = assertDeclareFunction; + generated$1.assertDeclareInterface = assertDeclareInterface; + generated$1.assertDeclareModule = assertDeclareModule; + generated$1.assertDeclareModuleExports = assertDeclareModuleExports; + generated$1.assertDeclareOpaqueType = assertDeclareOpaqueType; + generated$1.assertDeclareTypeAlias = assertDeclareTypeAlias; + generated$1.assertDeclareVariable = assertDeclareVariable; + generated$1.assertDeclaredPredicate = assertDeclaredPredicate; + generated$1.assertDecorator = assertDecorator; + generated$1.assertDirective = assertDirective; + generated$1.assertDirectiveLiteral = assertDirectiveLiteral; + generated$1.assertDoExpression = assertDoExpression; + generated$1.assertDoWhileStatement = assertDoWhileStatement; + generated$1.assertEmptyStatement = assertEmptyStatement; + generated$1.assertEmptyTypeAnnotation = assertEmptyTypeAnnotation; + generated$1.assertEnumBody = assertEnumBody; + generated$1.assertEnumBooleanBody = assertEnumBooleanBody; + generated$1.assertEnumBooleanMember = assertEnumBooleanMember; + generated$1.assertEnumDeclaration = assertEnumDeclaration; + generated$1.assertEnumDefaultedMember = assertEnumDefaultedMember; + generated$1.assertEnumMember = assertEnumMember; + generated$1.assertEnumNumberBody = assertEnumNumberBody; + generated$1.assertEnumNumberMember = assertEnumNumberMember; + generated$1.assertEnumStringBody = assertEnumStringBody; + generated$1.assertEnumStringMember = assertEnumStringMember; + generated$1.assertEnumSymbolBody = assertEnumSymbolBody; + generated$1.assertExistsTypeAnnotation = assertExistsTypeAnnotation; + generated$1.assertExportAllDeclaration = assertExportAllDeclaration; + generated$1.assertExportDeclaration = assertExportDeclaration; + generated$1.assertExportDefaultDeclaration = assertExportDefaultDeclaration; + generated$1.assertExportDefaultSpecifier = assertExportDefaultSpecifier; + generated$1.assertExportNamedDeclaration = assertExportNamedDeclaration; + generated$1.assertExportNamespaceSpecifier = assertExportNamespaceSpecifier; + generated$1.assertExportSpecifier = assertExportSpecifier; + generated$1.assertExpression = assertExpression; + generated$1.assertExpressionStatement = assertExpressionStatement; + generated$1.assertExpressionWrapper = assertExpressionWrapper; + generated$1.assertFile = assertFile; + generated$1.assertFlow = assertFlow; + generated$1.assertFlowBaseAnnotation = assertFlowBaseAnnotation; + generated$1.assertFlowDeclaration = assertFlowDeclaration; + generated$1.assertFlowPredicate = assertFlowPredicate; + generated$1.assertFlowType = assertFlowType; + generated$1.assertFor = assertFor; + generated$1.assertForInStatement = assertForInStatement; + generated$1.assertForOfStatement = assertForOfStatement; + generated$1.assertForStatement = assertForStatement; + generated$1.assertForXStatement = assertForXStatement; + generated$1.assertFunction = assertFunction; + generated$1.assertFunctionDeclaration = assertFunctionDeclaration; + generated$1.assertFunctionExpression = assertFunctionExpression; + generated$1.assertFunctionParent = assertFunctionParent; + generated$1.assertFunctionTypeAnnotation = assertFunctionTypeAnnotation; + generated$1.assertFunctionTypeParam = assertFunctionTypeParam; + generated$1.assertGenericTypeAnnotation = assertGenericTypeAnnotation; + generated$1.assertIdentifier = assertIdentifier; + generated$1.assertIfStatement = assertIfStatement; + generated$1.assertImmutable = assertImmutable; + generated$1.assertImport = assertImport; + generated$1.assertImportAttribute = assertImportAttribute; + generated$1.assertImportDeclaration = assertImportDeclaration; + generated$1.assertImportDefaultSpecifier = assertImportDefaultSpecifier; + generated$1.assertImportExpression = assertImportExpression; + generated$1.assertImportNamespaceSpecifier = assertImportNamespaceSpecifier; + generated$1.assertImportOrExportDeclaration = assertImportOrExportDeclaration; + generated$1.assertImportSpecifier = assertImportSpecifier; + generated$1.assertIndexedAccessType = assertIndexedAccessType; + generated$1.assertInferredPredicate = assertInferredPredicate; + generated$1.assertInterfaceDeclaration = assertInterfaceDeclaration; + generated$1.assertInterfaceExtends = assertInterfaceExtends; + generated$1.assertInterfaceTypeAnnotation = assertInterfaceTypeAnnotation; + generated$1.assertInterpreterDirective = assertInterpreterDirective; + generated$1.assertIntersectionTypeAnnotation = assertIntersectionTypeAnnotation; + generated$1.assertJSX = assertJSX; + generated$1.assertJSXAttribute = assertJSXAttribute; + generated$1.assertJSXClosingElement = assertJSXClosingElement; + generated$1.assertJSXClosingFragment = assertJSXClosingFragment; + generated$1.assertJSXElement = assertJSXElement; + generated$1.assertJSXEmptyExpression = assertJSXEmptyExpression; + generated$1.assertJSXExpressionContainer = assertJSXExpressionContainer; + generated$1.assertJSXFragment = assertJSXFragment; + generated$1.assertJSXIdentifier = assertJSXIdentifier; + generated$1.assertJSXMemberExpression = assertJSXMemberExpression; + generated$1.assertJSXNamespacedName = assertJSXNamespacedName; + generated$1.assertJSXOpeningElement = assertJSXOpeningElement; + generated$1.assertJSXOpeningFragment = assertJSXOpeningFragment; + generated$1.assertJSXSpreadAttribute = assertJSXSpreadAttribute; + generated$1.assertJSXSpreadChild = assertJSXSpreadChild; + generated$1.assertJSXText = assertJSXText; + generated$1.assertLVal = assertLVal; + generated$1.assertLabeledStatement = assertLabeledStatement; + generated$1.assertLiteral = assertLiteral; + generated$1.assertLogicalExpression = assertLogicalExpression; + generated$1.assertLoop = assertLoop; + generated$1.assertMemberExpression = assertMemberExpression; + generated$1.assertMetaProperty = assertMetaProperty; + generated$1.assertMethod = assertMethod; + generated$1.assertMiscellaneous = assertMiscellaneous; + generated$1.assertMixedTypeAnnotation = assertMixedTypeAnnotation; + generated$1.assertModuleDeclaration = assertModuleDeclaration; + generated$1.assertModuleExpression = assertModuleExpression; + generated$1.assertModuleSpecifier = assertModuleSpecifier; + generated$1.assertNewExpression = assertNewExpression; + generated$1.assertNoop = assertNoop; + generated$1.assertNullLiteral = assertNullLiteral; + generated$1.assertNullLiteralTypeAnnotation = assertNullLiteralTypeAnnotation; + generated$1.assertNullableTypeAnnotation = assertNullableTypeAnnotation; + generated$1.assertNumberLiteral = assertNumberLiteral; + generated$1.assertNumberLiteralTypeAnnotation = assertNumberLiteralTypeAnnotation; + generated$1.assertNumberTypeAnnotation = assertNumberTypeAnnotation; + generated$1.assertNumericLiteral = assertNumericLiteral; + generated$1.assertObjectExpression = assertObjectExpression; + generated$1.assertObjectMember = assertObjectMember; + generated$1.assertObjectMethod = assertObjectMethod; + generated$1.assertObjectPattern = assertObjectPattern; + generated$1.assertObjectProperty = assertObjectProperty; + generated$1.assertObjectTypeAnnotation = assertObjectTypeAnnotation; + generated$1.assertObjectTypeCallProperty = assertObjectTypeCallProperty; + generated$1.assertObjectTypeIndexer = assertObjectTypeIndexer; + generated$1.assertObjectTypeInternalSlot = assertObjectTypeInternalSlot; + generated$1.assertObjectTypeProperty = assertObjectTypeProperty; + generated$1.assertObjectTypeSpreadProperty = assertObjectTypeSpreadProperty; + generated$1.assertOpaqueType = assertOpaqueType; + generated$1.assertOptionalCallExpression = assertOptionalCallExpression; + generated$1.assertOptionalIndexedAccessType = assertOptionalIndexedAccessType; + generated$1.assertOptionalMemberExpression = assertOptionalMemberExpression; + generated$1.assertParenthesizedExpression = assertParenthesizedExpression; + generated$1.assertPattern = assertPattern; + generated$1.assertPatternLike = assertPatternLike; + generated$1.assertPipelineBareFunction = assertPipelineBareFunction; + generated$1.assertPipelinePrimaryTopicReference = assertPipelinePrimaryTopicReference; + generated$1.assertPipelineTopicExpression = assertPipelineTopicExpression; + generated$1.assertPlaceholder = assertPlaceholder; + generated$1.assertPrivate = assertPrivate; + generated$1.assertPrivateName = assertPrivateName; + generated$1.assertProgram = assertProgram; + generated$1.assertProperty = assertProperty; + generated$1.assertPureish = assertPureish; + generated$1.assertQualifiedTypeIdentifier = assertQualifiedTypeIdentifier; + generated$1.assertRecordExpression = assertRecordExpression; + generated$1.assertRegExpLiteral = assertRegExpLiteral; + generated$1.assertRegexLiteral = assertRegexLiteral; + generated$1.assertRestElement = assertRestElement; + generated$1.assertRestProperty = assertRestProperty; + generated$1.assertReturnStatement = assertReturnStatement; + generated$1.assertScopable = assertScopable; + generated$1.assertSequenceExpression = assertSequenceExpression; + generated$1.assertSpreadElement = assertSpreadElement; + generated$1.assertSpreadProperty = assertSpreadProperty; + generated$1.assertStandardized = assertStandardized; + generated$1.assertStatement = assertStatement; + generated$1.assertStaticBlock = assertStaticBlock; + generated$1.assertStringLiteral = assertStringLiteral; + generated$1.assertStringLiteralTypeAnnotation = assertStringLiteralTypeAnnotation; + generated$1.assertStringTypeAnnotation = assertStringTypeAnnotation; + generated$1.assertSuper = assertSuper; + generated$1.assertSwitchCase = assertSwitchCase; + generated$1.assertSwitchStatement = assertSwitchStatement; + generated$1.assertSymbolTypeAnnotation = assertSymbolTypeAnnotation; + generated$1.assertTSAnyKeyword = assertTSAnyKeyword; + generated$1.assertTSArrayType = assertTSArrayType; + generated$1.assertTSAsExpression = assertTSAsExpression; + generated$1.assertTSBaseType = assertTSBaseType; + generated$1.assertTSBigIntKeyword = assertTSBigIntKeyword; + generated$1.assertTSBooleanKeyword = assertTSBooleanKeyword; + generated$1.assertTSCallSignatureDeclaration = assertTSCallSignatureDeclaration; + generated$1.assertTSConditionalType = assertTSConditionalType; + generated$1.assertTSConstructSignatureDeclaration = assertTSConstructSignatureDeclaration; + generated$1.assertTSConstructorType = assertTSConstructorType; + generated$1.assertTSDeclareFunction = assertTSDeclareFunction; + generated$1.assertTSDeclareMethod = assertTSDeclareMethod; + generated$1.assertTSEntityName = assertTSEntityName; + generated$1.assertTSEnumDeclaration = assertTSEnumDeclaration; + generated$1.assertTSEnumMember = assertTSEnumMember; + generated$1.assertTSExportAssignment = assertTSExportAssignment; + generated$1.assertTSExpressionWithTypeArguments = assertTSExpressionWithTypeArguments; + generated$1.assertTSExternalModuleReference = assertTSExternalModuleReference; + generated$1.assertTSFunctionType = assertTSFunctionType; + generated$1.assertTSImportEqualsDeclaration = assertTSImportEqualsDeclaration; + generated$1.assertTSImportType = assertTSImportType; + generated$1.assertTSIndexSignature = assertTSIndexSignature; + generated$1.assertTSIndexedAccessType = assertTSIndexedAccessType; + generated$1.assertTSInferType = assertTSInferType; + generated$1.assertTSInstantiationExpression = assertTSInstantiationExpression; + generated$1.assertTSInterfaceBody = assertTSInterfaceBody; + generated$1.assertTSInterfaceDeclaration = assertTSInterfaceDeclaration; + generated$1.assertTSIntersectionType = assertTSIntersectionType; + generated$1.assertTSIntrinsicKeyword = assertTSIntrinsicKeyword; + generated$1.assertTSLiteralType = assertTSLiteralType; + generated$1.assertTSMappedType = assertTSMappedType; + generated$1.assertTSMethodSignature = assertTSMethodSignature; + generated$1.assertTSModuleBlock = assertTSModuleBlock; + generated$1.assertTSModuleDeclaration = assertTSModuleDeclaration; + generated$1.assertTSNamedTupleMember = assertTSNamedTupleMember; + generated$1.assertTSNamespaceExportDeclaration = assertTSNamespaceExportDeclaration; + generated$1.assertTSNeverKeyword = assertTSNeverKeyword; + generated$1.assertTSNonNullExpression = assertTSNonNullExpression; + generated$1.assertTSNullKeyword = assertTSNullKeyword; + generated$1.assertTSNumberKeyword = assertTSNumberKeyword; + generated$1.assertTSObjectKeyword = assertTSObjectKeyword; + generated$1.assertTSOptionalType = assertTSOptionalType; + generated$1.assertTSParameterProperty = assertTSParameterProperty; + generated$1.assertTSParenthesizedType = assertTSParenthesizedType; + generated$1.assertTSPropertySignature = assertTSPropertySignature; + generated$1.assertTSQualifiedName = assertTSQualifiedName; + generated$1.assertTSRestType = assertTSRestType; + generated$1.assertTSSatisfiesExpression = assertTSSatisfiesExpression; + generated$1.assertTSStringKeyword = assertTSStringKeyword; + generated$1.assertTSSymbolKeyword = assertTSSymbolKeyword; + generated$1.assertTSThisType = assertTSThisType; + generated$1.assertTSTupleType = assertTSTupleType; + generated$1.assertTSType = assertTSType; + generated$1.assertTSTypeAliasDeclaration = assertTSTypeAliasDeclaration; + generated$1.assertTSTypeAnnotation = assertTSTypeAnnotation; + generated$1.assertTSTypeAssertion = assertTSTypeAssertion; + generated$1.assertTSTypeElement = assertTSTypeElement; + generated$1.assertTSTypeLiteral = assertTSTypeLiteral; + generated$1.assertTSTypeOperator = assertTSTypeOperator; + generated$1.assertTSTypeParameter = assertTSTypeParameter; + generated$1.assertTSTypeParameterDeclaration = assertTSTypeParameterDeclaration; + generated$1.assertTSTypeParameterInstantiation = assertTSTypeParameterInstantiation; + generated$1.assertTSTypePredicate = assertTSTypePredicate; + generated$1.assertTSTypeQuery = assertTSTypeQuery; + generated$1.assertTSTypeReference = assertTSTypeReference; + generated$1.assertTSUndefinedKeyword = assertTSUndefinedKeyword; + generated$1.assertTSUnionType = assertTSUnionType; + generated$1.assertTSUnknownKeyword = assertTSUnknownKeyword; + generated$1.assertTSVoidKeyword = assertTSVoidKeyword; + generated$1.assertTaggedTemplateExpression = assertTaggedTemplateExpression; + generated$1.assertTemplateElement = assertTemplateElement; + generated$1.assertTemplateLiteral = assertTemplateLiteral; + generated$1.assertTerminatorless = assertTerminatorless; + generated$1.assertThisExpression = assertThisExpression; + generated$1.assertThisTypeAnnotation = assertThisTypeAnnotation; + generated$1.assertThrowStatement = assertThrowStatement; + generated$1.assertTopicReference = assertTopicReference; + generated$1.assertTryStatement = assertTryStatement; + generated$1.assertTupleExpression = assertTupleExpression; + generated$1.assertTupleTypeAnnotation = assertTupleTypeAnnotation; + generated$1.assertTypeAlias = assertTypeAlias; + generated$1.assertTypeAnnotation = assertTypeAnnotation; + generated$1.assertTypeCastExpression = assertTypeCastExpression; + generated$1.assertTypeParameter = assertTypeParameter; + generated$1.assertTypeParameterDeclaration = assertTypeParameterDeclaration; + generated$1.assertTypeParameterInstantiation = assertTypeParameterInstantiation; + generated$1.assertTypeScript = assertTypeScript; + generated$1.assertTypeofTypeAnnotation = assertTypeofTypeAnnotation; + generated$1.assertUnaryExpression = assertUnaryExpression; + generated$1.assertUnaryLike = assertUnaryLike; + generated$1.assertUnionTypeAnnotation = assertUnionTypeAnnotation; + generated$1.assertUpdateExpression = assertUpdateExpression; + generated$1.assertUserWhitespacable = assertUserWhitespacable; + generated$1.assertV8IntrinsicIdentifier = assertV8IntrinsicIdentifier; + generated$1.assertVariableDeclaration = assertVariableDeclaration; + generated$1.assertVariableDeclarator = assertVariableDeclarator; + generated$1.assertVariance = assertVariance; + generated$1.assertVoidTypeAnnotation = assertVoidTypeAnnotation; + generated$1.assertWhile = assertWhile; + generated$1.assertWhileStatement = assertWhileStatement; + generated$1.assertWithStatement = assertWithStatement; + generated$1.assertYieldExpression = assertYieldExpression; + var _is = requireIs(); + var _deprecationWarning = requireDeprecationWarning(); + function assert(type, node, opts) { + if (!(0, _is.default)(type, node, opts)) { + throw new Error(`Expected type "${type}" with option ${JSON.stringify(opts)}, ` + `but instead got "${node.type}".`); + } + } + function assertArrayExpression(node, opts) { + assert("ArrayExpression", node, opts); + } + function assertAssignmentExpression(node, opts) { + assert("AssignmentExpression", node, opts); + } + function assertBinaryExpression(node, opts) { + assert("BinaryExpression", node, opts); + } + function assertInterpreterDirective(node, opts) { + assert("InterpreterDirective", node, opts); + } + function assertDirective(node, opts) { + assert("Directive", node, opts); + } + function assertDirectiveLiteral(node, opts) { + assert("DirectiveLiteral", node, opts); + } + function assertBlockStatement(node, opts) { + assert("BlockStatement", node, opts); + } + function assertBreakStatement(node, opts) { + assert("BreakStatement", node, opts); + } + function assertCallExpression(node, opts) { + assert("CallExpression", node, opts); + } + function assertCatchClause(node, opts) { + assert("CatchClause", node, opts); + } + function assertConditionalExpression(node, opts) { + assert("ConditionalExpression", node, opts); + } + function assertContinueStatement(node, opts) { + assert("ContinueStatement", node, opts); + } + function assertDebuggerStatement(node, opts) { + assert("DebuggerStatement", node, opts); + } + function assertDoWhileStatement(node, opts) { + assert("DoWhileStatement", node, opts); + } + function assertEmptyStatement(node, opts) { + assert("EmptyStatement", node, opts); + } + function assertExpressionStatement(node, opts) { + assert("ExpressionStatement", node, opts); + } + function assertFile(node, opts) { + assert("File", node, opts); + } + function assertForInStatement(node, opts) { + assert("ForInStatement", node, opts); + } + function assertForStatement(node, opts) { + assert("ForStatement", node, opts); + } + function assertFunctionDeclaration(node, opts) { + assert("FunctionDeclaration", node, opts); + } + function assertFunctionExpression(node, opts) { + assert("FunctionExpression", node, opts); + } + function assertIdentifier(node, opts) { + assert("Identifier", node, opts); + } + function assertIfStatement(node, opts) { + assert("IfStatement", node, opts); + } + function assertLabeledStatement(node, opts) { + assert("LabeledStatement", node, opts); + } + function assertStringLiteral(node, opts) { + assert("StringLiteral", node, opts); + } + function assertNumericLiteral(node, opts) { + assert("NumericLiteral", node, opts); + } + function assertNullLiteral(node, opts) { + assert("NullLiteral", node, opts); + } + function assertBooleanLiteral(node, opts) { + assert("BooleanLiteral", node, opts); + } + function assertRegExpLiteral(node, opts) { + assert("RegExpLiteral", node, opts); + } + function assertLogicalExpression(node, opts) { + assert("LogicalExpression", node, opts); + } + function assertMemberExpression(node, opts) { + assert("MemberExpression", node, opts); + } + function assertNewExpression(node, opts) { + assert("NewExpression", node, opts); + } + function assertProgram(node, opts) { + assert("Program", node, opts); + } + function assertObjectExpression(node, opts) { + assert("ObjectExpression", node, opts); + } + function assertObjectMethod(node, opts) { + assert("ObjectMethod", node, opts); + } + function assertObjectProperty(node, opts) { + assert("ObjectProperty", node, opts); + } + function assertRestElement(node, opts) { + assert("RestElement", node, opts); + } + function assertReturnStatement(node, opts) { + assert("ReturnStatement", node, opts); + } + function assertSequenceExpression(node, opts) { + assert("SequenceExpression", node, opts); + } + function assertParenthesizedExpression(node, opts) { + assert("ParenthesizedExpression", node, opts); + } + function assertSwitchCase(node, opts) { + assert("SwitchCase", node, opts); + } + function assertSwitchStatement(node, opts) { + assert("SwitchStatement", node, opts); + } + function assertThisExpression(node, opts) { + assert("ThisExpression", node, opts); + } + function assertThrowStatement(node, opts) { + assert("ThrowStatement", node, opts); + } + function assertTryStatement(node, opts) { + assert("TryStatement", node, opts); + } + function assertUnaryExpression(node, opts) { + assert("UnaryExpression", node, opts); + } + function assertUpdateExpression(node, opts) { + assert("UpdateExpression", node, opts); + } + function assertVariableDeclaration(node, opts) { + assert("VariableDeclaration", node, opts); + } + function assertVariableDeclarator(node, opts) { + assert("VariableDeclarator", node, opts); + } + function assertWhileStatement(node, opts) { + assert("WhileStatement", node, opts); + } + function assertWithStatement(node, opts) { + assert("WithStatement", node, opts); + } + function assertAssignmentPattern(node, opts) { + assert("AssignmentPattern", node, opts); + } + function assertArrayPattern(node, opts) { + assert("ArrayPattern", node, opts); + } + function assertArrowFunctionExpression(node, opts) { + assert("ArrowFunctionExpression", node, opts); + } + function assertClassBody(node, opts) { + assert("ClassBody", node, opts); + } + function assertClassExpression(node, opts) { + assert("ClassExpression", node, opts); + } + function assertClassDeclaration(node, opts) { + assert("ClassDeclaration", node, opts); + } + function assertExportAllDeclaration(node, opts) { + assert("ExportAllDeclaration", node, opts); + } + function assertExportDefaultDeclaration(node, opts) { + assert("ExportDefaultDeclaration", node, opts); + } + function assertExportNamedDeclaration(node, opts) { + assert("ExportNamedDeclaration", node, opts); + } + function assertExportSpecifier(node, opts) { + assert("ExportSpecifier", node, opts); + } + function assertForOfStatement(node, opts) { + assert("ForOfStatement", node, opts); + } + function assertImportDeclaration(node, opts) { + assert("ImportDeclaration", node, opts); + } + function assertImportDefaultSpecifier(node, opts) { + assert("ImportDefaultSpecifier", node, opts); + } + function assertImportNamespaceSpecifier(node, opts) { + assert("ImportNamespaceSpecifier", node, opts); + } + function assertImportSpecifier(node, opts) { + assert("ImportSpecifier", node, opts); + } + function assertImportExpression(node, opts) { + assert("ImportExpression", node, opts); + } + function assertMetaProperty(node, opts) { + assert("MetaProperty", node, opts); + } + function assertClassMethod(node, opts) { + assert("ClassMethod", node, opts); + } + function assertObjectPattern(node, opts) { + assert("ObjectPattern", node, opts); + } + function assertSpreadElement(node, opts) { + assert("SpreadElement", node, opts); + } + function assertSuper(node, opts) { + assert("Super", node, opts); + } + function assertTaggedTemplateExpression(node, opts) { + assert("TaggedTemplateExpression", node, opts); + } + function assertTemplateElement(node, opts) { + assert("TemplateElement", node, opts); + } + function assertTemplateLiteral(node, opts) { + assert("TemplateLiteral", node, opts); + } + function assertYieldExpression(node, opts) { + assert("YieldExpression", node, opts); + } + function assertAwaitExpression(node, opts) { + assert("AwaitExpression", node, opts); + } + function assertImport(node, opts) { + assert("Import", node, opts); + } + function assertBigIntLiteral(node, opts) { + assert("BigIntLiteral", node, opts); + } + function assertExportNamespaceSpecifier(node, opts) { + assert("ExportNamespaceSpecifier", node, opts); + } + function assertOptionalMemberExpression(node, opts) { + assert("OptionalMemberExpression", node, opts); + } + function assertOptionalCallExpression(node, opts) { + assert("OptionalCallExpression", node, opts); + } + function assertClassProperty(node, opts) { + assert("ClassProperty", node, opts); + } + function assertClassAccessorProperty(node, opts) { + assert("ClassAccessorProperty", node, opts); + } + function assertClassPrivateProperty(node, opts) { + assert("ClassPrivateProperty", node, opts); + } + function assertClassPrivateMethod(node, opts) { + assert("ClassPrivateMethod", node, opts); + } + function assertPrivateName(node, opts) { + assert("PrivateName", node, opts); + } + function assertStaticBlock(node, opts) { + assert("StaticBlock", node, opts); + } + function assertAnyTypeAnnotation(node, opts) { + assert("AnyTypeAnnotation", node, opts); + } + function assertArrayTypeAnnotation(node, opts) { + assert("ArrayTypeAnnotation", node, opts); + } + function assertBooleanTypeAnnotation(node, opts) { + assert("BooleanTypeAnnotation", node, opts); + } + function assertBooleanLiteralTypeAnnotation(node, opts) { + assert("BooleanLiteralTypeAnnotation", node, opts); + } + function assertNullLiteralTypeAnnotation(node, opts) { + assert("NullLiteralTypeAnnotation", node, opts); + } + function assertClassImplements(node, opts) { + assert("ClassImplements", node, opts); + } + function assertDeclareClass(node, opts) { + assert("DeclareClass", node, opts); + } + function assertDeclareFunction(node, opts) { + assert("DeclareFunction", node, opts); + } + function assertDeclareInterface(node, opts) { + assert("DeclareInterface", node, opts); + } + function assertDeclareModule(node, opts) { + assert("DeclareModule", node, opts); + } + function assertDeclareModuleExports(node, opts) { + assert("DeclareModuleExports", node, opts); + } + function assertDeclareTypeAlias(node, opts) { + assert("DeclareTypeAlias", node, opts); + } + function assertDeclareOpaqueType(node, opts) { + assert("DeclareOpaqueType", node, opts); + } + function assertDeclareVariable(node, opts) { + assert("DeclareVariable", node, opts); + } + function assertDeclareExportDeclaration(node, opts) { + assert("DeclareExportDeclaration", node, opts); + } + function assertDeclareExportAllDeclaration(node, opts) { + assert("DeclareExportAllDeclaration", node, opts); + } + function assertDeclaredPredicate(node, opts) { + assert("DeclaredPredicate", node, opts); + } + function assertExistsTypeAnnotation(node, opts) { + assert("ExistsTypeAnnotation", node, opts); + } + function assertFunctionTypeAnnotation(node, opts) { + assert("FunctionTypeAnnotation", node, opts); + } + function assertFunctionTypeParam(node, opts) { + assert("FunctionTypeParam", node, opts); + } + function assertGenericTypeAnnotation(node, opts) { + assert("GenericTypeAnnotation", node, opts); + } + function assertInferredPredicate(node, opts) { + assert("InferredPredicate", node, opts); + } + function assertInterfaceExtends(node, opts) { + assert("InterfaceExtends", node, opts); + } + function assertInterfaceDeclaration(node, opts) { + assert("InterfaceDeclaration", node, opts); + } + function assertInterfaceTypeAnnotation(node, opts) { + assert("InterfaceTypeAnnotation", node, opts); + } + function assertIntersectionTypeAnnotation(node, opts) { + assert("IntersectionTypeAnnotation", node, opts); + } + function assertMixedTypeAnnotation(node, opts) { + assert("MixedTypeAnnotation", node, opts); + } + function assertEmptyTypeAnnotation(node, opts) { + assert("EmptyTypeAnnotation", node, opts); + } + function assertNullableTypeAnnotation(node, opts) { + assert("NullableTypeAnnotation", node, opts); + } + function assertNumberLiteralTypeAnnotation(node, opts) { + assert("NumberLiteralTypeAnnotation", node, opts); + } + function assertNumberTypeAnnotation(node, opts) { + assert("NumberTypeAnnotation", node, opts); + } + function assertObjectTypeAnnotation(node, opts) { + assert("ObjectTypeAnnotation", node, opts); + } + function assertObjectTypeInternalSlot(node, opts) { + assert("ObjectTypeInternalSlot", node, opts); + } + function assertObjectTypeCallProperty(node, opts) { + assert("ObjectTypeCallProperty", node, opts); + } + function assertObjectTypeIndexer(node, opts) { + assert("ObjectTypeIndexer", node, opts); + } + function assertObjectTypeProperty(node, opts) { + assert("ObjectTypeProperty", node, opts); + } + function assertObjectTypeSpreadProperty(node, opts) { + assert("ObjectTypeSpreadProperty", node, opts); + } + function assertOpaqueType(node, opts) { + assert("OpaqueType", node, opts); + } + function assertQualifiedTypeIdentifier(node, opts) { + assert("QualifiedTypeIdentifier", node, opts); + } + function assertStringLiteralTypeAnnotation(node, opts) { + assert("StringLiteralTypeAnnotation", node, opts); + } + function assertStringTypeAnnotation(node, opts) { + assert("StringTypeAnnotation", node, opts); + } + function assertSymbolTypeAnnotation(node, opts) { + assert("SymbolTypeAnnotation", node, opts); + } + function assertThisTypeAnnotation(node, opts) { + assert("ThisTypeAnnotation", node, opts); + } + function assertTupleTypeAnnotation(node, opts) { + assert("TupleTypeAnnotation", node, opts); + } + function assertTypeofTypeAnnotation(node, opts) { + assert("TypeofTypeAnnotation", node, opts); + } + function assertTypeAlias(node, opts) { + assert("TypeAlias", node, opts); + } + function assertTypeAnnotation(node, opts) { + assert("TypeAnnotation", node, opts); + } + function assertTypeCastExpression(node, opts) { + assert("TypeCastExpression", node, opts); + } + function assertTypeParameter(node, opts) { + assert("TypeParameter", node, opts); + } + function assertTypeParameterDeclaration(node, opts) { + assert("TypeParameterDeclaration", node, opts); + } + function assertTypeParameterInstantiation(node, opts) { + assert("TypeParameterInstantiation", node, opts); + } + function assertUnionTypeAnnotation(node, opts) { + assert("UnionTypeAnnotation", node, opts); + } + function assertVariance(node, opts) { + assert("Variance", node, opts); + } + function assertVoidTypeAnnotation(node, opts) { + assert("VoidTypeAnnotation", node, opts); + } + function assertEnumDeclaration(node, opts) { + assert("EnumDeclaration", node, opts); + } + function assertEnumBooleanBody(node, opts) { + assert("EnumBooleanBody", node, opts); + } + function assertEnumNumberBody(node, opts) { + assert("EnumNumberBody", node, opts); + } + function assertEnumStringBody(node, opts) { + assert("EnumStringBody", node, opts); + } + function assertEnumSymbolBody(node, opts) { + assert("EnumSymbolBody", node, opts); + } + function assertEnumBooleanMember(node, opts) { + assert("EnumBooleanMember", node, opts); + } + function assertEnumNumberMember(node, opts) { + assert("EnumNumberMember", node, opts); + } + function assertEnumStringMember(node, opts) { + assert("EnumStringMember", node, opts); + } + function assertEnumDefaultedMember(node, opts) { + assert("EnumDefaultedMember", node, opts); + } + function assertIndexedAccessType(node, opts) { + assert("IndexedAccessType", node, opts); + } + function assertOptionalIndexedAccessType(node, opts) { + assert("OptionalIndexedAccessType", node, opts); + } + function assertJSXAttribute(node, opts) { + assert("JSXAttribute", node, opts); + } + function assertJSXClosingElement(node, opts) { + assert("JSXClosingElement", node, opts); + } + function assertJSXElement(node, opts) { + assert("JSXElement", node, opts); + } + function assertJSXEmptyExpression(node, opts) { + assert("JSXEmptyExpression", node, opts); + } + function assertJSXExpressionContainer(node, opts) { + assert("JSXExpressionContainer", node, opts); + } + function assertJSXSpreadChild(node, opts) { + assert("JSXSpreadChild", node, opts); + } + function assertJSXIdentifier(node, opts) { + assert("JSXIdentifier", node, opts); + } + function assertJSXMemberExpression(node, opts) { + assert("JSXMemberExpression", node, opts); + } + function assertJSXNamespacedName(node, opts) { + assert("JSXNamespacedName", node, opts); + } + function assertJSXOpeningElement(node, opts) { + assert("JSXOpeningElement", node, opts); + } + function assertJSXSpreadAttribute(node, opts) { + assert("JSXSpreadAttribute", node, opts); + } + function assertJSXText(node, opts) { + assert("JSXText", node, opts); + } + function assertJSXFragment(node, opts) { + assert("JSXFragment", node, opts); + } + function assertJSXOpeningFragment(node, opts) { + assert("JSXOpeningFragment", node, opts); + } + function assertJSXClosingFragment(node, opts) { + assert("JSXClosingFragment", node, opts); + } + function assertNoop(node, opts) { + assert("Noop", node, opts); + } + function assertPlaceholder(node, opts) { + assert("Placeholder", node, opts); + } + function assertV8IntrinsicIdentifier(node, opts) { + assert("V8IntrinsicIdentifier", node, opts); + } + function assertArgumentPlaceholder(node, opts) { + assert("ArgumentPlaceholder", node, opts); + } + function assertBindExpression(node, opts) { + assert("BindExpression", node, opts); + } + function assertImportAttribute(node, opts) { + assert("ImportAttribute", node, opts); + } + function assertDecorator(node, opts) { + assert("Decorator", node, opts); + } + function assertDoExpression(node, opts) { + assert("DoExpression", node, opts); + } + function assertExportDefaultSpecifier(node, opts) { + assert("ExportDefaultSpecifier", node, opts); + } + function assertRecordExpression(node, opts) { + assert("RecordExpression", node, opts); + } + function assertTupleExpression(node, opts) { + assert("TupleExpression", node, opts); + } + function assertDecimalLiteral(node, opts) { + assert("DecimalLiteral", node, opts); + } + function assertModuleExpression(node, opts) { + assert("ModuleExpression", node, opts); + } + function assertTopicReference(node, opts) { + assert("TopicReference", node, opts); + } + function assertPipelineTopicExpression(node, opts) { + assert("PipelineTopicExpression", node, opts); + } + function assertPipelineBareFunction(node, opts) { + assert("PipelineBareFunction", node, opts); + } + function assertPipelinePrimaryTopicReference(node, opts) { + assert("PipelinePrimaryTopicReference", node, opts); + } + function assertTSParameterProperty(node, opts) { + assert("TSParameterProperty", node, opts); + } + function assertTSDeclareFunction(node, opts) { + assert("TSDeclareFunction", node, opts); + } + function assertTSDeclareMethod(node, opts) { + assert("TSDeclareMethod", node, opts); + } + function assertTSQualifiedName(node, opts) { + assert("TSQualifiedName", node, opts); + } + function assertTSCallSignatureDeclaration(node, opts) { + assert("TSCallSignatureDeclaration", node, opts); + } + function assertTSConstructSignatureDeclaration(node, opts) { + assert("TSConstructSignatureDeclaration", node, opts); + } + function assertTSPropertySignature(node, opts) { + assert("TSPropertySignature", node, opts); + } + function assertTSMethodSignature(node, opts) { + assert("TSMethodSignature", node, opts); + } + function assertTSIndexSignature(node, opts) { + assert("TSIndexSignature", node, opts); + } + function assertTSAnyKeyword(node, opts) { + assert("TSAnyKeyword", node, opts); + } + function assertTSBooleanKeyword(node, opts) { + assert("TSBooleanKeyword", node, opts); + } + function assertTSBigIntKeyword(node, opts) { + assert("TSBigIntKeyword", node, opts); + } + function assertTSIntrinsicKeyword(node, opts) { + assert("TSIntrinsicKeyword", node, opts); + } + function assertTSNeverKeyword(node, opts) { + assert("TSNeverKeyword", node, opts); + } + function assertTSNullKeyword(node, opts) { + assert("TSNullKeyword", node, opts); + } + function assertTSNumberKeyword(node, opts) { + assert("TSNumberKeyword", node, opts); + } + function assertTSObjectKeyword(node, opts) { + assert("TSObjectKeyword", node, opts); + } + function assertTSStringKeyword(node, opts) { + assert("TSStringKeyword", node, opts); + } + function assertTSSymbolKeyword(node, opts) { + assert("TSSymbolKeyword", node, opts); + } + function assertTSUndefinedKeyword(node, opts) { + assert("TSUndefinedKeyword", node, opts); + } + function assertTSUnknownKeyword(node, opts) { + assert("TSUnknownKeyword", node, opts); + } + function assertTSVoidKeyword(node, opts) { + assert("TSVoidKeyword", node, opts); + } + function assertTSThisType(node, opts) { + assert("TSThisType", node, opts); + } + function assertTSFunctionType(node, opts) { + assert("TSFunctionType", node, opts); + } + function assertTSConstructorType(node, opts) { + assert("TSConstructorType", node, opts); + } + function assertTSTypeReference(node, opts) { + assert("TSTypeReference", node, opts); + } + function assertTSTypePredicate(node, opts) { + assert("TSTypePredicate", node, opts); + } + function assertTSTypeQuery(node, opts) { + assert("TSTypeQuery", node, opts); + } + function assertTSTypeLiteral(node, opts) { + assert("TSTypeLiteral", node, opts); + } + function assertTSArrayType(node, opts) { + assert("TSArrayType", node, opts); + } + function assertTSTupleType(node, opts) { + assert("TSTupleType", node, opts); + } + function assertTSOptionalType(node, opts) { + assert("TSOptionalType", node, opts); + } + function assertTSRestType(node, opts) { + assert("TSRestType", node, opts); + } + function assertTSNamedTupleMember(node, opts) { + assert("TSNamedTupleMember", node, opts); + } + function assertTSUnionType(node, opts) { + assert("TSUnionType", node, opts); + } + function assertTSIntersectionType(node, opts) { + assert("TSIntersectionType", node, opts); + } + function assertTSConditionalType(node, opts) { + assert("TSConditionalType", node, opts); + } + function assertTSInferType(node, opts) { + assert("TSInferType", node, opts); + } + function assertTSParenthesizedType(node, opts) { + assert("TSParenthesizedType", node, opts); + } + function assertTSTypeOperator(node, opts) { + assert("TSTypeOperator", node, opts); + } + function assertTSIndexedAccessType(node, opts) { + assert("TSIndexedAccessType", node, opts); + } + function assertTSMappedType(node, opts) { + assert("TSMappedType", node, opts); + } + function assertTSLiteralType(node, opts) { + assert("TSLiteralType", node, opts); + } + function assertTSExpressionWithTypeArguments(node, opts) { + assert("TSExpressionWithTypeArguments", node, opts); + } + function assertTSInterfaceDeclaration(node, opts) { + assert("TSInterfaceDeclaration", node, opts); + } + function assertTSInterfaceBody(node, opts) { + assert("TSInterfaceBody", node, opts); + } + function assertTSTypeAliasDeclaration(node, opts) { + assert("TSTypeAliasDeclaration", node, opts); + } + function assertTSInstantiationExpression(node, opts) { + assert("TSInstantiationExpression", node, opts); + } + function assertTSAsExpression(node, opts) { + assert("TSAsExpression", node, opts); + } + function assertTSSatisfiesExpression(node, opts) { + assert("TSSatisfiesExpression", node, opts); + } + function assertTSTypeAssertion(node, opts) { + assert("TSTypeAssertion", node, opts); + } + function assertTSEnumDeclaration(node, opts) { + assert("TSEnumDeclaration", node, opts); + } + function assertTSEnumMember(node, opts) { + assert("TSEnumMember", node, opts); + } + function assertTSModuleDeclaration(node, opts) { + assert("TSModuleDeclaration", node, opts); + } + function assertTSModuleBlock(node, opts) { + assert("TSModuleBlock", node, opts); + } + function assertTSImportType(node, opts) { + assert("TSImportType", node, opts); + } + function assertTSImportEqualsDeclaration(node, opts) { + assert("TSImportEqualsDeclaration", node, opts); + } + function assertTSExternalModuleReference(node, opts) { + assert("TSExternalModuleReference", node, opts); + } + function assertTSNonNullExpression(node, opts) { + assert("TSNonNullExpression", node, opts); + } + function assertTSExportAssignment(node, opts) { + assert("TSExportAssignment", node, opts); + } + function assertTSNamespaceExportDeclaration(node, opts) { + assert("TSNamespaceExportDeclaration", node, opts); + } + function assertTSTypeAnnotation(node, opts) { + assert("TSTypeAnnotation", node, opts); + } + function assertTSTypeParameterInstantiation(node, opts) { + assert("TSTypeParameterInstantiation", node, opts); + } + function assertTSTypeParameterDeclaration(node, opts) { + assert("TSTypeParameterDeclaration", node, opts); + } + function assertTSTypeParameter(node, opts) { + assert("TSTypeParameter", node, opts); + } + function assertStandardized(node, opts) { + assert("Standardized", node, opts); + } + function assertExpression(node, opts) { + assert("Expression", node, opts); + } + function assertBinary(node, opts) { + assert("Binary", node, opts); + } + function assertScopable(node, opts) { + assert("Scopable", node, opts); + } + function assertBlockParent(node, opts) { + assert("BlockParent", node, opts); + } + function assertBlock(node, opts) { + assert("Block", node, opts); + } + function assertStatement(node, opts) { + assert("Statement", node, opts); + } + function assertTerminatorless(node, opts) { + assert("Terminatorless", node, opts); + } + function assertCompletionStatement(node, opts) { + assert("CompletionStatement", node, opts); + } + function assertConditional(node, opts) { + assert("Conditional", node, opts); + } + function assertLoop(node, opts) { + assert("Loop", node, opts); + } + function assertWhile(node, opts) { + assert("While", node, opts); + } + function assertExpressionWrapper(node, opts) { + assert("ExpressionWrapper", node, opts); + } + function assertFor(node, opts) { + assert("For", node, opts); + } + function assertForXStatement(node, opts) { + assert("ForXStatement", node, opts); + } + function assertFunction(node, opts) { + assert("Function", node, opts); + } + function assertFunctionParent(node, opts) { + assert("FunctionParent", node, opts); + } + function assertPureish(node, opts) { + assert("Pureish", node, opts); + } + function assertDeclaration(node, opts) { + assert("Declaration", node, opts); + } + function assertPatternLike(node, opts) { + assert("PatternLike", node, opts); + } + function assertLVal(node, opts) { + assert("LVal", node, opts); + } + function assertTSEntityName(node, opts) { + assert("TSEntityName", node, opts); + } + function assertLiteral(node, opts) { + assert("Literal", node, opts); + } + function assertImmutable(node, opts) { + assert("Immutable", node, opts); + } + function assertUserWhitespacable(node, opts) { + assert("UserWhitespacable", node, opts); + } + function assertMethod(node, opts) { + assert("Method", node, opts); + } + function assertObjectMember(node, opts) { + assert("ObjectMember", node, opts); + } + function assertProperty(node, opts) { + assert("Property", node, opts); + } + function assertUnaryLike(node, opts) { + assert("UnaryLike", node, opts); + } + function assertPattern(node, opts) { + assert("Pattern", node, opts); + } + function assertClass(node, opts) { + assert("Class", node, opts); + } + function assertImportOrExportDeclaration(node, opts) { + assert("ImportOrExportDeclaration", node, opts); + } + function assertExportDeclaration(node, opts) { + assert("ExportDeclaration", node, opts); + } + function assertModuleSpecifier(node, opts) { + assert("ModuleSpecifier", node, opts); + } + function assertAccessor(node, opts) { + assert("Accessor", node, opts); + } + function assertPrivate(node, opts) { + assert("Private", node, opts); + } + function assertFlow(node, opts) { + assert("Flow", node, opts); + } + function assertFlowType(node, opts) { + assert("FlowType", node, opts); + } + function assertFlowBaseAnnotation(node, opts) { + assert("FlowBaseAnnotation", node, opts); + } + function assertFlowDeclaration(node, opts) { + assert("FlowDeclaration", node, opts); + } + function assertFlowPredicate(node, opts) { + assert("FlowPredicate", node, opts); + } + function assertEnumBody(node, opts) { + assert("EnumBody", node, opts); + } + function assertEnumMember(node, opts) { + assert("EnumMember", node, opts); + } + function assertJSX(node, opts) { + assert("JSX", node, opts); + } + function assertMiscellaneous(node, opts) { + assert("Miscellaneous", node, opts); + } + function assertTypeScript(node, opts) { + assert("TypeScript", node, opts); + } + function assertTSTypeElement(node, opts) { + assert("TSTypeElement", node, opts); + } + function assertTSType(node, opts) { + assert("TSType", node, opts); + } + function assertTSBaseType(node, opts) { + assert("TSBaseType", node, opts); + } + function assertNumberLiteral(node, opts) { + (0, _deprecationWarning.default)("assertNumberLiteral", "assertNumericLiteral"); + assert("NumberLiteral", node, opts); + } + function assertRegexLiteral(node, opts) { + (0, _deprecationWarning.default)("assertRegexLiteral", "assertRegExpLiteral"); + assert("RegexLiteral", node, opts); + } + function assertRestProperty(node, opts) { + (0, _deprecationWarning.default)("assertRestProperty", "assertRestElement"); + assert("RestProperty", node, opts); + } + function assertSpreadProperty(node, opts) { + (0, _deprecationWarning.default)("assertSpreadProperty", "assertSpreadElement"); + assert("SpreadProperty", node, opts); + } + function assertModuleDeclaration(node, opts) { + (0, _deprecationWarning.default)("assertModuleDeclaration", "assertImportOrExportDeclaration"); + assert("ModuleDeclaration", node, opts); + } + + + return generated$1; +} + +var createTypeAnnotationBasedOnTypeof = {}; + +var hasRequiredCreateTypeAnnotationBasedOnTypeof; + +function requireCreateTypeAnnotationBasedOnTypeof () { + if (hasRequiredCreateTypeAnnotationBasedOnTypeof) return createTypeAnnotationBasedOnTypeof; + hasRequiredCreateTypeAnnotationBasedOnTypeof = 1; + + Object.defineProperty(createTypeAnnotationBasedOnTypeof, "__esModule", { + value: true + }); + createTypeAnnotationBasedOnTypeof.default = void 0; + var _index = requireGenerated$2(); + createTypeAnnotationBasedOnTypeof.default = createTypeAnnotationBasedOnTypeof$1; + function createTypeAnnotationBasedOnTypeof$1(type) { + switch (type) { + case "string": + return (0, _index.stringTypeAnnotation)(); + case "number": + return (0, _index.numberTypeAnnotation)(); + case "undefined": + return (0, _index.voidTypeAnnotation)(); + case "boolean": + return (0, _index.booleanTypeAnnotation)(); + case "function": + return (0, _index.genericTypeAnnotation)((0, _index.identifier)("Function")); + case "object": + return (0, _index.genericTypeAnnotation)((0, _index.identifier)("Object")); + case "symbol": + return (0, _index.genericTypeAnnotation)((0, _index.identifier)("Symbol")); + case "bigint": + return (0, _index.anyTypeAnnotation)(); + } + throw new Error("Invalid typeof value: " + type); + } + + + return createTypeAnnotationBasedOnTypeof; +} + +var createFlowUnionType = {}; + +var removeTypeDuplicates$1 = {}; + +var hasRequiredRemoveTypeDuplicates$1; + +function requireRemoveTypeDuplicates$1 () { + if (hasRequiredRemoveTypeDuplicates$1) return removeTypeDuplicates$1; + hasRequiredRemoveTypeDuplicates$1 = 1; + + Object.defineProperty(removeTypeDuplicates$1, "__esModule", { + value: true + }); + removeTypeDuplicates$1.default = removeTypeDuplicates; + var _index = requireGenerated$3(); + function getQualifiedName(node) { + return (0, _index.isIdentifier)(node) ? node.name : `${node.id.name}.${getQualifiedName(node.qualification)}`; + } + function removeTypeDuplicates(nodesIn) { + const nodes = Array.from(nodesIn); + const generics = new Map(); + const bases = new Map(); + const typeGroups = new Set(); + const types = []; + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + if (!node) continue; + if (types.includes(node)) { + continue; + } + if ((0, _index.isAnyTypeAnnotation)(node)) { + return [node]; + } + if ((0, _index.isFlowBaseAnnotation)(node)) { + bases.set(node.type, node); + continue; + } + if ((0, _index.isUnionTypeAnnotation)(node)) { + if (!typeGroups.has(node.types)) { + nodes.push(...node.types); + typeGroups.add(node.types); + } + continue; + } + if ((0, _index.isGenericTypeAnnotation)(node)) { + const name = getQualifiedName(node.id); + if (generics.has(name)) { + let existing = generics.get(name); + if (existing.typeParameters) { + if (node.typeParameters) { + existing.typeParameters.params.push(...node.typeParameters.params); + existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params); + } + } else { + existing = node.typeParameters; + } + } else { + generics.set(name, node); + } + continue; + } + types.push(node); + } + for (const [, baseType] of bases) { + types.push(baseType); + } + for (const [, genericName] of generics) { + types.push(genericName); + } + return types; + } + + + return removeTypeDuplicates$1; +} + +var hasRequiredCreateFlowUnionType; + +function requireCreateFlowUnionType () { + if (hasRequiredCreateFlowUnionType) return createFlowUnionType; + hasRequiredCreateFlowUnionType = 1; + + Object.defineProperty(createFlowUnionType, "__esModule", { + value: true + }); + createFlowUnionType.default = createFlowUnionType$1; + var _index = requireGenerated$2(); + var _removeTypeDuplicates = requireRemoveTypeDuplicates$1(); + function createFlowUnionType$1(types) { + const flattened = (0, _removeTypeDuplicates.default)(types); + if (flattened.length === 1) { + return flattened[0]; + } else { + return (0, _index.unionTypeAnnotation)(flattened); + } + } + + + return createFlowUnionType; +} + +var createTSUnionType = {}; + +var removeTypeDuplicates = {}; + +var hasRequiredRemoveTypeDuplicates; + +function requireRemoveTypeDuplicates () { + if (hasRequiredRemoveTypeDuplicates) return removeTypeDuplicates; + hasRequiredRemoveTypeDuplicates = 1; + + Object.defineProperty(removeTypeDuplicates, "__esModule", { + value: true + }); + removeTypeDuplicates.default = removeTypeDuplicates$1; + var _index = requireGenerated$3(); + function getQualifiedName(node) { + return (0, _index.isIdentifier)(node) ? node.name : `${node.right.name}.${getQualifiedName(node.left)}`; + } + function removeTypeDuplicates$1(nodesIn) { + const nodes = Array.from(nodesIn); + const generics = new Map(); + const bases = new Map(); + const typeGroups = new Set(); + const types = []; + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + if (!node) continue; + if (types.includes(node)) { + continue; + } + if ((0, _index.isTSAnyKeyword)(node)) { + return [node]; + } + if ((0, _index.isTSBaseType)(node)) { + bases.set(node.type, node); + continue; + } + if ((0, _index.isTSUnionType)(node)) { + if (!typeGroups.has(node.types)) { + nodes.push(...node.types); + typeGroups.add(node.types); + } + continue; + } + if ((0, _index.isTSTypeReference)(node) && node.typeParameters) { + const name = getQualifiedName(node.typeName); + if (generics.has(name)) { + let existing = generics.get(name); + if (existing.typeParameters) { + if (node.typeParameters) { + existing.typeParameters.params.push(...node.typeParameters.params); + existing.typeParameters.params = removeTypeDuplicates$1(existing.typeParameters.params); + } + } else { + existing = node.typeParameters; + } + } else { + generics.set(name, node); + } + continue; + } + types.push(node); + } + for (const [, baseType] of bases) { + types.push(baseType); + } + for (const [, genericName] of generics) { + types.push(genericName); + } + return types; + } + + + return removeTypeDuplicates; +} + +var hasRequiredCreateTSUnionType; + +function requireCreateTSUnionType () { + if (hasRequiredCreateTSUnionType) return createTSUnionType; + hasRequiredCreateTSUnionType = 1; + + Object.defineProperty(createTSUnionType, "__esModule", { + value: true + }); + createTSUnionType.default = createTSUnionType$1; + var _index = requireGenerated$2(); + var _removeTypeDuplicates = requireRemoveTypeDuplicates(); + var _index2 = requireGenerated$3(); + function createTSUnionType$1(typeAnnotations) { + const types = typeAnnotations.map(type => { + return (0, _index2.isTSTypeAnnotation)(type) ? type.typeAnnotation : type; + }); + const flattened = (0, _removeTypeDuplicates.default)(types); + if (flattened.length === 1) { + return flattened[0]; + } else { + return (0, _index.tsUnionType)(flattened); + } + } + + + return createTSUnionType; +} + +var uppercase = {}; + +var hasRequiredUppercase; + +function requireUppercase () { + if (hasRequiredUppercase) return uppercase; + hasRequiredUppercase = 1; + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "AnyTypeAnnotation", { + enumerable: true, + get: function () { + return _index.anyTypeAnnotation; + } + }); + Object.defineProperty(exports, "ArgumentPlaceholder", { + enumerable: true, + get: function () { + return _index.argumentPlaceholder; + } + }); + Object.defineProperty(exports, "ArrayExpression", { + enumerable: true, + get: function () { + return _index.arrayExpression; + } + }); + Object.defineProperty(exports, "ArrayPattern", { + enumerable: true, + get: function () { + return _index.arrayPattern; + } + }); + Object.defineProperty(exports, "ArrayTypeAnnotation", { + enumerable: true, + get: function () { + return _index.arrayTypeAnnotation; + } + }); + Object.defineProperty(exports, "ArrowFunctionExpression", { + enumerable: true, + get: function () { + return _index.arrowFunctionExpression; + } + }); + Object.defineProperty(exports, "AssignmentExpression", { + enumerable: true, + get: function () { + return _index.assignmentExpression; + } + }); + Object.defineProperty(exports, "AssignmentPattern", { + enumerable: true, + get: function () { + return _index.assignmentPattern; + } + }); + Object.defineProperty(exports, "AwaitExpression", { + enumerable: true, + get: function () { + return _index.awaitExpression; + } + }); + Object.defineProperty(exports, "BigIntLiteral", { + enumerable: true, + get: function () { + return _index.bigIntLiteral; + } + }); + Object.defineProperty(exports, "BinaryExpression", { + enumerable: true, + get: function () { + return _index.binaryExpression; + } + }); + Object.defineProperty(exports, "BindExpression", { + enumerable: true, + get: function () { + return _index.bindExpression; + } + }); + Object.defineProperty(exports, "BlockStatement", { + enumerable: true, + get: function () { + return _index.blockStatement; + } + }); + Object.defineProperty(exports, "BooleanLiteral", { + enumerable: true, + get: function () { + return _index.booleanLiteral; + } + }); + Object.defineProperty(exports, "BooleanLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _index.booleanLiteralTypeAnnotation; + } + }); + Object.defineProperty(exports, "BooleanTypeAnnotation", { + enumerable: true, + get: function () { + return _index.booleanTypeAnnotation; + } + }); + Object.defineProperty(exports, "BreakStatement", { + enumerable: true, + get: function () { + return _index.breakStatement; + } + }); + Object.defineProperty(exports, "CallExpression", { + enumerable: true, + get: function () { + return _index.callExpression; + } + }); + Object.defineProperty(exports, "CatchClause", { + enumerable: true, + get: function () { + return _index.catchClause; + } + }); + Object.defineProperty(exports, "ClassAccessorProperty", { + enumerable: true, + get: function () { + return _index.classAccessorProperty; + } + }); + Object.defineProperty(exports, "ClassBody", { + enumerable: true, + get: function () { + return _index.classBody; + } + }); + Object.defineProperty(exports, "ClassDeclaration", { + enumerable: true, + get: function () { + return _index.classDeclaration; + } + }); + Object.defineProperty(exports, "ClassExpression", { + enumerable: true, + get: function () { + return _index.classExpression; + } + }); + Object.defineProperty(exports, "ClassImplements", { + enumerable: true, + get: function () { + return _index.classImplements; + } + }); + Object.defineProperty(exports, "ClassMethod", { + enumerable: true, + get: function () { + return _index.classMethod; + } + }); + Object.defineProperty(exports, "ClassPrivateMethod", { + enumerable: true, + get: function () { + return _index.classPrivateMethod; + } + }); + Object.defineProperty(exports, "ClassPrivateProperty", { + enumerable: true, + get: function () { + return _index.classPrivateProperty; + } + }); + Object.defineProperty(exports, "ClassProperty", { + enumerable: true, + get: function () { + return _index.classProperty; + } + }); + Object.defineProperty(exports, "ConditionalExpression", { + enumerable: true, + get: function () { + return _index.conditionalExpression; + } + }); + Object.defineProperty(exports, "ContinueStatement", { + enumerable: true, + get: function () { + return _index.continueStatement; + } + }); + Object.defineProperty(exports, "DebuggerStatement", { + enumerable: true, + get: function () { + return _index.debuggerStatement; + } + }); + Object.defineProperty(exports, "DecimalLiteral", { + enumerable: true, + get: function () { + return _index.decimalLiteral; + } + }); + Object.defineProperty(exports, "DeclareClass", { + enumerable: true, + get: function () { + return _index.declareClass; + } + }); + Object.defineProperty(exports, "DeclareExportAllDeclaration", { + enumerable: true, + get: function () { + return _index.declareExportAllDeclaration; + } + }); + Object.defineProperty(exports, "DeclareExportDeclaration", { + enumerable: true, + get: function () { + return _index.declareExportDeclaration; + } + }); + Object.defineProperty(exports, "DeclareFunction", { + enumerable: true, + get: function () { + return _index.declareFunction; + } + }); + Object.defineProperty(exports, "DeclareInterface", { + enumerable: true, + get: function () { + return _index.declareInterface; + } + }); + Object.defineProperty(exports, "DeclareModule", { + enumerable: true, + get: function () { + return _index.declareModule; + } + }); + Object.defineProperty(exports, "DeclareModuleExports", { + enumerable: true, + get: function () { + return _index.declareModuleExports; + } + }); + Object.defineProperty(exports, "DeclareOpaqueType", { + enumerable: true, + get: function () { + return _index.declareOpaqueType; + } + }); + Object.defineProperty(exports, "DeclareTypeAlias", { + enumerable: true, + get: function () { + return _index.declareTypeAlias; + } + }); + Object.defineProperty(exports, "DeclareVariable", { + enumerable: true, + get: function () { + return _index.declareVariable; + } + }); + Object.defineProperty(exports, "DeclaredPredicate", { + enumerable: true, + get: function () { + return _index.declaredPredicate; + } + }); + Object.defineProperty(exports, "Decorator", { + enumerable: true, + get: function () { + return _index.decorator; + } + }); + Object.defineProperty(exports, "Directive", { + enumerable: true, + get: function () { + return _index.directive; + } + }); + Object.defineProperty(exports, "DirectiveLiteral", { + enumerable: true, + get: function () { + return _index.directiveLiteral; + } + }); + Object.defineProperty(exports, "DoExpression", { + enumerable: true, + get: function () { + return _index.doExpression; + } + }); + Object.defineProperty(exports, "DoWhileStatement", { + enumerable: true, + get: function () { + return _index.doWhileStatement; + } + }); + Object.defineProperty(exports, "EmptyStatement", { + enumerable: true, + get: function () { + return _index.emptyStatement; + } + }); + Object.defineProperty(exports, "EmptyTypeAnnotation", { + enumerable: true, + get: function () { + return _index.emptyTypeAnnotation; + } + }); + Object.defineProperty(exports, "EnumBooleanBody", { + enumerable: true, + get: function () { + return _index.enumBooleanBody; + } + }); + Object.defineProperty(exports, "EnumBooleanMember", { + enumerable: true, + get: function () { + return _index.enumBooleanMember; + } + }); + Object.defineProperty(exports, "EnumDeclaration", { + enumerable: true, + get: function () { + return _index.enumDeclaration; + } + }); + Object.defineProperty(exports, "EnumDefaultedMember", { + enumerable: true, + get: function () { + return _index.enumDefaultedMember; + } + }); + Object.defineProperty(exports, "EnumNumberBody", { + enumerable: true, + get: function () { + return _index.enumNumberBody; + } + }); + Object.defineProperty(exports, "EnumNumberMember", { + enumerable: true, + get: function () { + return _index.enumNumberMember; + } + }); + Object.defineProperty(exports, "EnumStringBody", { + enumerable: true, + get: function () { + return _index.enumStringBody; + } + }); + Object.defineProperty(exports, "EnumStringMember", { + enumerable: true, + get: function () { + return _index.enumStringMember; + } + }); + Object.defineProperty(exports, "EnumSymbolBody", { + enumerable: true, + get: function () { + return _index.enumSymbolBody; + } + }); + Object.defineProperty(exports, "ExistsTypeAnnotation", { + enumerable: true, + get: function () { + return _index.existsTypeAnnotation; + } + }); + Object.defineProperty(exports, "ExportAllDeclaration", { + enumerable: true, + get: function () { + return _index.exportAllDeclaration; + } + }); + Object.defineProperty(exports, "ExportDefaultDeclaration", { + enumerable: true, + get: function () { + return _index.exportDefaultDeclaration; + } + }); + Object.defineProperty(exports, "ExportDefaultSpecifier", { + enumerable: true, + get: function () { + return _index.exportDefaultSpecifier; + } + }); + Object.defineProperty(exports, "ExportNamedDeclaration", { + enumerable: true, + get: function () { + return _index.exportNamedDeclaration; + } + }); + Object.defineProperty(exports, "ExportNamespaceSpecifier", { + enumerable: true, + get: function () { + return _index.exportNamespaceSpecifier; + } + }); + Object.defineProperty(exports, "ExportSpecifier", { + enumerable: true, + get: function () { + return _index.exportSpecifier; + } + }); + Object.defineProperty(exports, "ExpressionStatement", { + enumerable: true, + get: function () { + return _index.expressionStatement; + } + }); + Object.defineProperty(exports, "File", { + enumerable: true, + get: function () { + return _index.file; + } + }); + Object.defineProperty(exports, "ForInStatement", { + enumerable: true, + get: function () { + return _index.forInStatement; + } + }); + Object.defineProperty(exports, "ForOfStatement", { + enumerable: true, + get: function () { + return _index.forOfStatement; + } + }); + Object.defineProperty(exports, "ForStatement", { + enumerable: true, + get: function () { + return _index.forStatement; + } + }); + Object.defineProperty(exports, "FunctionDeclaration", { + enumerable: true, + get: function () { + return _index.functionDeclaration; + } + }); + Object.defineProperty(exports, "FunctionExpression", { + enumerable: true, + get: function () { + return _index.functionExpression; + } + }); + Object.defineProperty(exports, "FunctionTypeAnnotation", { + enumerable: true, + get: function () { + return _index.functionTypeAnnotation; + } + }); + Object.defineProperty(exports, "FunctionTypeParam", { + enumerable: true, + get: function () { + return _index.functionTypeParam; + } + }); + Object.defineProperty(exports, "GenericTypeAnnotation", { + enumerable: true, + get: function () { + return _index.genericTypeAnnotation; + } + }); + Object.defineProperty(exports, "Identifier", { + enumerable: true, + get: function () { + return _index.identifier; + } + }); + Object.defineProperty(exports, "IfStatement", { + enumerable: true, + get: function () { + return _index.ifStatement; + } + }); + Object.defineProperty(exports, "Import", { + enumerable: true, + get: function () { + return _index.import; + } + }); + Object.defineProperty(exports, "ImportAttribute", { + enumerable: true, + get: function () { + return _index.importAttribute; + } + }); + Object.defineProperty(exports, "ImportDeclaration", { + enumerable: true, + get: function () { + return _index.importDeclaration; + } + }); + Object.defineProperty(exports, "ImportDefaultSpecifier", { + enumerable: true, + get: function () { + return _index.importDefaultSpecifier; + } + }); + Object.defineProperty(exports, "ImportExpression", { + enumerable: true, + get: function () { + return _index.importExpression; + } + }); + Object.defineProperty(exports, "ImportNamespaceSpecifier", { + enumerable: true, + get: function () { + return _index.importNamespaceSpecifier; + } + }); + Object.defineProperty(exports, "ImportSpecifier", { + enumerable: true, + get: function () { + return _index.importSpecifier; + } + }); + Object.defineProperty(exports, "IndexedAccessType", { + enumerable: true, + get: function () { + return _index.indexedAccessType; + } + }); + Object.defineProperty(exports, "InferredPredicate", { + enumerable: true, + get: function () { + return _index.inferredPredicate; + } + }); + Object.defineProperty(exports, "InterfaceDeclaration", { + enumerable: true, + get: function () { + return _index.interfaceDeclaration; + } + }); + Object.defineProperty(exports, "InterfaceExtends", { + enumerable: true, + get: function () { + return _index.interfaceExtends; + } + }); + Object.defineProperty(exports, "InterfaceTypeAnnotation", { + enumerable: true, + get: function () { + return _index.interfaceTypeAnnotation; + } + }); + Object.defineProperty(exports, "InterpreterDirective", { + enumerable: true, + get: function () { + return _index.interpreterDirective; + } + }); + Object.defineProperty(exports, "IntersectionTypeAnnotation", { + enumerable: true, + get: function () { + return _index.intersectionTypeAnnotation; + } + }); + Object.defineProperty(exports, "JSXAttribute", { + enumerable: true, + get: function () { + return _index.jsxAttribute; + } + }); + Object.defineProperty(exports, "JSXClosingElement", { + enumerable: true, + get: function () { + return _index.jsxClosingElement; + } + }); + Object.defineProperty(exports, "JSXClosingFragment", { + enumerable: true, + get: function () { + return _index.jsxClosingFragment; + } + }); + Object.defineProperty(exports, "JSXElement", { + enumerable: true, + get: function () { + return _index.jsxElement; + } + }); + Object.defineProperty(exports, "JSXEmptyExpression", { + enumerable: true, + get: function () { + return _index.jsxEmptyExpression; + } + }); + Object.defineProperty(exports, "JSXExpressionContainer", { + enumerable: true, + get: function () { + return _index.jsxExpressionContainer; + } + }); + Object.defineProperty(exports, "JSXFragment", { + enumerable: true, + get: function () { + return _index.jsxFragment; + } + }); + Object.defineProperty(exports, "JSXIdentifier", { + enumerable: true, + get: function () { + return _index.jsxIdentifier; + } + }); + Object.defineProperty(exports, "JSXMemberExpression", { + enumerable: true, + get: function () { + return _index.jsxMemberExpression; + } + }); + Object.defineProperty(exports, "JSXNamespacedName", { + enumerable: true, + get: function () { + return _index.jsxNamespacedName; + } + }); + Object.defineProperty(exports, "JSXOpeningElement", { + enumerable: true, + get: function () { + return _index.jsxOpeningElement; + } + }); + Object.defineProperty(exports, "JSXOpeningFragment", { + enumerable: true, + get: function () { + return _index.jsxOpeningFragment; + } + }); + Object.defineProperty(exports, "JSXSpreadAttribute", { + enumerable: true, + get: function () { + return _index.jsxSpreadAttribute; + } + }); + Object.defineProperty(exports, "JSXSpreadChild", { + enumerable: true, + get: function () { + return _index.jsxSpreadChild; + } + }); + Object.defineProperty(exports, "JSXText", { + enumerable: true, + get: function () { + return _index.jsxText; + } + }); + Object.defineProperty(exports, "LabeledStatement", { + enumerable: true, + get: function () { + return _index.labeledStatement; + } + }); + Object.defineProperty(exports, "LogicalExpression", { + enumerable: true, + get: function () { + return _index.logicalExpression; + } + }); + Object.defineProperty(exports, "MemberExpression", { + enumerable: true, + get: function () { + return _index.memberExpression; + } + }); + Object.defineProperty(exports, "MetaProperty", { + enumerable: true, + get: function () { + return _index.metaProperty; + } + }); + Object.defineProperty(exports, "MixedTypeAnnotation", { + enumerable: true, + get: function () { + return _index.mixedTypeAnnotation; + } + }); + Object.defineProperty(exports, "ModuleExpression", { + enumerable: true, + get: function () { + return _index.moduleExpression; + } + }); + Object.defineProperty(exports, "NewExpression", { + enumerable: true, + get: function () { + return _index.newExpression; + } + }); + Object.defineProperty(exports, "Noop", { + enumerable: true, + get: function () { + return _index.noop; + } + }); + Object.defineProperty(exports, "NullLiteral", { + enumerable: true, + get: function () { + return _index.nullLiteral; + } + }); + Object.defineProperty(exports, "NullLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _index.nullLiteralTypeAnnotation; + } + }); + Object.defineProperty(exports, "NullableTypeAnnotation", { + enumerable: true, + get: function () { + return _index.nullableTypeAnnotation; + } + }); + Object.defineProperty(exports, "NumberLiteral", { + enumerable: true, + get: function () { + return _index.numberLiteral; + } + }); + Object.defineProperty(exports, "NumberLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _index.numberLiteralTypeAnnotation; + } + }); + Object.defineProperty(exports, "NumberTypeAnnotation", { + enumerable: true, + get: function () { + return _index.numberTypeAnnotation; + } + }); + Object.defineProperty(exports, "NumericLiteral", { + enumerable: true, + get: function () { + return _index.numericLiteral; + } + }); + Object.defineProperty(exports, "ObjectExpression", { + enumerable: true, + get: function () { + return _index.objectExpression; + } + }); + Object.defineProperty(exports, "ObjectMethod", { + enumerable: true, + get: function () { + return _index.objectMethod; + } + }); + Object.defineProperty(exports, "ObjectPattern", { + enumerable: true, + get: function () { + return _index.objectPattern; + } + }); + Object.defineProperty(exports, "ObjectProperty", { + enumerable: true, + get: function () { + return _index.objectProperty; + } + }); + Object.defineProperty(exports, "ObjectTypeAnnotation", { + enumerable: true, + get: function () { + return _index.objectTypeAnnotation; + } + }); + Object.defineProperty(exports, "ObjectTypeCallProperty", { + enumerable: true, + get: function () { + return _index.objectTypeCallProperty; + } + }); + Object.defineProperty(exports, "ObjectTypeIndexer", { + enumerable: true, + get: function () { + return _index.objectTypeIndexer; + } + }); + Object.defineProperty(exports, "ObjectTypeInternalSlot", { + enumerable: true, + get: function () { + return _index.objectTypeInternalSlot; + } + }); + Object.defineProperty(exports, "ObjectTypeProperty", { + enumerable: true, + get: function () { + return _index.objectTypeProperty; + } + }); + Object.defineProperty(exports, "ObjectTypeSpreadProperty", { + enumerable: true, + get: function () { + return _index.objectTypeSpreadProperty; + } + }); + Object.defineProperty(exports, "OpaqueType", { + enumerable: true, + get: function () { + return _index.opaqueType; + } + }); + Object.defineProperty(exports, "OptionalCallExpression", { + enumerable: true, + get: function () { + return _index.optionalCallExpression; + } + }); + Object.defineProperty(exports, "OptionalIndexedAccessType", { + enumerable: true, + get: function () { + return _index.optionalIndexedAccessType; + } + }); + Object.defineProperty(exports, "OptionalMemberExpression", { + enumerable: true, + get: function () { + return _index.optionalMemberExpression; + } + }); + Object.defineProperty(exports, "ParenthesizedExpression", { + enumerable: true, + get: function () { + return _index.parenthesizedExpression; + } + }); + Object.defineProperty(exports, "PipelineBareFunction", { + enumerable: true, + get: function () { + return _index.pipelineBareFunction; + } + }); + Object.defineProperty(exports, "PipelinePrimaryTopicReference", { + enumerable: true, + get: function () { + return _index.pipelinePrimaryTopicReference; + } + }); + Object.defineProperty(exports, "PipelineTopicExpression", { + enumerable: true, + get: function () { + return _index.pipelineTopicExpression; + } + }); + Object.defineProperty(exports, "Placeholder", { + enumerable: true, + get: function () { + return _index.placeholder; + } + }); + Object.defineProperty(exports, "PrivateName", { + enumerable: true, + get: function () { + return _index.privateName; + } + }); + Object.defineProperty(exports, "Program", { + enumerable: true, + get: function () { + return _index.program; + } + }); + Object.defineProperty(exports, "QualifiedTypeIdentifier", { + enumerable: true, + get: function () { + return _index.qualifiedTypeIdentifier; + } + }); + Object.defineProperty(exports, "RecordExpression", { + enumerable: true, + get: function () { + return _index.recordExpression; + } + }); + Object.defineProperty(exports, "RegExpLiteral", { + enumerable: true, + get: function () { + return _index.regExpLiteral; + } + }); + Object.defineProperty(exports, "RegexLiteral", { + enumerable: true, + get: function () { + return _index.regexLiteral; + } + }); + Object.defineProperty(exports, "RestElement", { + enumerable: true, + get: function () { + return _index.restElement; + } + }); + Object.defineProperty(exports, "RestProperty", { + enumerable: true, + get: function () { + return _index.restProperty; + } + }); + Object.defineProperty(exports, "ReturnStatement", { + enumerable: true, + get: function () { + return _index.returnStatement; + } + }); + Object.defineProperty(exports, "SequenceExpression", { + enumerable: true, + get: function () { + return _index.sequenceExpression; + } + }); + Object.defineProperty(exports, "SpreadElement", { + enumerable: true, + get: function () { + return _index.spreadElement; + } + }); + Object.defineProperty(exports, "SpreadProperty", { + enumerable: true, + get: function () { + return _index.spreadProperty; + } + }); + Object.defineProperty(exports, "StaticBlock", { + enumerable: true, + get: function () { + return _index.staticBlock; + } + }); + Object.defineProperty(exports, "StringLiteral", { + enumerable: true, + get: function () { + return _index.stringLiteral; + } + }); + Object.defineProperty(exports, "StringLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _index.stringLiteralTypeAnnotation; + } + }); + Object.defineProperty(exports, "StringTypeAnnotation", { + enumerable: true, + get: function () { + return _index.stringTypeAnnotation; + } + }); + Object.defineProperty(exports, "Super", { + enumerable: true, + get: function () { + return _index.super; + } + }); + Object.defineProperty(exports, "SwitchCase", { + enumerable: true, + get: function () { + return _index.switchCase; + } + }); + Object.defineProperty(exports, "SwitchStatement", { + enumerable: true, + get: function () { + return _index.switchStatement; + } + }); + Object.defineProperty(exports, "SymbolTypeAnnotation", { + enumerable: true, + get: function () { + return _index.symbolTypeAnnotation; + } + }); + Object.defineProperty(exports, "TSAnyKeyword", { + enumerable: true, + get: function () { + return _index.tsAnyKeyword; + } + }); + Object.defineProperty(exports, "TSArrayType", { + enumerable: true, + get: function () { + return _index.tsArrayType; + } + }); + Object.defineProperty(exports, "TSAsExpression", { + enumerable: true, + get: function () { + return _index.tsAsExpression; + } + }); + Object.defineProperty(exports, "TSBigIntKeyword", { + enumerable: true, + get: function () { + return _index.tsBigIntKeyword; + } + }); + Object.defineProperty(exports, "TSBooleanKeyword", { + enumerable: true, + get: function () { + return _index.tsBooleanKeyword; + } + }); + Object.defineProperty(exports, "TSCallSignatureDeclaration", { + enumerable: true, + get: function () { + return _index.tsCallSignatureDeclaration; + } + }); + Object.defineProperty(exports, "TSConditionalType", { + enumerable: true, + get: function () { + return _index.tsConditionalType; + } + }); + Object.defineProperty(exports, "TSConstructSignatureDeclaration", { + enumerable: true, + get: function () { + return _index.tsConstructSignatureDeclaration; + } + }); + Object.defineProperty(exports, "TSConstructorType", { + enumerable: true, + get: function () { + return _index.tsConstructorType; + } + }); + Object.defineProperty(exports, "TSDeclareFunction", { + enumerable: true, + get: function () { + return _index.tsDeclareFunction; + } + }); + Object.defineProperty(exports, "TSDeclareMethod", { + enumerable: true, + get: function () { + return _index.tsDeclareMethod; + } + }); + Object.defineProperty(exports, "TSEnumDeclaration", { + enumerable: true, + get: function () { + return _index.tsEnumDeclaration; + } + }); + Object.defineProperty(exports, "TSEnumMember", { + enumerable: true, + get: function () { + return _index.tsEnumMember; + } + }); + Object.defineProperty(exports, "TSExportAssignment", { + enumerable: true, + get: function () { + return _index.tsExportAssignment; + } + }); + Object.defineProperty(exports, "TSExpressionWithTypeArguments", { + enumerable: true, + get: function () { + return _index.tsExpressionWithTypeArguments; + } + }); + Object.defineProperty(exports, "TSExternalModuleReference", { + enumerable: true, + get: function () { + return _index.tsExternalModuleReference; + } + }); + Object.defineProperty(exports, "TSFunctionType", { + enumerable: true, + get: function () { + return _index.tsFunctionType; + } + }); + Object.defineProperty(exports, "TSImportEqualsDeclaration", { + enumerable: true, + get: function () { + return _index.tsImportEqualsDeclaration; + } + }); + Object.defineProperty(exports, "TSImportType", { + enumerable: true, + get: function () { + return _index.tsImportType; + } + }); + Object.defineProperty(exports, "TSIndexSignature", { + enumerable: true, + get: function () { + return _index.tsIndexSignature; + } + }); + Object.defineProperty(exports, "TSIndexedAccessType", { + enumerable: true, + get: function () { + return _index.tsIndexedAccessType; + } + }); + Object.defineProperty(exports, "TSInferType", { + enumerable: true, + get: function () { + return _index.tsInferType; + } + }); + Object.defineProperty(exports, "TSInstantiationExpression", { + enumerable: true, + get: function () { + return _index.tsInstantiationExpression; + } + }); + Object.defineProperty(exports, "TSInterfaceBody", { + enumerable: true, + get: function () { + return _index.tsInterfaceBody; + } + }); + Object.defineProperty(exports, "TSInterfaceDeclaration", { + enumerable: true, + get: function () { + return _index.tsInterfaceDeclaration; + } + }); + Object.defineProperty(exports, "TSIntersectionType", { + enumerable: true, + get: function () { + return _index.tsIntersectionType; + } + }); + Object.defineProperty(exports, "TSIntrinsicKeyword", { + enumerable: true, + get: function () { + return _index.tsIntrinsicKeyword; + } + }); + Object.defineProperty(exports, "TSLiteralType", { + enumerable: true, + get: function () { + return _index.tsLiteralType; + } + }); + Object.defineProperty(exports, "TSMappedType", { + enumerable: true, + get: function () { + return _index.tsMappedType; + } + }); + Object.defineProperty(exports, "TSMethodSignature", { + enumerable: true, + get: function () { + return _index.tsMethodSignature; + } + }); + Object.defineProperty(exports, "TSModuleBlock", { + enumerable: true, + get: function () { + return _index.tsModuleBlock; + } + }); + Object.defineProperty(exports, "TSModuleDeclaration", { + enumerable: true, + get: function () { + return _index.tsModuleDeclaration; + } + }); + Object.defineProperty(exports, "TSNamedTupleMember", { + enumerable: true, + get: function () { + return _index.tsNamedTupleMember; + } + }); + Object.defineProperty(exports, "TSNamespaceExportDeclaration", { + enumerable: true, + get: function () { + return _index.tsNamespaceExportDeclaration; + } + }); + Object.defineProperty(exports, "TSNeverKeyword", { + enumerable: true, + get: function () { + return _index.tsNeverKeyword; + } + }); + Object.defineProperty(exports, "TSNonNullExpression", { + enumerable: true, + get: function () { + return _index.tsNonNullExpression; + } + }); + Object.defineProperty(exports, "TSNullKeyword", { + enumerable: true, + get: function () { + return _index.tsNullKeyword; + } + }); + Object.defineProperty(exports, "TSNumberKeyword", { + enumerable: true, + get: function () { + return _index.tsNumberKeyword; + } + }); + Object.defineProperty(exports, "TSObjectKeyword", { + enumerable: true, + get: function () { + return _index.tsObjectKeyword; + } + }); + Object.defineProperty(exports, "TSOptionalType", { + enumerable: true, + get: function () { + return _index.tsOptionalType; + } + }); + Object.defineProperty(exports, "TSParameterProperty", { + enumerable: true, + get: function () { + return _index.tsParameterProperty; + } + }); + Object.defineProperty(exports, "TSParenthesizedType", { + enumerable: true, + get: function () { + return _index.tsParenthesizedType; + } + }); + Object.defineProperty(exports, "TSPropertySignature", { + enumerable: true, + get: function () { + return _index.tsPropertySignature; + } + }); + Object.defineProperty(exports, "TSQualifiedName", { + enumerable: true, + get: function () { + return _index.tsQualifiedName; + } + }); + Object.defineProperty(exports, "TSRestType", { + enumerable: true, + get: function () { + return _index.tsRestType; + } + }); + Object.defineProperty(exports, "TSSatisfiesExpression", { + enumerable: true, + get: function () { + return _index.tsSatisfiesExpression; + } + }); + Object.defineProperty(exports, "TSStringKeyword", { + enumerable: true, + get: function () { + return _index.tsStringKeyword; + } + }); + Object.defineProperty(exports, "TSSymbolKeyword", { + enumerable: true, + get: function () { + return _index.tsSymbolKeyword; + } + }); + Object.defineProperty(exports, "TSThisType", { + enumerable: true, + get: function () { + return _index.tsThisType; + } + }); + Object.defineProperty(exports, "TSTupleType", { + enumerable: true, + get: function () { + return _index.tsTupleType; + } + }); + Object.defineProperty(exports, "TSTypeAliasDeclaration", { + enumerable: true, + get: function () { + return _index.tsTypeAliasDeclaration; + } + }); + Object.defineProperty(exports, "TSTypeAnnotation", { + enumerable: true, + get: function () { + return _index.tsTypeAnnotation; + } + }); + Object.defineProperty(exports, "TSTypeAssertion", { + enumerable: true, + get: function () { + return _index.tsTypeAssertion; + } + }); + Object.defineProperty(exports, "TSTypeLiteral", { + enumerable: true, + get: function () { + return _index.tsTypeLiteral; + } + }); + Object.defineProperty(exports, "TSTypeOperator", { + enumerable: true, + get: function () { + return _index.tsTypeOperator; + } + }); + Object.defineProperty(exports, "TSTypeParameter", { + enumerable: true, + get: function () { + return _index.tsTypeParameter; + } + }); + Object.defineProperty(exports, "TSTypeParameterDeclaration", { + enumerable: true, + get: function () { + return _index.tsTypeParameterDeclaration; + } + }); + Object.defineProperty(exports, "TSTypeParameterInstantiation", { + enumerable: true, + get: function () { + return _index.tsTypeParameterInstantiation; + } + }); + Object.defineProperty(exports, "TSTypePredicate", { + enumerable: true, + get: function () { + return _index.tsTypePredicate; + } + }); + Object.defineProperty(exports, "TSTypeQuery", { + enumerable: true, + get: function () { + return _index.tsTypeQuery; + } + }); + Object.defineProperty(exports, "TSTypeReference", { + enumerable: true, + get: function () { + return _index.tsTypeReference; + } + }); + Object.defineProperty(exports, "TSUndefinedKeyword", { + enumerable: true, + get: function () { + return _index.tsUndefinedKeyword; + } + }); + Object.defineProperty(exports, "TSUnionType", { + enumerable: true, + get: function () { + return _index.tsUnionType; + } + }); + Object.defineProperty(exports, "TSUnknownKeyword", { + enumerable: true, + get: function () { + return _index.tsUnknownKeyword; + } + }); + Object.defineProperty(exports, "TSVoidKeyword", { + enumerable: true, + get: function () { + return _index.tsVoidKeyword; + } + }); + Object.defineProperty(exports, "TaggedTemplateExpression", { + enumerable: true, + get: function () { + return _index.taggedTemplateExpression; + } + }); + Object.defineProperty(exports, "TemplateElement", { + enumerable: true, + get: function () { + return _index.templateElement; + } + }); + Object.defineProperty(exports, "TemplateLiteral", { + enumerable: true, + get: function () { + return _index.templateLiteral; + } + }); + Object.defineProperty(exports, "ThisExpression", { + enumerable: true, + get: function () { + return _index.thisExpression; + } + }); + Object.defineProperty(exports, "ThisTypeAnnotation", { + enumerable: true, + get: function () { + return _index.thisTypeAnnotation; + } + }); + Object.defineProperty(exports, "ThrowStatement", { + enumerable: true, + get: function () { + return _index.throwStatement; + } + }); + Object.defineProperty(exports, "TopicReference", { + enumerable: true, + get: function () { + return _index.topicReference; + } + }); + Object.defineProperty(exports, "TryStatement", { + enumerable: true, + get: function () { + return _index.tryStatement; + } + }); + Object.defineProperty(exports, "TupleExpression", { + enumerable: true, + get: function () { + return _index.tupleExpression; + } + }); + Object.defineProperty(exports, "TupleTypeAnnotation", { + enumerable: true, + get: function () { + return _index.tupleTypeAnnotation; + } + }); + Object.defineProperty(exports, "TypeAlias", { + enumerable: true, + get: function () { + return _index.typeAlias; + } + }); + Object.defineProperty(exports, "TypeAnnotation", { + enumerable: true, + get: function () { + return _index.typeAnnotation; + } + }); + Object.defineProperty(exports, "TypeCastExpression", { + enumerable: true, + get: function () { + return _index.typeCastExpression; + } + }); + Object.defineProperty(exports, "TypeParameter", { + enumerable: true, + get: function () { + return _index.typeParameter; + } + }); + Object.defineProperty(exports, "TypeParameterDeclaration", { + enumerable: true, + get: function () { + return _index.typeParameterDeclaration; + } + }); + Object.defineProperty(exports, "TypeParameterInstantiation", { + enumerable: true, + get: function () { + return _index.typeParameterInstantiation; + } + }); + Object.defineProperty(exports, "TypeofTypeAnnotation", { + enumerable: true, + get: function () { + return _index.typeofTypeAnnotation; + } + }); + Object.defineProperty(exports, "UnaryExpression", { + enumerable: true, + get: function () { + return _index.unaryExpression; + } + }); + Object.defineProperty(exports, "UnionTypeAnnotation", { + enumerable: true, + get: function () { + return _index.unionTypeAnnotation; + } + }); + Object.defineProperty(exports, "UpdateExpression", { + enumerable: true, + get: function () { + return _index.updateExpression; + } + }); + Object.defineProperty(exports, "V8IntrinsicIdentifier", { + enumerable: true, + get: function () { + return _index.v8IntrinsicIdentifier; + } + }); + Object.defineProperty(exports, "VariableDeclaration", { + enumerable: true, + get: function () { + return _index.variableDeclaration; + } + }); + Object.defineProperty(exports, "VariableDeclarator", { + enumerable: true, + get: function () { + return _index.variableDeclarator; + } + }); + Object.defineProperty(exports, "Variance", { + enumerable: true, + get: function () { + return _index.variance; + } + }); + Object.defineProperty(exports, "VoidTypeAnnotation", { + enumerable: true, + get: function () { + return _index.voidTypeAnnotation; + } + }); + Object.defineProperty(exports, "WhileStatement", { + enumerable: true, + get: function () { + return _index.whileStatement; + } + }); + Object.defineProperty(exports, "WithStatement", { + enumerable: true, + get: function () { + return _index.withStatement; + } + }); + Object.defineProperty(exports, "YieldExpression", { + enumerable: true, + get: function () { + return _index.yieldExpression; + } + }); + var _index = requireGenerated$2(); + + +} (uppercase)); + return uppercase; +} + +var productions = {}; + +var hasRequiredProductions; + +function requireProductions () { + if (hasRequiredProductions) return productions; + hasRequiredProductions = 1; + + Object.defineProperty(productions, "__esModule", { + value: true + }); + productions.buildUndefinedNode = buildUndefinedNode; + var _index = requireGenerated$2(); + function buildUndefinedNode() { + return (0, _index.unaryExpression)("void", (0, _index.numericLiteral)(0), true); + } + + + return productions; +} + +var cloneNode = {}; + +var hasRequiredCloneNode; + +function requireCloneNode () { + if (hasRequiredCloneNode) return cloneNode; + hasRequiredCloneNode = 1; + + Object.defineProperty(cloneNode, "__esModule", { + value: true + }); + cloneNode.default = cloneNode$1; + var _index = requireDefinitions(); + var _index2 = requireGenerated$3(); + const { + hasOwn + } = { + hasOwn: Function.call.bind(Object.prototype.hasOwnProperty) + }; + function cloneIfNode(obj, deep, withoutLoc, commentsCache) { + if (obj && typeof obj.type === "string") { + return cloneNodeInternal(obj, deep, withoutLoc, commentsCache); + } + return obj; + } + function cloneIfNodeOrArray(obj, deep, withoutLoc, commentsCache) { + if (Array.isArray(obj)) { + return obj.map(node => cloneIfNode(node, deep, withoutLoc, commentsCache)); + } + return cloneIfNode(obj, deep, withoutLoc, commentsCache); + } + function cloneNode$1(node, deep = true, withoutLoc = false) { + return cloneNodeInternal(node, deep, withoutLoc, new Map()); + } + function cloneNodeInternal(node, deep = true, withoutLoc = false, commentsCache) { + if (!node) return node; + const { + type + } = node; + const newNode = { + type: node.type + }; + if ((0, _index2.isIdentifier)(node)) { + newNode.name = node.name; + if (hasOwn(node, "optional") && typeof node.optional === "boolean") { + newNode.optional = node.optional; + } + if (hasOwn(node, "typeAnnotation")) { + newNode.typeAnnotation = deep ? cloneIfNodeOrArray(node.typeAnnotation, true, withoutLoc, commentsCache) : node.typeAnnotation; + } + if (hasOwn(node, "decorators")) { + newNode.decorators = deep ? cloneIfNodeOrArray(node.decorators, true, withoutLoc, commentsCache) : node.decorators; + } + } else if (!hasOwn(_index.NODE_FIELDS, type)) { + throw new Error(`Unknown node type: "${type}"`); + } else { + for (const field of Object.keys(_index.NODE_FIELDS[type])) { + if (hasOwn(node, field)) { + if (deep) { + newNode[field] = (0, _index2.isFile)(node) && field === "comments" ? maybeCloneComments(node.comments, deep, withoutLoc, commentsCache) : cloneIfNodeOrArray(node[field], true, withoutLoc, commentsCache); + } else { + newNode[field] = node[field]; + } + } + } + } + if (hasOwn(node, "loc")) { + if (withoutLoc) { + newNode.loc = null; + } else { + newNode.loc = node.loc; + } + } + if (hasOwn(node, "leadingComments")) { + newNode.leadingComments = maybeCloneComments(node.leadingComments, deep, withoutLoc, commentsCache); + } + if (hasOwn(node, "innerComments")) { + newNode.innerComments = maybeCloneComments(node.innerComments, deep, withoutLoc, commentsCache); + } + if (hasOwn(node, "trailingComments")) { + newNode.trailingComments = maybeCloneComments(node.trailingComments, deep, withoutLoc, commentsCache); + } + if (hasOwn(node, "extra")) { + newNode.extra = Object.assign({}, node.extra); + } + return newNode; + } + function maybeCloneComments(comments, deep, withoutLoc, commentsCache) { + if (!comments || !deep) { + return comments; + } + return comments.map(comment => { + const cache = commentsCache.get(comment); + if (cache) return cache; + const { + type, + value, + loc + } = comment; + const ret = { + type, + value, + loc + }; + if (withoutLoc) { + ret.loc = null; + } + commentsCache.set(comment, ret); + return ret; + }); + } + + + return cloneNode; +} + +var clone = {}; + +var hasRequiredClone; + +function requireClone () { + if (hasRequiredClone) return clone; + hasRequiredClone = 1; + + Object.defineProperty(clone, "__esModule", { + value: true + }); + clone.default = clone$1; + var _cloneNode = requireCloneNode(); + function clone$1(node) { + return (0, _cloneNode.default)(node, false); + } + + + return clone; +} + +var cloneDeep = {}; + +var hasRequiredCloneDeep; + +function requireCloneDeep () { + if (hasRequiredCloneDeep) return cloneDeep; + hasRequiredCloneDeep = 1; + + Object.defineProperty(cloneDeep, "__esModule", { + value: true + }); + cloneDeep.default = cloneDeep$1; + var _cloneNode = requireCloneNode(); + function cloneDeep$1(node) { + return (0, _cloneNode.default)(node); + } + + + return cloneDeep; +} + +var cloneDeepWithoutLoc = {}; + +var hasRequiredCloneDeepWithoutLoc; + +function requireCloneDeepWithoutLoc () { + if (hasRequiredCloneDeepWithoutLoc) return cloneDeepWithoutLoc; + hasRequiredCloneDeepWithoutLoc = 1; + + Object.defineProperty(cloneDeepWithoutLoc, "__esModule", { + value: true + }); + cloneDeepWithoutLoc.default = cloneDeepWithoutLoc$1; + var _cloneNode = requireCloneNode(); + function cloneDeepWithoutLoc$1(node) { + return (0, _cloneNode.default)(node, true, true); + } + + + return cloneDeepWithoutLoc; +} + +var cloneWithoutLoc = {}; + +var hasRequiredCloneWithoutLoc; + +function requireCloneWithoutLoc () { + if (hasRequiredCloneWithoutLoc) return cloneWithoutLoc; + hasRequiredCloneWithoutLoc = 1; + + Object.defineProperty(cloneWithoutLoc, "__esModule", { + value: true + }); + cloneWithoutLoc.default = cloneWithoutLoc$1; + var _cloneNode = requireCloneNode(); + function cloneWithoutLoc$1(node) { + return (0, _cloneNode.default)(node, false, true); + } + + + return cloneWithoutLoc; +} + +var addComment = {}; + +var addComments = {}; + +var hasRequiredAddComments; + +function requireAddComments () { + if (hasRequiredAddComments) return addComments; + hasRequiredAddComments = 1; + + Object.defineProperty(addComments, "__esModule", { + value: true + }); + addComments.default = addComments$1; + function addComments$1(node, type, comments) { + if (!comments || !node) return node; + const key = `${type}Comments`; + if (node[key]) { + if (type === "leading") { + node[key] = comments.concat(node[key]); + } else { + node[key].push(...comments); + } + } else { + node[key] = comments; + } + return node; + } + + + return addComments; +} + +var hasRequiredAddComment; + +function requireAddComment () { + if (hasRequiredAddComment) return addComment; + hasRequiredAddComment = 1; + + Object.defineProperty(addComment, "__esModule", { + value: true + }); + addComment.default = addComment$1; + var _addComments = requireAddComments(); + function addComment$1(node, type, content, line) { + return (0, _addComments.default)(node, type, [{ + type: line ? "CommentLine" : "CommentBlock", + value: content + }]); + } + + + return addComment; +} + +var inheritInnerComments = {}; + +var inherit = {}; + +var hasRequiredInherit; + +function requireInherit () { + if (hasRequiredInherit) return inherit; + hasRequiredInherit = 1; + + Object.defineProperty(inherit, "__esModule", { + value: true + }); + inherit.default = inherit$1; + function inherit$1(key, child, parent) { + if (child && parent) { + child[key] = Array.from(new Set([].concat(child[key], parent[key]).filter(Boolean))); + } + } + + + return inherit; +} + +var hasRequiredInheritInnerComments; + +function requireInheritInnerComments () { + if (hasRequiredInheritInnerComments) return inheritInnerComments; + hasRequiredInheritInnerComments = 1; + + Object.defineProperty(inheritInnerComments, "__esModule", { + value: true + }); + inheritInnerComments.default = inheritInnerComments$1; + var _inherit = requireInherit(); + function inheritInnerComments$1(child, parent) { + (0, _inherit.default)("innerComments", child, parent); + } + + + return inheritInnerComments; +} + +var inheritLeadingComments = {}; + +var hasRequiredInheritLeadingComments; + +function requireInheritLeadingComments () { + if (hasRequiredInheritLeadingComments) return inheritLeadingComments; + hasRequiredInheritLeadingComments = 1; + + Object.defineProperty(inheritLeadingComments, "__esModule", { + value: true + }); + inheritLeadingComments.default = inheritLeadingComments$1; + var _inherit = requireInherit(); + function inheritLeadingComments$1(child, parent) { + (0, _inherit.default)("leadingComments", child, parent); + } + + + return inheritLeadingComments; +} + +var inheritsComments = {}; + +var inheritTrailingComments = {}; + +var hasRequiredInheritTrailingComments; + +function requireInheritTrailingComments () { + if (hasRequiredInheritTrailingComments) return inheritTrailingComments; + hasRequiredInheritTrailingComments = 1; + + Object.defineProperty(inheritTrailingComments, "__esModule", { + value: true + }); + inheritTrailingComments.default = inheritTrailingComments$1; + var _inherit = requireInherit(); + function inheritTrailingComments$1(child, parent) { + (0, _inherit.default)("trailingComments", child, parent); + } + + + return inheritTrailingComments; +} + +var hasRequiredInheritsComments; + +function requireInheritsComments () { + if (hasRequiredInheritsComments) return inheritsComments; + hasRequiredInheritsComments = 1; + + Object.defineProperty(inheritsComments, "__esModule", { + value: true + }); + inheritsComments.default = inheritsComments$1; + var _inheritTrailingComments = requireInheritTrailingComments(); + var _inheritLeadingComments = requireInheritLeadingComments(); + var _inheritInnerComments = requireInheritInnerComments(); + function inheritsComments$1(child, parent) { + (0, _inheritTrailingComments.default)(child, parent); + (0, _inheritLeadingComments.default)(child, parent); + (0, _inheritInnerComments.default)(child, parent); + return child; + } + + + return inheritsComments; +} + +var removeComments = {}; + +var hasRequiredRemoveComments; + +function requireRemoveComments () { + if (hasRequiredRemoveComments) return removeComments; + hasRequiredRemoveComments = 1; + + Object.defineProperty(removeComments, "__esModule", { + value: true + }); + removeComments.default = removeComments$1; + var _index = requireConstants(); + function removeComments$1(node) { + _index.COMMENT_KEYS.forEach(key => { + node[key] = null; + }); + return node; + } + + + return removeComments; +} + +var generated = {}; + +var hasRequiredGenerated; + +function requireGenerated () { + if (hasRequiredGenerated) return generated; + hasRequiredGenerated = 1; + + Object.defineProperty(generated, "__esModule", { + value: true + }); + generated.WHILE_TYPES = generated.USERWHITESPACABLE_TYPES = generated.UNARYLIKE_TYPES = generated.TYPESCRIPT_TYPES = generated.TSTYPE_TYPES = generated.TSTYPEELEMENT_TYPES = generated.TSENTITYNAME_TYPES = generated.TSBASETYPE_TYPES = generated.TERMINATORLESS_TYPES = generated.STATEMENT_TYPES = generated.STANDARDIZED_TYPES = generated.SCOPABLE_TYPES = generated.PUREISH_TYPES = generated.PROPERTY_TYPES = generated.PRIVATE_TYPES = generated.PATTERN_TYPES = generated.PATTERNLIKE_TYPES = generated.OBJECTMEMBER_TYPES = generated.MODULESPECIFIER_TYPES = generated.MODULEDECLARATION_TYPES = generated.MISCELLANEOUS_TYPES = generated.METHOD_TYPES = generated.LVAL_TYPES = generated.LOOP_TYPES = generated.LITERAL_TYPES = generated.JSX_TYPES = generated.IMPORTOREXPORTDECLARATION_TYPES = generated.IMMUTABLE_TYPES = generated.FUNCTION_TYPES = generated.FUNCTIONPARENT_TYPES = generated.FOR_TYPES = generated.FORXSTATEMENT_TYPES = generated.FLOW_TYPES = generated.FLOWTYPE_TYPES = generated.FLOWPREDICATE_TYPES = generated.FLOWDECLARATION_TYPES = generated.FLOWBASEANNOTATION_TYPES = generated.EXPRESSION_TYPES = generated.EXPRESSIONWRAPPER_TYPES = generated.EXPORTDECLARATION_TYPES = generated.ENUMMEMBER_TYPES = generated.ENUMBODY_TYPES = generated.DECLARATION_TYPES = generated.CONDITIONAL_TYPES = generated.COMPLETIONSTATEMENT_TYPES = generated.CLASS_TYPES = generated.BLOCK_TYPES = generated.BLOCKPARENT_TYPES = generated.BINARY_TYPES = generated.ACCESSOR_TYPES = void 0; + var _index = requireDefinitions(); + generated.STANDARDIZED_TYPES = _index.FLIPPED_ALIAS_KEYS["Standardized"]; + generated.EXPRESSION_TYPES = _index.FLIPPED_ALIAS_KEYS["Expression"]; + generated.BINARY_TYPES = _index.FLIPPED_ALIAS_KEYS["Binary"]; + generated.SCOPABLE_TYPES = _index.FLIPPED_ALIAS_KEYS["Scopable"]; + generated.BLOCKPARENT_TYPES = _index.FLIPPED_ALIAS_KEYS["BlockParent"]; + generated.BLOCK_TYPES = _index.FLIPPED_ALIAS_KEYS["Block"]; + generated.STATEMENT_TYPES = _index.FLIPPED_ALIAS_KEYS["Statement"]; + generated.TERMINATORLESS_TYPES = _index.FLIPPED_ALIAS_KEYS["Terminatorless"]; + generated.COMPLETIONSTATEMENT_TYPES = _index.FLIPPED_ALIAS_KEYS["CompletionStatement"]; + generated.CONDITIONAL_TYPES = _index.FLIPPED_ALIAS_KEYS["Conditional"]; + generated.LOOP_TYPES = _index.FLIPPED_ALIAS_KEYS["Loop"]; + generated.WHILE_TYPES = _index.FLIPPED_ALIAS_KEYS["While"]; + generated.EXPRESSIONWRAPPER_TYPES = _index.FLIPPED_ALIAS_KEYS["ExpressionWrapper"]; + generated.FOR_TYPES = _index.FLIPPED_ALIAS_KEYS["For"]; + generated.FORXSTATEMENT_TYPES = _index.FLIPPED_ALIAS_KEYS["ForXStatement"]; + generated.FUNCTION_TYPES = _index.FLIPPED_ALIAS_KEYS["Function"]; + generated.FUNCTIONPARENT_TYPES = _index.FLIPPED_ALIAS_KEYS["FunctionParent"]; + generated.PUREISH_TYPES = _index.FLIPPED_ALIAS_KEYS["Pureish"]; + generated.DECLARATION_TYPES = _index.FLIPPED_ALIAS_KEYS["Declaration"]; + generated.PATTERNLIKE_TYPES = _index.FLIPPED_ALIAS_KEYS["PatternLike"]; + generated.LVAL_TYPES = _index.FLIPPED_ALIAS_KEYS["LVal"]; + generated.TSENTITYNAME_TYPES = _index.FLIPPED_ALIAS_KEYS["TSEntityName"]; + generated.LITERAL_TYPES = _index.FLIPPED_ALIAS_KEYS["Literal"]; + generated.IMMUTABLE_TYPES = _index.FLIPPED_ALIAS_KEYS["Immutable"]; + generated.USERWHITESPACABLE_TYPES = _index.FLIPPED_ALIAS_KEYS["UserWhitespacable"]; + generated.METHOD_TYPES = _index.FLIPPED_ALIAS_KEYS["Method"]; + generated.OBJECTMEMBER_TYPES = _index.FLIPPED_ALIAS_KEYS["ObjectMember"]; + generated.PROPERTY_TYPES = _index.FLIPPED_ALIAS_KEYS["Property"]; + generated.UNARYLIKE_TYPES = _index.FLIPPED_ALIAS_KEYS["UnaryLike"]; + generated.PATTERN_TYPES = _index.FLIPPED_ALIAS_KEYS["Pattern"]; + generated.CLASS_TYPES = _index.FLIPPED_ALIAS_KEYS["Class"]; + const IMPORTOREXPORTDECLARATION_TYPES = generated.IMPORTOREXPORTDECLARATION_TYPES = _index.FLIPPED_ALIAS_KEYS["ImportOrExportDeclaration"]; + generated.EXPORTDECLARATION_TYPES = _index.FLIPPED_ALIAS_KEYS["ExportDeclaration"]; + generated.MODULESPECIFIER_TYPES = _index.FLIPPED_ALIAS_KEYS["ModuleSpecifier"]; + generated.ACCESSOR_TYPES = _index.FLIPPED_ALIAS_KEYS["Accessor"]; + generated.PRIVATE_TYPES = _index.FLIPPED_ALIAS_KEYS["Private"]; + generated.FLOW_TYPES = _index.FLIPPED_ALIAS_KEYS["Flow"]; + generated.FLOWTYPE_TYPES = _index.FLIPPED_ALIAS_KEYS["FlowType"]; + generated.FLOWBASEANNOTATION_TYPES = _index.FLIPPED_ALIAS_KEYS["FlowBaseAnnotation"]; + generated.FLOWDECLARATION_TYPES = _index.FLIPPED_ALIAS_KEYS["FlowDeclaration"]; + generated.FLOWPREDICATE_TYPES = _index.FLIPPED_ALIAS_KEYS["FlowPredicate"]; + generated.ENUMBODY_TYPES = _index.FLIPPED_ALIAS_KEYS["EnumBody"]; + generated.ENUMMEMBER_TYPES = _index.FLIPPED_ALIAS_KEYS["EnumMember"]; + generated.JSX_TYPES = _index.FLIPPED_ALIAS_KEYS["JSX"]; + generated.MISCELLANEOUS_TYPES = _index.FLIPPED_ALIAS_KEYS["Miscellaneous"]; + generated.TYPESCRIPT_TYPES = _index.FLIPPED_ALIAS_KEYS["TypeScript"]; + generated.TSTYPEELEMENT_TYPES = _index.FLIPPED_ALIAS_KEYS["TSTypeElement"]; + generated.TSTYPE_TYPES = _index.FLIPPED_ALIAS_KEYS["TSType"]; + generated.TSBASETYPE_TYPES = _index.FLIPPED_ALIAS_KEYS["TSBaseType"]; + generated.MODULEDECLARATION_TYPES = IMPORTOREXPORTDECLARATION_TYPES; + + + return generated; +} + +var ensureBlock = {}; + +var toBlock = {}; + +var hasRequiredToBlock; + +function requireToBlock () { + if (hasRequiredToBlock) return toBlock; + hasRequiredToBlock = 1; + + Object.defineProperty(toBlock, "__esModule", { + value: true + }); + toBlock.default = toBlock$1; + var _index = requireGenerated$3(); + var _index2 = requireGenerated$2(); + function toBlock$1(node, parent) { + if ((0, _index.isBlockStatement)(node)) { + return node; + } + let blockNodes = []; + if ((0, _index.isEmptyStatement)(node)) { + blockNodes = []; + } else { + if (!(0, _index.isStatement)(node)) { + if ((0, _index.isFunction)(parent)) { + node = (0, _index2.returnStatement)(node); + } else { + node = (0, _index2.expressionStatement)(node); + } + } + blockNodes = [node]; + } + return (0, _index2.blockStatement)(blockNodes); + } + + + return toBlock; +} + +var hasRequiredEnsureBlock; + +function requireEnsureBlock () { + if (hasRequiredEnsureBlock) return ensureBlock; + hasRequiredEnsureBlock = 1; + + Object.defineProperty(ensureBlock, "__esModule", { + value: true + }); + ensureBlock.default = ensureBlock$1; + var _toBlock = requireToBlock(); + function ensureBlock$1(node, key = "body") { + const result = (0, _toBlock.default)(node[key], node); + node[key] = result; + return result; + } + + + return ensureBlock; +} + +var toBindingIdentifierName = {}; + +var toIdentifier = {}; + +var hasRequiredToIdentifier; + +function requireToIdentifier () { + if (hasRequiredToIdentifier) return toIdentifier; + hasRequiredToIdentifier = 1; + + Object.defineProperty(toIdentifier, "__esModule", { + value: true + }); + toIdentifier.default = toIdentifier$1; + var _isValidIdentifier = requireIsValidIdentifier(); + var _helperValidatorIdentifier = requireLib$3(); + function toIdentifier$1(input) { + input = input + ""; + let name = ""; + for (const c of input) { + name += (0, _helperValidatorIdentifier.isIdentifierChar)(c.codePointAt(0)) ? c : "-"; + } + name = name.replace(/^[-0-9]+/, ""); + name = name.replace(/[-\s]+(.)?/g, function (match, c) { + return c ? c.toUpperCase() : ""; + }); + if (!(0, _isValidIdentifier.default)(name)) { + name = `_${name}`; + } + return name || "_"; + } + + + return toIdentifier; +} + +var hasRequiredToBindingIdentifierName; + +function requireToBindingIdentifierName () { + if (hasRequiredToBindingIdentifierName) return toBindingIdentifierName; + hasRequiredToBindingIdentifierName = 1; + + Object.defineProperty(toBindingIdentifierName, "__esModule", { + value: true + }); + toBindingIdentifierName.default = toBindingIdentifierName$1; + var _toIdentifier = requireToIdentifier(); + function toBindingIdentifierName$1(name) { + name = (0, _toIdentifier.default)(name); + if (name === "eval" || name === "arguments") name = "_" + name; + return name; + } + + + return toBindingIdentifierName; +} + +var toComputedKey = {}; + +var hasRequiredToComputedKey; + +function requireToComputedKey () { + if (hasRequiredToComputedKey) return toComputedKey; + hasRequiredToComputedKey = 1; + + Object.defineProperty(toComputedKey, "__esModule", { + value: true + }); + toComputedKey.default = toComputedKey$1; + var _index = requireGenerated$3(); + var _index2 = requireGenerated$2(); + function toComputedKey$1(node, key = node.key || node.property) { + if (!node.computed && (0, _index.isIdentifier)(key)) key = (0, _index2.stringLiteral)(key.name); + return key; + } + + + return toComputedKey; +} + +var toExpression = {}; + +var hasRequiredToExpression; + +function requireToExpression () { + if (hasRequiredToExpression) return toExpression; + hasRequiredToExpression = 1; + + Object.defineProperty(toExpression, "__esModule", { + value: true + }); + toExpression.default = void 0; + var _index = requireGenerated$3(); + toExpression.default = toExpression$1; + function toExpression$1(node) { + if ((0, _index.isExpressionStatement)(node)) { + node = node.expression; + } + if ((0, _index.isExpression)(node)) { + return node; + } + if ((0, _index.isClass)(node)) { + node.type = "ClassExpression"; + } else if ((0, _index.isFunction)(node)) { + node.type = "FunctionExpression"; + } + if (!(0, _index.isExpression)(node)) { + throw new Error(`cannot turn ${node.type} to an expression`); + } + return node; + } + + + return toExpression; +} + +var toKeyAlias = {}; + +var removePropertiesDeep = {}; + +var traverseFast = {}; + +var hasRequiredTraverseFast; + +function requireTraverseFast () { + if (hasRequiredTraverseFast) return traverseFast; + hasRequiredTraverseFast = 1; + + Object.defineProperty(traverseFast, "__esModule", { + value: true + }); + traverseFast.default = traverseFast$1; + var _index = requireDefinitions(); + function traverseFast$1(node, enter, opts) { + if (!node) return; + const keys = _index.VISITOR_KEYS[node.type]; + if (!keys) return; + opts = opts || {}; + enter(node, opts); + for (const key of keys) { + const subNode = node[key]; + if (Array.isArray(subNode)) { + for (const node of subNode) { + traverseFast$1(node, enter, opts); + } + } else { + traverseFast$1(subNode, enter, opts); + } + } + } + + + return traverseFast; +} + +var removeProperties = {}; + +var hasRequiredRemoveProperties; + +function requireRemoveProperties () { + if (hasRequiredRemoveProperties) return removeProperties; + hasRequiredRemoveProperties = 1; + + Object.defineProperty(removeProperties, "__esModule", { + value: true + }); + removeProperties.default = removeProperties$1; + var _index = requireConstants(); + const CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"]; + const CLEAR_KEYS_PLUS_COMMENTS = [..._index.COMMENT_KEYS, "comments", ...CLEAR_KEYS]; + function removeProperties$1(node, opts = {}) { + const map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; + for (const key of map) { + if (node[key] != null) node[key] = undefined; + } + for (const key of Object.keys(node)) { + if (key[0] === "_" && node[key] != null) node[key] = undefined; + } + const symbols = Object.getOwnPropertySymbols(node); + for (const sym of symbols) { + node[sym] = null; + } + } + + + return removeProperties; +} + +var hasRequiredRemovePropertiesDeep; + +function requireRemovePropertiesDeep () { + if (hasRequiredRemovePropertiesDeep) return removePropertiesDeep; + hasRequiredRemovePropertiesDeep = 1; + + Object.defineProperty(removePropertiesDeep, "__esModule", { + value: true + }); + removePropertiesDeep.default = removePropertiesDeep$1; + var _traverseFast = requireTraverseFast(); + var _removeProperties = requireRemoveProperties(); + function removePropertiesDeep$1(tree, opts) { + (0, _traverseFast.default)(tree, _removeProperties.default, opts); + return tree; + } + + + return removePropertiesDeep; +} + +var hasRequiredToKeyAlias; + +function requireToKeyAlias () { + if (hasRequiredToKeyAlias) return toKeyAlias; + hasRequiredToKeyAlias = 1; + + Object.defineProperty(toKeyAlias, "__esModule", { + value: true + }); + toKeyAlias.default = toKeyAlias$1; + var _index = requireGenerated$3(); + var _cloneNode = requireCloneNode(); + var _removePropertiesDeep = requireRemovePropertiesDeep(); + function toKeyAlias$1(node, key = node.key) { + let alias; + if (node.kind === "method") { + return toKeyAlias$1.increment() + ""; + } else if ((0, _index.isIdentifier)(key)) { + alias = key.name; + } else if ((0, _index.isStringLiteral)(key)) { + alias = JSON.stringify(key.value); + } else { + alias = JSON.stringify((0, _removePropertiesDeep.default)((0, _cloneNode.default)(key))); + } + if (node.computed) { + alias = `[${alias}]`; + } + if (node.static) { + alias = `static:${alias}`; + } + return alias; + } + toKeyAlias$1.uid = 0; + toKeyAlias$1.increment = function () { + if (toKeyAlias$1.uid >= Number.MAX_SAFE_INTEGER) { + return toKeyAlias$1.uid = 0; + } else { + return toKeyAlias$1.uid++; + } + }; + + + return toKeyAlias; +} + +var toStatement = {}; + +var hasRequiredToStatement; + +function requireToStatement () { + if (hasRequiredToStatement) return toStatement; + hasRequiredToStatement = 1; + + Object.defineProperty(toStatement, "__esModule", { + value: true + }); + toStatement.default = void 0; + var _index = requireGenerated$3(); + var _index2 = requireGenerated$2(); + toStatement.default = toStatement$1; + function toStatement$1(node, ignore) { + if ((0, _index.isStatement)(node)) { + return node; + } + let mustHaveId = false; + let newType; + if ((0, _index.isClass)(node)) { + mustHaveId = true; + newType = "ClassDeclaration"; + } else if ((0, _index.isFunction)(node)) { + mustHaveId = true; + newType = "FunctionDeclaration"; + } else if ((0, _index.isAssignmentExpression)(node)) { + return (0, _index2.expressionStatement)(node); + } + if (mustHaveId && !node.id) { + newType = false; + } + if (!newType) { + if (ignore) { + return false; + } else { + throw new Error(`cannot turn ${node.type} to a statement`); + } + } + node.type = newType; + return node; + } + + + return toStatement; +} + +var valueToNode = {}; + +var hasRequiredValueToNode; + +function requireValueToNode () { + if (hasRequiredValueToNode) return valueToNode; + hasRequiredValueToNode = 1; + + Object.defineProperty(valueToNode, "__esModule", { + value: true + }); + valueToNode.default = void 0; + var _isValidIdentifier = requireIsValidIdentifier(); + var _index = requireGenerated$2(); + valueToNode.default = valueToNode$1; + const objectToString = Function.call.bind(Object.prototype.toString); + function isRegExp(value) { + return objectToString(value) === "[object RegExp]"; + } + function isPlainObject(value) { + if (typeof value !== "object" || value === null || Object.prototype.toString.call(value) !== "[object Object]") { + return false; + } + const proto = Object.getPrototypeOf(value); + return proto === null || Object.getPrototypeOf(proto) === null; + } + function valueToNode$1(value) { + if (value === undefined) { + return (0, _index.identifier)("undefined"); + } + if (value === true || value === false) { + return (0, _index.booleanLiteral)(value); + } + if (value === null) { + return (0, _index.nullLiteral)(); + } + if (typeof value === "string") { + return (0, _index.stringLiteral)(value); + } + if (typeof value === "number") { + let result; + if (Number.isFinite(value)) { + result = (0, _index.numericLiteral)(Math.abs(value)); + } else { + let numerator; + if (Number.isNaN(value)) { + numerator = (0, _index.numericLiteral)(0); + } else { + numerator = (0, _index.numericLiteral)(1); + } + result = (0, _index.binaryExpression)("/", numerator, (0, _index.numericLiteral)(0)); + } + if (value < 0 || Object.is(value, -0)) { + result = (0, _index.unaryExpression)("-", result); + } + return result; + } + if (isRegExp(value)) { + const pattern = value.source; + const flags = /\/([a-z]*)$/.exec(value.toString())[1]; + return (0, _index.regExpLiteral)(pattern, flags); + } + if (Array.isArray(value)) { + return (0, _index.arrayExpression)(value.map(valueToNode$1)); + } + if (isPlainObject(value)) { + const props = []; + for (const key of Object.keys(value)) { + let nodeKey; + if ((0, _isValidIdentifier.default)(key)) { + nodeKey = (0, _index.identifier)(key); + } else { + nodeKey = (0, _index.stringLiteral)(key); + } + props.push((0, _index.objectProperty)(nodeKey, valueToNode$1(value[key]))); + } + return (0, _index.objectExpression)(props); + } + throw new Error("don't know how to turn this value into a node"); + } + + + return valueToNode; +} + +var appendToMemberExpression = {}; + +var hasRequiredAppendToMemberExpression; + +function requireAppendToMemberExpression () { + if (hasRequiredAppendToMemberExpression) return appendToMemberExpression; + hasRequiredAppendToMemberExpression = 1; + + Object.defineProperty(appendToMemberExpression, "__esModule", { + value: true + }); + appendToMemberExpression.default = appendToMemberExpression$1; + var _index = requireGenerated$2(); + function appendToMemberExpression$1(member, append, computed = false) { + member.object = (0, _index.memberExpression)(member.object, member.property, member.computed); + member.property = append; + member.computed = !!computed; + return member; + } + + + return appendToMemberExpression; +} + +var inherits = {}; + +var hasRequiredInherits; + +function requireInherits () { + if (hasRequiredInherits) return inherits; + hasRequiredInherits = 1; + + Object.defineProperty(inherits, "__esModule", { + value: true + }); + inherits.default = inherits$1; + var _index = requireConstants(); + var _inheritsComments = requireInheritsComments(); + function inherits$1(child, parent) { + if (!child || !parent) return child; + for (const key of _index.INHERIT_KEYS.optional) { + if (child[key] == null) { + child[key] = parent[key]; + } + } + for (const key of Object.keys(parent)) { + if (key[0] === "_" && key !== "__clone") { + child[key] = parent[key]; + } + } + for (const key of _index.INHERIT_KEYS.force) { + child[key] = parent[key]; + } + (0, _inheritsComments.default)(child, parent); + return child; + } + + + return inherits; +} + +var prependToMemberExpression = {}; + +var hasRequiredPrependToMemberExpression; + +function requirePrependToMemberExpression () { + if (hasRequiredPrependToMemberExpression) return prependToMemberExpression; + hasRequiredPrependToMemberExpression = 1; + + Object.defineProperty(prependToMemberExpression, "__esModule", { + value: true + }); + prependToMemberExpression.default = prependToMemberExpression$1; + var _index = requireGenerated$2(); + var _index2 = requireLib$1(); + function prependToMemberExpression$1(member, prepend) { + if ((0, _index2.isSuper)(member.object)) { + throw new Error("Cannot prepend node to super property access (`super.foo`)."); + } + member.object = (0, _index.memberExpression)(prepend, member.object); + return member; + } + + + return prependToMemberExpression; +} + +var getAssignmentIdentifiers = {}; + +var hasRequiredGetAssignmentIdentifiers; + +function requireGetAssignmentIdentifiers () { + if (hasRequiredGetAssignmentIdentifiers) return getAssignmentIdentifiers; + hasRequiredGetAssignmentIdentifiers = 1; + + Object.defineProperty(getAssignmentIdentifiers, "__esModule", { + value: true + }); + getAssignmentIdentifiers.default = getAssignmentIdentifiers$1; + function getAssignmentIdentifiers$1(node) { + const search = [].concat(node); + const ids = Object.create(null); + while (search.length) { + const id = search.pop(); + if (!id) continue; + switch (id.type) { + case "ArrayPattern": + search.push(...id.elements); + break; + case "AssignmentExpression": + case "AssignmentPattern": + case "ForInStatement": + case "ForOfStatement": + search.push(id.left); + break; + case "ObjectPattern": + search.push(...id.properties); + break; + case "ObjectProperty": + search.push(id.value); + break; + case "RestElement": + case "UpdateExpression": + search.push(id.argument); + break; + case "UnaryExpression": + if (id.operator === "delete") { + search.push(id.argument); + } + break; + case "Identifier": + ids[id.name] = id; + break; + } + } + return ids; + } + + + return getAssignmentIdentifiers; +} + +var getBindingIdentifiers = {}; + +var hasRequiredGetBindingIdentifiers; + +function requireGetBindingIdentifiers () { + if (hasRequiredGetBindingIdentifiers) return getBindingIdentifiers; + hasRequiredGetBindingIdentifiers = 1; + + Object.defineProperty(getBindingIdentifiers, "__esModule", { + value: true + }); + getBindingIdentifiers.default = getBindingIdentifiers$1; + var _index = requireGenerated$3(); + function getBindingIdentifiers$1(node, duplicates, outerOnly, newBindingsOnly) { + const search = [].concat(node); + const ids = Object.create(null); + while (search.length) { + const id = search.shift(); + if (!id) continue; + if (newBindingsOnly && ((0, _index.isAssignmentExpression)(id) || (0, _index.isUnaryExpression)(id) || (0, _index.isUpdateExpression)(id))) { + continue; + } + if ((0, _index.isIdentifier)(id)) { + if (duplicates) { + const _ids = ids[id.name] = ids[id.name] || []; + _ids.push(id); + } else { + ids[id.name] = id; + } + continue; + } + if ((0, _index.isExportDeclaration)(id) && !(0, _index.isExportAllDeclaration)(id)) { + if ((0, _index.isDeclaration)(id.declaration)) { + search.push(id.declaration); + } + continue; + } + if (outerOnly) { + if ((0, _index.isFunctionDeclaration)(id)) { + search.push(id.id); + continue; + } + if ((0, _index.isFunctionExpression)(id)) { + continue; + } + } + const keys = getBindingIdentifiers$1.keys[id.type]; + if (keys) { + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const nodes = id[key]; + if (nodes) { + if (Array.isArray(nodes)) { + search.push(...nodes); + } else { + search.push(nodes); + } + } + } + } + } + return ids; + } + const keys = { + DeclareClass: ["id"], + DeclareFunction: ["id"], + DeclareModule: ["id"], + DeclareVariable: ["id"], + DeclareInterface: ["id"], + DeclareTypeAlias: ["id"], + DeclareOpaqueType: ["id"], + InterfaceDeclaration: ["id"], + TypeAlias: ["id"], + OpaqueType: ["id"], + CatchClause: ["param"], + LabeledStatement: ["label"], + UnaryExpression: ["argument"], + AssignmentExpression: ["left"], + ImportSpecifier: ["local"], + ImportNamespaceSpecifier: ["local"], + ImportDefaultSpecifier: ["local"], + ImportDeclaration: ["specifiers"], + ExportSpecifier: ["exported"], + ExportNamespaceSpecifier: ["exported"], + ExportDefaultSpecifier: ["exported"], + FunctionDeclaration: ["id", "params"], + FunctionExpression: ["id", "params"], + ArrowFunctionExpression: ["params"], + ObjectMethod: ["params"], + ClassMethod: ["params"], + ClassPrivateMethod: ["params"], + ForInStatement: ["left"], + ForOfStatement: ["left"], + ClassDeclaration: ["id"], + ClassExpression: ["id"], + RestElement: ["argument"], + UpdateExpression: ["argument"], + ObjectProperty: ["value"], + AssignmentPattern: ["left"], + ArrayPattern: ["elements"], + ObjectPattern: ["properties"], + VariableDeclaration: ["declarations"], + VariableDeclarator: ["id"] + }; + getBindingIdentifiers$1.keys = keys; + + + return getBindingIdentifiers; +} + +var getOuterBindingIdentifiers = {}; + +var hasRequiredGetOuterBindingIdentifiers; + +function requireGetOuterBindingIdentifiers () { + if (hasRequiredGetOuterBindingIdentifiers) return getOuterBindingIdentifiers; + hasRequiredGetOuterBindingIdentifiers = 1; + + Object.defineProperty(getOuterBindingIdentifiers, "__esModule", { + value: true + }); + getOuterBindingIdentifiers.default = void 0; + var _getBindingIdentifiers = requireGetBindingIdentifiers(); + getOuterBindingIdentifiers.default = getOuterBindingIdentifiers$1; + function getOuterBindingIdentifiers$1(node, duplicates) { + return (0, _getBindingIdentifiers.default)(node, duplicates, true); + } + + + return getOuterBindingIdentifiers; +} + +var getFunctionName$3 = {}; + +var hasRequiredGetFunctionName; + +function requireGetFunctionName () { + if (hasRequiredGetFunctionName) return getFunctionName$3; + hasRequiredGetFunctionName = 1; + + Object.defineProperty(getFunctionName$3, "__esModule", { + value: true + }); + getFunctionName$3.default = getFunctionName; + var _index = requireGenerated$3(); + function getNameFromLiteralId(id) { + if ((0, _index.isNullLiteral)(id)) { + return "null"; + } + if ((0, _index.isRegExpLiteral)(id)) { + return `/${id.pattern}/${id.flags}`; + } + if ((0, _index.isTemplateLiteral)(id)) { + return id.quasis.map(quasi => quasi.value.raw).join(""); + } + if (id.value !== undefined) { + return String(id.value); + } + return null; + } + function getObjectMemberKey(node) { + if (!node.computed || (0, _index.isLiteral)(node.key)) { + return node.key; + } + } + function getFunctionName(node, parent) { + if ("id" in node && node.id) { + return { + name: node.id.name, + originalNode: node.id + }; + } + let prefix = ""; + let id; + if ((0, _index.isObjectProperty)(parent, { + value: node + })) { + id = getObjectMemberKey(parent); + } else if ((0, _index.isObjectMethod)(node) || (0, _index.isClassMethod)(node)) { + id = getObjectMemberKey(node); + if (node.kind === "get") prefix = "get ";else if (node.kind === "set") prefix = "set "; + } else if ((0, _index.isVariableDeclarator)(parent, { + init: node + })) { + id = parent.id; + } else if ((0, _index.isAssignmentExpression)(parent, { + operator: "=", + right: node + })) { + id = parent.left; + } + if (!id) return null; + const name = (0, _index.isLiteral)(id) ? getNameFromLiteralId(id) : (0, _index.isIdentifier)(id) ? id.name : (0, _index.isPrivateName)(id) ? id.id.name : null; + if (name == null) return null; + return { + name: prefix + name, + originalNode: id + }; + } + + + return getFunctionName$3; +} + +var traverse = {}; + +var hasRequiredTraverse; + +function requireTraverse () { + if (hasRequiredTraverse) return traverse; + hasRequiredTraverse = 1; + + Object.defineProperty(traverse, "__esModule", { + value: true + }); + traverse.default = traverse$1; + var _index = requireDefinitions(); + function traverse$1(node, handlers, state) { + if (typeof handlers === "function") { + handlers = { + enter: handlers + }; + } + const { + enter, + exit + } = handlers; + traverseSimpleImpl(node, enter, exit, state, []); + } + function traverseSimpleImpl(node, enter, exit, state, ancestors) { + const keys = _index.VISITOR_KEYS[node.type]; + if (!keys) return; + if (enter) enter(node, ancestors, state); + for (const key of keys) { + const subNode = node[key]; + if (Array.isArray(subNode)) { + for (let i = 0; i < subNode.length; i++) { + const child = subNode[i]; + if (!child) continue; + ancestors.push({ + node, + key, + index: i + }); + traverseSimpleImpl(child, enter, exit, state, ancestors); + ancestors.pop(); + } + } else if (subNode) { + ancestors.push({ + node, + key + }); + traverseSimpleImpl(subNode, enter, exit, state, ancestors); + ancestors.pop(); + } + } + if (exit) exit(node, ancestors, state); + } + + + return traverse; +} + +var isBinding = {}; + +var hasRequiredIsBinding; + +function requireIsBinding () { + if (hasRequiredIsBinding) return isBinding; + hasRequiredIsBinding = 1; + + Object.defineProperty(isBinding, "__esModule", { + value: true + }); + isBinding.default = isBinding$1; + var _getBindingIdentifiers = requireGetBindingIdentifiers(); + function isBinding$1(node, parent, grandparent) { + if (grandparent && node.type === "Identifier" && parent.type === "ObjectProperty" && grandparent.type === "ObjectExpression") { + return false; + } + const keys = _getBindingIdentifiers.default.keys[parent.type]; + if (keys) { + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const val = parent[key]; + if (Array.isArray(val)) { + if (val.includes(node)) return true; + } else { + if (val === node) return true; + } + } + } + return false; + } + + + return isBinding; +} + +var isBlockScoped = {}; + +var isLet = {}; + +var hasRequiredIsLet; + +function requireIsLet () { + if (hasRequiredIsLet) return isLet; + hasRequiredIsLet = 1; + + Object.defineProperty(isLet, "__esModule", { + value: true + }); + isLet.default = isLet$1; + var _index = requireGenerated$3(); + var _index2 = requireConstants(); + function isLet$1(node) { + return (0, _index.isVariableDeclaration)(node) && (node.kind !== "var" || node[_index2.BLOCK_SCOPED_SYMBOL]); + } + + + return isLet; +} + +var hasRequiredIsBlockScoped; + +function requireIsBlockScoped () { + if (hasRequiredIsBlockScoped) return isBlockScoped; + hasRequiredIsBlockScoped = 1; + + Object.defineProperty(isBlockScoped, "__esModule", { + value: true + }); + isBlockScoped.default = isBlockScoped$1; + var _index = requireGenerated$3(); + var _isLet = requireIsLet(); + function isBlockScoped$1(node) { + return (0, _index.isFunctionDeclaration)(node) || (0, _index.isClassDeclaration)(node) || (0, _isLet.default)(node); + } + + + return isBlockScoped; +} + +var isImmutable = {}; + +var hasRequiredIsImmutable; + +function requireIsImmutable () { + if (hasRequiredIsImmutable) return isImmutable; + hasRequiredIsImmutable = 1; + + Object.defineProperty(isImmutable, "__esModule", { + value: true + }); + isImmutable.default = isImmutable$1; + var _isType = requireIsType(); + var _index = requireGenerated$3(); + function isImmutable$1(node) { + if ((0, _isType.default)(node.type, "Immutable")) return true; + if ((0, _index.isIdentifier)(node)) { + if (node.name === "undefined") { + return true; + } else { + return false; + } + } + return false; + } + + + return isImmutable; +} + +var isNodesEquivalent = {}; + +var hasRequiredIsNodesEquivalent; + +function requireIsNodesEquivalent () { + if (hasRequiredIsNodesEquivalent) return isNodesEquivalent; + hasRequiredIsNodesEquivalent = 1; + + Object.defineProperty(isNodesEquivalent, "__esModule", { + value: true + }); + isNodesEquivalent.default = isNodesEquivalent$1; + var _index = requireDefinitions(); + function isNodesEquivalent$1(a, b) { + if (typeof a !== "object" || typeof b !== "object" || a == null || b == null) { + return a === b; + } + if (a.type !== b.type) { + return false; + } + const fields = Object.keys(_index.NODE_FIELDS[a.type] || a.type); + const visitorKeys = _index.VISITOR_KEYS[a.type]; + for (const field of fields) { + const val_a = a[field]; + const val_b = b[field]; + if (typeof val_a !== typeof val_b) { + return false; + } + if (val_a == null && val_b == null) { + continue; + } else if (val_a == null || val_b == null) { + return false; + } + if (Array.isArray(val_a)) { + if (!Array.isArray(val_b)) { + return false; + } + if (val_a.length !== val_b.length) { + return false; + } + for (let i = 0; i < val_a.length; i++) { + if (!isNodesEquivalent$1(val_a[i], val_b[i])) { + return false; + } + } + continue; + } + if (typeof val_a === "object" && !(visitorKeys != null && visitorKeys.includes(field))) { + for (const key of Object.keys(val_a)) { + if (val_a[key] !== val_b[key]) { + return false; + } + } + continue; + } + if (!isNodesEquivalent$1(val_a, val_b)) { + return false; + } + } + return true; + } + + + return isNodesEquivalent; +} + +var isReferenced = {}; + +var hasRequiredIsReferenced; + +function requireIsReferenced () { + if (hasRequiredIsReferenced) return isReferenced; + hasRequiredIsReferenced = 1; + + Object.defineProperty(isReferenced, "__esModule", { + value: true + }); + isReferenced.default = isReferenced$1; + function isReferenced$1(node, parent, grandparent) { + switch (parent.type) { + case "MemberExpression": + case "OptionalMemberExpression": + if (parent.property === node) { + return !!parent.computed; + } + return parent.object === node; + case "JSXMemberExpression": + return parent.object === node; + case "VariableDeclarator": + return parent.init === node; + case "ArrowFunctionExpression": + return parent.body === node; + case "PrivateName": + return false; + case "ClassMethod": + case "ClassPrivateMethod": + case "ObjectMethod": + if (parent.key === node) { + return !!parent.computed; + } + return false; + case "ObjectProperty": + if (parent.key === node) { + return !!parent.computed; + } + return !grandparent || grandparent.type !== "ObjectPattern"; + case "ClassProperty": + case "ClassAccessorProperty": + if (parent.key === node) { + return !!parent.computed; + } + return true; + case "ClassPrivateProperty": + return parent.key !== node; + case "ClassDeclaration": + case "ClassExpression": + return parent.superClass === node; + case "AssignmentExpression": + return parent.right === node; + case "AssignmentPattern": + return parent.right === node; + case "LabeledStatement": + return false; + case "CatchClause": + return false; + case "RestElement": + return false; + case "BreakStatement": + case "ContinueStatement": + return false; + case "FunctionDeclaration": + case "FunctionExpression": + return false; + case "ExportNamespaceSpecifier": + case "ExportDefaultSpecifier": + return false; + case "ExportSpecifier": + if (grandparent != null && grandparent.source) { + return false; + } + return parent.local === node; + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "ImportSpecifier": + return false; + case "ImportAttribute": + return false; + case "JSXAttribute": + return false; + case "ObjectPattern": + case "ArrayPattern": + return false; + case "MetaProperty": + return false; + case "ObjectTypeProperty": + return parent.key !== node; + case "TSEnumMember": + return parent.id !== node; + case "TSPropertySignature": + if (parent.key === node) { + return !!parent.computed; + } + return true; + } + return true; + } + + + return isReferenced; +} + +var isScope = {}; + +var hasRequiredIsScope; + +function requireIsScope () { + if (hasRequiredIsScope) return isScope; + hasRequiredIsScope = 1; + + Object.defineProperty(isScope, "__esModule", { + value: true + }); + isScope.default = isScope$1; + var _index = requireGenerated$3(); + function isScope$1(node, parent) { + if ((0, _index.isBlockStatement)(node) && ((0, _index.isFunction)(parent) || (0, _index.isCatchClause)(parent))) { + return false; + } + if ((0, _index.isPattern)(node) && ((0, _index.isFunction)(parent) || (0, _index.isCatchClause)(parent))) { + return true; + } + return (0, _index.isScopable)(node); + } + + + return isScope; +} + +var isSpecifierDefault = {}; + +var hasRequiredIsSpecifierDefault; + +function requireIsSpecifierDefault () { + if (hasRequiredIsSpecifierDefault) return isSpecifierDefault; + hasRequiredIsSpecifierDefault = 1; + + Object.defineProperty(isSpecifierDefault, "__esModule", { + value: true + }); + isSpecifierDefault.default = isSpecifierDefault$1; + var _index = requireGenerated$3(); + function isSpecifierDefault$1(specifier) { + return (0, _index.isImportDefaultSpecifier)(specifier) || (0, _index.isIdentifier)(specifier.imported || specifier.exported, { + name: "default" + }); + } + + + return isSpecifierDefault; +} + +var isValidES3Identifier = {}; + +var hasRequiredIsValidES3Identifier; + +function requireIsValidES3Identifier () { + if (hasRequiredIsValidES3Identifier) return isValidES3Identifier; + hasRequiredIsValidES3Identifier = 1; + + Object.defineProperty(isValidES3Identifier, "__esModule", { + value: true + }); + isValidES3Identifier.default = isValidES3Identifier$1; + var _isValidIdentifier = requireIsValidIdentifier(); + const RESERVED_WORDS_ES3_ONLY = new Set(["abstract", "boolean", "byte", "char", "double", "enum", "final", "float", "goto", "implements", "int", "interface", "long", "native", "package", "private", "protected", "public", "short", "static", "synchronized", "throws", "transient", "volatile"]); + function isValidES3Identifier$1(name) { + return (0, _isValidIdentifier.default)(name) && !RESERVED_WORDS_ES3_ONLY.has(name); + } + + + return isValidES3Identifier; +} + +var isVar = {}; + +var hasRequiredIsVar; + +function requireIsVar () { + if (hasRequiredIsVar) return isVar; + hasRequiredIsVar = 1; + + Object.defineProperty(isVar, "__esModule", { + value: true + }); + isVar.default = isVar$1; + var _index = requireGenerated$3(); + var _index2 = requireConstants(); + function isVar$1(node) { + return (0, _index.isVariableDeclaration)(node, { + kind: "var" + }) && !node[_index2.BLOCK_SCOPED_SYMBOL]; + } + + + return isVar; +} + +var toSequenceExpression = {}; + +var gatherSequenceExpressions = {}; + +var hasRequiredGatherSequenceExpressions; + +function requireGatherSequenceExpressions () { + if (hasRequiredGatherSequenceExpressions) return gatherSequenceExpressions; + hasRequiredGatherSequenceExpressions = 1; + + Object.defineProperty(gatherSequenceExpressions, "__esModule", { + value: true + }); + gatherSequenceExpressions.default = gatherSequenceExpressions$1; + var _getBindingIdentifiers = requireGetBindingIdentifiers(); + var _index = requireGenerated$3(); + var _index2 = requireGenerated$2(); + var _productions = requireProductions(); + var _cloneNode = requireCloneNode(); + function gatherSequenceExpressions$1(nodes, declars) { + const exprs = []; + let ensureLastUndefined = true; + for (const node of nodes) { + if (!(0, _index.isEmptyStatement)(node)) { + ensureLastUndefined = false; + } + if ((0, _index.isExpression)(node)) { + exprs.push(node); + } else if ((0, _index.isExpressionStatement)(node)) { + exprs.push(node.expression); + } else if ((0, _index.isVariableDeclaration)(node)) { + if (node.kind !== "var") return; + for (const declar of node.declarations) { + const bindings = (0, _getBindingIdentifiers.default)(declar); + for (const key of Object.keys(bindings)) { + declars.push({ + kind: node.kind, + id: (0, _cloneNode.default)(bindings[key]) + }); + } + if (declar.init) { + exprs.push((0, _index2.assignmentExpression)("=", declar.id, declar.init)); + } + } + ensureLastUndefined = true; + } else if ((0, _index.isIfStatement)(node)) { + const consequent = node.consequent ? gatherSequenceExpressions$1([node.consequent], declars) : (0, _productions.buildUndefinedNode)(); + const alternate = node.alternate ? gatherSequenceExpressions$1([node.alternate], declars) : (0, _productions.buildUndefinedNode)(); + if (!consequent || !alternate) return; + exprs.push((0, _index2.conditionalExpression)(node.test, consequent, alternate)); + } else if ((0, _index.isBlockStatement)(node)) { + const body = gatherSequenceExpressions$1(node.body, declars); + if (!body) return; + exprs.push(body); + } else if ((0, _index.isEmptyStatement)(node)) { + if (nodes.indexOf(node) === 0) { + ensureLastUndefined = true; + } + } else { + return; + } + } + if (ensureLastUndefined) { + exprs.push((0, _productions.buildUndefinedNode)()); + } + if (exprs.length === 1) { + return exprs[0]; + } else { + return (0, _index2.sequenceExpression)(exprs); + } + } + + + return gatherSequenceExpressions; +} + +var hasRequiredToSequenceExpression; + +function requireToSequenceExpression () { + if (hasRequiredToSequenceExpression) return toSequenceExpression; + hasRequiredToSequenceExpression = 1; + + Object.defineProperty(toSequenceExpression, "__esModule", { + value: true + }); + toSequenceExpression.default = toSequenceExpression$1; + var _gatherSequenceExpressions = requireGatherSequenceExpressions(); + function toSequenceExpression$1(nodes, scope) { + if (!(nodes != null && nodes.length)) return; + const declars = []; + const result = (0, _gatherSequenceExpressions.default)(nodes, declars); + if (!result) return; + for (const declar of declars) { + scope.push(declar); + } + return result; + } + + + return toSequenceExpression; +} + +var hasRequiredLib$1; + +function requireLib$1 () { + if (hasRequiredLib$1) return lib$3; + hasRequiredLib$1 = 1; + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + var _exportNames = { + react: true, + assertNode: true, + createTypeAnnotationBasedOnTypeof: true, + createUnionTypeAnnotation: true, + createFlowUnionType: true, + createTSUnionType: true, + cloneNode: true, + clone: true, + cloneDeep: true, + cloneDeepWithoutLoc: true, + cloneWithoutLoc: true, + addComment: true, + addComments: true, + inheritInnerComments: true, + inheritLeadingComments: true, + inheritsComments: true, + inheritTrailingComments: true, + removeComments: true, + ensureBlock: true, + toBindingIdentifierName: true, + toBlock: true, + toComputedKey: true, + toExpression: true, + toIdentifier: true, + toKeyAlias: true, + toStatement: true, + valueToNode: true, + appendToMemberExpression: true, + inherits: true, + prependToMemberExpression: true, + removeProperties: true, + removePropertiesDeep: true, + removeTypeDuplicates: true, + getAssignmentIdentifiers: true, + getBindingIdentifiers: true, + getOuterBindingIdentifiers: true, + getFunctionName: true, + traverse: true, + traverseFast: true, + shallowEqual: true, + is: true, + isBinding: true, + isBlockScoped: true, + isImmutable: true, + isLet: true, + isNode: true, + isNodesEquivalent: true, + isPlaceholderType: true, + isReferenced: true, + isScope: true, + isSpecifierDefault: true, + isType: true, + isValidES3Identifier: true, + isValidIdentifier: true, + isVar: true, + matchesPattern: true, + validate: true, + buildMatchMemberExpression: true, + __internal__deprecationWarning: true + }; + Object.defineProperty(exports, "__internal__deprecationWarning", { + enumerable: true, + get: function () { + return _deprecationWarning.default; + } + }); + Object.defineProperty(exports, "addComment", { + enumerable: true, + get: function () { + return _addComment.default; + } + }); + Object.defineProperty(exports, "addComments", { + enumerable: true, + get: function () { + return _addComments.default; + } + }); + Object.defineProperty(exports, "appendToMemberExpression", { + enumerable: true, + get: function () { + return _appendToMemberExpression.default; + } + }); + Object.defineProperty(exports, "assertNode", { + enumerable: true, + get: function () { + return _assertNode.default; + } + }); + Object.defineProperty(exports, "buildMatchMemberExpression", { + enumerable: true, + get: function () { + return _buildMatchMemberExpression.default; + } + }); + Object.defineProperty(exports, "clone", { + enumerable: true, + get: function () { + return _clone.default; + } + }); + Object.defineProperty(exports, "cloneDeep", { + enumerable: true, + get: function () { + return _cloneDeep.default; + } + }); + Object.defineProperty(exports, "cloneDeepWithoutLoc", { + enumerable: true, + get: function () { + return _cloneDeepWithoutLoc.default; + } + }); + Object.defineProperty(exports, "cloneNode", { + enumerable: true, + get: function () { + return _cloneNode.default; + } + }); + Object.defineProperty(exports, "cloneWithoutLoc", { + enumerable: true, + get: function () { + return _cloneWithoutLoc.default; + } + }); + Object.defineProperty(exports, "createFlowUnionType", { + enumerable: true, + get: function () { + return _createFlowUnionType.default; + } + }); + Object.defineProperty(exports, "createTSUnionType", { + enumerable: true, + get: function () { + return _createTSUnionType.default; + } + }); + Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", { + enumerable: true, + get: function () { + return _createTypeAnnotationBasedOnTypeof.default; + } + }); + Object.defineProperty(exports, "createUnionTypeAnnotation", { + enumerable: true, + get: function () { + return _createFlowUnionType.default; + } + }); + Object.defineProperty(exports, "ensureBlock", { + enumerable: true, + get: function () { + return _ensureBlock.default; + } + }); + Object.defineProperty(exports, "getAssignmentIdentifiers", { + enumerable: true, + get: function () { + return _getAssignmentIdentifiers.default; + } + }); + Object.defineProperty(exports, "getBindingIdentifiers", { + enumerable: true, + get: function () { + return _getBindingIdentifiers.default; + } + }); + Object.defineProperty(exports, "getFunctionName", { + enumerable: true, + get: function () { + return _getFunctionName.default; + } + }); + Object.defineProperty(exports, "getOuterBindingIdentifiers", { + enumerable: true, + get: function () { + return _getOuterBindingIdentifiers.default; + } + }); + Object.defineProperty(exports, "inheritInnerComments", { + enumerable: true, + get: function () { + return _inheritInnerComments.default; + } + }); + Object.defineProperty(exports, "inheritLeadingComments", { + enumerable: true, + get: function () { + return _inheritLeadingComments.default; + } + }); + Object.defineProperty(exports, "inheritTrailingComments", { + enumerable: true, + get: function () { + return _inheritTrailingComments.default; + } + }); + Object.defineProperty(exports, "inherits", { + enumerable: true, + get: function () { + return _inherits.default; + } + }); + Object.defineProperty(exports, "inheritsComments", { + enumerable: true, + get: function () { + return _inheritsComments.default; + } + }); + Object.defineProperty(exports, "is", { + enumerable: true, + get: function () { + return _is.default; + } + }); + Object.defineProperty(exports, "isBinding", { + enumerable: true, + get: function () { + return _isBinding.default; + } + }); + Object.defineProperty(exports, "isBlockScoped", { + enumerable: true, + get: function () { + return _isBlockScoped.default; + } + }); + Object.defineProperty(exports, "isImmutable", { + enumerable: true, + get: function () { + return _isImmutable.default; + } + }); + Object.defineProperty(exports, "isLet", { + enumerable: true, + get: function () { + return _isLet.default; + } + }); + Object.defineProperty(exports, "isNode", { + enumerable: true, + get: function () { + return _isNode.default; + } + }); + Object.defineProperty(exports, "isNodesEquivalent", { + enumerable: true, + get: function () { + return _isNodesEquivalent.default; + } + }); + Object.defineProperty(exports, "isPlaceholderType", { + enumerable: true, + get: function () { + return _isPlaceholderType.default; + } + }); + Object.defineProperty(exports, "isReferenced", { + enumerable: true, + get: function () { + return _isReferenced.default; + } + }); + Object.defineProperty(exports, "isScope", { + enumerable: true, + get: function () { + return _isScope.default; + } + }); + Object.defineProperty(exports, "isSpecifierDefault", { + enumerable: true, + get: function () { + return _isSpecifierDefault.default; + } + }); + Object.defineProperty(exports, "isType", { + enumerable: true, + get: function () { + return _isType.default; + } + }); + Object.defineProperty(exports, "isValidES3Identifier", { + enumerable: true, + get: function () { + return _isValidES3Identifier.default; + } + }); + Object.defineProperty(exports, "isValidIdentifier", { + enumerable: true, + get: function () { + return _isValidIdentifier.default; + } + }); + Object.defineProperty(exports, "isVar", { + enumerable: true, + get: function () { + return _isVar.default; + } + }); + Object.defineProperty(exports, "matchesPattern", { + enumerable: true, + get: function () { + return _matchesPattern.default; + } + }); + Object.defineProperty(exports, "prependToMemberExpression", { + enumerable: true, + get: function () { + return _prependToMemberExpression.default; + } + }); + exports.react = void 0; + Object.defineProperty(exports, "removeComments", { + enumerable: true, + get: function () { + return _removeComments.default; + } + }); + Object.defineProperty(exports, "removeProperties", { + enumerable: true, + get: function () { + return _removeProperties.default; + } + }); + Object.defineProperty(exports, "removePropertiesDeep", { + enumerable: true, + get: function () { + return _removePropertiesDeep.default; + } + }); + Object.defineProperty(exports, "removeTypeDuplicates", { + enumerable: true, + get: function () { + return _removeTypeDuplicates.default; + } + }); + Object.defineProperty(exports, "shallowEqual", { + enumerable: true, + get: function () { + return _shallowEqual.default; + } + }); + Object.defineProperty(exports, "toBindingIdentifierName", { + enumerable: true, + get: function () { + return _toBindingIdentifierName.default; + } + }); + Object.defineProperty(exports, "toBlock", { + enumerable: true, + get: function () { + return _toBlock.default; + } + }); + Object.defineProperty(exports, "toComputedKey", { + enumerable: true, + get: function () { + return _toComputedKey.default; + } + }); + Object.defineProperty(exports, "toExpression", { + enumerable: true, + get: function () { + return _toExpression.default; + } + }); + Object.defineProperty(exports, "toIdentifier", { + enumerable: true, + get: function () { + return _toIdentifier.default; + } + }); + Object.defineProperty(exports, "toKeyAlias", { + enumerable: true, + get: function () { + return _toKeyAlias.default; + } + }); + Object.defineProperty(exports, "toStatement", { + enumerable: true, + get: function () { + return _toStatement.default; + } + }); + Object.defineProperty(exports, "traverse", { + enumerable: true, + get: function () { + return _traverse.default; + } + }); + Object.defineProperty(exports, "traverseFast", { + enumerable: true, + get: function () { + return _traverseFast.default; + } + }); + Object.defineProperty(exports, "validate", { + enumerable: true, + get: function () { + return _validate.default; + } + }); + Object.defineProperty(exports, "valueToNode", { + enumerable: true, + get: function () { + return _valueToNode.default; + } + }); + var _isReactComponent = requireIsReactComponent(); + var _isCompatTag = requireIsCompatTag(); + var _buildChildren = requireBuildChildren(); + var _assertNode = requireAssertNode(); + var _index = requireGenerated$1(); + Object.keys(_index).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index[key]; + } + }); + }); + var _createTypeAnnotationBasedOnTypeof = requireCreateTypeAnnotationBasedOnTypeof(); + var _createFlowUnionType = requireCreateFlowUnionType(); + var _createTSUnionType = requireCreateTSUnionType(); + var _index2 = requireGenerated$2(); + Object.keys(_index2).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index2[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index2[key]; + } + }); + }); + var _uppercase = requireUppercase(); + Object.keys(_uppercase).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _uppercase[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _uppercase[key]; + } + }); + }); + var _productions = requireProductions(); + Object.keys(_productions).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _productions[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _productions[key]; + } + }); + }); + var _cloneNode = requireCloneNode(); + var _clone = requireClone(); + var _cloneDeep = requireCloneDeep(); + var _cloneDeepWithoutLoc = requireCloneDeepWithoutLoc(); + var _cloneWithoutLoc = requireCloneWithoutLoc(); + var _addComment = requireAddComment(); + var _addComments = requireAddComments(); + var _inheritInnerComments = requireInheritInnerComments(); + var _inheritLeadingComments = requireInheritLeadingComments(); + var _inheritsComments = requireInheritsComments(); + var _inheritTrailingComments = requireInheritTrailingComments(); + var _removeComments = requireRemoveComments(); + var _index3 = requireGenerated(); + Object.keys(_index3).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index3[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index3[key]; + } + }); + }); + var _index4 = requireConstants(); + Object.keys(_index4).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index4[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index4[key]; + } + }); + }); + var _ensureBlock = requireEnsureBlock(); + var _toBindingIdentifierName = requireToBindingIdentifierName(); + var _toBlock = requireToBlock(); + var _toComputedKey = requireToComputedKey(); + var _toExpression = requireToExpression(); + var _toIdentifier = requireToIdentifier(); + var _toKeyAlias = requireToKeyAlias(); + var _toStatement = requireToStatement(); + var _valueToNode = requireValueToNode(); + var _index5 = requireDefinitions(); + Object.keys(_index5).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index5[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index5[key]; + } + }); + }); + var _appendToMemberExpression = requireAppendToMemberExpression(); + var _inherits = requireInherits(); + var _prependToMemberExpression = requirePrependToMemberExpression(); + var _removeProperties = requireRemoveProperties(); + var _removePropertiesDeep = requireRemovePropertiesDeep(); + var _removeTypeDuplicates = requireRemoveTypeDuplicates$1(); + var _getAssignmentIdentifiers = requireGetAssignmentIdentifiers(); + var _getBindingIdentifiers = requireGetBindingIdentifiers(); + var _getOuterBindingIdentifiers = requireGetOuterBindingIdentifiers(); + var _getFunctionName = requireGetFunctionName(); + var _traverse = requireTraverse(); + Object.keys(_traverse).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _traverse[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _traverse[key]; + } + }); + }); + var _traverseFast = requireTraverseFast(); + var _shallowEqual = requireShallowEqual(); + var _is = requireIs(); + var _isBinding = requireIsBinding(); + var _isBlockScoped = requireIsBlockScoped(); + var _isImmutable = requireIsImmutable(); + var _isLet = requireIsLet(); + var _isNode = requireIsNode(); + var _isNodesEquivalent = requireIsNodesEquivalent(); + var _isPlaceholderType = requireIsPlaceholderType(); + var _isReferenced = requireIsReferenced(); + var _isScope = requireIsScope(); + var _isSpecifierDefault = requireIsSpecifierDefault(); + var _isType = requireIsType(); + var _isValidES3Identifier = requireIsValidES3Identifier(); + var _isValidIdentifier = requireIsValidIdentifier(); + var _isVar = requireIsVar(); + var _matchesPattern = requireMatchesPattern(); + var _validate = requireValidate(); + var _buildMatchMemberExpression = requireBuildMatchMemberExpression(); + var _index6 = requireGenerated$3(); + Object.keys(_index6).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index6[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index6[key]; + } + }); + }); + var _deprecationWarning = requireDeprecationWarning(); + exports.react = { + isReactComponent: _isReactComponent.default, + isCompatTag: _isCompatTag.default, + buildChildren: _buildChildren.default + }; + { + exports.toSequenceExpression = requireToSequenceExpression().default; + } + if (process.env.BABEL_TYPES_8_BREAKING) { + console.warn("BABEL_TYPES_8_BREAKING is not supported anymore. Use the latest Babel 8.0.0 pre-release instead!"); + } + + +} (lib$3)); + return lib$3; +} + +var libExports$1 = requireLib$1(); + +var lib = {}; + +var picocolorsExports = {}; +var picocolors = { + get exports(){ return picocolorsExports; }, + set exports(v){ picocolorsExports = v; }, +}; + +var hasRequiredPicocolors; + +function requirePicocolors () { + if (hasRequiredPicocolors) return picocolorsExports; + hasRequiredPicocolors = 1; + let p = process || {}, argv = p.argv || [], env = p.env || {}; + let isColorSupported = + !(!!env.NO_COLOR || argv.includes("--no-color")) && + (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI); + + let formatter = (open, close, replace = open) => + input => { + let string = "" + input, index = string.indexOf(close, open.length); + return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close + }; + + let replaceClose = (string, close, replace, index) => { + let result = "", cursor = 0; + do { + result += string.substring(cursor, index) + replace; + cursor = index + close.length; + index = string.indexOf(close, cursor); + } while (~index) + return result + string.substring(cursor) + }; + + let createColors = (enabled = isColorSupported) => { + let f = enabled ? formatter : () => String; + return { + isColorSupported: enabled, + reset: f("\x1b[0m", "\x1b[0m"), + bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), + dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), + italic: f("\x1b[3m", "\x1b[23m"), + underline: f("\x1b[4m", "\x1b[24m"), + inverse: f("\x1b[7m", "\x1b[27m"), + hidden: f("\x1b[8m", "\x1b[28m"), + strikethrough: f("\x1b[9m", "\x1b[29m"), + + black: f("\x1b[30m", "\x1b[39m"), + red: f("\x1b[31m", "\x1b[39m"), + green: f("\x1b[32m", "\x1b[39m"), + yellow: f("\x1b[33m", "\x1b[39m"), + blue: f("\x1b[34m", "\x1b[39m"), + magenta: f("\x1b[35m", "\x1b[39m"), + cyan: f("\x1b[36m", "\x1b[39m"), + white: f("\x1b[37m", "\x1b[39m"), + gray: f("\x1b[90m", "\x1b[39m"), + + bgBlack: f("\x1b[40m", "\x1b[49m"), + bgRed: f("\x1b[41m", "\x1b[49m"), + bgGreen: f("\x1b[42m", "\x1b[49m"), + bgYellow: f("\x1b[43m", "\x1b[49m"), + bgBlue: f("\x1b[44m", "\x1b[49m"), + bgMagenta: f("\x1b[45m", "\x1b[49m"), + bgCyan: f("\x1b[46m", "\x1b[49m"), + bgWhite: f("\x1b[47m", "\x1b[49m"), + + blackBright: f("\x1b[90m", "\x1b[39m"), + redBright: f("\x1b[91m", "\x1b[39m"), + greenBright: f("\x1b[92m", "\x1b[39m"), + yellowBright: f("\x1b[93m", "\x1b[39m"), + blueBright: f("\x1b[94m", "\x1b[39m"), + magentaBright: f("\x1b[95m", "\x1b[39m"), + cyanBright: f("\x1b[96m", "\x1b[39m"), + whiteBright: f("\x1b[97m", "\x1b[39m"), + + bgBlackBright: f("\x1b[100m", "\x1b[49m"), + bgRedBright: f("\x1b[101m", "\x1b[49m"), + bgGreenBright: f("\x1b[102m", "\x1b[49m"), + bgYellowBright: f("\x1b[103m", "\x1b[49m"), + bgBlueBright: f("\x1b[104m", "\x1b[49m"), + bgMagentaBright: f("\x1b[105m", "\x1b[49m"), + bgCyanBright: f("\x1b[106m", "\x1b[49m"), + bgWhiteBright: f("\x1b[107m", "\x1b[49m"), + } + }; + + picocolors.exports = createColors(); + picocolorsExports.createColors = createColors; + return picocolorsExports; +} + +var jsTokens = {}; + +var hasRequiredJsTokens; + +function requireJsTokens () { + if (hasRequiredJsTokens) return jsTokens; + hasRequiredJsTokens = 1; + // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell + // License: MIT. (See LICENSE.) + + Object.defineProperty(jsTokens, "__esModule", { + value: true + }); + + // This regex comes from regex.coffee, and is inserted here by generate-index.js + // (run `npm run build`). + jsTokens.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; + + jsTokens.matchToToken = function(match) { + var token = {type: "invalid", value: match[0], closed: undefined}; + if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]); + else if (match[ 5]) token.type = "comment"; + else if (match[ 6]) token.type = "comment", token.closed = !!match[7]; + else if (match[ 8]) token.type = "regex"; + else if (match[ 9]) token.type = "number"; + else if (match[10]) token.type = "name"; + else if (match[11]) token.type = "punctuator"; + else if (match[12]) token.type = "whitespace"; + return token + }; + return jsTokens; +} + +var hasRequiredLib; + +function requireLib () { + if (hasRequiredLib) return lib; + hasRequiredLib = 1; + + Object.defineProperty(lib, '__esModule', { value: true }); + + var picocolors = requirePicocolors(); + var jsTokens = requireJsTokens(); + var helperValidatorIdentifier = requireLib$3(); + + function isColorSupported() { + return (typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported + ); + } + const compose = (f, g) => v => f(g(v)); + function buildDefs(colors) { + return { + keyword: colors.cyan, + capitalized: colors.yellow, + jsxIdentifier: colors.yellow, + punctuator: colors.yellow, + number: colors.magenta, + string: colors.green, + regex: colors.magenta, + comment: colors.gray, + invalid: compose(compose(colors.white, colors.bgRed), colors.bold), + gutter: colors.gray, + marker: compose(colors.red, colors.bold), + message: compose(colors.red, colors.bold), + reset: colors.reset + }; + } + const defsOn = buildDefs(picocolors.createColors(true)); + const defsOff = buildDefs(picocolors.createColors(false)); + function getDefs(enabled) { + return enabled ? defsOn : defsOff; + } + + const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]); + const NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/; + const BRACKET = /^[()[\]{}]$/; + let tokenize; + { + const JSX_TAG = /^[a-z][\w-]*$/i; + const getTokenType = function (token, offset, text) { + if (token.type === "name") { + if (helperValidatorIdentifier.isKeyword(token.value) || helperValidatorIdentifier.isStrictReservedWord(token.value, true) || sometimesKeywords.has(token.value)) { + return "keyword"; + } + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === " defs[type](str)).join("\n"); + } else { + highlighted += value; + } + } + return highlighted; + } + + let deprecationWarningShown = false; + const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + function getMarkerLines(loc, source, opts) { + const startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + const endLoc = Object.assign({}, startLoc, loc.end); + const { + linesAbove = 2, + linesBelow = 3 + } = opts || {}; + const startLine = startLoc.line; + const startColumn = startLoc.column; + const endLine = endLoc.line; + const endColumn = endLoc.column; + let start = Math.max(startLine - (linesAbove + 1), 0); + let end = Math.min(source.length, endLine + linesBelow); + if (startLine === -1) { + start = 0; + } + if (endLine === -1) { + end = source.length; + } + const lineDiff = endLine - startLine; + const markerLines = {}; + if (lineDiff) { + for (let i = 0; i <= lineDiff; i++) { + const lineNumber = i + startLine; + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + const sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + const sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, sourceLength]; + } + } + } else { + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } + } + return { + start, + end, + markerLines + }; + } + function codeFrameColumns(rawLines, loc, opts = {}) { + const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode; + const defs = getDefs(shouldHighlight); + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end).length; + const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines; + let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number}`.slice(-numberMaxWidth); + const gutter = ` ${paddedNumber} |`; + const hasMarker = markerLines[number]; + const lastMarkerLine = !markerLines[number + 1]; + if (hasMarker) { + let markerLine = ""; + if (Array.isArray(hasMarker)) { + const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + const numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join(""); + if (lastMarkerLine && opts.message) { + markerLine += " " + defs.message(opts.message); + } + } + return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join(""); + } else { + return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`; + } + }).join("\n"); + if (opts.message && !hasColumns) { + frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; + } + if (shouldHighlight) { + return defs.reset(frame); + } else { + return frame; + } + } + function index (rawLines, lineNumber, colNumber, opts = {}) { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + const deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + colNumber = Math.max(colNumber, 0); + const location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); + } + + lib.codeFrameColumns = codeFrameColumns; + lib.default = index; + lib.highlight = highlight; + + return lib; +} + +var libExports = requireLib(); + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + + +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +var _OkImpl_val, _ErrImpl_val; +function Ok(val) { + return new OkImpl(val); +} +class OkImpl { + constructor(val) { + _OkImpl_val.set(this, void 0); + __classPrivateFieldSet(this, _OkImpl_val, val, "f"); + } + map(fn) { + return new OkImpl(fn(__classPrivateFieldGet(this, _OkImpl_val, "f"))); + } + mapErr(_fn) { + return this; + } + mapOr(_fallback, fn) { + return fn(__classPrivateFieldGet(this, _OkImpl_val, "f")); + } + mapOrElse(_fallback, fn) { + return fn(__classPrivateFieldGet(this, _OkImpl_val, "f")); + } + andThen(fn) { + return fn(__classPrivateFieldGet(this, _OkImpl_val, "f")); + } + and(res) { + return res; + } + or(_res) { + return this; + } + orElse(_fn) { + return this; + } + isOk() { + return true; + } + isErr() { + return false; + } + expect(_msg) { + return __classPrivateFieldGet(this, _OkImpl_val, "f"); + } + expectErr(msg) { + throw new Error(`${msg}: ${__classPrivateFieldGet(this, _OkImpl_val, "f")}`); + } + unwrap() { + return __classPrivateFieldGet(this, _OkImpl_val, "f"); + } + unwrapOr(_fallback) { + return __classPrivateFieldGet(this, _OkImpl_val, "f"); + } + unwrapOrElse(_fallback) { + return __classPrivateFieldGet(this, _OkImpl_val, "f"); + } + unwrapErr() { + if (__classPrivateFieldGet(this, _OkImpl_val, "f") instanceof Error) { + throw __classPrivateFieldGet(this, _OkImpl_val, "f"); + } + throw new Error(`Can't unwrap \`Ok\` to \`Err\`: ${__classPrivateFieldGet(this, _OkImpl_val, "f")}`); + } +} +_OkImpl_val = new WeakMap(); +function Err(val) { + return new ErrImpl(val); +} +class ErrImpl { + constructor(val) { + _ErrImpl_val.set(this, void 0); + __classPrivateFieldSet(this, _ErrImpl_val, val, "f"); + } + map(_fn) { + return this; + } + mapErr(fn) { + return new ErrImpl(fn(__classPrivateFieldGet(this, _ErrImpl_val, "f"))); + } + mapOr(fallback, _fn) { + return fallback; + } + mapOrElse(fallback, _fn) { + return fallback(); + } + andThen(_fn) { + return this; + } + and(_res) { + return this; + } + or(res) { + return res; + } + orElse(fn) { + return fn(__classPrivateFieldGet(this, _ErrImpl_val, "f")); + } + isOk() { + return false; + } + isErr() { + return true; + } + expect(msg) { + throw new Error(`${msg}: ${__classPrivateFieldGet(this, _ErrImpl_val, "f")}`); + } + expectErr(_msg) { + return __classPrivateFieldGet(this, _ErrImpl_val, "f"); + } + unwrap() { + if (__classPrivateFieldGet(this, _ErrImpl_val, "f") instanceof Error) { + throw __classPrivateFieldGet(this, _ErrImpl_val, "f"); + } + throw new Error(`Can't unwrap \`Err\` to \`Ok\`: ${__classPrivateFieldGet(this, _ErrImpl_val, "f")}`); + } + unwrapOr(fallback) { + return fallback; + } + unwrapOrElse(fallback) { + return fallback(__classPrivateFieldGet(this, _ErrImpl_val, "f")); + } + unwrapErr() { + return __classPrivateFieldGet(this, _ErrImpl_val, "f"); + } +} +_ErrImpl_val = new WeakMap(); + +function assertExhaustive$1(_, errorMsg) { + throw new Error(errorMsg); +} +function retainWhere(array, predicate) { + let writeIndex = 0; + for (let readIndex = 0; readIndex < array.length; readIndex++) { + const item = array[readIndex]; + if (predicate(item, readIndex) === true) { + array[writeIndex++] = item; + } + } + array.length = writeIndex; +} +function retainWhere_Set(items, predicate) { + for (const item of items) { + if (!predicate(item)) { + items.delete(item); + } + } +} +function getOrInsertWith(m, key, makeDefault) { + if (m.has(key)) { + return m.get(key); + } + else { + const defaultValue = makeDefault(); + m.set(key, defaultValue); + return defaultValue; + } +} +function getOrInsertDefault(m, key, defaultValue) { + if (m.has(key)) { + return m.get(key); + } + else { + m.set(key, defaultValue); + return defaultValue; + } +} +function Set_equal(a, b) { + if (a.size !== b.size) { + return false; + } + for (const item of a) { + if (!b.has(item)) { + return false; + } + } + return true; +} +function Set_union(a, b) { + const union = new Set(a); + for (const item of b) { + union.add(item); + } + return union; +} +function Set_intersect(sets) { + if (sets.length === 0 || sets.some(s => s.size === 0)) { + return new Set(); + } + else if (sets.length === 1) { + return new Set(sets[0]); + } + const result = new Set(); + const first = sets[0]; + outer: for (const e of first) { + for (let i = 1; i < sets.length; i++) { + if (!sets[i].has(e)) { + continue outer; + } + } + result.add(e); + } + return result; +} +function Set_isSuperset(a, b) { + for (const v of b) { + if (!a.has(v)) { + return false; + } + } + return true; +} +function Iterable_some(iter, pred) { + for (const item of iter) { + if (pred(item)) { + return true; + } + } + return false; +} +function Set_filter(source, fn) { + const result = new Set(); + for (const entry of source) { + if (fn(entry)) { + result.add(entry); + } + } + return result; +} +function hasNode(input) { + return input.node != null; +} +function hasOwnProperty$1(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +const CODEFRAME_LINES_ABOVE = 2; +const CODEFRAME_LINES_BELOW = 3; +const CODEFRAME_MAX_LINES = 10; +const CODEFRAME_ABBREVIATED_SOURCE_LINES = 5; +var ErrorSeverity; +(function (ErrorSeverity) { + ErrorSeverity["Error"] = "Error"; + ErrorSeverity["Warning"] = "Warning"; + ErrorSeverity["Hint"] = "Hint"; + ErrorSeverity["Off"] = "Off"; +})(ErrorSeverity || (ErrorSeverity = {})); +var CompilerSuggestionOperation; +(function (CompilerSuggestionOperation) { + CompilerSuggestionOperation[CompilerSuggestionOperation["InsertBefore"] = 0] = "InsertBefore"; + CompilerSuggestionOperation[CompilerSuggestionOperation["InsertAfter"] = 1] = "InsertAfter"; + CompilerSuggestionOperation[CompilerSuggestionOperation["Remove"] = 2] = "Remove"; + CompilerSuggestionOperation[CompilerSuggestionOperation["Replace"] = 3] = "Replace"; +})(CompilerSuggestionOperation || (CompilerSuggestionOperation = {})); +class CompilerDiagnostic { + constructor(options) { + this.options = options; + } + static create(options) { + return new CompilerDiagnostic(Object.assign(Object.assign({}, options), { details: [] })); + } + get reason() { + return this.options.reason; + } + get description() { + return this.options.description; + } + get severity() { + return getRuleForCategory(this.category).severity; + } + get suggestions() { + return this.options.suggestions; + } + get category() { + return this.options.category; + } + withDetails(...details) { + this.options.details.push(...details); + return this; + } + primaryLocation() { + const firstErrorDetail = this.options.details.filter(d => d.kind === 'error')[0]; + return firstErrorDetail != null && firstErrorDetail.kind === 'error' + ? firstErrorDetail.loc + : null; + } + printErrorMessage(source, options) { + var _a, _b; + const buffer = [printErrorSummary(this.category, this.reason)]; + if (this.description != null) { + buffer.push('\n\n', `${this.description}.`); + } + for (const detail of this.options.details) { + switch (detail.kind) { + case 'error': { + const loc = detail.loc; + if (loc == null || typeof loc === 'symbol') { + continue; + } + let codeFrame; + try { + codeFrame = printCodeFrame(source, loc, (_a = detail.message) !== null && _a !== void 0 ? _a : ''); + } + catch (e) { + codeFrame = (_b = detail.message) !== null && _b !== void 0 ? _b : ''; + } + buffer.push('\n\n'); + if (loc.filename != null) { + const line = loc.start.line; + const column = options.eslint + ? loc.start.column + 1 + : loc.start.column; + buffer.push(`${loc.filename}:${line}:${column}\n`); + } + buffer.push(codeFrame); + break; + } + case 'hint': { + buffer.push('\n\n'); + buffer.push(detail.message); + break; + } + default: { + assertExhaustive$1(detail, `Unexpected detail kind ${detail.kind}`); + } + } + } + return buffer.join(''); + } + toString() { + const buffer = [printErrorSummary(this.category, this.reason)]; + if (this.description != null) { + buffer.push(`. ${this.description}.`); + } + const loc = this.primaryLocation(); + if (loc != null && typeof loc !== 'symbol') { + buffer.push(` (${loc.start.line}:${loc.start.column})`); + } + return buffer.join(''); + } +} +class CompilerErrorDetail { + constructor(options) { + this.options = options; + } + get reason() { + return this.options.reason; + } + get description() { + return this.options.description; + } + get severity() { + return getRuleForCategory(this.category).severity; + } + get loc() { + return this.options.loc; + } + get suggestions() { + return this.options.suggestions; + } + get category() { + return this.options.category; + } + primaryLocation() { + return this.loc; + } + printErrorMessage(source, options) { + const buffer = [printErrorSummary(this.category, this.reason)]; + if (this.description != null) { + buffer.push(`\n\n${this.description}.`); + } + const loc = this.loc; + if (loc != null && typeof loc !== 'symbol') { + let codeFrame; + try { + codeFrame = printCodeFrame(source, loc, this.reason); + } + catch (e) { + codeFrame = ''; + } + buffer.push(`\n\n`); + if (loc.filename != null) { + const line = loc.start.line; + const column = options.eslint ? loc.start.column + 1 : loc.start.column; + buffer.push(`${loc.filename}:${line}:${column}\n`); + } + buffer.push(codeFrame); + buffer.push('\n\n'); + } + return buffer.join(''); + } + toString() { + const buffer = [printErrorSummary(this.category, this.reason)]; + if (this.description != null) { + buffer.push(`. ${this.description}.`); + } + const loc = this.loc; + if (loc != null && typeof loc !== 'symbol') { + buffer.push(` (${loc.start.line}:${loc.start.column})`); + } + return buffer.join(''); + } +} +class CompilerError extends Error { + static invariant(condition, options) { + var _a, _b; + if (!condition) { + const errors = new CompilerError(); + errors.pushDiagnostic(CompilerDiagnostic.create({ + reason: options.reason, + description: (_a = options.description) !== null && _a !== void 0 ? _a : null, + category: ErrorCategory.Invariant, + }).withDetails({ + kind: 'error', + loc: options.loc, + message: (_b = options.message) !== null && _b !== void 0 ? _b : options.reason, + })); + throw errors; + } + } + static throwDiagnostic(options) { + const errors = new CompilerError(); + errors.pushDiagnostic(new CompilerDiagnostic(options)); + throw errors; + } + static throwTodo(options) { + const errors = new CompilerError(); + errors.pushErrorDetail(new CompilerErrorDetail(Object.assign(Object.assign({}, options), { category: ErrorCategory.Todo }))); + throw errors; + } + static throwInvalidJS(options) { + const errors = new CompilerError(); + errors.pushErrorDetail(new CompilerErrorDetail(Object.assign(Object.assign({}, options), { category: ErrorCategory.Syntax }))); + throw errors; + } + static throwInvalidReact(options) { + const errors = new CompilerError(); + errors.pushErrorDetail(new CompilerErrorDetail(options)); + throw errors; + } + static throwInvalidConfig(options) { + const errors = new CompilerError(); + errors.pushErrorDetail(new CompilerErrorDetail(Object.assign(Object.assign({}, options), { category: ErrorCategory.Config }))); + throw errors; + } + static throw(options) { + const errors = new CompilerError(); + errors.pushErrorDetail(new CompilerErrorDetail(options)); + throw errors; + } + constructor(...args) { + super(...args); + this.details = []; + this.disabledDetails = []; + this.printedMessage = null; + this.name = 'ReactCompilerError'; + this.details = []; + this.disabledDetails = []; + } + get message() { + var _a; + return (_a = this.printedMessage) !== null && _a !== void 0 ? _a : this.toString(); + } + set message(_message) { } + toString() { + if (this.printedMessage) { + return this.printedMessage; + } + if (Array.isArray(this.details)) { + return this.details.map(detail => detail.toString()).join('\n\n'); + } + return this.name; + } + withPrintedMessage(source, options) { + this.printedMessage = this.printErrorMessage(source, options); + return this; + } + printErrorMessage(source, options) { + if (options.eslint && this.details.length === 1) { + return this.details[0].printErrorMessage(source, options); + } + return (`Found ${this.details.length} error${this.details.length === 1 ? '' : 's'}:\n\n` + + this.details + .map(detail => detail.printErrorMessage(source, options).trim()) + .join('\n\n')); + } + merge(other) { + this.details.push(...other.details); + this.disabledDetails.push(...other.disabledDetails); + } + pushDiagnostic(diagnostic) { + if (diagnostic.severity === ErrorSeverity.Off) { + this.disabledDetails.push(diagnostic); + } + else { + this.details.push(diagnostic); + } + } + push(options) { + var _a; + const detail = new CompilerErrorDetail({ + category: options.category, + reason: options.reason, + description: (_a = options.description) !== null && _a !== void 0 ? _a : null, + suggestions: options.suggestions, + loc: typeof options.loc === 'symbol' ? null : options.loc, + }); + return this.pushErrorDetail(detail); + } + pushErrorDetail(detail) { + if (detail.severity === ErrorSeverity.Off) { + this.disabledDetails.push(detail); + } + else { + this.details.push(detail); + } + return detail; + } + hasAnyErrors() { + return this.details.length > 0; + } + asResult() { + return this.hasAnyErrors() ? Err(this) : Ok(undefined); + } + hasErrors() { + for (const detail of this.details) { + if (detail.severity === ErrorSeverity.Error) { + return true; + } + } + return false; + } + hasWarning() { + let res = false; + for (const detail of this.details) { + if (detail.severity === ErrorSeverity.Error) { + return false; + } + if (detail.severity === ErrorSeverity.Warning) { + res = true; + } + } + return res; + } + hasHints() { + let res = false; + for (const detail of this.details) { + if (detail.severity === ErrorSeverity.Error) { + return false; + } + if (detail.severity === ErrorSeverity.Warning) { + return false; + } + if (detail.severity === ErrorSeverity.Hint) { + res = true; + } + } + return res; + } +} +function printCodeFrame(source, loc, message) { + const printed = libExports.codeFrameColumns(source, { + start: { + line: loc.start.line, + column: loc.start.column + 1, + }, + end: { + line: loc.end.line, + column: loc.end.column + 1, + }, + }, { + message, + linesAbove: CODEFRAME_LINES_ABOVE, + linesBelow: CODEFRAME_LINES_BELOW, + }); + const lines = printed.split(/\r?\n/); + if (loc.end.line - loc.start.line < CODEFRAME_MAX_LINES) { + return printed; + } + const pipeIndex = lines[0].indexOf('|'); + return [ + ...lines.slice(0, CODEFRAME_LINES_ABOVE + CODEFRAME_ABBREVIATED_SOURCE_LINES), + ' '.repeat(pipeIndex) + '…', + ...lines.slice(-(CODEFRAME_LINES_BELOW + CODEFRAME_ABBREVIATED_SOURCE_LINES)), + ].join('\n'); +} +function printErrorSummary(category, message) { + let heading; + switch (category) { + case ErrorCategory.CapitalizedCalls: + case ErrorCategory.Config: + case ErrorCategory.EffectDerivationsOfState: + case ErrorCategory.EffectSetState: + case ErrorCategory.ErrorBoundaries: + case ErrorCategory.FBT: + case ErrorCategory.Gating: + case ErrorCategory.Globals: + case ErrorCategory.Hooks: + case ErrorCategory.Immutability: + case ErrorCategory.Purity: + case ErrorCategory.Refs: + case ErrorCategory.RenderSetState: + case ErrorCategory.StaticComponents: + case ErrorCategory.Suppression: + case ErrorCategory.Syntax: + case ErrorCategory.UseMemo: + case ErrorCategory.VoidUseMemo: + case ErrorCategory.MemoDependencies: + case ErrorCategory.EffectExhaustiveDependencies: { + heading = 'Error'; + break; + } + case ErrorCategory.EffectDependencies: + case ErrorCategory.IncompatibleLibrary: + case ErrorCategory.PreserveManualMemo: + case ErrorCategory.UnsupportedSyntax: { + heading = 'Compilation Skipped'; + break; + } + case ErrorCategory.Invariant: { + heading = 'Invariant'; + break; + } + case ErrorCategory.Todo: { + heading = 'Todo'; + break; + } + default: { + assertExhaustive$1(category, `Unhandled category '${category}'`); + } + } + return `${heading}: ${message}`; +} +var ErrorCategory; +(function (ErrorCategory) { + ErrorCategory["Hooks"] = "Hooks"; + ErrorCategory["CapitalizedCalls"] = "CapitalizedCalls"; + ErrorCategory["StaticComponents"] = "StaticComponents"; + ErrorCategory["UseMemo"] = "UseMemo"; + ErrorCategory["VoidUseMemo"] = "VoidUseMemo"; + ErrorCategory["PreserveManualMemo"] = "PreserveManualMemo"; + ErrorCategory["MemoDependencies"] = "MemoDependencies"; + ErrorCategory["IncompatibleLibrary"] = "IncompatibleLibrary"; + ErrorCategory["Immutability"] = "Immutability"; + ErrorCategory["Globals"] = "Globals"; + ErrorCategory["Refs"] = "Refs"; + ErrorCategory["EffectDependencies"] = "EffectDependencies"; + ErrorCategory["EffectExhaustiveDependencies"] = "EffectExhaustiveDependencies"; + ErrorCategory["EffectSetState"] = "EffectSetState"; + ErrorCategory["EffectDerivationsOfState"] = "EffectDerivationsOfState"; + ErrorCategory["ErrorBoundaries"] = "ErrorBoundaries"; + ErrorCategory["Purity"] = "Purity"; + ErrorCategory["RenderSetState"] = "RenderSetState"; + ErrorCategory["Invariant"] = "Invariant"; + ErrorCategory["Todo"] = "Todo"; + ErrorCategory["Syntax"] = "Syntax"; + ErrorCategory["UnsupportedSyntax"] = "UnsupportedSyntax"; + ErrorCategory["Config"] = "Config"; + ErrorCategory["Gating"] = "Gating"; + ErrorCategory["Suppression"] = "Suppression"; + ErrorCategory["FBT"] = "FBT"; +})(ErrorCategory || (ErrorCategory = {})); +var LintRulePreset; +(function (LintRulePreset) { + LintRulePreset["Recommended"] = "recommended"; + LintRulePreset["RecommendedLatest"] = "recommended-latest"; + LintRulePreset["Off"] = "off"; +})(LintRulePreset || (LintRulePreset = {})); +const RULE_NAME_PATTERN = /^[a-z]+(-[a-z]+)*$/; +function getRuleForCategory(category) { + const rule = getRuleForCategoryImpl(category); + invariant(RULE_NAME_PATTERN.test(rule.name), `Invalid rule name, got '${rule.name}' but rules must match ${RULE_NAME_PATTERN.toString()}`); + return rule; +} +function getRuleForCategoryImpl(category) { + switch (category) { + case ErrorCategory.CapitalizedCalls: { + return { + category, + severity: ErrorSeverity.Error, + name: 'capitalized-calls', + description: 'Validates against calling capitalized functions/methods instead of using JSX', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.Config: { + return { + category, + severity: ErrorSeverity.Error, + name: 'config', + description: 'Validates the compiler configuration options', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.EffectDependencies: { + return { + category, + severity: ErrorSeverity.Error, + name: 'memoized-effect-dependencies', + description: 'Validates that effect dependencies are memoized', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.EffectExhaustiveDependencies: { + return { + category, + severity: ErrorSeverity.Error, + name: 'exhaustive-effect-dependencies', + description: 'Validates that effect dependencies are exhaustive and without extraneous values', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.EffectDerivationsOfState: { + return { + category, + severity: ErrorSeverity.Error, + name: 'no-deriving-state-in-effects', + description: 'Validates against deriving values from state in an effect', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.EffectSetState: { + return { + category, + severity: ErrorSeverity.Error, + name: 'set-state-in-effect', + description: 'Validates against calling setState synchronously in an effect. ' + + 'This can indicate non-local derived data, a derived event pattern, or ' + + 'improper external data synchronization.', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.ErrorBoundaries: { + return { + category, + severity: ErrorSeverity.Error, + name: 'error-boundaries', + description: 'Validates usage of error boundaries instead of try/catch for errors in child components', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.FBT: { + return { + category, + severity: ErrorSeverity.Error, + name: 'fbt', + description: 'Validates usage of fbt', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.Gating: { + return { + category, + severity: ErrorSeverity.Error, + name: 'gating', + description: 'Validates configuration of [gating mode](https://react.dev/reference/react-compiler/gating)', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Globals: { + return { + category, + severity: ErrorSeverity.Error, + name: 'globals', + description: 'Validates against assignment/mutation of globals during render, part of ensuring that ' + + '[side effects must render outside of render](https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render)', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Hooks: { + return { + category, + severity: ErrorSeverity.Error, + name: 'hooks', + description: 'Validates the rules of hooks', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.Immutability: { + return { + category, + severity: ErrorSeverity.Error, + name: 'immutability', + description: 'Validates against mutating props, state, and other values that [are immutable](https://react.dev/reference/rules/components-and-hooks-must-be-pure#props-and-state-are-immutable)', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Invariant: { + return { + category, + severity: ErrorSeverity.Error, + name: 'invariant', + description: 'Internal invariants', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.PreserveManualMemo: { + return { + category, + severity: ErrorSeverity.Error, + name: 'preserve-manual-memoization', + description: 'Validates that existing manual memoized is preserved by the compiler. ' + + 'React Compiler will only compile components and hooks if its inference ' + + '[matches or exceeds the existing manual memoization](https://react.dev/learn/react-compiler/introduction#what-should-i-do-about-usememo-usecallback-and-reactmemo)', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Purity: { + return { + category, + severity: ErrorSeverity.Error, + name: 'purity', + description: 'Validates that [components/hooks are pure](https://react.dev/reference/rules/components-and-hooks-must-be-pure) by checking that they do not call known-impure functions', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Refs: { + return { + category, + severity: ErrorSeverity.Error, + name: 'refs', + description: 'Validates correct usage of refs, not reading/writing during render. See the "pitfalls" section in [`useRef()` usage](https://react.dev/reference/react/useRef#usage)', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.RenderSetState: { + return { + category, + severity: ErrorSeverity.Error, + name: 'set-state-in-render', + description: 'Validates against setting state during render, which can trigger additional renders and potential infinite render loops', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.StaticComponents: { + return { + category, + severity: ErrorSeverity.Error, + name: 'static-components', + description: 'Validates that components are static, not recreated every render. Components that are recreated dynamically can reset state and trigger excessive re-rendering', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Suppression: { + return { + category, + severity: ErrorSeverity.Error, + name: 'rule-suppression', + description: 'Validates against suppression of other rules', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.Syntax: { + return { + category, + severity: ErrorSeverity.Error, + name: 'syntax', + description: 'Validates against invalid syntax', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.Todo: { + return { + category, + severity: ErrorSeverity.Hint, + name: 'todo', + description: 'Unimplemented features', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.UnsupportedSyntax: { + return { + category, + severity: ErrorSeverity.Warning, + name: 'unsupported-syntax', + description: 'Validates against syntax that we do not plan to support in React Compiler', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.UseMemo: { + return { + category, + severity: ErrorSeverity.Error, + name: 'use-memo', + description: 'Validates usage of the useMemo() hook against common mistakes. See [`useMemo()` docs](https://react.dev/reference/react/useMemo) for more information.', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.VoidUseMemo: { + return { + category, + severity: ErrorSeverity.Error, + name: 'void-use-memo', + description: 'Validates that useMemos always return a value and that the result of the useMemo is used by the component/hook. See [`useMemo()` docs](https://react.dev/reference/react/useMemo) for more information.', + preset: LintRulePreset.RecommendedLatest, + }; + } + case ErrorCategory.MemoDependencies: { + return { + category, + severity: ErrorSeverity.Error, + name: 'memo-dependencies', + description: 'Validates that useMemo() and useCallback() specify comprehensive dependencies without extraneous values. See [`useMemo()` docs](https://react.dev/reference/react/useMemo) for more information.', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.IncompatibleLibrary: { + return { + category, + severity: ErrorSeverity.Warning, + name: 'incompatible-library', + description: 'Validates against usage of libraries which are incompatible with memoization (manual or automatic)', + preset: LintRulePreset.Recommended, + }; + } + default: { + assertExhaustive$1(category, `Unsupported category ${category}`); + } + } +} +const LintRules = Object.keys(ErrorCategory).map(category => getRuleForCategory(category)); + +function makeTypeId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected instruction id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +let typeCounter = 0; +function makeType() { + return { + kind: 'Type', + id: makeTypeId(typeCounter++), + }; +} +function typeEquals(tA, tB) { + if (tA.kind !== tB.kind) + return false; + return (typeVarEquals(tA, tB) || + funcTypeEquals(tA, tB) || + objectTypeEquals(tA, tB) || + primitiveTypeEquals(tA, tB) || + polyTypeEquals(tA, tB) || + phiTypeEquals(tA, tB) || + propTypeEquals(tA, tB) || + objectMethodTypeEquals(tA, tB)); +} +function typeVarEquals(tA, tB) { + if (tA.kind === 'Type' && tB.kind === 'Type') { + return tA.id === tB.id; + } + return false; +} +function typeKindCheck(tA, tb, type) { + return tA.kind === type && tb.kind === type; +} +function objectMethodTypeEquals(tA, tB) { + return typeKindCheck(tA, tB, 'ObjectMethod'); +} +function propTypeEquals(tA, tB) { + if (tA.kind === 'Property' && tB.kind === 'Property') { + if (!typeEquals(tA.objectType, tB.objectType)) { + return false; + } + return (tA.propertyName === tB.propertyName && tA.objectName === tB.objectName); + } + return false; +} +function primitiveTypeEquals(tA, tB) { + return typeKindCheck(tA, tB, 'Primitive'); +} +function polyTypeEquals(tA, tB) { + return typeKindCheck(tA, tB, 'Poly'); +} +function objectTypeEquals(tA, tB) { + if (tA.kind === 'Object' && tB.kind == 'Object') { + return tA.shapeId === tB.shapeId; + } + return false; +} +function funcTypeEquals(tA, tB) { + if (tA.kind !== 'Function' || tB.kind !== 'Function') { + return false; + } + return typeEquals(tA.return, tB.return); +} +function phiTypeEquals(tA, tB) { + if (tA.kind === 'Phi' && tB.kind === 'Phi') { + if (tA.operands.length !== tB.operands.length) { + return false; + } + let operands = new Set(tA.operands); + for (let i = 0; i < tB.operands.length; i++) { + if (!operands.has(tB.operands[i])) { + return false; + } + } + } + return false; +} + +const RESERVED_WORDS = new Set([ + 'break', + 'case', + 'catch', + 'class', + 'const', + 'continue', + 'debugger', + 'default', + 'delete', + 'do', + 'else', + 'enum', + 'export', + 'extends', + 'false', + 'finally', + 'for', + 'function', + 'if', + 'import', + 'in', + 'instanceof', + 'new', + 'null', + 'return', + 'super', + 'switch', + 'this', + 'throw', + 'true', + 'try', + 'typeof', + 'var', + 'void', + 'while', + 'with', +]); +const STRICT_MODE_RESERVED_WORDS = new Set([ + 'let', + 'static', + 'implements', + 'interface', + 'package', + 'private', + 'protected', + 'public', +]); +const STRICT_MODE_RESTRICTED_WORDS = new Set(['eval', 'arguments']); +function isReservedWord(identifierName) { + return (RESERVED_WORDS.has(identifierName) || + STRICT_MODE_RESERVED_WORDS.has(identifierName) || + STRICT_MODE_RESTRICTED_WORDS.has(identifierName)); +} + +const GeneratedSource = Symbol(); +function isStatementBlockKind(kind) { + return kind === 'block' || kind === 'catch'; +} +var GotoVariant; +(function (GotoVariant) { + GotoVariant["Break"] = "Break"; + GotoVariant["Continue"] = "Continue"; + GotoVariant["Try"] = "Try"; +})(GotoVariant || (GotoVariant = {})); +var InstructionKind; +(function (InstructionKind) { + InstructionKind["Const"] = "Const"; + InstructionKind["Let"] = "Let"; + InstructionKind["Reassign"] = "Reassign"; + InstructionKind["Catch"] = "Catch"; + InstructionKind["HoistedConst"] = "HoistedConst"; + InstructionKind["HoistedLet"] = "HoistedLet"; + InstructionKind["HoistedFunction"] = "HoistedFunction"; + InstructionKind["Function"] = "Function"; +})(InstructionKind || (InstructionKind = {})); +function convertHoistedLValueKind(kind) { + switch (kind) { + case InstructionKind.HoistedLet: + return InstructionKind.Let; + case InstructionKind.HoistedConst: + return InstructionKind.Const; + case InstructionKind.HoistedFunction: + return InstructionKind.Function; + case InstructionKind.Let: + case InstructionKind.Const: + case InstructionKind.Function: + case InstructionKind.Reassign: + case InstructionKind.Catch: + return null; + default: + assertExhaustive$1(kind, 'Unexpected lvalue kind'); + } +} +function makeTemporaryIdentifier(id, loc) { + return { + id, + name: null, + declarationId: makeDeclarationId(id), + mutableRange: { start: makeInstructionId(0), end: makeInstructionId(0) }, + scope: null, + type: makeType(), + loc, + }; +} +function validateIdentifierName(name) { + if (isReservedWord(name)) { + const error = new CompilerError(); + error.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Syntax, + reason: 'Expected a non-reserved identifier name', + description: `\`${name}\` is a reserved word in JavaScript and cannot be used as an identifier name`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc: GeneratedSource, + message: 'reserved word', + })); + return Err(error); + } + else if (!libExports$1.isValidIdentifier(name)) { + const error = new CompilerError(); + error.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Syntax, + reason: `Expected a valid identifier name`, + description: `\`${name}\` is not a valid JavaScript identifier`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc: GeneratedSource, + message: 'reserved word', + })); + } + return Ok({ + kind: 'named', + value: name, + }); +} +function makeIdentifierName(name) { + return validateIdentifierName(name).unwrap(); +} +function promoteTemporary(identifier) { + CompilerError.invariant(identifier.name === null, { + reason: `Expected a temporary (unnamed) identifier`, + description: `Identifier already has a name, \`${identifier.name}\``, + loc: GeneratedSource, + }); + identifier.name = { + kind: 'promoted', + value: `#t${identifier.declarationId}`, + }; +} +function isPromotedTemporary(name) { + return name.startsWith('#t'); +} +function promoteTemporaryJsxTag(identifier) { + CompilerError.invariant(identifier.name === null, { + reason: `Expected a temporary (unnamed) identifier`, + description: `Identifier already has a name, \`${identifier.name}\``, + loc: GeneratedSource, + }); + identifier.name = { + kind: 'promoted', + value: `#T${identifier.declarationId}`, + }; +} +function isPromotedJsxTemporary(name) { + return name.startsWith('#T'); +} +var ValueReason; +(function (ValueReason) { + ValueReason["Global"] = "global"; + ValueReason["JsxCaptured"] = "jsx-captured"; + ValueReason["HookCaptured"] = "hook-captured"; + ValueReason["HookReturn"] = "hook-return"; + ValueReason["Effect"] = "effect"; + ValueReason["KnownReturnSignature"] = "known-return-signature"; + ValueReason["Context"] = "context"; + ValueReason["State"] = "state"; + ValueReason["ReducerState"] = "reducer-state"; + ValueReason["ReactiveFunctionArgument"] = "reactive-function-argument"; + ValueReason["Other"] = "other"; +})(ValueReason || (ValueReason = {})); +var ValueKind; +(function (ValueKind) { + ValueKind["MaybeFrozen"] = "maybefrozen"; + ValueKind["Frozen"] = "frozen"; + ValueKind["Primitive"] = "primitive"; + ValueKind["Global"] = "global"; + ValueKind["Mutable"] = "mutable"; + ValueKind["Context"] = "context"; +})(ValueKind || (ValueKind = {})); +const ValueKindSchema = v4.z.enum([ + ValueKind.MaybeFrozen, + ValueKind.Frozen, + ValueKind.Primitive, + ValueKind.Global, + ValueKind.Mutable, + ValueKind.Context, +]); +const ValueReasonSchema = v4.z.enum([ + ValueReason.Context, + ValueReason.Effect, + ValueReason.Global, + ValueReason.HookCaptured, + ValueReason.HookReturn, + ValueReason.JsxCaptured, + ValueReason.KnownReturnSignature, + ValueReason.Other, + ValueReason.ReactiveFunctionArgument, + ValueReason.ReducerState, + ValueReason.State, +]); +var Effect; +(function (Effect) { + Effect["Unknown"] = ""; + Effect["Freeze"] = "freeze"; + Effect["Read"] = "read"; + Effect["Capture"] = "capture"; + Effect["ConditionallyMutateIterator"] = "mutate-iterator?"; + Effect["ConditionallyMutate"] = "mutate?"; + Effect["Mutate"] = "mutate"; + Effect["Store"] = "store"; +})(Effect || (Effect = {})); +const EffectSchema = v4.z.enum([ + Effect.Read, + Effect.Mutate, + Effect.ConditionallyMutate, + Effect.ConditionallyMutateIterator, + Effect.Capture, + Effect.Store, + Effect.Freeze, +]); +function isMutableEffect(effect, location) { + switch (effect) { + case Effect.Capture: + case Effect.Store: + case Effect.ConditionallyMutate: + case Effect.ConditionallyMutateIterator: + case Effect.Mutate: { + return true; + } + case Effect.Unknown: { + CompilerError.invariant(false, { + reason: 'Unexpected unknown effect', + loc: location, + }); + } + case Effect.Read: + case Effect.Freeze: { + return false; + } + default: { + assertExhaustive$1(effect, `Unexpected effect \`${effect}\``); + } + } +} +function makePropertyLiteral(value) { + return value; +} +function areEqualPaths(a, b) { + return (a.length === b.length && + a.every((item, ix) => item.property === b[ix].property && item.optional === b[ix].optional)); +} +function isSubPath(subpath, path) { + return (subpath.length <= path.length && + subpath.every((item, ix) => item.property === path[ix].property && + item.optional === path[ix].optional)); +} +function isSubPathIgnoringOptionals(subpath, path) { + return (subpath.length <= path.length && + subpath.every((item, ix) => item.property === path[ix].property)); +} +function getPlaceScope(id, place) { + const scope = place.identifier.scope; + if (scope !== null && isScopeActive(scope, id)) { + return scope; + } + return null; +} +function isScopeActive(scope, id) { + return id >= scope.range.start && id < scope.range.end; +} +function makeBlockId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected block id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function makeScopeId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected block id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function makeIdentifierId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected identifier id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function makeDeclarationId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected declaration id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function makeInstructionId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected instruction id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function isObjectMethodType(id) { + return id.type.kind == 'ObjectMethod'; +} +function isPrimitiveType(id) { + return id.type.kind === 'Primitive'; +} +function isPlainObjectType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInObject'; +} +function isArrayType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInArray'; +} +function isMapType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInMap'; +} +function isSetType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInSet'; +} +function isPropsType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInProps'; +} +function isRefValueType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInRefValue'; +} +function isUseRefType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInUseRefId'; +} +function isUseStateType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInUseState'; +} +function isJsxType(type) { + return type.kind === 'Object' && type.shapeId === 'BuiltInJsx'; +} +function isRefOrRefValue(id) { + return isUseRefType(id) || isRefValueType(id); +} +function isRefOrRefLikeMutableType(type) { + return (type.kind === 'Object' && + (type.shapeId === 'BuiltInUseRefId' || + type.shapeId == 'ReanimatedSharedValueId')); +} +function isSetStateType(id) { + return id.type.kind === 'Function' && id.type.shapeId === 'BuiltInSetState'; +} +function isUseActionStateType(id) { + return (id.type.kind === 'Object' && id.type.shapeId === 'BuiltInUseActionState'); +} +function isStartTransitionType(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInStartTransition'); +} +function isUseOptimisticType(id) { + return (id.type.kind === 'Object' && id.type.shapeId === 'BuiltInUseOptimistic'); +} +function isSetOptimisticType(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInSetOptimistic'); +} +function isSetActionStateType(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInSetActionState'); +} +function isUseReducerType(id) { + return id.type.kind === 'Function' && id.type.shapeId === 'BuiltInUseReducer'; +} +function isDispatcherType(id) { + return id.type.kind === 'Function' && id.type.shapeId === 'BuiltInDispatch'; +} +function isEffectEventFunctionType(id) { + return (id.type.kind === 'Function' && + id.type.shapeId === 'BuiltInEffectEventFunction'); +} +function isStableType(id) { + return (isSetStateType(id) || + isSetActionStateType(id) || + isDispatcherType(id) || + isUseRefType(id) || + isStartTransitionType(id) || + isSetOptimisticType(id)); +} +function isStableTypeContainer(id) { + const type_ = id.type; + if (type_.kind !== 'Object') { + return false; + } + return (isUseStateType(id) || + isUseActionStateType(id) || + isUseReducerType(id) || + isUseOptimisticType(id) || + type_.shapeId === 'BuiltInUseTransition'); +} +function evaluatesToStableTypeOrContainer(env, { value }) { + if (value.kind === 'CallExpression' || value.kind === 'MethodCall') { + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + const calleeHookKind = getHookKind(env, callee.identifier); + switch (calleeHookKind) { + case 'useState': + case 'useReducer': + case 'useActionState': + case 'useRef': + case 'useTransition': + case 'useOptimistic': + return true; + } + } + return false; +} +function isUseEffectHookType(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInUseEffectHook'); +} +function isUseLayoutEffectHookType(id) { + return (id.type.kind === 'Function' && + id.type.shapeId === 'BuiltInUseLayoutEffectHook'); +} +function isUseInsertionEffectHookType(id) { + return (id.type.kind === 'Function' && + id.type.shapeId === 'BuiltInUseInsertionEffectHook'); +} +function isUseEffectEventType(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInUseEffectEvent'); +} +function getHookKind(env, id) { + return getHookKindForType(env, id.type); +} +function isUseOperator(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInUseOperator'); +} +function getHookKindForType(env, type) { + var _a; + if (type.kind === 'Function') { + const signature = env.getFunctionSignature(type); + return (_a = signature === null || signature === void 0 ? void 0 : signature.hookKind) !== null && _a !== void 0 ? _a : null; + } + return null; +} + +function printReactiveScopeSummary(scope) { + const items = []; + items.push('scope'); + items.push(`@${scope.id}`); + items.push(`[${scope.range.start}:${scope.range.end}]`); + items.push(`dependencies=[${Array.from(scope.dependencies) + .map(dep => printDependency(dep)) + .join(', ')}]`); + items.push(`declarations=[${Array.from(scope.declarations) + .map(([, decl]) => printIdentifier(Object.assign(Object.assign({}, decl.identifier), { scope: decl.scope }))) + .join(', ')}]`); + items.push(`reassignments=[${Array.from(scope.reassignments).map(reassign => printIdentifier(reassign))}]`); + if (scope.earlyReturnValue !== null) { + items.push(`earlyReturn={id: ${printIdentifier(scope.earlyReturnValue.value)}, label: ${scope.earlyReturnValue.label}}}`); + } + return items.join(' '); +} +function printDependency(dependency) { + const identifier = printIdentifier(dependency.identifier) + + printType(dependency.identifier.type); + return `${identifier}${dependency.path.map(token => `${token.optional ? '?.' : '.'}${token.property}`).join('')}_${printSourceLocation(dependency.loc)}`; +} + +function printFunction(fn) { + const output = []; + let definition = ''; + if (fn.id !== null) { + definition += fn.id; + } + else { + definition += '<>'; + } + if (fn.nameHint != null) { + definition += ` ${fn.nameHint}`; + } + if (fn.params.length !== 0) { + definition += + '(' + + fn.params + .map(param => { + if (param.kind === 'Identifier') { + return printPlace(param); + } + else { + return `...${printPlace(param.place)}`; + } + }) + .join(', ') + + ')'; + } + else { + definition += '()'; + } + definition += `: ${printPlace(fn.returns)}`; + output.push(definition); + output.push(...fn.directives); + output.push(printHIR(fn.body)); + return output.join('\n'); +} +function printHIR(ir, options = null) { + var _a; + let output = []; + let indent = ' '.repeat((_a = options === null || options === void 0 ? void 0 : options.indent) !== null && _a !== void 0 ? _a : 0); + const push = (text, indent = ' ') => { + output.push(`${indent}${text}`); + }; + for (const [blockId, block] of ir.blocks) { + output.push(`bb${blockId} (${block.kind}):`); + if (block.preds.size > 0) { + const preds = ['predecessor blocks:']; + for (const pred of block.preds) { + preds.push(`bb${pred}`); + } + push(preds.join(' ')); + } + for (const phi of block.phis) { + push(printPhi(phi)); + } + for (const instr of block.instructions) { + push(printInstruction(instr)); + } + const terminal = printTerminal(block.terminal); + if (Array.isArray(terminal)) { + terminal.forEach(line => push(line)); + } + else { + push(terminal); + } + } + return output.map(line => indent + line).join('\n'); +} +function printInstruction(instr) { + const id = `[${instr.id}]`; + let value = printInstructionValue(instr.value); + if (instr.effects != null) { + value += `\n ${instr.effects.map(printAliasingEffect).join('\n ')}`; + } + if (instr.lvalue !== null) { + return `${id} ${printPlace(instr.lvalue)} = ${value}`; + } + else { + return `${id} ${value}`; + } +} +function printPhi(phi) { + const items = []; + items.push(printPlace(phi.place)); + items.push(printMutableRange(phi.place.identifier)); + items.push(printType(phi.place.identifier.type)); + items.push(': phi('); + const phis = []; + for (const [blockId, place] of phi.operands) { + phis.push(`bb${blockId}: ${printPlace(place)}`); + } + items.push(phis.join(', ')); + items.push(')'); + return items.join(''); +} +function printTerminal(terminal) { + let value; + switch (terminal.kind) { + case 'if': { + value = `[${terminal.id}] If (${printPlace(terminal.test)}) then:bb${terminal.consequent} else:bb${terminal.alternate}${terminal.fallthrough ? ` fallthrough=bb${terminal.fallthrough}` : ''}`; + break; + } + case 'branch': { + value = `[${terminal.id}] Branch (${printPlace(terminal.test)}) then:bb${terminal.consequent} else:bb${terminal.alternate} fallthrough:bb${terminal.fallthrough}`; + break; + } + case 'logical': { + value = `[${terminal.id}] Logical ${terminal.operator} test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'ternary': { + value = `[${terminal.id}] Ternary test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'optional': { + value = `[${terminal.id}] Optional (optional=${terminal.optional}) test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'throw': { + value = `[${terminal.id}] Throw ${printPlace(terminal.value)}`; + break; + } + case 'return': { + value = `[${terminal.id}] Return ${terminal.returnVariant}${terminal.value != null ? ' ' + printPlace(terminal.value) : ''}`; + if (terminal.effects != null) { + value += `\n ${terminal.effects.map(printAliasingEffect).join('\n ')}`; + } + break; + } + case 'goto': { + value = `[${terminal.id}] Goto${terminal.variant === GotoVariant.Continue ? '(Continue)' : ''} bb${terminal.block}`; + break; + } + case 'switch': { + const output = []; + output.push(`[${terminal.id}] Switch (${printPlace(terminal.test)})`); + terminal.cases.forEach(case_ => { + if (case_.test !== null) { + output.push(` Case ${printPlace(case_.test)}: bb${case_.block}`); + } + else { + output.push(` Default: bb${case_.block}`); + } + }); + if (terminal.fallthrough) { + output.push(` Fallthrough: bb${terminal.fallthrough}`); + } + value = output; + break; + } + case 'do-while': { + value = `[${terminal.id}] DoWhile loop=${`bb${terminal.loop}`} test=bb${terminal.test} fallthrough=${`bb${terminal.fallthrough}`}`; + break; + } + case 'while': { + value = `[${terminal.id}] While test=bb${terminal.test} loop=${terminal.loop !== null ? `bb${terminal.loop}` : ''} fallthrough=${terminal.fallthrough ? `bb${terminal.fallthrough}` : ''}`; + break; + } + case 'for': { + value = `[${terminal.id}] For init=bb${terminal.init} test=bb${terminal.test} loop=bb${terminal.loop} update=bb${terminal.update} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'for-of': { + value = `[${terminal.id}] ForOf init=bb${terminal.init} test=bb${terminal.test} loop=bb${terminal.loop} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'for-in': { + value = `[${terminal.id}] ForIn init=bb${terminal.init} loop=bb${terminal.loop} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'label': { + value = `[${terminal.id}] Label block=bb${terminal.block} fallthrough=${terminal.fallthrough ? `bb${terminal.fallthrough}` : ''}`; + break; + } + case 'sequence': { + value = `[${terminal.id}] Sequence block=bb${terminal.block} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'unreachable': { + value = `[${terminal.id}] Unreachable`; + break; + } + case 'unsupported': { + value = `[${terminal.id}] Unsupported`; + break; + } + case 'maybe-throw': { + const handlerStr = terminal.handler !== null ? `bb${terminal.handler}` : '(none)'; + value = `[${terminal.id}] MaybeThrow continuation=bb${terminal.continuation} handler=${handlerStr}`; + if (terminal.effects != null) { + value += `\n ${terminal.effects.map(printAliasingEffect).join('\n ')}`; + } + break; + } + case 'scope': { + value = `[${terminal.id}] Scope ${printReactiveScopeSummary(terminal.scope)} block=bb${terminal.block} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'pruned-scope': { + value = `[${terminal.id}] Scope ${printReactiveScopeSummary(terminal.scope)} block=bb${terminal.block} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'try': { + value = `[${terminal.id}] Try block=bb${terminal.block} handler=bb${terminal.handler}${terminal.handlerBinding !== null + ? ` handlerBinding=(${printPlace(terminal.handlerBinding)})` + : ''} fallthrough=${terminal.fallthrough != null ? `bb${terminal.fallthrough}` : ''}`; + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal}\``); + } + } + return value; +} +function printHole() { + return ''; +} +function printObjectPropertyKey(key) { + switch (key.kind) { + case 'identifier': + return key.name; + case 'string': + return `"${key.name}"`; + case 'computed': { + return `[${printPlace(key.name)}]`; + } + case 'number': { + return String(key.name); + } + } +} +function printInstructionValue(instrValue) { + var _a, _b, _c, _d, _e; + let value = ''; + switch (instrValue.kind) { + case 'ArrayExpression': { + value = `Array [${instrValue.elements + .map(element => { + if (element.kind === 'Identifier') { + return printPlace(element); + } + else if (element.kind === 'Hole') { + return printHole(); + } + else { + return `...${printPlace(element.place)}`; + } + }) + .join(', ')}]`; + break; + } + case 'ObjectExpression': { + const properties = []; + if (instrValue.properties !== null) { + for (const property of instrValue.properties) { + if (property.kind === 'ObjectProperty') { + properties.push(`${printObjectPropertyKey(property.key)}: ${printPlace(property.place)}`); + } + else { + properties.push(`...${printPlace(property.place)}`); + } + } + } + value = `Object { ${properties.join(', ')} }`; + break; + } + case 'UnaryExpression': { + value = `Unary ${printPlace(instrValue.value)}`; + break; + } + case 'BinaryExpression': { + value = `Binary ${printPlace(instrValue.left)} ${instrValue.operator} ${printPlace(instrValue.right)}`; + break; + } + case 'NewExpression': { + value = `New ${printPlace(instrValue.callee)}(${instrValue.args + .map(arg => printPattern(arg)) + .join(', ')})`; + break; + } + case 'CallExpression': { + value = `Call ${printPlace(instrValue.callee)}(${instrValue.args + .map(arg => printPattern(arg)) + .join(', ')})`; + break; + } + case 'MethodCall': { + value = `MethodCall ${printPlace(instrValue.receiver)}.${printPlace(instrValue.property)}(${instrValue.args.map(arg => printPattern(arg)).join(', ')})`; + break; + } + case 'JSXText': { + value = `JSXText ${JSON.stringify(instrValue.value)}`; + break; + } + case 'Primitive': { + if (instrValue.value === undefined) { + value = ''; + } + else { + value = JSON.stringify(instrValue.value); + } + break; + } + case 'TypeCastExpression': { + value = `TypeCast ${printPlace(instrValue.value)}: ${printType(instrValue.type)}`; + break; + } + case 'JsxExpression': { + const propItems = []; + for (const attribute of instrValue.props) { + if (attribute.kind === 'JsxAttribute') { + propItems.push(`${attribute.name}={${attribute.place !== null ? printPlace(attribute.place) : ''}}`); + } + else { + propItems.push(`...${printPlace(attribute.argument)}`); + } + } + const tag = instrValue.tag.kind === 'Identifier' + ? printPlace(instrValue.tag) + : instrValue.tag.name; + const props = propItems.length !== 0 ? ' ' + propItems.join(' ') : ''; + if (instrValue.children !== null) { + const children = instrValue.children.map(child => { + return `{${printPlace(child)}}`; + }); + value = `JSX <${tag}${props}${props.length > 0 ? ' ' : ''}>${children.join('')}`; + } + else { + value = `JSX <${tag}${props}${props.length > 0 ? ' ' : ''}/>`; + } + break; + } + case 'JsxFragment': { + value = `JsxFragment [${instrValue.children + .map(child => printPlace(child)) + .join(', ')}]`; + break; + } + case 'UnsupportedNode': { + value = `UnsupportedNode ${instrValue.node.type}`; + break; + } + case 'LoadLocal': { + value = `LoadLocal ${printPlace(instrValue.place)}`; + break; + } + case 'DeclareLocal': { + value = `DeclareLocal ${instrValue.lvalue.kind} ${printPlace(instrValue.lvalue.place)}`; + break; + } + case 'DeclareContext': { + value = `DeclareContext ${instrValue.lvalue.kind} ${printPlace(instrValue.lvalue.place)}`; + break; + } + case 'StoreLocal': { + value = `StoreLocal ${instrValue.lvalue.kind} ${printPlace(instrValue.lvalue.place)} = ${printPlace(instrValue.value)}`; + break; + } + case 'LoadContext': { + value = `LoadContext ${printPlace(instrValue.place)}`; + break; + } + case 'StoreContext': { + value = `StoreContext ${instrValue.lvalue.kind} ${printPlace(instrValue.lvalue.place)} = ${printPlace(instrValue.value)}`; + break; + } + case 'Destructure': { + value = `Destructure ${instrValue.lvalue.kind} ${printPattern(instrValue.lvalue.pattern)} = ${printPlace(instrValue.value)}`; + break; + } + case 'PropertyLoad': { + value = `PropertyLoad ${printPlace(instrValue.object)}.${instrValue.property}`; + break; + } + case 'PropertyStore': { + value = `PropertyStore ${printPlace(instrValue.object)}.${instrValue.property} = ${printPlace(instrValue.value)}`; + break; + } + case 'PropertyDelete': { + value = `PropertyDelete ${printPlace(instrValue.object)}.${instrValue.property}`; + break; + } + case 'ComputedLoad': { + value = `ComputedLoad ${printPlace(instrValue.object)}[${printPlace(instrValue.property)}]`; + break; + } + case 'ComputedStore': { + value = `ComputedStore ${printPlace(instrValue.object)}[${printPlace(instrValue.property)}] = ${printPlace(instrValue.value)}`; + break; + } + case 'ComputedDelete': { + value = `ComputedDelete ${printPlace(instrValue.object)}[${printPlace(instrValue.property)}]`; + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + const kind = instrValue.kind === 'FunctionExpression' ? 'Function' : 'ObjectMethod'; + const name = getFunctionName$2(instrValue, ''); + const fn = printFunction(instrValue.loweredFunc.func) + .split('\n') + .map(line => ` ${line}`) + .join('\n'); + const context = instrValue.loweredFunc.func.context + .map(dep => printPlace(dep)) + .join(','); + const aliasingEffects = (_c = (_b = (_a = instrValue.loweredFunc.func.aliasingEffects) === null || _a === void 0 ? void 0 : _a.map(printAliasingEffect)) === null || _b === void 0 ? void 0 : _b.join(', ')) !== null && _c !== void 0 ? _c : ''; + value = `${kind} ${name} @context[${context}] @aliasingEffects=[${aliasingEffects}]\n${fn}`; + break; + } + case 'TaggedTemplateExpression': { + value = `${printPlace(instrValue.tag)}\`${instrValue.value.raw}\``; + break; + } + case 'LogicalExpression': { + value = `Logical ${printInstructionValue(instrValue.left)} ${instrValue.operator} ${printInstructionValue(instrValue.right)}`; + break; + } + case 'SequenceExpression': { + value = [ + `Sequence`, + ...instrValue.instructions.map(instr => ` ${printInstruction(instr)}`), + ` ${printInstructionValue(instrValue.value)}`, + ].join('\n'); + break; + } + case 'ConditionalExpression': { + value = `Ternary ${printInstructionValue(instrValue.test)} ? ${printInstructionValue(instrValue.consequent)} : ${printInstructionValue(instrValue.alternate)}`; + break; + } + case 'TemplateLiteral': { + value = '`'; + CompilerError.invariant(instrValue.subexprs.length === instrValue.quasis.length - 1, { + reason: 'Bad assumption about quasi length.', + loc: instrValue.loc, + }); + for (let i = 0; i < instrValue.subexprs.length; i++) { + value += instrValue.quasis[i].raw; + value += `\${${printPlace(instrValue.subexprs[i])}}`; + } + value += instrValue.quasis.at(-1).raw + '`'; + break; + } + case 'LoadGlobal': { + switch (instrValue.binding.kind) { + case 'Global': { + value = `LoadGlobal(global) ${instrValue.binding.name}`; + break; + } + case 'ModuleLocal': { + value = `LoadGlobal(module) ${instrValue.binding.name}`; + break; + } + case 'ImportDefault': { + value = `LoadGlobal import ${instrValue.binding.name} from '${instrValue.binding.module}'`; + break; + } + case 'ImportNamespace': { + value = `LoadGlobal import * as ${instrValue.binding.name} from '${instrValue.binding.module}'`; + break; + } + case 'ImportSpecifier': { + if (instrValue.binding.imported !== instrValue.binding.name) { + value = `LoadGlobal import { ${instrValue.binding.imported} as ${instrValue.binding.name} } from '${instrValue.binding.module}'`; + } + else { + value = `LoadGlobal import { ${instrValue.binding.name} } from '${instrValue.binding.module}'`; + } + break; + } + default: { + assertExhaustive$1(instrValue.binding, `Unexpected binding kind \`${instrValue.binding.kind}\``); + } + } + break; + } + case 'StoreGlobal': { + value = `StoreGlobal ${instrValue.name} = ${printPlace(instrValue.value)}`; + break; + } + case 'OptionalExpression': { + value = `OptionalExpression ${printInstructionValue(instrValue.value)}`; + break; + } + case 'RegExpLiteral': { + value = `RegExp /${instrValue.pattern}/${instrValue.flags}`; + break; + } + case 'MetaProperty': { + value = `MetaProperty ${instrValue.meta}.${instrValue.property}`; + break; + } + case 'Await': { + value = `Await ${printPlace(instrValue.value)}`; + break; + } + case 'GetIterator': { + value = `GetIterator collection=${printPlace(instrValue.collection)}`; + break; + } + case 'IteratorNext': { + value = `IteratorNext iterator=${printPlace(instrValue.iterator)} collection=${printPlace(instrValue.collection)}`; + break; + } + case 'NextPropertyOf': { + value = `NextPropertyOf ${printPlace(instrValue.value)}`; + break; + } + case 'Debugger': { + value = `Debugger`; + break; + } + case 'PostfixUpdate': { + value = `PostfixUpdate ${printPlace(instrValue.lvalue)} = ${printPlace(instrValue.value)} ${instrValue.operation}`; + break; + } + case 'PrefixUpdate': { + value = `PrefixUpdate ${printPlace(instrValue.lvalue)} = ${instrValue.operation} ${printPlace(instrValue.value)}`; + break; + } + case 'StartMemoize': { + value = `StartMemoize deps=${(_e = (_d = instrValue.deps) === null || _d === void 0 ? void 0 : _d.map(dep => printManualMemoDependency$1(dep, false))) !== null && _e !== void 0 ? _e : '(none)'}`; + break; + } + case 'FinishMemoize': { + value = `FinishMemoize decl=${printPlace(instrValue.decl)}${instrValue.pruned ? ' pruned' : ''}`; + break; + } + default: { + assertExhaustive$1(instrValue, `Unexpected instruction kind '${instrValue.kind}'`); + } + } + return value; +} +function isMutable$1(range) { + return range.end > range.start + 1; +} +function printMutableRange(identifier) { + var _b, _c; + const range = (_c = (_b = identifier.scope) === null || _b === void 0 ? void 0 : _b.range) !== null && _c !== void 0 ? _c : identifier.mutableRange; + return isMutable$1(range) ? `[${range.start}:${range.end}]` : ''; +} +function printPattern(pattern) { + switch (pattern.kind) { + case 'ArrayPattern': { + return ('[ ' + + pattern.items + .map(item => { + if (item.kind === 'Hole') { + return ''; + } + return printPattern(item); + }) + .join(', ') + + ' ]'); + } + case 'ObjectPattern': { + return ('{ ' + + pattern.properties + .map(item => { + switch (item.kind) { + case 'ObjectProperty': { + return `${printObjectPropertyKey(item.key)}: ${printPattern(item.place)}`; + } + case 'Spread': { + return printPattern(item); + } + default: { + assertExhaustive$1(item, 'Unexpected object property kind'); + } + } + }) + .join(', ') + + ' }'); + } + case 'Spread': { + return `...${printPlace(pattern.place)}`; + } + case 'Identifier': { + return printPlace(pattern); + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } +} +function printPlace(place) { + const items = [ + place.effect, + ' ', + printIdentifier(place.identifier), + printMutableRange(place.identifier), + printType(place.identifier.type), + place.reactive ? '{reactive}' : null, + ]; + return items.filter(x => x != null).join(''); +} +function printIdentifier(id) { + return `${printName(id.name)}\$${id.id}${printScope(id.scope)}`; +} +function printName(name) { + if (name === null) { + return ''; + } + return name.value; +} +function printScope(scope) { + return `${scope !== null ? `_@${scope.id}` : ''}`; +} +function printManualMemoDependency$1(val, nameOnly) { + var _a; + let rootStr; + if (val.root.kind === 'Global') { + rootStr = val.root.identifierName; + } + else { + CompilerError.invariant(((_a = val.root.value.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named', { + reason: 'DepsValidation: expected named local variable in depslist', + loc: val.root.value.loc, + }); + rootStr = nameOnly + ? val.root.value.identifier.name.value + : printIdentifier(val.root.value.identifier); + } + return `${rootStr}${val.path.map(v => `${v.optional ? '?.' : '.'}${v.property}`).join('')}`; +} +function printType(type) { + if (type.kind === 'Type') + return ''; + if (type.kind === 'Object' && type.shapeId != null) { + return `:T${type.kind}<${type.shapeId}>`; + } + else if (type.kind === 'Function' && type.shapeId != null) { + const returnType = printType(type.return); + return `:T${type.kind}<${type.shapeId}>()${returnType !== '' ? `: ${returnType}` : ''}`; + } + else { + return `:T${type.kind}`; + } +} +function printSourceLocation(loc) { + if (typeof loc === 'symbol') { + return 'generated'; + } + else { + return `${loc.start.line}:${loc.start.column}:${loc.end.line}:${loc.end.column}`; + } +} +function getFunctionName$2(instrValue, defaultValue) { + var _a; + switch (instrValue.kind) { + case 'FunctionExpression': + return (_a = instrValue.name) !== null && _a !== void 0 ? _a : defaultValue; + case 'ObjectMethod': + return defaultValue; + } +} +function printAliasingEffect(effect) { + var _a; + switch (effect.kind) { + case 'Assign': { + return `Assign ${printPlaceForAliasEffect(effect.into)} = ${printPlaceForAliasEffect(effect.from)}`; + } + case 'Alias': { + return `Alias ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; + } + case 'MaybeAlias': { + return `MaybeAlias ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; + } + case 'Capture': { + return `Capture ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; + } + case 'ImmutableCapture': { + return `ImmutableCapture ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; + } + case 'Create': { + return `Create ${printPlaceForAliasEffect(effect.into)} = ${effect.value}`; + } + case 'CreateFrom': { + return `Create ${printPlaceForAliasEffect(effect.into)} = kindOf(${printPlaceForAliasEffect(effect.from)})`; + } + case 'CreateFunction': { + return `Function ${printPlaceForAliasEffect(effect.into)} = Function captures=[${effect.captures.map(printPlaceForAliasEffect).join(', ')}]`; + } + case 'Apply': { + const receiverCallee = effect.receiver.identifier.id === effect.function.identifier.id + ? printPlaceForAliasEffect(effect.receiver) + : `${printPlaceForAliasEffect(effect.receiver)}.${printPlaceForAliasEffect(effect.function)}`; + const args = effect.args + .map(arg => { + if (arg.kind === 'Identifier') { + return printPlaceForAliasEffect(arg); + } + else if (arg.kind === 'Hole') { + return ' '; + } + return `...${printPlaceForAliasEffect(arg.place)}`; + }) + .join(', '); + let signature = ''; + if (effect.signature != null) { + if (effect.signature.aliasing != null) { + signature = printAliasingSignature(effect.signature.aliasing); + } + else { + signature = JSON.stringify(effect.signature, null, 2); + } + } + return `Apply ${printPlaceForAliasEffect(effect.into)} = ${receiverCallee}(${args})${signature != '' ? '\n ' : ''}${signature}`; + } + case 'Freeze': { + return `Freeze ${printPlaceForAliasEffect(effect.value)} ${effect.reason}`; + } + case 'Mutate': + case 'MutateConditionally': + case 'MutateTransitive': + case 'MutateTransitiveConditionally': { + return `${effect.kind} ${printPlaceForAliasEffect(effect.value)}${effect.kind === 'Mutate' && ((_a = effect.reason) === null || _a === void 0 ? void 0 : _a.kind) === 'AssignCurrentProperty' ? ' (assign `.current`)' : ''}`; + } + case 'MutateFrozen': { + return `MutateFrozen ${printPlaceForAliasEffect(effect.place)} reason=${JSON.stringify(effect.error.reason)}`; + } + case 'MutateGlobal': { + return `MutateGlobal ${printPlaceForAliasEffect(effect.place)} reason=${JSON.stringify(effect.error.reason)}`; + } + case 'Impure': { + return `Impure ${printPlaceForAliasEffect(effect.place)} reason=${JSON.stringify(effect.error.reason)}`; + } + case 'Render': { + return `Render ${printPlaceForAliasEffect(effect.place)}`; + } + default: { + assertExhaustive$1(effect, `Unexpected kind '${effect.kind}'`); + } + } +} +function printPlaceForAliasEffect(place) { + return printIdentifier(place.identifier); +} +function printAliasingSignature(signature) { + const tokens = ['function ']; + if (signature.temporaries.length !== 0) { + tokens.push('<'); + tokens.push(signature.temporaries.map(temp => `$${temp.identifier.id}`).join(', ')); + tokens.push('>'); + } + tokens.push('('); + tokens.push('this=$' + String(signature.receiver)); + for (const param of signature.params) { + tokens.push(', $' + String(param)); + } + if (signature.rest != null) { + tokens.push(`, ...$${String(signature.rest)}`); + } + tokens.push('): '); + tokens.push('$' + String(signature.returns) + ':'); + for (const effect of signature.effects) { + tokens.push('\n ' + printAliasingEffect(effect)); + } + return tokens.join(''); +} + +var _ScopeBlockTraversal_activeScopes; +function* eachInstructionLValue(instr) { + if (instr.lvalue !== null) { + yield instr.lvalue; + } + yield* eachInstructionValueLValue(instr.value); +} +function* eachInstructionLValueWithKind(instr) { + switch (instr.value.kind) { + case 'DeclareContext': + case 'StoreContext': + case 'DeclareLocal': + case 'StoreLocal': { + yield [instr.value.lvalue.place, instr.value.lvalue.kind]; + break; + } + case 'Destructure': { + const kind = instr.value.lvalue.kind; + for (const place of eachPatternOperand(instr.value.lvalue.pattern)) { + yield [place, kind]; + } + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + yield [instr.value.lvalue, InstructionKind.Reassign]; + break; + } + } +} +function* eachInstructionValueLValue(value) { + switch (value.kind) { + case 'DeclareContext': + case 'StoreContext': + case 'DeclareLocal': + case 'StoreLocal': { + yield value.lvalue.place; + break; + } + case 'Destructure': { + yield* eachPatternOperand(value.lvalue.pattern); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + yield value.lvalue; + break; + } + } +} +function* eachInstructionOperand(instr) { + yield* eachInstructionValueOperand(instr.value); +} +function* eachInstructionValueOperand(instrValue) { + switch (instrValue.kind) { + case 'NewExpression': + case 'CallExpression': { + yield instrValue.callee; + yield* eachCallArgument(instrValue.args); + break; + } + case 'BinaryExpression': { + yield instrValue.left; + yield instrValue.right; + break; + } + case 'MethodCall': { + yield instrValue.receiver; + yield instrValue.property; + yield* eachCallArgument(instrValue.args); + break; + } + case 'DeclareContext': + case 'DeclareLocal': { + break; + } + case 'LoadLocal': + case 'LoadContext': { + yield instrValue.place; + break; + } + case 'StoreLocal': { + yield instrValue.value; + break; + } + case 'StoreContext': { + yield instrValue.lvalue.place; + yield instrValue.value; + break; + } + case 'StoreGlobal': { + yield instrValue.value; + break; + } + case 'Destructure': { + yield instrValue.value; + break; + } + case 'PropertyLoad': { + yield instrValue.object; + break; + } + case 'PropertyDelete': { + yield instrValue.object; + break; + } + case 'PropertyStore': { + yield instrValue.object; + yield instrValue.value; + break; + } + case 'ComputedLoad': { + yield instrValue.object; + yield instrValue.property; + break; + } + case 'ComputedDelete': { + yield instrValue.object; + yield instrValue.property; + break; + } + case 'ComputedStore': { + yield instrValue.object; + yield instrValue.property; + yield instrValue.value; + break; + } + case 'UnaryExpression': { + yield instrValue.value; + break; + } + case 'JsxExpression': { + if (instrValue.tag.kind === 'Identifier') { + yield instrValue.tag; + } + for (const attribute of instrValue.props) { + switch (attribute.kind) { + case 'JsxAttribute': { + yield attribute.place; + break; + } + case 'JsxSpreadAttribute': { + yield attribute.argument; + break; + } + default: { + assertExhaustive$1(attribute, `Unexpected attribute kind \`${attribute.kind}\``); + } + } + } + if (instrValue.children) { + yield* instrValue.children; + } + break; + } + case 'JsxFragment': { + yield* instrValue.children; + break; + } + case 'ObjectExpression': { + for (const property of instrValue.properties) { + if (property.kind === 'ObjectProperty' && + property.key.kind === 'computed') { + yield property.key.name; + } + yield property.place; + } + break; + } + case 'ArrayExpression': { + for (const element of instrValue.elements) { + if (element.kind === 'Identifier') { + yield element; + } + else if (element.kind === 'Spread') { + yield element.place; + } + } + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + yield* instrValue.loweredFunc.func.context; + break; + } + case 'TaggedTemplateExpression': { + yield instrValue.tag; + break; + } + case 'TypeCastExpression': { + yield instrValue.value; + break; + } + case 'TemplateLiteral': { + yield* instrValue.subexprs; + break; + } + case 'Await': { + yield instrValue.value; + break; + } + case 'GetIterator': { + yield instrValue.collection; + break; + } + case 'IteratorNext': { + yield instrValue.iterator; + yield instrValue.collection; + break; + } + case 'NextPropertyOf': { + yield instrValue.value; + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + yield instrValue.value; + break; + } + case 'StartMemoize': { + if (instrValue.deps != null) { + for (const dep of instrValue.deps) { + if (dep.root.kind === 'NamedLocal') { + yield dep.root.value; + } + } + } + break; + } + case 'FinishMemoize': { + yield instrValue.decl; + break; + } + case 'Debugger': + case 'RegExpLiteral': + case 'MetaProperty': + case 'LoadGlobal': + case 'UnsupportedNode': + case 'Primitive': + case 'JSXText': { + break; + } + default: { + assertExhaustive$1(instrValue, `Unexpected instruction kind \`${instrValue.kind}\``); + } + } +} +function* eachCallArgument(args) { + for (const arg of args) { + if (arg.kind === 'Identifier') { + yield arg; + } + else { + yield arg.place; + } + } +} +function doesPatternContainSpreadElement(pattern) { + switch (pattern.kind) { + case 'ArrayPattern': { + for (const item of pattern.items) { + if (item.kind === 'Spread') { + return true; + } + } + break; + } + case 'ObjectPattern': { + for (const property of pattern.properties) { + if (property.kind === 'Spread') { + return true; + } + } + break; + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } + return false; +} +function* eachPatternOperand(pattern) { + switch (pattern.kind) { + case 'ArrayPattern': { + for (const item of pattern.items) { + if (item.kind === 'Identifier') { + yield item; + } + else if (item.kind === 'Spread') { + yield item.place; + } + else if (item.kind === 'Hole') { + continue; + } + else { + assertExhaustive$1(item, `Unexpected item kind \`${item.kind}\``); + } + } + break; + } + case 'ObjectPattern': { + for (const property of pattern.properties) { + if (property.kind === 'ObjectProperty') { + yield property.place; + } + else if (property.kind === 'Spread') { + yield property.place; + } + else { + assertExhaustive$1(property, `Unexpected item kind \`${property.kind}\``); + } + } + break; + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } +} +function* eachPatternItem(pattern) { + switch (pattern.kind) { + case 'ArrayPattern': { + for (const item of pattern.items) { + if (item.kind === 'Identifier') { + yield item; + } + else if (item.kind === 'Spread') { + yield item; + } + else if (item.kind === 'Hole') { + continue; + } + else { + assertExhaustive$1(item, `Unexpected item kind \`${item.kind}\``); + } + } + break; + } + case 'ObjectPattern': { + for (const property of pattern.properties) { + if (property.kind === 'ObjectProperty') { + yield property.place; + } + else if (property.kind === 'Spread') { + yield property; + } + else { + assertExhaustive$1(property, `Unexpected item kind \`${property.kind}\``); + } + } + break; + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } +} +function mapInstructionLValues(instr, fn) { + switch (instr.value.kind) { + case 'DeclareLocal': + case 'StoreLocal': { + const lvalue = instr.value.lvalue; + lvalue.place = fn(lvalue.place); + break; + } + case 'Destructure': { + mapPatternOperands(instr.value.lvalue.pattern, fn); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + instr.value.lvalue = fn(instr.value.lvalue); + break; + } + } + if (instr.lvalue !== null) { + instr.lvalue = fn(instr.lvalue); + } +} +function mapInstructionOperands(instr, fn) { + mapInstructionValueOperands(instr.value, fn); +} +function mapInstructionValueOperands(instrValue, fn) { + switch (instrValue.kind) { + case 'BinaryExpression': { + instrValue.left = fn(instrValue.left); + instrValue.right = fn(instrValue.right); + break; + } + case 'PropertyLoad': { + instrValue.object = fn(instrValue.object); + break; + } + case 'PropertyDelete': { + instrValue.object = fn(instrValue.object); + break; + } + case 'PropertyStore': { + instrValue.object = fn(instrValue.object); + instrValue.value = fn(instrValue.value); + break; + } + case 'ComputedLoad': { + instrValue.object = fn(instrValue.object); + instrValue.property = fn(instrValue.property); + break; + } + case 'ComputedDelete': { + instrValue.object = fn(instrValue.object); + instrValue.property = fn(instrValue.property); + break; + } + case 'ComputedStore': { + instrValue.object = fn(instrValue.object); + instrValue.property = fn(instrValue.property); + instrValue.value = fn(instrValue.value); + break; + } + case 'DeclareContext': + case 'DeclareLocal': { + break; + } + case 'LoadLocal': + case 'LoadContext': { + instrValue.place = fn(instrValue.place); + break; + } + case 'StoreLocal': { + instrValue.value = fn(instrValue.value); + break; + } + case 'StoreContext': { + instrValue.lvalue.place = fn(instrValue.lvalue.place); + instrValue.value = fn(instrValue.value); + break; + } + case 'StoreGlobal': { + instrValue.value = fn(instrValue.value); + break; + } + case 'Destructure': { + instrValue.value = fn(instrValue.value); + break; + } + case 'NewExpression': + case 'CallExpression': { + instrValue.callee = fn(instrValue.callee); + instrValue.args = mapCallArguments(instrValue.args, fn); + break; + } + case 'MethodCall': { + instrValue.receiver = fn(instrValue.receiver); + instrValue.property = fn(instrValue.property); + instrValue.args = mapCallArguments(instrValue.args, fn); + break; + } + case 'UnaryExpression': { + instrValue.value = fn(instrValue.value); + break; + } + case 'JsxExpression': { + if (instrValue.tag.kind === 'Identifier') { + instrValue.tag = fn(instrValue.tag); + } + for (const attribute of instrValue.props) { + switch (attribute.kind) { + case 'JsxAttribute': { + attribute.place = fn(attribute.place); + break; + } + case 'JsxSpreadAttribute': { + attribute.argument = fn(attribute.argument); + break; + } + default: { + assertExhaustive$1(attribute, `Unexpected attribute kind \`${attribute.kind}\``); + } + } + } + if (instrValue.children) { + instrValue.children = instrValue.children.map(p => fn(p)); + } + break; + } + case 'ObjectExpression': { + for (const property of instrValue.properties) { + if (property.kind === 'ObjectProperty' && + property.key.kind === 'computed') { + property.key.name = fn(property.key.name); + } + property.place = fn(property.place); + } + break; + } + case 'ArrayExpression': { + instrValue.elements = instrValue.elements.map(element => { + if (element.kind === 'Identifier') { + return fn(element); + } + else if (element.kind === 'Spread') { + element.place = fn(element.place); + return element; + } + else { + return element; + } + }); + break; + } + case 'JsxFragment': { + instrValue.children = instrValue.children.map(e => fn(e)); + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + instrValue.loweredFunc.func.context = + instrValue.loweredFunc.func.context.map(d => fn(d)); + break; + } + case 'TaggedTemplateExpression': { + instrValue.tag = fn(instrValue.tag); + break; + } + case 'TypeCastExpression': { + instrValue.value = fn(instrValue.value); + break; + } + case 'TemplateLiteral': { + instrValue.subexprs = instrValue.subexprs.map(fn); + break; + } + case 'Await': { + instrValue.value = fn(instrValue.value); + break; + } + case 'GetIterator': { + instrValue.collection = fn(instrValue.collection); + break; + } + case 'IteratorNext': { + instrValue.iterator = fn(instrValue.iterator); + instrValue.collection = fn(instrValue.collection); + break; + } + case 'NextPropertyOf': { + instrValue.value = fn(instrValue.value); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + instrValue.value = fn(instrValue.value); + break; + } + case 'StartMemoize': { + if (instrValue.deps != null) { + for (const dep of instrValue.deps) { + if (dep.root.kind === 'NamedLocal') { + dep.root.value = fn(dep.root.value); + } + } + } + break; + } + case 'FinishMemoize': { + instrValue.decl = fn(instrValue.decl); + break; + } + case 'Debugger': + case 'RegExpLiteral': + case 'MetaProperty': + case 'LoadGlobal': + case 'UnsupportedNode': + case 'Primitive': + case 'JSXText': { + break; + } + default: { + assertExhaustive$1(instrValue, 'Unexpected instruction kind'); + } + } +} +function mapCallArguments(args, fn) { + return args.map(arg => { + if (arg.kind === 'Identifier') { + return fn(arg); + } + else { + arg.place = fn(arg.place); + return arg; + } + }); +} +function mapPatternOperands(pattern, fn) { + switch (pattern.kind) { + case 'ArrayPattern': { + pattern.items = pattern.items.map(item => { + if (item.kind === 'Identifier') { + return fn(item); + } + else if (item.kind === 'Spread') { + item.place = fn(item.place); + return item; + } + else { + return item; + } + }); + break; + } + case 'ObjectPattern': { + for (const property of pattern.properties) { + property.place = fn(property.place); + } + break; + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } +} +function mapTerminalSuccessors(terminal, fn) { + switch (terminal.kind) { + case 'goto': { + const target = fn(terminal.block); + return { + kind: 'goto', + block: target, + variant: terminal.variant, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'if': { + const consequent = fn(terminal.consequent); + const alternate = fn(terminal.alternate); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'if', + test: terminal.test, + consequent, + alternate, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'branch': { + const consequent = fn(terminal.consequent); + const alternate = fn(terminal.alternate); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'branch', + test: terminal.test, + consequent, + alternate, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'switch': { + const cases = terminal.cases.map(case_ => { + const target = fn(case_.block); + return { + test: case_.test, + block: target, + }; + }); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'switch', + test: terminal.test, + cases, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'logical': { + const test = fn(terminal.test); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'logical', + test, + fallthrough, + operator: terminal.operator, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'ternary': { + const test = fn(terminal.test); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'ternary', + test, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'optional': { + const test = fn(terminal.test); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'optional', + optional: terminal.optional, + test, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'return': { + return { + kind: 'return', + returnVariant: terminal.returnVariant, + loc: terminal.loc, + value: terminal.value, + id: makeInstructionId(0), + effects: terminal.effects, + }; + } + case 'throw': { + return terminal; + } + case 'do-while': { + const loop = fn(terminal.loop); + const test = fn(terminal.test); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'do-while', + loc: terminal.loc, + test, + loop, + fallthrough, + id: makeInstructionId(0), + }; + } + case 'while': { + const test = fn(terminal.test); + const loop = fn(terminal.loop); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'while', + loc: terminal.loc, + test, + loop, + fallthrough, + id: makeInstructionId(0), + }; + } + case 'for': { + const init = fn(terminal.init); + const test = fn(terminal.test); + const update = terminal.update !== null ? fn(terminal.update) : null; + const loop = fn(terminal.loop); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'for', + loc: terminal.loc, + init, + test, + update, + loop, + fallthrough, + id: makeInstructionId(0), + }; + } + case 'for-of': { + const init = fn(terminal.init); + const loop = fn(terminal.loop); + const test = fn(terminal.test); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'for-of', + loc: terminal.loc, + init, + test, + loop, + fallthrough, + id: makeInstructionId(0), + }; + } + case 'for-in': { + const init = fn(terminal.init); + const loop = fn(terminal.loop); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'for-in', + loc: terminal.loc, + init, + loop, + fallthrough, + id: makeInstructionId(0), + }; + } + case 'label': { + const block = fn(terminal.block); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'label', + block, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'sequence': { + const block = fn(terminal.block); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'sequence', + block, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'maybe-throw': { + const continuation = fn(terminal.continuation); + const handler = terminal.handler !== null ? fn(terminal.handler) : null; + return { + kind: 'maybe-throw', + continuation, + handler, + id: makeInstructionId(0), + loc: terminal.loc, + effects: terminal.effects, + }; + } + case 'try': { + const block = fn(terminal.block); + const handler = fn(terminal.handler); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'try', + block, + handlerBinding: terminal.handlerBinding, + handler, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'scope': + case 'pruned-scope': { + const block = fn(terminal.block); + const fallthrough = fn(terminal.fallthrough); + return { + kind: terminal.kind, + scope: terminal.scope, + block, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'unreachable': + case 'unsupported': { + return terminal; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +function terminalHasFallthrough(terminal) { + switch (terminal.kind) { + case 'maybe-throw': + case 'goto': + case 'return': + case 'throw': + case 'unreachable': + case 'unsupported': { + return false; + } + case 'branch': + case 'try': + case 'do-while': + case 'for-of': + case 'for-in': + case 'for': + case 'if': + case 'label': + case 'logical': + case 'optional': + case 'sequence': + case 'switch': + case 'ternary': + case 'while': + case 'scope': + case 'pruned-scope': { + return true; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +function terminalFallthrough(terminal) { + if (terminalHasFallthrough(terminal)) { + return terminal.fallthrough; + } + else { + return null; + } +} +function* eachTerminalSuccessor(terminal) { + switch (terminal.kind) { + case 'goto': { + yield terminal.block; + break; + } + case 'if': { + yield terminal.consequent; + yield terminal.alternate; + break; + } + case 'branch': { + yield terminal.consequent; + yield terminal.alternate; + break; + } + case 'switch': { + for (const case_ of terminal.cases) { + yield case_.block; + } + break; + } + case 'optional': + case 'ternary': + case 'logical': { + yield terminal.test; + break; + } + case 'return': { + break; + } + case 'throw': { + break; + } + case 'do-while': { + yield terminal.loop; + break; + } + case 'while': { + yield terminal.test; + break; + } + case 'for': { + yield terminal.init; + break; + } + case 'for-of': { + yield terminal.init; + break; + } + case 'for-in': { + yield terminal.init; + break; + } + case 'label': { + yield terminal.block; + break; + } + case 'sequence': { + yield terminal.block; + break; + } + case 'maybe-throw': { + yield terminal.continuation; + if (terminal.handler !== null) { + yield terminal.handler; + } + break; + } + case 'try': { + yield terminal.block; + break; + } + case 'scope': + case 'pruned-scope': { + yield terminal.block; + break; + } + case 'unreachable': + case 'unsupported': + break; + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +function mapTerminalOperands(terminal, fn) { + switch (terminal.kind) { + case 'if': { + terminal.test = fn(terminal.test); + break; + } + case 'branch': { + terminal.test = fn(terminal.test); + break; + } + case 'switch': { + terminal.test = fn(terminal.test); + for (const case_ of terminal.cases) { + if (case_.test === null) { + continue; + } + case_.test = fn(case_.test); + } + break; + } + case 'return': + case 'throw': { + terminal.value = fn(terminal.value); + break; + } + case 'try': { + if (terminal.handlerBinding !== null) { + terminal.handlerBinding = fn(terminal.handlerBinding); + } + else { + terminal.handlerBinding = null; + } + break; + } + case 'maybe-throw': + case 'sequence': + case 'label': + case 'optional': + case 'ternary': + case 'logical': + case 'do-while': + case 'while': + case 'for': + case 'for-of': + case 'for-in': + case 'goto': + case 'unreachable': + case 'unsupported': + case 'scope': + case 'pruned-scope': { + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +function* eachTerminalOperand(terminal) { + switch (terminal.kind) { + case 'if': { + yield terminal.test; + break; + } + case 'branch': { + yield terminal.test; + break; + } + case 'switch': { + yield terminal.test; + for (const case_ of terminal.cases) { + if (case_.test === null) { + continue; + } + yield case_.test; + } + break; + } + case 'return': + case 'throw': { + yield terminal.value; + break; + } + case 'try': { + if (terminal.handlerBinding !== null) { + yield terminal.handlerBinding; + } + break; + } + case 'maybe-throw': + case 'sequence': + case 'label': + case 'optional': + case 'ternary': + case 'logical': + case 'do-while': + case 'while': + case 'for': + case 'for-of': + case 'for-in': + case 'goto': + case 'unreachable': + case 'unsupported': + case 'scope': + case 'pruned-scope': { + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +class ScopeBlockTraversal { + constructor() { + _ScopeBlockTraversal_activeScopes.set(this, []); + this.blockInfos = new Map(); + } + recordScopes(block) { + var _a, _b; + const blockInfo = this.blockInfos.get(block.id); + if ((blockInfo === null || blockInfo === void 0 ? void 0 : blockInfo.kind) === 'begin') { + __classPrivateFieldGet(this, _ScopeBlockTraversal_activeScopes, "f").push(blockInfo.scope.id); + } + else if ((blockInfo === null || blockInfo === void 0 ? void 0 : blockInfo.kind) === 'end') { + const top = __classPrivateFieldGet(this, _ScopeBlockTraversal_activeScopes, "f").at(-1); + CompilerError.invariant(blockInfo.scope.id === top, { + reason: 'Expected traversed block fallthrough to match top-most active scope', + loc: (_b = (_a = block.instructions[0]) === null || _a === void 0 ? void 0 : _a.loc) !== null && _b !== void 0 ? _b : block.terminal.loc, + }); + __classPrivateFieldGet(this, _ScopeBlockTraversal_activeScopes, "f").pop(); + } + if (block.terminal.kind === 'scope' || + block.terminal.kind === 'pruned-scope') { + CompilerError.invariant(!this.blockInfos.has(block.terminal.block) && + !this.blockInfos.has(block.terminal.fallthrough), { + reason: 'Expected unique scope blocks and fallthroughs', + loc: block.terminal.loc, + }); + this.blockInfos.set(block.terminal.block, { + kind: 'begin', + scope: block.terminal.scope, + pruned: block.terminal.kind === 'pruned-scope', + fallthrough: block.terminal.fallthrough, + }); + this.blockInfos.set(block.terminal.fallthrough, { + kind: 'end', + scope: block.terminal.scope, + pruned: block.terminal.kind === 'pruned-scope', + }); + } + } + isScopeActive(scopeId) { + return __classPrivateFieldGet(this, _ScopeBlockTraversal_activeScopes, "f").indexOf(scopeId) !== -1; + } + get currentScope() { + var _a; + return (_a = __classPrivateFieldGet(this, _ScopeBlockTraversal_activeScopes, "f").at(-1)) !== null && _a !== void 0 ? _a : null; + } +} +_ScopeBlockTraversal_activeScopes = new WeakMap(); + +function assertConsistentIdentifiers(fn) { + const identifiers = new Map(); + const assignments = new Set(); + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + validate(identifiers, phi.place.identifier); + for (const [, operand] of phi.operands) { + validate(identifiers, operand.identifier); + } + } + for (const instr of block.instructions) { + CompilerError.invariant(instr.lvalue.identifier.name === null, { + reason: `Expected all lvalues to be temporaries`, + description: `Found named lvalue \`${instr.lvalue.identifier.name}\``, + loc: instr.lvalue.loc, + }); + CompilerError.invariant(!assignments.has(instr.lvalue.identifier.id), { + reason: `Expected lvalues to be assigned exactly once`, + description: `Found duplicate assignment of '${printPlace(instr.lvalue)}'`, + loc: instr.lvalue.loc, + }); + assignments.add(instr.lvalue.identifier.id); + for (const operand of eachInstructionLValue(instr)) { + validate(identifiers, operand.identifier, operand.loc); + } + for (const operand of eachInstructionValueOperand(instr.value)) { + validate(identifiers, operand.identifier, operand.loc); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + validate(identifiers, operand.identifier, operand.loc); + } + } +} +function validate(identifiers, identifier, loc = null) { + const previous = identifiers.get(identifier.id); + if (previous === undefined) { + identifiers.set(identifier.id, identifier); + } + else { + CompilerError.invariant(identifier === previous, { + reason: `Duplicate identifier object`, + description: `Found duplicate identifier object for id ${identifier.id}`, + loc: loc !== null && loc !== void 0 ? loc : GeneratedSource, + }); + } +} + +function assertTerminalSuccessorsExist(fn) { + for (const [, block] of fn.body.blocks) { + mapTerminalSuccessors(block.terminal, successor => { + var _a; + CompilerError.invariant(fn.body.blocks.has(successor), { + reason: `Terminal successor references unknown block`, + description: `Block bb${successor} does not exist for terminal '${printTerminal(block.terminal)}'`, + loc: (_a = block.terminal.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + return successor; + }); + } +} +function assertTerminalPredsExist(fn) { + for (const [, block] of fn.body.blocks) { + for (const pred of block.preds) { + const predBlock = fn.body.blocks.get(pred); + CompilerError.invariant(predBlock != null, { + reason: 'Expected predecessor block to exist', + description: `Block ${block.id} references non-existent ${pred}`, + loc: GeneratedSource, + }); + CompilerError.invariant([...eachTerminalSuccessor(predBlock.terminal)].includes(block.id), { + reason: 'Terminal successor does not reference correct predecessor', + description: `Block bb${block.id} has bb${predBlock.id} as a predecessor, but bb${predBlock.id}'s successors do not include bb${block.id}`, + loc: GeneratedSource, + }); + } + } +} + +function getScopes(fn) { + const scopes = new Set(); + function visitPlace(place) { + const scope = place.identifier.scope; + if (scope != null) { + if (scope.range.start !== scope.range.end) { + scopes.add(scope); + } + } + } + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + for (const operand of eachInstructionLValue(instr)) { + visitPlace(operand); + } + for (const operand of eachInstructionOperand(instr)) { + visitPlace(operand); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + visitPlace(operand); + } + } + return scopes; +} +function rangePreOrderComparator(a, b) { + const startDiff = a.start - b.start; + if (startDiff !== 0) + return startDiff; + return b.end - a.end; +} +function recursivelyTraverseItems(items, getRange, context, enter, exit) { + items.sort((a, b) => rangePreOrderComparator(getRange(a), getRange(b))); + let activeItems = []; + const ranges = items.map(getRange); + for (let i = 0; i < items.length; i++) { + const curr = items[i]; + const currRange = ranges[i]; + for (let i = activeItems.length - 1; i >= 0; i--) { + const maybeParent = activeItems[i]; + const maybeParentRange = getRange(maybeParent); + const disjoint = currRange.start >= maybeParentRange.end; + const nested = currRange.end <= maybeParentRange.end; + CompilerError.invariant(disjoint || nested, { + reason: 'Invalid nesting in program blocks or scopes', + description: `Items overlap but are not nested: ${maybeParentRange.start}:${maybeParentRange.end}(${currRange.start}:${currRange.end})`, + loc: GeneratedSource, + }); + if (disjoint) { + exit(maybeParent, context); + activeItems.length = i; + } + else { + break; + } + } + enter(curr, context); + activeItems.push(curr); + } + let curr = activeItems.pop(); + while (curr != null) { + exit(curr, context); + curr = activeItems.pop(); + } +} +const no_op = () => { }; +function assertValidBlockNesting(fn) { + var _a, _b; + const scopes = getScopes(fn); + const blocks = [...scopes].map(scope => (Object.assign({ kind: 'Scope', id: scope.id }, scope.range))); + for (const [, block] of fn.body.blocks) { + const fallthroughId = terminalFallthrough(block.terminal); + if (fallthroughId != null) { + const fallthrough = fn.body.blocks.get(fallthroughId); + const end = (_b = (_a = fallthrough.instructions[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : fallthrough.terminal.id; + blocks.push({ + kind: 'ProgramBlockSubtree', + id: block.id, + start: block.terminal.id, + end, + }); + } + } + recursivelyTraverseItems(blocks, block => block, null, no_op, no_op); +} + +function assertValidMutableRanges(fn) { + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + visit$1(phi.place, `phi for block bb${block.id}`); + for (const [pred, operand] of phi.operands) { + visit$1(operand, `phi predecessor bb${pred} for block bb${block.id}`); + } + } + for (const instr of block.instructions) { + for (const operand of eachInstructionLValue(instr)) { + visit$1(operand, `instruction [${instr.id}]`); + } + for (const operand of eachInstructionOperand(instr)) { + visit$1(operand, `instruction [${instr.id}]`); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + visit$1(operand, `terminal [${block.terminal.id}]`); + } + } +} +function visit$1(place, description) { + validateMutableRange(place, place.identifier.mutableRange, description); + if (place.identifier.scope !== null) { + validateMutableRange(place, place.identifier.scope.range, description); + } +} +function validateMutableRange(place, range, description) { + CompilerError.invariant((range.start === 0 && range.end === 0) || range.end > range.start, { + reason: `Invalid mutable range: [${range.start}:${range.end}]`, + description: `${printPlace(place)} in ${description}`, + loc: place.loc, + }); +} + +var _HIRBuilder_instances, _HIRBuilder_completed, _HIRBuilder_current, _HIRBuilder_entry, _HIRBuilder_scopes, _HIRBuilder_context, _HIRBuilder_bindings, _HIRBuilder_env, _HIRBuilder_exceptionHandlerStack, _HIRBuilder_resolveBabelBinding; +function newBlock(id, kind) { + return { id, kind, instructions: [] }; +} +class HIRBuilder { + get nextIdentifierId() { + return __classPrivateFieldGet(this, _HIRBuilder_env, "f").nextIdentifierId; + } + get context() { + return __classPrivateFieldGet(this, _HIRBuilder_context, "f"); + } + get bindings() { + return __classPrivateFieldGet(this, _HIRBuilder_bindings, "f"); + } + get environment() { + return __classPrivateFieldGet(this, _HIRBuilder_env, "f"); + } + constructor(env, options) { + var _a, _b, _c; + _HIRBuilder_instances.add(this); + _HIRBuilder_completed.set(this, new Map()); + _HIRBuilder_current.set(this, void 0); + _HIRBuilder_entry.set(this, void 0); + _HIRBuilder_scopes.set(this, []); + _HIRBuilder_context.set(this, void 0); + _HIRBuilder_bindings.set(this, void 0); + _HIRBuilder_env.set(this, void 0); + _HIRBuilder_exceptionHandlerStack.set(this, []); + this.fbtDepth = 0; + __classPrivateFieldSet(this, _HIRBuilder_env, env, "f"); + __classPrivateFieldSet(this, _HIRBuilder_bindings, (_a = options === null || options === void 0 ? void 0 : options.bindings) !== null && _a !== void 0 ? _a : new Map(), "f"); + __classPrivateFieldSet(this, _HIRBuilder_context, (_b = options === null || options === void 0 ? void 0 : options.context) !== null && _b !== void 0 ? _b : new Map(), "f"); + __classPrivateFieldSet(this, _HIRBuilder_entry, makeBlockId(env.nextBlockId), "f"); + __classPrivateFieldSet(this, _HIRBuilder_current, newBlock(__classPrivateFieldGet(this, _HIRBuilder_entry, "f"), (_c = options === null || options === void 0 ? void 0 : options.entryBlockKind) !== null && _c !== void 0 ? _c : 'block'), "f"); + } + recordError(error) { + __classPrivateFieldGet(this, _HIRBuilder_env, "f").recordError(error); + } + currentBlockKind() { + return __classPrivateFieldGet(this, _HIRBuilder_current, "f").kind; + } + push(instruction) { + __classPrivateFieldGet(this, _HIRBuilder_current, "f").instructions.push(instruction); + const exceptionHandler = __classPrivateFieldGet(this, _HIRBuilder_exceptionHandlerStack, "f").at(-1); + if (exceptionHandler !== undefined) { + const continuationBlock = this.reserve(this.currentBlockKind()); + this.terminateWithContinuation({ + kind: 'maybe-throw', + continuation: continuationBlock.id, + handler: exceptionHandler, + id: makeInstructionId(0), + loc: instruction.loc, + effects: null, + }, continuationBlock); + } + } + enterTryCatch(handler, fn) { + __classPrivateFieldGet(this, _HIRBuilder_exceptionHandlerStack, "f").push(handler); + fn(); + __classPrivateFieldGet(this, _HIRBuilder_exceptionHandlerStack, "f").pop(); + } + resolveThrowHandler() { + const handler = __classPrivateFieldGet(this, _HIRBuilder_exceptionHandlerStack, "f").at(-1); + return handler !== null && handler !== void 0 ? handler : null; + } + makeTemporary(loc) { + const id = this.nextIdentifierId; + return makeTemporaryIdentifier(id, loc); + } + resolveIdentifier(path) { + const originalName = path.node.name; + const babelBinding = __classPrivateFieldGet(this, _HIRBuilder_instances, "m", _HIRBuilder_resolveBabelBinding).call(this, path); + if (babelBinding == null) { + return { kind: 'Global', name: originalName }; + } + const outerBinding = __classPrivateFieldGet(this, _HIRBuilder_env, "f").parentFunction.scope.parent.getBinding(originalName); + if (babelBinding === outerBinding) { + const path = babelBinding.path; + if (path.isImportDefaultSpecifier()) { + const importDeclaration = path.parentPath; + return { + kind: 'ImportDefault', + name: originalName, + module: importDeclaration.node.source.value, + }; + } + else if (path.isImportSpecifier()) { + const importDeclaration = path.parentPath; + return { + kind: 'ImportSpecifier', + name: originalName, + module: importDeclaration.node.source.value, + imported: path.node.imported.type === 'Identifier' + ? path.node.imported.name + : path.node.imported.value, + }; + } + else if (path.isImportNamespaceSpecifier()) { + const importDeclaration = path.parentPath; + return { + kind: 'ImportNamespace', + name: originalName, + module: importDeclaration.node.source.value, + }; + } + else { + return { + kind: 'ModuleLocal', + name: originalName, + }; + } + } + const resolvedBinding = this.resolveBinding(babelBinding.identifier); + if (resolvedBinding.name && resolvedBinding.name.value !== originalName) { + babelBinding.scope.rename(originalName, resolvedBinding.name.value); + } + return { + kind: 'Identifier', + identifier: resolvedBinding, + bindingKind: babelBinding.kind, + }; + } + isContextIdentifier(path) { + const binding = __classPrivateFieldGet(this, _HIRBuilder_instances, "m", _HIRBuilder_resolveBabelBinding).call(this, path); + if (binding) { + const outerBinding = __classPrivateFieldGet(this, _HIRBuilder_env, "f").parentFunction.scope.parent.getBinding(path.node.name); + if (binding === outerBinding) { + return false; + } + return __classPrivateFieldGet(this, _HIRBuilder_env, "f").isContextIdentifier(binding.identifier); + } + else { + return false; + } + } + resolveBinding(node) { + var _a, _b, _c; + if (node.name === 'fbt') { + this.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Support local variables named `fbt`', + description: 'Local variables named `fbt` may conflict with the fbt plugin and are not yet supported', + loc: (_a = node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + suggestions: null, + })); + } + if (node.name === 'this') { + this.recordError(new CompilerErrorDetail({ + category: ErrorCategory.UnsupportedSyntax, + reason: '`this` is not supported syntax', + description: 'React Compiler does not support compiling functions that use `this`', + loc: (_b = node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + suggestions: null, + })); + } + const originalName = node.name; + let name = originalName; + let index = 0; + while (true) { + const mapping = __classPrivateFieldGet(this, _HIRBuilder_bindings, "f").get(name); + if (mapping === undefined) { + const id = this.nextIdentifierId; + const identifier = { + id, + declarationId: makeDeclarationId(id), + name: makeIdentifierName(name), + mutableRange: { + start: makeInstructionId(0), + end: makeInstructionId(0), + }, + scope: null, + type: makeType(), + loc: (_c = node.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + }; + __classPrivateFieldGet(this, _HIRBuilder_env, "f").programContext.addNewReference(name); + __classPrivateFieldGet(this, _HIRBuilder_bindings, "f").set(name, { node, identifier }); + return identifier; + } + else if (mapping.node === node) { + return mapping.identifier; + } + else { + name = `${originalName}_${index++}`; + } + } + } + build() { + var _a, _b; + let ir = { + blocks: __classPrivateFieldGet(this, _HIRBuilder_completed, "f"), + entry: __classPrivateFieldGet(this, _HIRBuilder_entry, "f"), + }; + const rpoBlocks = getReversePostorderedBlocks(ir); + for (const [id, block] of ir.blocks) { + if (!rpoBlocks.has(id) && + block.instructions.some(instr => instr.value.kind === 'FunctionExpression')) { + this.recordError(new CompilerErrorDetail({ + reason: `Support functions with unreachable code that may contain hoisted declarations`, + loc: (_b = (_a = block.instructions[0]) === null || _a === void 0 ? void 0 : _a.loc) !== null && _b !== void 0 ? _b : block.terminal.loc, + description: null, + suggestions: null, + category: ErrorCategory.Todo, + })); + } + } + ir.blocks = rpoBlocks; + removeUnreachableForUpdates(ir); + removeDeadDoWhileStatements(ir); + removeUnnecessaryTryCatch(ir); + markInstructionIds(ir); + markPredecessors(ir); + return ir; + } + terminate(terminal, nextBlockKind) { + const { id: blockId, kind, instructions } = __classPrivateFieldGet(this, _HIRBuilder_current, "f"); + __classPrivateFieldGet(this, _HIRBuilder_completed, "f").set(blockId, { + kind, + id: blockId, + instructions, + terminal, + preds: new Set(), + phis: new Set(), + }); + if (nextBlockKind) { + const nextId = __classPrivateFieldGet(this, _HIRBuilder_env, "f").nextBlockId; + __classPrivateFieldSet(this, _HIRBuilder_current, newBlock(nextId, nextBlockKind), "f"); + } + return blockId; + } + terminateWithContinuation(terminal, continuation) { + const { id: blockId, kind, instructions } = __classPrivateFieldGet(this, _HIRBuilder_current, "f"); + __classPrivateFieldGet(this, _HIRBuilder_completed, "f").set(blockId, { + kind: kind, + id: blockId, + instructions, + terminal: terminal, + preds: new Set(), + phis: new Set(), + }); + __classPrivateFieldSet(this, _HIRBuilder_current, continuation, "f"); + } + reserve(kind) { + return newBlock(makeBlockId(__classPrivateFieldGet(this, _HIRBuilder_env, "f").nextBlockId), kind); + } + complete(block, terminal) { + const { id: blockId, kind, instructions } = block; + __classPrivateFieldGet(this, _HIRBuilder_completed, "f").set(blockId, { + kind, + id: blockId, + instructions, + terminal, + preds: new Set(), + phis: new Set(), + }); + } + enterReserved(wip, fn) { + const current = __classPrivateFieldGet(this, _HIRBuilder_current, "f"); + __classPrivateFieldSet(this, _HIRBuilder_current, wip, "f"); + const terminal = fn(); + const { id: blockId, kind, instructions } = __classPrivateFieldGet(this, _HIRBuilder_current, "f"); + __classPrivateFieldGet(this, _HIRBuilder_completed, "f").set(blockId, { + kind, + id: blockId, + instructions, + terminal, + preds: new Set(), + phis: new Set(), + }); + __classPrivateFieldSet(this, _HIRBuilder_current, current, "f"); + } + enter(nextBlockKind, fn) { + const wip = this.reserve(nextBlockKind); + this.enterReserved(wip, () => { + return fn(wip.id); + }); + return wip.id; + } + label(label, breakBlock, fn) { + __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").push({ + kind: 'label', + breakBlock, + label, + }); + const value = fn(); + const last = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").pop(); + CompilerError.invariant(last != null && + last.kind === 'label' && + last.label === label && + last.breakBlock === breakBlock, { + reason: 'Mismatched label', + loc: GeneratedSource, + }); + return value; + } + switch(label, breakBlock, fn) { + __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").push({ + kind: 'switch', + breakBlock, + label, + }); + const value = fn(); + const last = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").pop(); + CompilerError.invariant(last != null && + last.kind === 'switch' && + last.label === label && + last.breakBlock === breakBlock, { + reason: 'Mismatched label', + loc: GeneratedSource, + }); + return value; + } + loop(label, continueBlock, breakBlock, fn) { + __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").push({ + kind: 'loop', + label, + continueBlock, + breakBlock, + }); + const value = fn(); + const last = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").pop(); + CompilerError.invariant(last != null && + last.kind === 'loop' && + last.label === label && + last.continueBlock === continueBlock && + last.breakBlock === breakBlock, { + reason: 'Mismatched loops', + loc: GeneratedSource, + }); + return value; + } + lookupBreak(label) { + for (let ii = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").length - 1; ii >= 0; ii--) { + const scope = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f")[ii]; + if ((label === null && + (scope.kind === 'loop' || scope.kind === 'switch')) || + label === scope.label) { + return scope.breakBlock; + } + } + CompilerError.invariant(false, { + reason: 'Expected a loop or switch to be in scope', + loc: GeneratedSource, + }); + } + lookupContinue(label) { + for (let ii = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").length - 1; ii >= 0; ii--) { + const scope = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f")[ii]; + if (scope.kind === 'loop') { + if (label === null || label === scope.label) { + return scope.continueBlock; + } + } + else if (label !== null && scope.label === label) { + CompilerError.invariant(false, { + reason: 'Continue may only refer to a labeled loop', + loc: GeneratedSource, + }); + } + } + CompilerError.invariant(false, { + reason: 'Expected a loop to be in scope', + loc: GeneratedSource, + }); + } +} +_HIRBuilder_completed = new WeakMap(), _HIRBuilder_current = new WeakMap(), _HIRBuilder_entry = new WeakMap(), _HIRBuilder_scopes = new WeakMap(), _HIRBuilder_context = new WeakMap(), _HIRBuilder_bindings = new WeakMap(), _HIRBuilder_env = new WeakMap(), _HIRBuilder_exceptionHandlerStack = new WeakMap(), _HIRBuilder_instances = new WeakSet(), _HIRBuilder_resolveBabelBinding = function _HIRBuilder_resolveBabelBinding(path) { + const originalName = path.node.name; + const binding = path.scope.getBinding(originalName); + if (binding == null) { + return null; + } + return binding; +}; +function removeUnreachableForUpdates(fn) { + for (const [, block] of fn.blocks) { + if (block.terminal.kind === 'for' && + block.terminal.update !== null && + !fn.blocks.has(block.terminal.update)) { + block.terminal.update = null; + } + } +} +function removeDeadDoWhileStatements(func) { + const visited = new Set(); + for (const [_, block] of func.blocks) { + visited.add(block.id); + } + for (const [_, block] of func.blocks) { + if (block.terminal.kind === 'do-while') { + if (!visited.has(block.terminal.test)) { + block.terminal = { + kind: 'goto', + block: block.terminal.loop, + variant: GotoVariant.Break, + id: block.terminal.id, + loc: block.terminal.loc, + }; + } + } + } +} +function reversePostorderBlocks(func) { + const rpoBlocks = getReversePostorderedBlocks(func); + func.blocks = rpoBlocks; +} +function getReversePostorderedBlocks(func) { + const visited = new Set(); + const used = new Set(); + const usedFallthroughs = new Set(); + const postorder = []; + function visit(blockId, isUsed) { + const wasUsed = used.has(blockId); + const wasVisited = visited.has(blockId); + visited.add(blockId); + if (isUsed) { + used.add(blockId); + } + if (wasVisited && (wasUsed || !isUsed)) { + return; + } + const block = func.blocks.get(blockId); + CompilerError.invariant(block != null, { + reason: '[HIRBuilder] Unexpected null block', + description: `expected block ${blockId} to exist`, + loc: GeneratedSource, + }); + const successors = [...eachTerminalSuccessor(block.terminal)].reverse(); + const fallthrough = terminalFallthrough(block.terminal); + if (fallthrough != null) { + if (isUsed) { + usedFallthroughs.add(fallthrough); + } + visit(fallthrough, false); + } + for (const successor of successors) { + visit(successor, isUsed); + } + if (!wasVisited) { + postorder.push(blockId); + } + } + visit(func.entry, true); + const blocks = new Map(); + for (const blockId of postorder.reverse()) { + const block = func.blocks.get(blockId); + if (used.has(blockId)) { + blocks.set(blockId, func.blocks.get(blockId)); + } + else if (usedFallthroughs.has(blockId)) { + blocks.set(blockId, Object.assign(Object.assign({}, block), { instructions: [], terminal: { + kind: 'unreachable', + id: block.terminal.id, + loc: block.terminal.loc, + } })); + } + } + return blocks; +} +function markInstructionIds(func) { + let id = 0; + const visited = new Set(); + for (const [_, block] of func.blocks) { + for (const instr of block.instructions) { + CompilerError.invariant(!visited.has(instr), { + reason: `${printInstruction(instr)} already visited!`, + loc: instr.loc, + }); + visited.add(instr); + instr.id = makeInstructionId(++id); + } + block.terminal.id = makeInstructionId(++id); + } +} +function markPredecessors(func) { + for (const [, block] of func.blocks) { + block.preds.clear(); + } + const visited = new Set(); + function visit(blockId, prevBlock) { + const block = func.blocks.get(blockId); + if (block == null) { + return; + } + CompilerError.invariant(block != null, { + reason: 'unexpected missing block', + description: `block ${blockId}`, + loc: GeneratedSource, + }); + if (prevBlock) { + block.preds.add(prevBlock.id); + } + if (visited.has(blockId)) { + return; + } + visited.add(blockId); + const { terminal } = block; + for (const successor of eachTerminalSuccessor(terminal)) { + visit(successor, block); + } + } + visit(func.entry, null); +} +function removeUnnecessaryTryCatch(fn) { + for (const [, block] of fn.blocks) { + if (block.terminal.kind === 'try' && + !fn.blocks.has(block.terminal.handler)) { + const handlerId = block.terminal.handler; + const fallthroughId = block.terminal.fallthrough; + const fallthrough = fn.blocks.get(fallthroughId); + block.terminal = { + kind: 'goto', + block: block.terminal.block, + id: makeInstructionId(0), + loc: block.terminal.loc, + variant: GotoVariant.Break, + }; + if (fallthrough != null) { + if (fallthrough.preds.size === 1 && fallthrough.preds.has(handlerId)) { + fn.blocks.delete(fallthroughId); + } + else { + fallthrough.preds.delete(handlerId); + } + } + } + } +} +function createTemporaryPlace(env, loc) { + return { + kind: 'Identifier', + identifier: makeTemporaryIdentifier(env.nextIdentifierId, loc), + reactive: false, + effect: Effect.Unknown, + loc: GeneratedSource, + }; +} +function clonePlaceToTemporary(env, place) { + const temp = createTemporaryPlace(env, place.loc); + temp.effect = place.effect; + temp.identifier.type = place.identifier.type; + temp.reactive = place.reactive; + return temp; +} +function fixScopeAndIdentifierRanges(func) { + var _a, _b; + for (const [, block] of func.blocks) { + const terminal = block.terminal; + if (terminal.kind === 'scope' || terminal.kind === 'pruned-scope') { + const fallthroughBlock = func.blocks.get(terminal.fallthrough); + const firstId = (_b = (_a = fallthroughBlock.instructions[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : fallthroughBlock.terminal.id; + terminal.scope.range.start = terminal.id; + terminal.scope.range.end = firstId; + } + } +} + +const PRIMITIVE_TYPE = { + kind: 'Primitive', +}; +let nextAnonId = 0; +function createAnonId() { + return ``; +} +function addFunction(registry, properties, fn, id = null, isConstructor = false) { + const shapeId = id !== null && id !== void 0 ? id : createAnonId(); + const aliasing = fn.aliasing != null + ? parseAliasingSignatureConfig(fn.aliasing, '', GeneratedSource) + : null; + addShape(registry, shapeId, properties, Object.assign(Object.assign({}, fn), { aliasing, hookKind: null })); + return { + kind: 'Function', + return: fn.returnType, + shapeId, + isConstructor, + }; +} +function addHook(registry, fn, id = null) { + const shapeId = id !== null && id !== void 0 ? id : createAnonId(); + const aliasing = fn.aliasing != null + ? parseAliasingSignatureConfig(fn.aliasing, '', GeneratedSource) + : null; + addShape(registry, shapeId, [], Object.assign(Object.assign({}, fn), { aliasing })); + return { + kind: 'Function', + return: fn.returnType, + shapeId, + isConstructor: false, + }; +} +function parseAliasingSignatureConfig(typeConfig, moduleName, loc) { + const lifetimes = new Map(); + function define(temp) { + CompilerError.invariant(!lifetimes.has(temp), { + reason: `Invalid type configuration for module`, + description: `Expected aliasing signature to have unique names for receiver, params, rest, returns, and temporaries in module '${moduleName}'`, + loc, + }); + const place = signatureArgument(lifetimes.size); + lifetimes.set(temp, place); + return place; + } + function lookup(temp) { + const place = lifetimes.get(temp); + CompilerError.invariant(place != null, { + reason: `Invalid type configuration for module`, + description: `Expected aliasing signature effects to reference known names from receiver/params/rest/returns/temporaries, but '${temp}' is not a known name in '${moduleName}'`, + loc, + }); + return place; + } + const receiver = define(typeConfig.receiver); + const params = typeConfig.params.map(define); + const rest = typeConfig.rest != null ? define(typeConfig.rest) : null; + const returns = define(typeConfig.returns); + const temporaries = typeConfig.temporaries.map(define); + const effects = typeConfig.effects.map((effect) => { + switch (effect.kind) { + case 'ImmutableCapture': + case 'CreateFrom': + case 'Capture': + case 'Alias': + case 'Assign': { + const from = lookup(effect.from); + const into = lookup(effect.into); + return { + kind: effect.kind, + from, + into, + }; + } + case 'Mutate': + case 'MutateTransitiveConditionally': { + const value = lookup(effect.value); + return { kind: effect.kind, value }; + } + case 'Create': { + const into = lookup(effect.into); + return { + kind: 'Create', + into, + reason: effect.reason, + value: effect.value, + }; + } + case 'Freeze': { + const value = lookup(effect.value); + return { + kind: 'Freeze', + value, + reason: effect.reason, + }; + } + case 'Impure': { + const place = lookup(effect.place); + return { + kind: 'Impure', + place, + error: CompilerError.throwTodo({ + reason: 'Support impure effect declarations', + loc: GeneratedSource, + }), + }; + } + case 'Apply': { + const receiver = lookup(effect.receiver); + const fn = lookup(effect.function); + const args = effect.args.map(arg => { + if (typeof arg === 'string') { + return lookup(arg); + } + else if (arg.kind === 'Spread') { + return { kind: 'Spread', place: lookup(arg.place) }; + } + else { + return arg; + } + }); + const into = lookup(effect.into); + return { + kind: 'Apply', + receiver, + function: fn, + mutatesFunction: effect.mutatesFunction, + args, + into, + loc, + signature: null, + }; + } + default: { + assertExhaustive$1(effect, `Unexpected effect kind '${effect.kind}'`); + } + } + }); + return { + receiver: receiver.identifier.id, + params: params.map(p => p.identifier.id), + rest: rest != null ? rest.identifier.id : null, + returns: returns.identifier.id, + temporaries, + effects, + }; +} +function addObject(registry, id, properties) { + const shapeId = id !== null && id !== void 0 ? id : createAnonId(); + addShape(registry, shapeId, properties, null); + return { + kind: 'Object', + shapeId, + }; +} +function addShape(registry, id, properties, functionType) { + const shape = { + properties: new Map(properties), + functionType, + }; + CompilerError.invariant(!registry.has(id), { + reason: `[ObjectShape] Could not add shape to registry: name ${id} already exists.`, + loc: GeneratedSource, + }); + registry.set(id, shape); + return shape; +} +const BuiltInPropsId = 'BuiltInProps'; +const BuiltInArrayId = 'BuiltInArray'; +const BuiltInSetId = 'BuiltInSet'; +const BuiltInMapId = 'BuiltInMap'; +const BuiltInWeakSetId = 'BuiltInWeakSet'; +const BuiltInWeakMapId = 'BuiltInWeakMap'; +const BuiltInFunctionId = 'BuiltInFunction'; +const BuiltInJsxId = 'BuiltInJsx'; +const BuiltInObjectId = 'BuiltInObject'; +const BuiltInUseStateId = 'BuiltInUseState'; +const BuiltInSetStateId = 'BuiltInSetState'; +const BuiltInUseActionStateId = 'BuiltInUseActionState'; +const BuiltInSetActionStateId = 'BuiltInSetActionState'; +const BuiltInUseRefId = 'BuiltInUseRefId'; +const BuiltInRefValueId = 'BuiltInRefValue'; +const BuiltInMixedReadonlyId = 'BuiltInMixedReadonly'; +const BuiltInUseEffectHookId = 'BuiltInUseEffectHook'; +const BuiltInUseLayoutEffectHookId = 'BuiltInUseLayoutEffectHook'; +const BuiltInUseInsertionEffectHookId = 'BuiltInUseInsertionEffectHook'; +const BuiltInUseOperatorId = 'BuiltInUseOperator'; +const BuiltInUseReducerId = 'BuiltInUseReducer'; +const BuiltInDispatchId = 'BuiltInDispatch'; +const BuiltInUseContextHookId = 'BuiltInUseContextHook'; +const BuiltInUseTransitionId = 'BuiltInUseTransition'; +const BuiltInUseOptimisticId = 'BuiltInUseOptimistic'; +const BuiltInSetOptimisticId = 'BuiltInSetOptimistic'; +const BuiltInStartTransitionId = 'BuiltInStartTransition'; +const BuiltInUseEffectEventId = 'BuiltInUseEffectEvent'; +const BuiltInEffectEventId = 'BuiltInEffectEventFunction'; +const ReanimatedSharedValueId = 'ReanimatedSharedValueId'; +const BUILTIN_SHAPES = new Map(); +addObject(BUILTIN_SHAPES, BuiltInPropsId, [ + ['ref', { kind: 'Object', shapeId: BuiltInUseRefId }], +]); +addObject(BUILTIN_SHAPES, BuiltInArrayId, [ + [ + 'indexOf', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'includes', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'pop', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'at', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'concat', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Capture, + returnType: { + kind: 'Object', + shapeId: BuiltInArrayId, + }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + ['length', PRIMITIVE_TYPE], + [ + 'push', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Capture, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + aliasing: { + receiver: '@receiver', + params: [], + rest: '@rest', + returns: '@returns', + temporaries: [], + effects: [ + { kind: 'Mutate', value: '@receiver' }, + { + kind: 'Capture', + from: '@rest', + into: '@receiver', + }, + { + kind: 'Create', + into: '@returns', + value: ValueKind.Primitive, + reason: ValueReason.KnownReturnSignature, + }, + ], + }, + }), + ], + [ + 'slice', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { + kind: 'Object', + shapeId: BuiltInArrayId, + }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'map', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + aliasing: { + receiver: '@receiver', + params: ['@callback'], + rest: null, + returns: '@returns', + temporaries: [ + '@item', + '@callbackReturn', + '@thisArg', + ], + effects: [ + { + kind: 'Create', + into: '@returns', + value: ValueKind.Mutable, + reason: ValueReason.KnownReturnSignature, + }, + { + kind: 'CreateFrom', + from: '@receiver', + into: '@item', + }, + { + kind: 'Create', + into: '@thisArg', + value: ValueKind.Primitive, + reason: ValueReason.KnownReturnSignature, + }, + { + kind: 'Apply', + receiver: '@thisArg', + args: ['@item', { kind: 'Hole' }, '@receiver'], + function: '@callback', + into: '@callbackReturn', + mutatesFunction: false, + }, + { + kind: 'Capture', + from: '@callbackReturn', + into: '@returns', + }, + ], + }, + }), + ], + [ + 'flatMap', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'filter', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'every', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'some', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'find', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'findIndex', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'join', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInObjectId, [ + [ + 'toString', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInSetId, [ + [ + 'add', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInSetId }, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Mutable, + aliasing: { + receiver: '@receiver', + params: [], + rest: '@rest', + returns: '@returns', + temporaries: [], + effects: [ + { + kind: 'Assign', + from: '@receiver', + into: '@returns', + }, + { + kind: 'Mutate', + value: '@receiver', + }, + { + kind: 'Capture', + from: '@rest', + into: '@receiver', + }, + ], + }, + }), + ], + [ + 'clear', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'delete', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'has', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + ['size', PRIMITIVE_TYPE], + [ + 'difference', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInSetId }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'union', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInSetId }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'symmetricalDifference', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInSetId }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'isSubsetOf', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'isSupersetOf', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'forEach', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'entries', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'keys', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'values', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInMapId, [ + [ + 'clear', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'delete', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'get', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'has', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'set', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture, Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInMapId }, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Mutable, + }), + ], + ['size', PRIMITIVE_TYPE], + [ + 'forEach', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'entries', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'keys', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'values', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInWeakSetId, [ + [ + 'add', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInWeakSetId }, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'delete', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'has', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInWeakMapId, [ + [ + 'delete', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'get', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'has', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'set', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture, Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInWeakMapId }, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Mutable, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseStateId, [ + ['0', { kind: 'Poly' }], + [ + '1', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }, BuiltInSetStateId), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseTransitionId, [ + ['0', { kind: 'Primitive' }], + [ + '1', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }, BuiltInStartTransitionId), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseOptimisticId, [ + ['0', { kind: 'Poly' }], + [ + '1', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }, BuiltInSetOptimisticId), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseActionStateId, [ + ['0', { kind: 'Poly' }], + [ + '1', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }, BuiltInSetActionStateId), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseReducerId, [ + ['0', { kind: 'Poly' }], + [ + '1', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }, BuiltInDispatchId), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseRefId, [ + ['current', { kind: 'Object', shapeId: BuiltInRefValueId }], +]); +addObject(BUILTIN_SHAPES, BuiltInRefValueId, [ + ['*', { kind: 'Object', shapeId: BuiltInRefValueId }], +]); +addObject(BUILTIN_SHAPES, ReanimatedSharedValueId, []); +addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, +}, BuiltInEffectEventId); +addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [ + [ + 'toString', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'indexOf', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'includes', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'at', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInMixedReadonlyId }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'map', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + }), + ], + [ + 'flatMap', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + }), + ], + [ + 'filter', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + }), + ], + [ + 'concat', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Capture, + returnType: { + kind: 'Object', + shapeId: BuiltInArrayId, + }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'slice', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { + kind: 'Object', + shapeId: BuiltInArrayId, + }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'every', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'some', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'find', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInMixedReadonlyId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Frozen, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'findIndex', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'join', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + ['*', { kind: 'Object', shapeId: BuiltInMixedReadonlyId }], +]); +addObject(BUILTIN_SHAPES, BuiltInJsxId, []); +addObject(BUILTIN_SHAPES, BuiltInFunctionId, []); +const DefaultMutatingHook = addHook(BUILTIN_SHAPES, { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'Custom', + returnValueKind: ValueKind.Mutable, +}, 'DefaultMutatingHook'); +const DefaultNonmutatingHook = addHook(BUILTIN_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'Custom', + returnValueKind: ValueKind.Frozen, + aliasing: { + receiver: '@receiver', + params: [], + rest: '@rest', + returns: '@returns', + temporaries: [], + effects: [ + { + kind: 'Freeze', + value: '@rest', + reason: ValueReason.HookCaptured, + }, + { + kind: 'Create', + into: '@returns', + value: ValueKind.Frozen, + reason: ValueReason.HookReturn, + }, + { + kind: 'Alias', + from: '@rest', + into: '@returns', + }, + ], + }, +}, 'DefaultNonmutatingHook'); +function signatureArgument(id) { + const place = { + kind: 'Identifier', + effect: Effect.Unknown, + loc: GeneratedSource, + reactive: false, + identifier: { + declarationId: makeDeclarationId(id), + id: makeIdentifierId(id), + loc: GeneratedSource, + mutableRange: { start: makeInstructionId(0), end: makeInstructionId(0) }, + name: null, + scope: null, + type: makeType(), + }, + }; + return place; +} + +function lower(func, env, bindings = null, capturedRefs = new Map()) { + var _a, _b, _c; + const builder = new HIRBuilder(env, { + bindings, + context: capturedRefs, + }); + const context = []; + for (const [ref, loc] of capturedRefs !== null && capturedRefs !== void 0 ? capturedRefs : []) { + context.push({ + kind: 'Identifier', + identifier: builder.resolveBinding(ref), + effect: Effect.Unknown, + reactive: false, + loc, + }); + } + let id = null; + if (func.isFunctionDeclaration() || func.isFunctionExpression()) { + const idNode = func.get('id'); + if (hasNode(idNode)) { + id = idNode.node.name; + } + } + const params = []; + func.get('params').forEach(param => { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (param.isIdentifier()) { + const binding = builder.resolveIdentifier(param); + if (binding.kind !== 'Identifier') { + builder.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Invariant, + reason: 'Could not find binding', + description: `[BuildHIR] Could not find binding for param \`${param.node.name}\``, + }).withDetails({ + kind: 'error', + loc: (_a = param.node.loc) !== null && _a !== void 0 ? _a : null, + message: 'Could not find binding', + })); + return; + } + const place = { + kind: 'Identifier', + identifier: binding.identifier, + effect: Effect.Unknown, + reactive: false, + loc: (_b = param.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + params.push(place); + } + else if (param.isObjectPattern() || + param.isArrayPattern() || + param.isAssignmentPattern()) { + const place = { + kind: 'Identifier', + identifier: builder.makeTemporary((_c = param.node.loc) !== null && _c !== void 0 ? _c : GeneratedSource), + effect: Effect.Unknown, + reactive: false, + loc: (_d = param.node.loc) !== null && _d !== void 0 ? _d : GeneratedSource, + }; + promoteTemporary(place.identifier); + params.push(place); + lowerAssignment(builder, (_e = param.node.loc) !== null && _e !== void 0 ? _e : GeneratedSource, InstructionKind.Let, param, place, 'Assignment'); + } + else if (param.isRestElement()) { + const place = { + kind: 'Identifier', + identifier: builder.makeTemporary((_f = param.node.loc) !== null && _f !== void 0 ? _f : GeneratedSource), + effect: Effect.Unknown, + reactive: false, + loc: (_g = param.node.loc) !== null && _g !== void 0 ? _g : GeneratedSource, + }; + params.push({ + kind: 'Spread', + place, + }); + lowerAssignment(builder, (_h = param.node.loc) !== null && _h !== void 0 ? _h : GeneratedSource, InstructionKind.Let, param.get('argument'), place, 'Assignment'); + } + else { + builder.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Todo, + reason: `Handle ${param.node.type} parameters`, + description: `[BuildHIR] Add support for ${param.node.type} parameters`, + }).withDetails({ + kind: 'error', + loc: (_j = param.node.loc) !== null && _j !== void 0 ? _j : null, + message: 'Unsupported parameter type', + })); + } + }); + let directives = []; + const body = func.get('body'); + if (body.isExpression()) { + const fallthrough = builder.reserve('block'); + const terminal = { + kind: 'return', + returnVariant: 'Implicit', + loc: GeneratedSource, + value: lowerExpressionToTemporary(builder, body), + id: makeInstructionId(0), + effects: null, + }; + builder.terminateWithContinuation(terminal, fallthrough); + } + else if (body.isBlockStatement()) { + lowerStatement(builder, body); + directives = body.get('directives').map(d => d.node.value.value); + } + else { + builder.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Syntax, + reason: `Unexpected function body kind`, + description: `Expected function body to be an expression or a block statement, got \`${body.type}\``, + }).withDetails({ + kind: 'error', + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : null, + message: 'Expected a block statement or expression', + })); + } + let validatedId = null; + if (id != null) { + const idResult = validateIdentifierName(id); + if (idResult.isErr()) { + for (const detail of idResult.unwrapErr().details) { + builder.recordError(detail); + } + } + else { + validatedId = idResult.unwrap().value; + } + } + builder.terminate({ + kind: 'return', + returnVariant: 'Void', + loc: GeneratedSource, + value: lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc: GeneratedSource, + }), + id: makeInstructionId(0), + effects: null, + }, null); + const hirBody = builder.build(); + return { + id: validatedId, + nameHint: null, + params, + fnType: bindings == null ? env.fnType : 'Other', + returnTypeAnnotation: null, + returns: createTemporaryPlace(env, (_b = func.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource), + body: hirBody, + context, + generator: func.node.generator === true, + async: func.node.async === true, + loc: (_c = func.node.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + env, + aliasingEffects: null, + directives, + }; +} +function lowerStatement(builder, stmtPath, label = null) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38; + const stmtNode = stmtPath.node; + switch (stmtNode.type) { + case 'ThrowStatement': { + const stmt = stmtPath; + const value = lowerExpressionToTemporary(builder, stmt.get('argument')); + const handler = builder.resolveThrowHandler(); + if (handler != null) { + builder.recordError(new CompilerErrorDetail({ + reason: '(BuildHIR::lowerStatement) Support ThrowStatement inside of try/catch', + category: ErrorCategory.Todo, + loc: (_a = stmt.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + } + const terminal = { + kind: 'throw', + value, + id: makeInstructionId(0), + loc: (_b = stmt.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + builder.terminate(terminal, 'block'); + return; + } + case 'ReturnStatement': { + const stmt = stmtPath; + const argument = stmt.get('argument'); + let value; + if (argument.node === null) { + value = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc: GeneratedSource, + }); + } + else { + value = lowerExpressionToTemporary(builder, argument); + } + const terminal = { + kind: 'return', + returnVariant: 'Explicit', + loc: (_c = stmt.node.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + value, + id: makeInstructionId(0), + effects: null, + }; + builder.terminate(terminal, 'block'); + return; + } + case 'IfStatement': { + const stmt = stmtPath; + const continuationBlock = builder.reserve('block'); + const consequentBlock = builder.enter('block', _blockId => { + var _a; + const consequent = stmt.get('consequent'); + lowerStatement(builder, consequent); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_a = consequent.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + let alternateBlock; + const alternate = stmt.get('alternate'); + if (hasNode(alternate)) { + alternateBlock = builder.enter('block', _blockId => { + var _a, _b; + lowerStatement(builder, alternate); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_b = (_a = alternate.node) === null || _a === void 0 ? void 0 : _a.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + }); + } + else { + alternateBlock = continuationBlock.id; + } + const test = lowerExpressionToTemporary(builder, stmt.get('test')); + const terminal = { + kind: 'if', + test, + consequent: consequentBlock, + alternate: alternateBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_d = stmt.node.loc) !== null && _d !== void 0 ? _d : GeneratedSource, + }; + builder.terminateWithContinuation(terminal, continuationBlock); + return; + } + case 'BlockStatement': { + const stmt = stmtPath; + const statements = stmt.get('body'); + const hoistableIdentifiers = new Set(); + for (const [, binding] of Object.entries(stmt.scope.bindings)) { + if (binding.kind !== 'param') { + hoistableIdentifiers.add(binding.identifier); + } + } + for (const s of statements) { + const willHoist = new Set(); + let fnDepth = s.isFunctionDeclaration() ? 1 : 0; + const withFunctionContext = { + enter: () => { + fnDepth++; + }, + exit: () => { + fnDepth--; + }, + }; + s.traverse({ + FunctionExpression: withFunctionContext, + FunctionDeclaration: withFunctionContext, + ArrowFunctionExpression: withFunctionContext, + ObjectMethod: withFunctionContext, + Identifier(id) { + const id2 = id; + if (!id2.isReferencedIdentifier() && + id.parent.type !== 'AssignmentExpression') { + return; + } + const binding = id.scope.getBinding(id.node.name); + if (binding != null && + hoistableIdentifiers.has(binding.identifier) && + (fnDepth > 0 || binding.kind === 'hoisted')) { + willHoist.add(id); + } + }, + }); + s.traverse({ + Identifier(path) { + if (hoistableIdentifiers.has(path.node)) { + hoistableIdentifiers.delete(path.node); + } + }, + }); + for (const id of willHoist) { + const binding = stmt.scope.getBinding(id.node.name); + CompilerError.invariant(binding != null, { + reason: 'Expected to find binding for hoisted identifier', + description: `Could not find a binding for ${id.node.name}`, + loc: (_e = id.node.loc) !== null && _e !== void 0 ? _e : GeneratedSource, + }); + if (builder.environment.isHoistedIdentifier(binding.identifier)) { + continue; + } + let kind; + if (binding.kind === 'const' || binding.kind === 'var') { + kind = InstructionKind.HoistedConst; + } + else if (binding.kind === 'let') { + kind = InstructionKind.HoistedLet; + } + else if (binding.path.isFunctionDeclaration()) { + kind = InstructionKind.HoistedFunction; + } + else if (!binding.path.isVariableDeclarator()) { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Unsupported declaration type for hoisting', + description: `variable "${binding.identifier.name}" declared with ${binding.path.type}`, + suggestions: null, + loc: (_f = id.parentPath.node.loc) !== null && _f !== void 0 ? _f : GeneratedSource, + })); + continue; + } + else { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Handle non-const declarations for hoisting', + description: `variable "${binding.identifier.name}" declared with ${binding.kind}`, + suggestions: null, + loc: (_g = id.parentPath.node.loc) !== null && _g !== void 0 ? _g : GeneratedSource, + })); + continue; + } + const identifier = builder.resolveIdentifier(id); + CompilerError.invariant(identifier.kind === 'Identifier', { + reason: 'Expected hoisted binding to be a local identifier, not a global', + loc: (_h = id.node.loc) !== null && _h !== void 0 ? _h : GeneratedSource, + }); + const place = { + effect: Effect.Unknown, + identifier: identifier.identifier, + kind: 'Identifier', + reactive: false, + loc: (_j = id.node.loc) !== null && _j !== void 0 ? _j : GeneratedSource, + }; + lowerValueToTemporary(builder, { + kind: 'DeclareContext', + lvalue: { + kind, + place, + }, + loc: (_k = id.node.loc) !== null && _k !== void 0 ? _k : GeneratedSource, + }); + builder.environment.addHoistedIdentifier(binding.identifier); + } + lowerStatement(builder, s); + } + return; + } + case 'BreakStatement': { + const stmt = stmtPath; + const block = builder.lookupBreak((_m = (_l = stmt.node.label) === null || _l === void 0 ? void 0 : _l.name) !== null && _m !== void 0 ? _m : null); + builder.terminate({ + kind: 'goto', + block, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_o = stmt.node.loc) !== null && _o !== void 0 ? _o : GeneratedSource, + }, 'block'); + return; + } + case 'ContinueStatement': { + const stmt = stmtPath; + const block = builder.lookupContinue((_q = (_p = stmt.node.label) === null || _p === void 0 ? void 0 : _p.name) !== null && _q !== void 0 ? _q : null); + builder.terminate({ + kind: 'goto', + block, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_r = stmt.node.loc) !== null && _r !== void 0 ? _r : GeneratedSource, + }, 'block'); + return; + } + case 'ForStatement': { + const stmt = stmtPath; + const testBlock = builder.reserve('loop'); + const continuationBlock = builder.reserve('block'); + const initBlock = builder.enter('loop', _blockId => { + var _a, _b, _c, _d, _e, _f; + const init = stmt.get('init'); + if (init.node == null) { + lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc: (_a = stmt.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + return { + kind: 'goto', + block: testBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_b = stmt.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + } + if (!init.isVariableDeclaration()) { + builder.recordError(new CompilerErrorDetail({ + reason: '(BuildHIR::lowerStatement) Handle non-variable initialization in ForStatement', + category: ErrorCategory.Todo, + loc: (_c = stmt.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + if (init.isExpression()) { + lowerExpressionToTemporary(builder, init); + } + return { + kind: 'goto', + block: testBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_e = (_d = init.node) === null || _d === void 0 ? void 0 : _d.loc) !== null && _e !== void 0 ? _e : GeneratedSource, + }; + } + lowerStatement(builder, init); + return { + kind: 'goto', + block: testBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_f = init.node.loc) !== null && _f !== void 0 ? _f : GeneratedSource, + }; + }); + let updateBlock = null; + const update = stmt.get('update'); + if (hasNode(update)) { + updateBlock = builder.enter('loop', _blockId => { + var _a, _b; + lowerExpressionToTemporary(builder, update); + return { + kind: 'goto', + block: testBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_b = (_a = update.node) === null || _a === void 0 ? void 0 : _a.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + }); + } + const bodyBlock = builder.enter('block', _blockId => { + return builder.loop(label, updateBlock !== null && updateBlock !== void 0 ? updateBlock : testBlock.id, continuationBlock.id, () => { + var _a; + const body = stmt.get('body'); + lowerStatement(builder, body); + return { + kind: 'goto', + block: updateBlock !== null && updateBlock !== void 0 ? updateBlock : testBlock.id, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + builder.terminateWithContinuation({ + kind: 'for', + loc: (_s = stmtNode.loc) !== null && _s !== void 0 ? _s : GeneratedSource, + init: initBlock, + test: testBlock.id, + update: updateBlock, + loop: bodyBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + }, testBlock); + const test = stmt.get('test'); + if (test.node == null) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerStatement) Handle empty test in ForStatement`, + category: ErrorCategory.Todo, + loc: (_t = stmt.node.loc) !== null && _t !== void 0 ? _t : null, + suggestions: null, + })); + builder.terminateWithContinuation({ + kind: 'branch', + test: lowerValueToTemporary(builder, { + kind: 'Primitive', + value: true, + loc: (_u = stmt.node.loc) !== null && _u !== void 0 ? _u : GeneratedSource, + }), + consequent: bodyBlock, + alternate: continuationBlock.id, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_v = stmt.node.loc) !== null && _v !== void 0 ? _v : GeneratedSource, + }, continuationBlock); + } + else { + builder.terminateWithContinuation({ + kind: 'branch', + test: lowerExpressionToTemporary(builder, test), + consequent: bodyBlock, + alternate: continuationBlock.id, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_w = stmt.node.loc) !== null && _w !== void 0 ? _w : GeneratedSource, + }, continuationBlock); + } + return; + } + case 'WhileStatement': { + const stmt = stmtPath; + const conditionalBlock = builder.reserve('loop'); + const continuationBlock = builder.reserve('block'); + const loopBlock = builder.enter('block', _blockId => { + return builder.loop(label, conditionalBlock.id, continuationBlock.id, () => { + var _a; + const body = stmt.get('body'); + lowerStatement(builder, body); + return { + kind: 'goto', + block: conditionalBlock.id, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + const loc = (_x = stmt.node.loc) !== null && _x !== void 0 ? _x : GeneratedSource; + builder.terminateWithContinuation({ + kind: 'while', + loc, + test: conditionalBlock.id, + loop: loopBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + }, conditionalBlock); + const test = lowerExpressionToTemporary(builder, stmt.get('test')); + const terminal = { + kind: 'branch', + test, + consequent: loopBlock, + alternate: continuationBlock.id, + fallthrough: conditionalBlock.id, + id: makeInstructionId(0), + loc: (_y = stmt.node.loc) !== null && _y !== void 0 ? _y : GeneratedSource, + }; + builder.terminateWithContinuation(terminal, continuationBlock); + return; + } + case 'LabeledStatement': { + const stmt = stmtPath; + const label = stmt.node.label.name; + const body = stmt.get('body'); + switch (body.node.type) { + case 'ForInStatement': + case 'ForOfStatement': + case 'ForStatement': + case 'WhileStatement': + case 'DoWhileStatement': { + lowerStatement(builder, stmt.get('body'), label); + break; + } + default: { + const continuationBlock = builder.reserve('block'); + const block = builder.enter('block', () => { + var _a; + const body = stmt.get('body'); + builder.label(label, continuationBlock.id, () => { + lowerStatement(builder, body); + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + builder.terminateWithContinuation({ + kind: 'label', + block, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_z = stmt.node.loc) !== null && _z !== void 0 ? _z : GeneratedSource, + }, continuationBlock); + } + } + return; + } + case 'SwitchStatement': { + const stmt = stmtPath; + const continuationBlock = builder.reserve('block'); + let fallthrough = continuationBlock.id; + const cases = []; + let hasDefault = false; + for (let ii = stmt.get('cases').length - 1; ii >= 0; ii--) { + const case_ = stmt.get('cases')[ii]; + const testExpr = case_.get('test'); + if (testExpr.node == null) { + if (hasDefault) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected at most one \`default\` branch in a switch statement, this code should have failed to parse`, + category: ErrorCategory.Syntax, + loc: (_0 = case_.node.loc) !== null && _0 !== void 0 ? _0 : null, + suggestions: null, + })); + break; + } + hasDefault = true; + } + const block = builder.enter('block', _blockId => { + return builder.switch(label, continuationBlock.id, () => { + var _a; + case_ + .get('consequent') + .forEach(consequent => lowerStatement(builder, consequent)); + return { + kind: 'goto', + block: fallthrough, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_a = case_.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + let test = null; + if (hasNode(testExpr)) { + test = lowerReorderableExpression(builder, testExpr); + } + cases.push({ + test, + block, + }); + fallthrough = block; + } + cases.reverse(); + if (!hasDefault) { + cases.push({ test: null, block: continuationBlock.id }); + } + const test = lowerExpressionToTemporary(builder, stmt.get('discriminant')); + builder.terminateWithContinuation({ + kind: 'switch', + test, + cases, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_1 = stmt.node.loc) !== null && _1 !== void 0 ? _1 : GeneratedSource, + }, continuationBlock); + return; + } + case 'VariableDeclaration': { + const stmt = stmtPath; + const nodeKind = stmt.node.kind; + if (nodeKind === 'var') { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerStatement) Handle ${nodeKind} kinds in VariableDeclaration`, + category: ErrorCategory.Todo, + loc: (_2 = stmt.node.loc) !== null && _2 !== void 0 ? _2 : null, + suggestions: null, + })); + } + const kind = nodeKind === 'let' || nodeKind === 'var' + ? InstructionKind.Let + : InstructionKind.Const; + for (const declaration of stmt.get('declarations')) { + const id = declaration.get('id'); + const init = declaration.get('init'); + if (hasNode(init)) { + const value = lowerExpressionToTemporary(builder, init); + lowerAssignment(builder, (_3 = stmt.node.loc) !== null && _3 !== void 0 ? _3 : GeneratedSource, kind, id, value, id.isObjectPattern() || id.isArrayPattern() + ? 'Destructure' + : 'Assignment'); + } + else if (id.isIdentifier()) { + const binding = builder.resolveIdentifier(id); + if (binding.kind !== 'Identifier') { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Could not find binding for declaration.`, + category: ErrorCategory.Invariant, + loc: (_4 = id.node.loc) !== null && _4 !== void 0 ? _4 : null, + suggestions: null, + })); + } + else { + const place = { + effect: Effect.Unknown, + identifier: binding.identifier, + kind: 'Identifier', + reactive: false, + loc: (_5 = id.node.loc) !== null && _5 !== void 0 ? _5 : GeneratedSource, + }; + if (builder.isContextIdentifier(id)) { + if (kind === InstructionKind.Const) { + const declRangeStart = declaration.parentPath.node.start; + builder.recordError(new CompilerErrorDetail({ + reason: `Expect \`const\` declaration not to be reassigned`, + category: ErrorCategory.Syntax, + loc: (_6 = id.node.loc) !== null && _6 !== void 0 ? _6 : null, + suggestions: [ + { + description: 'Change to a `let` declaration', + op: CompilerSuggestionOperation.Replace, + range: [declRangeStart, declRangeStart + 5], + text: 'let', + }, + ], + })); + } + lowerValueToTemporary(builder, { + kind: 'DeclareContext', + lvalue: { + kind: InstructionKind.Let, + place, + }, + loc: (_7 = id.node.loc) !== null && _7 !== void 0 ? _7 : GeneratedSource, + }); + } + else { + const typeAnnotation = id.get('typeAnnotation'); + let type; + if (typeAnnotation.isTSTypeAnnotation()) { + const typePath = typeAnnotation.get('typeAnnotation'); + type = typePath.node; + } + else if (typeAnnotation.isTypeAnnotation()) { + const typePath = typeAnnotation.get('typeAnnotation'); + type = typePath.node; + } + else { + type = null; + } + lowerValueToTemporary(builder, { + kind: 'DeclareLocal', + lvalue: { + kind, + place, + }, + type, + loc: (_8 = id.node.loc) !== null && _8 !== void 0 ? _8 : GeneratedSource, + }); + } + } + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected variable declaration to be an identifier if no initializer was provided`, + description: `Got a \`${id.type}\``, + category: ErrorCategory.Syntax, + loc: (_9 = stmt.node.loc) !== null && _9 !== void 0 ? _9 : null, + suggestions: null, + })); + } + } + return; + } + case 'ExpressionStatement': { + const stmt = stmtPath; + const expression = stmt.get('expression'); + lowerExpressionToTemporary(builder, expression); + return; + } + case 'DoWhileStatement': { + const stmt = stmtPath; + const conditionalBlock = builder.reserve('loop'); + const continuationBlock = builder.reserve('block'); + const loopBlock = builder.enter('block', _loopBlockId => { + return builder.loop(label, conditionalBlock.id, continuationBlock.id, () => { + var _a; + const body = stmt.get('body'); + lowerStatement(builder, body); + return { + kind: 'goto', + block: conditionalBlock.id, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + const loc = (_10 = stmt.node.loc) !== null && _10 !== void 0 ? _10 : GeneratedSource; + builder.terminateWithContinuation({ + kind: 'do-while', + loc, + test: conditionalBlock.id, + loop: loopBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + }, conditionalBlock); + const test = lowerExpressionToTemporary(builder, stmt.get('test')); + const terminal = { + kind: 'branch', + test, + consequent: loopBlock, + alternate: continuationBlock.id, + fallthrough: conditionalBlock.id, + id: makeInstructionId(0), + loc, + }; + builder.terminateWithContinuation(terminal, continuationBlock); + return; + } + case 'FunctionDeclaration': { + const stmt = stmtPath; + stmt.skip(); + CompilerError.invariant(stmt.get('id').type === 'Identifier', { + reason: 'function declarations must have a name', + loc: (_11 = stmt.node.loc) !== null && _11 !== void 0 ? _11 : GeneratedSource, + }); + const id = stmt.get('id'); + const fn = lowerValueToTemporary(builder, lowerFunctionToValue(builder, stmt)); + lowerAssignment(builder, (_12 = stmt.node.loc) !== null && _12 !== void 0 ? _12 : GeneratedSource, InstructionKind.Function, id, fn, 'Assignment'); + return; + } + case 'ForOfStatement': { + const stmt = stmtPath; + const continuationBlock = builder.reserve('block'); + const initBlock = builder.reserve('loop'); + const testBlock = builder.reserve('loop'); + if (stmt.node.await) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerStatement) Handle for-await loops`, + category: ErrorCategory.Todo, + loc: (_13 = stmt.node.loc) !== null && _13 !== void 0 ? _13 : null, + suggestions: null, + })); + return; + } + const loopBlock = builder.enter('block', _blockId => { + return builder.loop(label, initBlock.id, continuationBlock.id, () => { + var _a; + const body = stmt.get('body'); + lowerStatement(builder, body); + return { + kind: 'goto', + block: initBlock.id, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + const loc = (_14 = stmt.node.loc) !== null && _14 !== void 0 ? _14 : GeneratedSource; + const value = lowerExpressionToTemporary(builder, stmt.get('right')); + builder.terminateWithContinuation({ + kind: 'for-of', + loc, + init: initBlock.id, + test: testBlock.id, + loop: loopBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + }, initBlock); + const iterator = lowerValueToTemporary(builder, { + kind: 'GetIterator', + loc: value.loc, + collection: Object.assign({}, value), + }); + builder.terminateWithContinuation({ + id: makeInstructionId(0), + kind: 'goto', + block: testBlock.id, + variant: GotoVariant.Break, + loc: (_15 = stmt.node.loc) !== null && _15 !== void 0 ? _15 : GeneratedSource, + }, testBlock); + const left = stmt.get('left'); + const leftLoc = (_16 = left.node.loc) !== null && _16 !== void 0 ? _16 : GeneratedSource; + let test; + const advanceIterator = lowerValueToTemporary(builder, { + kind: 'IteratorNext', + loc: leftLoc, + iterator: Object.assign({}, iterator), + collection: Object.assign({}, value), + }); + if (left.isVariableDeclaration()) { + const declarations = left.get('declarations'); + CompilerError.invariant(declarations.length === 1, { + reason: `Expected only one declaration in the init of a ForOfStatement, got ${declarations.length}`, + loc: (_17 = left.node.loc) !== null && _17 !== void 0 ? _17 : GeneratedSource, + }); + const id = declarations[0].get('id'); + const assign = lowerAssignment(builder, leftLoc, InstructionKind.Let, id, advanceIterator, 'Assignment'); + test = lowerValueToTemporary(builder, assign); + } + else { + CompilerError.invariant(left.isLVal(), { + reason: 'Expected ForOf init to be a variable declaration or lval', + loc: leftLoc, + }); + const assign = lowerAssignment(builder, leftLoc, InstructionKind.Reassign, left, advanceIterator, 'Assignment'); + test = lowerValueToTemporary(builder, assign); + } + builder.terminateWithContinuation({ + id: makeInstructionId(0), + kind: 'branch', + test, + consequent: loopBlock, + alternate: continuationBlock.id, + loc: (_18 = stmt.node.loc) !== null && _18 !== void 0 ? _18 : GeneratedSource, + fallthrough: continuationBlock.id, + }, continuationBlock); + return; + } + case 'ForInStatement': { + const stmt = stmtPath; + const continuationBlock = builder.reserve('block'); + const initBlock = builder.reserve('loop'); + const loopBlock = builder.enter('block', _blockId => { + return builder.loop(label, initBlock.id, continuationBlock.id, () => { + var _a; + const body = stmt.get('body'); + lowerStatement(builder, body); + return { + kind: 'goto', + block: initBlock.id, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + const loc = (_19 = stmt.node.loc) !== null && _19 !== void 0 ? _19 : GeneratedSource; + const value = lowerExpressionToTemporary(builder, stmt.get('right')); + builder.terminateWithContinuation({ + kind: 'for-in', + loc, + init: initBlock.id, + loop: loopBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + }, initBlock); + const left = stmt.get('left'); + const leftLoc = (_20 = left.node.loc) !== null && _20 !== void 0 ? _20 : GeneratedSource; + let test; + const nextPropertyTemp = lowerValueToTemporary(builder, { + kind: 'NextPropertyOf', + loc: leftLoc, + value, + }); + if (left.isVariableDeclaration()) { + const declarations = left.get('declarations'); + CompilerError.invariant(declarations.length === 1, { + reason: `Expected only one declaration in the init of a ForInStatement, got ${declarations.length}`, + loc: (_21 = left.node.loc) !== null && _21 !== void 0 ? _21 : GeneratedSource, + }); + const id = declarations[0].get('id'); + const assign = lowerAssignment(builder, leftLoc, InstructionKind.Let, id, nextPropertyTemp, 'Assignment'); + test = lowerValueToTemporary(builder, assign); + } + else { + CompilerError.invariant(left.isLVal(), { + reason: 'Expected ForIn init to be a variable declaration or lval', + loc: leftLoc, + }); + const assign = lowerAssignment(builder, leftLoc, InstructionKind.Reassign, left, nextPropertyTemp, 'Assignment'); + test = lowerValueToTemporary(builder, assign); + } + builder.terminateWithContinuation({ + id: makeInstructionId(0), + kind: 'branch', + test, + consequent: loopBlock, + alternate: continuationBlock.id, + fallthrough: continuationBlock.id, + loc: (_22 = stmt.node.loc) !== null && _22 !== void 0 ? _22 : GeneratedSource, + }, continuationBlock); + return; + } + case 'DebuggerStatement': { + const stmt = stmtPath; + const loc = (_23 = stmt.node.loc) !== null && _23 !== void 0 ? _23 : GeneratedSource; + builder.push({ + id: makeInstructionId(0), + lvalue: buildTemporaryPlace(builder, loc), + value: { + kind: 'Debugger', + loc, + }, + effects: null, + loc, + }); + return; + } + case 'EmptyStatement': { + return; + } + case 'TryStatement': { + const stmt = stmtPath; + const continuationBlock = builder.reserve('block'); + const handlerPath = stmt.get('handler'); + if (!hasNode(handlerPath)) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerStatement) Handle TryStatement without a catch clause`, + category: ErrorCategory.Todo, + loc: (_24 = stmt.node.loc) !== null && _24 !== void 0 ? _24 : null, + suggestions: null, + })); + return; + } + if (hasNode(stmt.get('finalizer'))) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerStatement) Handle TryStatement with a finalizer ('finally') clause`, + category: ErrorCategory.Todo, + loc: (_25 = stmt.node.loc) !== null && _25 !== void 0 ? _25 : null, + suggestions: null, + })); + } + const handlerBindingPath = handlerPath.get('param'); + let handlerBinding = null; + if (hasNode(handlerBindingPath)) { + const place = { + kind: 'Identifier', + identifier: builder.makeTemporary((_26 = handlerBindingPath.node.loc) !== null && _26 !== void 0 ? _26 : GeneratedSource), + effect: Effect.Unknown, + reactive: false, + loc: (_27 = handlerBindingPath.node.loc) !== null && _27 !== void 0 ? _27 : GeneratedSource, + }; + promoteTemporary(place.identifier); + lowerValueToTemporary(builder, { + kind: 'DeclareLocal', + lvalue: { + kind: InstructionKind.Catch, + place: Object.assign({}, place), + }, + type: null, + loc: (_28 = handlerBindingPath.node.loc) !== null && _28 !== void 0 ? _28 : GeneratedSource, + }); + handlerBinding = { + path: handlerBindingPath, + place, + }; + } + const handler = builder.enter('catch', _blockId => { + var _a, _b; + if (handlerBinding !== null) { + lowerAssignment(builder, (_a = handlerBinding.path.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, InstructionKind.Catch, handlerBinding.path, Object.assign({}, handlerBinding.place), 'Assignment'); + } + lowerStatement(builder, handlerPath.get('body')); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_b = handlerPath.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + }); + const block = builder.enter('block', _blockId => { + var _a; + const block = stmt.get('block'); + builder.enterTryCatch(handler, () => { + lowerStatement(builder, block); + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Try, + id: makeInstructionId(0), + loc: (_a = block.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + builder.terminateWithContinuation({ + kind: 'try', + block, + handlerBinding: handlerBinding !== null ? Object.assign({}, handlerBinding.place) : null, + handler, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_29 = stmt.node.loc) !== null && _29 !== void 0 ? _29 : GeneratedSource, + }, continuationBlock); + return; + } + case 'WithStatement': { + builder.recordError(new CompilerErrorDetail({ + reason: `JavaScript 'with' syntax is not supported`, + description: `'with' syntax is considered deprecated and removed from JavaScript standards, consider alternatives`, + category: ErrorCategory.UnsupportedSyntax, + loc: (_30 = stmtPath.node.loc) !== null && _30 !== void 0 ? _30 : null, + suggestions: null, + })); + lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + loc: (_31 = stmtPath.node.loc) !== null && _31 !== void 0 ? _31 : GeneratedSource, + node: stmtPath.node, + }); + return; + } + case 'ClassDeclaration': { + builder.recordError(new CompilerErrorDetail({ + reason: 'Inline `class` declarations are not supported', + description: `Move class declarations outside of components/hooks`, + category: ErrorCategory.UnsupportedSyntax, + loc: (_32 = stmtPath.node.loc) !== null && _32 !== void 0 ? _32 : null, + suggestions: null, + })); + lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + loc: (_33 = stmtPath.node.loc) !== null && _33 !== void 0 ? _33 : GeneratedSource, + node: stmtPath.node, + }); + return; + } + case 'EnumDeclaration': + case 'TSEnumDeclaration': { + lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + loc: (_34 = stmtPath.node.loc) !== null && _34 !== void 0 ? _34 : GeneratedSource, + node: stmtPath.node, + }); + return; + } + case 'ExportAllDeclaration': + case 'ExportDefaultDeclaration': + case 'ExportNamedDeclaration': + case 'ImportDeclaration': + case 'TSExportAssignment': + case 'TSImportEqualsDeclaration': { + builder.recordError(new CompilerErrorDetail({ + reason: 'JavaScript `import` and `export` statements may only appear at the top level of a module', + category: ErrorCategory.Syntax, + loc: (_35 = stmtPath.node.loc) !== null && _35 !== void 0 ? _35 : null, + suggestions: null, + })); + lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + loc: (_36 = stmtPath.node.loc) !== null && _36 !== void 0 ? _36 : GeneratedSource, + node: stmtPath.node, + }); + return; + } + case 'TSNamespaceExportDeclaration': { + builder.recordError(new CompilerErrorDetail({ + reason: 'TypeScript `namespace` statements may only appear at the top level of a module', + category: ErrorCategory.Syntax, + loc: (_37 = stmtPath.node.loc) !== null && _37 !== void 0 ? _37 : null, + suggestions: null, + })); + lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + loc: (_38 = stmtPath.node.loc) !== null && _38 !== void 0 ? _38 : GeneratedSource, + node: stmtPath.node, + }); + return; + } + case 'DeclareClass': + case 'DeclareExportAllDeclaration': + case 'DeclareExportDeclaration': + case 'DeclareFunction': + case 'DeclareInterface': + case 'DeclareModule': + case 'DeclareModuleExports': + case 'DeclareOpaqueType': + case 'DeclareTypeAlias': + case 'DeclareVariable': + case 'InterfaceDeclaration': + case 'OpaqueType': + case 'TSDeclareFunction': + case 'TSInterfaceDeclaration': + case 'TSModuleDeclaration': + case 'TSTypeAliasDeclaration': + case 'TypeAlias': { + return; + } + default: { + return assertExhaustive$1(stmtNode, `Unsupported statement kind '${stmtNode.type}'`); + } + } +} +function lowerObjectMethod(builder, property) { + var _a; + const loc = (_a = property.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const loweredFunc = lowerFunction(builder, property); + return { + kind: 'ObjectMethod', + loc, + loweredFunc, + }; +} +function lowerObjectPropertyKey(builder, property) { + var _a; + const key = property.get('key'); + if (key.isStringLiteral()) { + return { + kind: 'string', + name: key.node.value, + }; + } + else if (property.node.computed && key.isExpression()) { + const place = lowerExpressionToTemporary(builder, key); + return { + kind: 'computed', + name: place, + }; + } + else if (key.isIdentifier()) { + return { + kind: 'identifier', + name: key.node.name, + }; + } + else if (key.isNumericLiteral()) { + return { + kind: 'identifier', + name: String(key.node.value), + }; + } + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Expected Identifier, got ${key.type} key in ObjectExpression`, + category: ErrorCategory.Todo, + loc: (_a = key.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + return null; +} +function lowerExpression(builder, exprPath) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23; + const exprNode = exprPath.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + switch (exprNode.type) { + case 'Identifier': { + const expr = exprPath; + const place = lowerIdentifier(builder, expr); + return { + kind: getLoadKind(builder, expr), + place, + loc: exprLoc, + }; + } + case 'NullLiteral': { + return { + kind: 'Primitive', + value: null, + loc: exprLoc, + }; + } + case 'BooleanLiteral': + case 'NumericLiteral': + case 'StringLiteral': { + const expr = exprPath; + const value = expr.node.value; + return { + kind: 'Primitive', + value, + loc: exprLoc, + }; + } + case 'ObjectExpression': { + const expr = exprPath; + const propertyPaths = expr.get('properties'); + const properties = []; + for (const propertyPath of propertyPaths) { + if (propertyPath.isObjectProperty()) { + const loweredKey = lowerObjectPropertyKey(builder, propertyPath); + if (!loweredKey) { + continue; + } + const valuePath = propertyPath.get('value'); + if (!valuePath.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${valuePath.type} values in ObjectExpression`, + category: ErrorCategory.Todo, + loc: (_b = valuePath.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + continue; + } + const value = lowerExpressionToTemporary(builder, valuePath); + properties.push({ + kind: 'ObjectProperty', + type: 'property', + place: value, + key: loweredKey, + }); + } + else if (propertyPath.isSpreadElement()) { + const place = lowerExpressionToTemporary(builder, propertyPath.get('argument')); + properties.push({ + kind: 'Spread', + place, + }); + } + else if (propertyPath.isObjectMethod()) { + if (propertyPath.node.kind !== 'method') { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${propertyPath.node.kind} functions in ObjectExpression`, + category: ErrorCategory.Todo, + loc: (_c = propertyPath.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + continue; + } + const method = lowerObjectMethod(builder, propertyPath); + const place = lowerValueToTemporary(builder, method); + const loweredKey = lowerObjectPropertyKey(builder, propertyPath); + if (!loweredKey) { + continue; + } + properties.push({ + kind: 'ObjectProperty', + type: 'method', + place, + key: loweredKey, + }); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${propertyPath.type} properties in ObjectExpression`, + category: ErrorCategory.Todo, + loc: (_d = propertyPath.node.loc) !== null && _d !== void 0 ? _d : null, + suggestions: null, + })); + continue; + } + } + return { + kind: 'ObjectExpression', + properties, + loc: exprLoc, + }; + } + case 'ArrayExpression': { + const expr = exprPath; + let elements = []; + for (const element of expr.get('elements')) { + if (element.node == null) { + elements.push({ + kind: 'Hole', + }); + continue; + } + else if (element.isExpression()) { + elements.push(lowerExpressionToTemporary(builder, element)); + } + else if (element.isSpreadElement()) { + const place = lowerExpressionToTemporary(builder, element.get('argument')); + elements.push({ kind: 'Spread', place }); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${element.type} elements in ArrayExpression`, + category: ErrorCategory.Todo, + loc: (_e = element.node.loc) !== null && _e !== void 0 ? _e : null, + suggestions: null, + })); + continue; + } + } + return { + kind: 'ArrayExpression', + elements, + loc: exprLoc, + }; + } + case 'NewExpression': { + const expr = exprPath; + const calleePath = expr.get('callee'); + if (!calleePath.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected an expression as the \`new\` expression receiver (v8 intrinsics are not supported)`, + description: `Got a \`${calleePath.node.type}\``, + category: ErrorCategory.Syntax, + loc: (_f = calleePath.node.loc) !== null && _f !== void 0 ? _f : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const callee = lowerExpressionToTemporary(builder, calleePath); + const args = lowerArguments(builder, expr.get('arguments')); + return { + kind: 'NewExpression', + callee, + args, + loc: exprLoc, + }; + } + case 'OptionalCallExpression': { + const expr = exprPath; + return lowerOptionalCallExpression(builder, expr, null); + } + case 'CallExpression': { + const expr = exprPath; + const calleePath = expr.get('callee'); + if (!calleePath.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected Expression, got ${calleePath.type} in CallExpression (v8 intrinsics not supported). This error is likely caused by a bug in React Compiler. Please file an issue`, + category: ErrorCategory.Todo, + loc: (_g = calleePath.node.loc) !== null && _g !== void 0 ? _g : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + if (calleePath.isMemberExpression()) { + const memberExpr = lowerMemberExpression(builder, calleePath); + const propertyPlace = lowerValueToTemporary(builder, memberExpr.value); + const args = lowerArguments(builder, expr.get('arguments')); + return { + kind: 'MethodCall', + receiver: memberExpr.object, + property: Object.assign({}, propertyPlace), + args, + loc: exprLoc, + }; + } + else { + const callee = lowerExpressionToTemporary(builder, calleePath); + const args = lowerArguments(builder, expr.get('arguments')); + return { + kind: 'CallExpression', + callee, + args, + loc: exprLoc, + }; + } + } + case 'BinaryExpression': { + const expr = exprPath; + const leftPath = expr.get('left'); + if (!leftPath.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Expected Expression, got ${leftPath.type} lval in BinaryExpression`, + category: ErrorCategory.Todo, + loc: (_h = leftPath.node.loc) !== null && _h !== void 0 ? _h : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const left = lowerExpressionToTemporary(builder, leftPath); + const right = lowerExpressionToTemporary(builder, expr.get('right')); + const operator = expr.node.operator; + if (operator === '|>') { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Pipe operator not supported`, + category: ErrorCategory.Todo, + loc: (_j = leftPath.node.loc) !== null && _j !== void 0 ? _j : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + return { + kind: 'BinaryExpression', + operator, + left, + right, + loc: exprLoc, + }; + } + case 'SequenceExpression': { + const expr = exprPath; + const exprLoc = (_k = expr.node.loc) !== null && _k !== void 0 ? _k : GeneratedSource; + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const place = buildTemporaryPlace(builder, exprLoc); + const sequenceBlock = builder.enter('sequence', _ => { + var _a; + let last = null; + for (const item of expr.get('expressions')) { + last = lowerExpressionToTemporary(builder, item); + } + if (last === null) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected sequence expression to have at least one expression`, + category: ErrorCategory.Syntax, + loc: (_a = expr.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + } + else { + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: last, + type: null, + loc: exprLoc, + }); + } + return { + kind: 'goto', + id: makeInstructionId(0), + block: continuationBlock.id, + loc: exprLoc, + variant: GotoVariant.Break, + }; + }); + builder.terminateWithContinuation({ + kind: 'sequence', + block: sequenceBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: exprLoc, + }, continuationBlock); + return { kind: 'LoadLocal', place, loc: place.loc }; + } + case 'ConditionalExpression': { + const expr = exprPath; + const exprLoc = (_l = expr.node.loc) !== null && _l !== void 0 ? _l : GeneratedSource; + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const testBlock = builder.reserve('value'); + const place = buildTemporaryPlace(builder, exprLoc); + const consequentBlock = builder.enter('value', _blockId => { + var _a; + const consequentPath = expr.get('consequent'); + const consequent = lowerExpressionToTemporary(builder, consequentPath); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: consequent, + type: null, + loc: exprLoc, + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_a = consequentPath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + const alternateBlock = builder.enter('value', _blockId => { + var _a; + const alternatePath = expr.get('alternate'); + const alternate = lowerExpressionToTemporary(builder, alternatePath); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: alternate, + type: null, + loc: exprLoc, + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_a = alternatePath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + builder.terminateWithContinuation({ + kind: 'ternary', + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + test: testBlock.id, + loc: exprLoc, + }, testBlock); + const testPlace = lowerExpressionToTemporary(builder, expr.get('test')); + builder.terminateWithContinuation({ + kind: 'branch', + test: Object.assign({}, testPlace), + consequent: consequentBlock, + alternate: alternateBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: exprLoc, + }, continuationBlock); + return { kind: 'LoadLocal', place, loc: place.loc }; + } + case 'LogicalExpression': { + const expr = exprPath; + const exprLoc = (_m = expr.node.loc) !== null && _m !== void 0 ? _m : GeneratedSource; + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const testBlock = builder.reserve('value'); + const place = buildTemporaryPlace(builder, exprLoc); + const leftPlace = buildTemporaryPlace(builder, (_o = expr.get('left').node.loc) !== null && _o !== void 0 ? _o : GeneratedSource); + const consequent = builder.enter('value', () => { + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, leftPlace), + type: null, + loc: leftPlace.loc, + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: leftPlace.loc, + }; + }); + const alternate = builder.enter('value', () => { + const right = lowerExpressionToTemporary(builder, expr.get('right')); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, right), + type: null, + loc: right.loc, + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: right.loc, + }; + }); + builder.terminateWithContinuation({ + kind: 'logical', + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + test: testBlock.id, + operator: expr.node.operator, + loc: exprLoc, + }, testBlock); + const leftValue = lowerExpressionToTemporary(builder, expr.get('left')); + builder.push({ + id: makeInstructionId(0), + lvalue: Object.assign({}, leftPlace), + value: { + kind: 'LoadLocal', + place: leftValue, + loc: exprLoc, + }, + effects: null, + loc: exprLoc, + }); + builder.terminateWithContinuation({ + kind: 'branch', + test: Object.assign({}, leftPlace), + consequent, + alternate, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: exprLoc, + }, continuationBlock); + return { kind: 'LoadLocal', place, loc: place.loc }; + } + case 'AssignmentExpression': { + const expr = exprPath; + const operator = expr.node.operator; + if (operator === '=') { + const left = expr.get('left'); + if (left.isLVal()) { + return lowerAssignment(builder, (_p = left.node.loc) !== null && _p !== void 0 ? _p : GeneratedSource, InstructionKind.Reassign, left, lowerExpressionToTemporary(builder, expr.get('right')), left.isArrayPattern() || left.isObjectPattern() + ? 'Destructure' + : 'Assignment'); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Unsupported syntax on the left side of an AssignmentExpression`, + description: `Expected an LVal, got: ${left.type}`, + category: ErrorCategory.Todo, + loc: (_q = left.node.loc) !== null && _q !== void 0 ? _q : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + } + const operators = { + '+=': '+', + '-=': '-', + '/=': '/', + '%=': '%', + '*=': '*', + '**=': '**', + '&=': '&', + '|=': '|', + '>>=': '>>', + '>>>=': '>>>', + '<<=': '<<', + '^=': '^', + }; + const binaryOperator = operators[operator]; + if (binaryOperator == null) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${operator} operators in AssignmentExpression`, + category: ErrorCategory.Todo, + loc: (_r = expr.node.loc) !== null && _r !== void 0 ? _r : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const left = expr.get('left'); + const leftNode = left.node; + switch (leftNode.type) { + case 'Identifier': { + const leftExpr = left; + const leftPlace = lowerExpressionToTemporary(builder, leftExpr); + const right = lowerExpressionToTemporary(builder, expr.get('right')); + const binaryPlace = lowerValueToTemporary(builder, { + kind: 'BinaryExpression', + operator: binaryOperator, + left: leftPlace, + right, + loc: exprLoc, + }); + const binding = builder.resolveIdentifier(leftExpr); + if (binding.kind === 'Identifier') { + const identifier = lowerIdentifier(builder, leftExpr); + const kind = getStoreKind(builder, leftExpr); + if (kind === 'StoreLocal') { + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { + place: Object.assign({}, identifier), + kind: InstructionKind.Reassign, + }, + value: Object.assign({}, binaryPlace), + type: null, + loc: exprLoc, + }); + return { kind: 'LoadLocal', place: identifier, loc: exprLoc }; + } + else { + lowerValueToTemporary(builder, { + kind: 'StoreContext', + lvalue: { + place: Object.assign({}, identifier), + kind: InstructionKind.Reassign, + }, + value: Object.assign({}, binaryPlace), + loc: exprLoc, + }); + return { kind: 'LoadContext', place: identifier, loc: exprLoc }; + } + } + else { + const temporary = lowerValueToTemporary(builder, { + kind: 'StoreGlobal', + name: leftExpr.node.name, + value: Object.assign({}, binaryPlace), + loc: exprLoc, + }); + return { kind: 'LoadLocal', place: temporary, loc: temporary.loc }; + } + } + case 'MemberExpression': { + const leftExpr = left; + const { object, property, value } = lowerMemberExpression(builder, leftExpr); + const previousValuePlace = lowerValueToTemporary(builder, value); + const newValuePlace = lowerValueToTemporary(builder, { + kind: 'BinaryExpression', + operator: binaryOperator, + left: Object.assign({}, previousValuePlace), + right: lowerExpressionToTemporary(builder, expr.get('right')), + loc: (_s = leftExpr.node.loc) !== null && _s !== void 0 ? _s : GeneratedSource, + }); + if (typeof property === 'string' || typeof property === 'number') { + return { + kind: 'PropertyStore', + object: Object.assign({}, object), + property: makePropertyLiteral(property), + value: Object.assign({}, newValuePlace), + loc: (_t = leftExpr.node.loc) !== null && _t !== void 0 ? _t : GeneratedSource, + }; + } + else { + return { + kind: 'ComputedStore', + object: Object.assign({}, object), + property: Object.assign({}, property), + value: Object.assign({}, newValuePlace), + loc: (_u = leftExpr.node.loc) !== null && _u !== void 0 ? _u : GeneratedSource, + }; + } + } + default: { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Expected Identifier or MemberExpression, got ${expr.type} lval in AssignmentExpression`, + category: ErrorCategory.Todo, + loc: (_v = expr.node.loc) !== null && _v !== void 0 ? _v : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + } + } + case 'OptionalMemberExpression': { + const expr = exprPath; + const { value } = lowerOptionalMemberExpression(builder, expr, null); + return { kind: 'LoadLocal', place: value, loc: value.loc }; + } + case 'MemberExpression': { + const expr = exprPath; + const { value } = lowerMemberExpression(builder, expr); + const place = lowerValueToTemporary(builder, value); + return { kind: 'LoadLocal', place, loc: place.loc }; + } + case 'JSXElement': { + const expr = exprPath; + const opening = expr.get('openingElement'); + const openingLoc = (_w = opening.node.loc) !== null && _w !== void 0 ? _w : GeneratedSource; + const tag = lowerJsxElementName(builder, opening.get('name')); + const props = []; + for (const attribute of opening.get('attributes')) { + if (attribute.isJSXSpreadAttribute()) { + const argument = lowerExpressionToTemporary(builder, attribute.get('argument')); + props.push({ kind: 'JsxSpreadAttribute', argument }); + continue; + } + if (!attribute.isJSXAttribute()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${attribute.type} attributes in JSXElement`, + category: ErrorCategory.Todo, + loc: (_x = attribute.node.loc) !== null && _x !== void 0 ? _x : null, + suggestions: null, + })); + continue; + } + const namePath = attribute.get('name'); + let propName; + if (namePath.isJSXIdentifier()) { + propName = namePath.node.name; + if (propName.indexOf(':') !== -1) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Unexpected colon in attribute name \`${propName}\``, + category: ErrorCategory.Todo, + loc: (_y = namePath.node.loc) !== null && _y !== void 0 ? _y : null, + suggestions: null, + })); + } + } + else { + CompilerError.invariant(namePath.isJSXNamespacedName(), { + reason: 'Refinement', + loc: (_z = namePath.node.loc) !== null && _z !== void 0 ? _z : GeneratedSource, + }); + const namespace = namePath.node.namespace.name; + const name = namePath.node.name.name; + propName = `${namespace}:${name}`; + } + const valueExpr = attribute.get('value'); + let value; + if (valueExpr.isJSXElement() || valueExpr.isStringLiteral()) { + value = lowerExpressionToTemporary(builder, valueExpr); + } + else if (valueExpr.type == null) { + value = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: true, + loc: (_0 = attribute.node.loc) !== null && _0 !== void 0 ? _0 : GeneratedSource, + }); + } + else { + if (!valueExpr.isJSXExpressionContainer()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${valueExpr.type} attribute values in JSXElement`, + category: ErrorCategory.Todo, + loc: (_2 = (_1 = valueExpr.node) === null || _1 === void 0 ? void 0 : _1.loc) !== null && _2 !== void 0 ? _2 : null, + suggestions: null, + })); + continue; + } + const expression = valueExpr.get('expression'); + if (!expression.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${expression.type} expressions in JSXExpressionContainer within JSXElement`, + category: ErrorCategory.Todo, + loc: (_3 = valueExpr.node.loc) !== null && _3 !== void 0 ? _3 : null, + suggestions: null, + })); + continue; + } + value = lowerExpressionToTemporary(builder, expression); + } + props.push({ kind: 'JsxAttribute', name: propName, place: value }); + } + const isFbt = tag.kind === 'BuiltinTag' && (tag.name === 'fbt' || tag.name === 'fbs'); + if (isFbt) { + const tagName = tag.name; + const openingIdentifier = opening.get('name'); + const tagIdentifier = openingIdentifier.isJSXIdentifier() + ? builder.resolveIdentifier(openingIdentifier) + : null; + if (tagIdentifier != null) { + CompilerError.invariant(tagIdentifier.kind !== 'Identifier', { + reason: `<${tagName}> tags should be module-level imports`, + loc: (_4 = openingIdentifier.node.loc) !== null && _4 !== void 0 ? _4 : GeneratedSource, + }); + } + const fbtLocations = { + enum: new Array(), + plural: new Array(), + pronoun: new Array(), + }; + expr.traverse({ + JSXClosingElement(path) { + path.skip(); + }, + JSXNamespacedName(path) { + var _a, _b, _c; + if (path.node.namespace.name === tagName) { + switch (path.node.name.name) { + case 'enum': + fbtLocations.enum.push((_a = path.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource); + break; + case 'plural': + fbtLocations.plural.push((_b = path.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource); + break; + case 'pronoun': + fbtLocations.pronoun.push((_c = path.node.loc) !== null && _c !== void 0 ? _c : GeneratedSource); + break; + } + } + }, + }); + for (const [name, locations] of Object.entries(fbtLocations)) { + if (locations.length > 1) { + builder.recordError(new CompilerDiagnostic({ + category: ErrorCategory.Todo, + reason: 'Support duplicate fbt tags', + description: `Support \`<${tagName}>\` tags with multiple \`<${tagName}:${name}>\` values`, + details: locations.map(loc => { + return { + kind: 'error', + message: `Multiple \`<${tagName}:${name}>\` tags found`, + loc, + }; + }), + })); + } + } + } + isFbt && builder.fbtDepth++; + const children = expr + .get('children') + .map(child => lowerJsxElement(builder, child)) + .filter(notNull); + isFbt && builder.fbtDepth--; + return { + kind: 'JsxExpression', + tag, + props, + children: children.length === 0 ? null : children, + loc: exprLoc, + openingLoc: openingLoc, + closingLoc: (_6 = (_5 = expr.get('closingElement').node) === null || _5 === void 0 ? void 0 : _5.loc) !== null && _6 !== void 0 ? _6 : GeneratedSource, + }; + } + case 'JSXFragment': { + const expr = exprPath; + const children = expr + .get('children') + .map(child => lowerJsxElement(builder, child)) + .filter(notNull); + return { + kind: 'JsxFragment', + children, + loc: exprLoc, + }; + } + case 'ArrowFunctionExpression': + case 'FunctionExpression': { + const expr = exprPath; + return lowerFunctionToValue(builder, expr); + } + case 'TaggedTemplateExpression': { + const expr = exprPath; + if (expr.get('quasi').get('expressions').length !== 0) { + builder.recordError(new CompilerErrorDetail({ + reason: '(BuildHIR::lowerExpression) Handle tagged template with interpolations', + category: ErrorCategory.Todo, + loc: (_7 = exprPath.node.loc) !== null && _7 !== void 0 ? _7 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + CompilerError.invariant(expr.get('quasi').get('quasis').length == 1, { + reason: "there should be only one quasi as we don't support interpolations yet", + loc: (_8 = expr.node.loc) !== null && _8 !== void 0 ? _8 : GeneratedSource, + }); + const value = expr.get('quasi').get('quasis').at(0).node.value; + if (value.raw !== value.cooked) { + builder.recordError(new CompilerErrorDetail({ + reason: '(BuildHIR::lowerExpression) Handle tagged template where cooked value is different from raw value', + category: ErrorCategory.Todo, + loc: (_9 = exprPath.node.loc) !== null && _9 !== void 0 ? _9 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + return { + kind: 'TaggedTemplateExpression', + tag: lowerExpressionToTemporary(builder, expr.get('tag')), + value, + loc: exprLoc, + }; + } + case 'TemplateLiteral': { + const expr = exprPath; + const subexprs = expr.get('expressions'); + const quasis = expr.get('quasis'); + if (subexprs.length !== quasis.length - 1) { + builder.recordError(new CompilerErrorDetail({ + reason: `Unexpected quasi and subexpression lengths in template literal`, + category: ErrorCategory.Syntax, + loc: (_10 = exprPath.node.loc) !== null && _10 !== void 0 ? _10 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + if (subexprs.some(e => !e.isExpression())) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle TSType in TemplateLiteral.`, + category: ErrorCategory.Todo, + loc: (_11 = exprPath.node.loc) !== null && _11 !== void 0 ? _11 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const subexprPlaces = subexprs.map(e => lowerExpressionToTemporary(builder, e)); + return { + kind: 'TemplateLiteral', + subexprs: subexprPlaces, + quasis: expr.get('quasis').map(q => q.node.value), + loc: exprLoc, + }; + } + case 'UnaryExpression': { + let expr = exprPath; + if (expr.node.operator === 'delete') { + const argument = expr.get('argument'); + if (argument.isMemberExpression()) { + const { object, property } = lowerMemberExpression(builder, argument); + if (typeof property === 'string' || typeof property === 'number') { + return { + kind: 'PropertyDelete', + object, + property: makePropertyLiteral(property), + loc: exprLoc, + }; + } + else { + return { + kind: 'ComputedDelete', + object, + property, + loc: exprLoc, + }; + } + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `Only object properties can be deleted`, + category: ErrorCategory.Syntax, + loc: (_12 = expr.node.loc) !== null && _12 !== void 0 ? _12 : null, + suggestions: [ + { + description: 'Remove this line', + range: [expr.node.start, expr.node.end], + op: CompilerSuggestionOperation.Remove, + }, + ], + })); + return { kind: 'UnsupportedNode', node: expr.node, loc: exprLoc }; + } + } + else if (expr.node.operator === 'throw') { + builder.recordError(new CompilerErrorDetail({ + reason: `Throw expressions are not supported`, + category: ErrorCategory.Syntax, + loc: (_13 = expr.node.loc) !== null && _13 !== void 0 ? _13 : null, + suggestions: [ + { + description: 'Remove this line', + range: [expr.node.start, expr.node.end], + op: CompilerSuggestionOperation.Remove, + }, + ], + })); + return { kind: 'UnsupportedNode', node: expr.node, loc: exprLoc }; + } + else { + return { + kind: 'UnaryExpression', + operator: expr.node.operator, + value: lowerExpressionToTemporary(builder, expr.get('argument')), + loc: exprLoc, + }; + } + } + case 'AwaitExpression': { + let expr = exprPath; + return { + kind: 'Await', + value: lowerExpressionToTemporary(builder, expr.get('argument')), + loc: exprLoc, + }; + } + case 'TypeCastExpression': { + let expr = exprPath; + const typeAnnotation = expr.get('typeAnnotation').get('typeAnnotation'); + return { + kind: 'TypeCastExpression', + value: lowerExpressionToTemporary(builder, expr.get('expression')), + typeAnnotation: typeAnnotation.node, + typeAnnotationKind: 'cast', + type: lowerType(typeAnnotation.node), + loc: exprLoc, + }; + } + case 'TSSatisfiesExpression': { + let expr = exprPath; + const typeAnnotation = expr.get('typeAnnotation'); + return { + kind: 'TypeCastExpression', + value: lowerExpressionToTemporary(builder, expr.get('expression')), + typeAnnotation: typeAnnotation.node, + typeAnnotationKind: 'satisfies', + type: lowerType(typeAnnotation.node), + loc: exprLoc, + }; + } + case 'TSAsExpression': { + let expr = exprPath; + const typeAnnotation = expr.get('typeAnnotation'); + return { + kind: 'TypeCastExpression', + value: lowerExpressionToTemporary(builder, expr.get('expression')), + typeAnnotation: typeAnnotation.node, + typeAnnotationKind: 'as', + type: lowerType(typeAnnotation.node), + loc: exprLoc, + }; + } + case 'UpdateExpression': { + let expr = exprPath; + const argument = expr.get('argument'); + if (argument.isMemberExpression()) { + const binaryOperator = expr.node.operator === '++' ? '+' : '-'; + const leftExpr = argument; + const { object, property, value } = lowerMemberExpression(builder, leftExpr); + const previousValuePlace = lowerValueToTemporary(builder, value); + const updatedValue = lowerValueToTemporary(builder, { + kind: 'BinaryExpression', + operator: binaryOperator, + left: Object.assign({}, previousValuePlace), + right: lowerValueToTemporary(builder, { + kind: 'Primitive', + value: 1, + loc: GeneratedSource, + }), + loc: (_14 = leftExpr.node.loc) !== null && _14 !== void 0 ? _14 : GeneratedSource, + }); + let newValuePlace; + if (typeof property === 'string' || typeof property === 'number') { + newValuePlace = lowerValueToTemporary(builder, { + kind: 'PropertyStore', + object: Object.assign({}, object), + property: makePropertyLiteral(property), + value: Object.assign({}, updatedValue), + loc: (_15 = leftExpr.node.loc) !== null && _15 !== void 0 ? _15 : GeneratedSource, + }); + } + else { + newValuePlace = lowerValueToTemporary(builder, { + kind: 'ComputedStore', + object: Object.assign({}, object), + property: Object.assign({}, property), + value: Object.assign({}, updatedValue), + loc: (_16 = leftExpr.node.loc) !== null && _16 !== void 0 ? _16 : GeneratedSource, + }); + } + return { + kind: 'LoadLocal', + place: expr.node.prefix + ? Object.assign({}, newValuePlace) : Object.assign({}, previousValuePlace), + loc: exprLoc, + }; + } + if (!argument.isIdentifier()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle UpdateExpression with ${argument.type} argument`, + category: ErrorCategory.Todo, + loc: (_17 = exprPath.node.loc) !== null && _17 !== void 0 ? _17 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + else if (builder.isContextIdentifier(argument)) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle UpdateExpression to variables captured within lambdas.`, + category: ErrorCategory.Todo, + loc: (_18 = exprPath.node.loc) !== null && _18 !== void 0 ? _18 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const lvalue = lowerIdentifierForAssignment(builder, (_19 = argument.node.loc) !== null && _19 !== void 0 ? _19 : GeneratedSource, InstructionKind.Reassign, argument); + if (lvalue === null) { + if (!builder.environment.hasErrors()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Found an invalid UpdateExpression without a previously reported error`, + category: ErrorCategory.Invariant, + loc: exprLoc, + suggestions: null, + })); + } + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + else if (lvalue.kind === 'Global') { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Support UpdateExpression where argument is a global`, + category: ErrorCategory.Todo, + loc: exprLoc, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const value = lowerIdentifier(builder, argument); + if (expr.node.prefix) { + return { + kind: 'PrefixUpdate', + lvalue, + operation: expr.node.operator, + value, + loc: exprLoc, + }; + } + else { + return { + kind: 'PostfixUpdate', + lvalue, + operation: expr.node.operator, + value, + loc: exprLoc, + }; + } + } + case 'RegExpLiteral': { + let expr = exprPath; + return { + kind: 'RegExpLiteral', + pattern: expr.node.pattern, + flags: expr.node.flags, + loc: (_20 = expr.node.loc) !== null && _20 !== void 0 ? _20 : GeneratedSource, + }; + } + case 'TSInstantiationExpression': + case 'TSNonNullExpression': { + let expr = exprPath; + return lowerExpression(builder, expr.get('expression')); + } + case 'MetaProperty': { + let expr = exprPath; + if (expr.node.meta.name === 'import' && + expr.node.property.name === 'meta') { + return { + kind: 'MetaProperty', + meta: expr.node.meta.name, + property: expr.node.property.name, + loc: (_21 = expr.node.loc) !== null && _21 !== void 0 ? _21 : GeneratedSource, + }; + } + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle MetaProperty expressions other than import.meta`, + category: ErrorCategory.Todo, + loc: (_22 = exprPath.node.loc) !== null && _22 !== void 0 ? _22 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + default: { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${exprPath.type} expressions`, + category: ErrorCategory.Todo, + loc: (_23 = exprPath.node.loc) !== null && _23 !== void 0 ? _23 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + } +} +function lowerOptionalMemberExpression(builder, expr, parentAlternate) { + var _a; + const optional = expr.node.optional; + const loc = (_a = expr.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const place = buildTemporaryPlace(builder, loc); + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const consequent = builder.reserve('value'); + const alternate = parentAlternate !== null + ? parentAlternate + : builder.enter('value', () => { + const temp = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc, + }); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, temp), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + let object = null; + const testBlock = builder.enter('value', () => { + const objectPath = expr.get('object'); + if (objectPath.isOptionalMemberExpression()) { + const { value } = lowerOptionalMemberExpression(builder, objectPath, alternate); + object = value; + } + else if (objectPath.isOptionalCallExpression()) { + const value = lowerOptionalCallExpression(builder, objectPath, alternate); + object = lowerValueToTemporary(builder, value); + } + else { + object = lowerExpressionToTemporary(builder, objectPath); + } + return { + kind: 'branch', + test: Object.assign({}, object), + consequent: consequent.id, + alternate, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + CompilerError.invariant(object !== null, { + reason: 'Satisfy type checker', + loc: GeneratedSource, + }); + builder.enterReserved(consequent, () => { + const { value } = lowerMemberExpression(builder, expr, object); + const temp = lowerValueToTemporary(builder, value); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, temp), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + builder.terminateWithContinuation({ + kind: 'optional', + optional, + test: testBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }, continuationBlock); + return { object, value: place }; +} +function lowerOptionalCallExpression(builder, expr, parentAlternate) { + var _a; + const optional = expr.node.optional; + const calleePath = expr.get('callee'); + const loc = (_a = expr.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const place = buildTemporaryPlace(builder, loc); + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const consequent = builder.reserve('value'); + const alternate = parentAlternate !== null + ? parentAlternate + : builder.enter('value', () => { + const temp = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc, + }); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, temp), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + let callee; + const testBlock = builder.enter('value', () => { + if (calleePath.isOptionalCallExpression()) { + const value = lowerOptionalCallExpression(builder, calleePath, alternate); + const valuePlace = lowerValueToTemporary(builder, value); + callee = { + kind: 'CallExpression', + callee: valuePlace, + }; + } + else if (calleePath.isOptionalMemberExpression()) { + const { object, value } = lowerOptionalMemberExpression(builder, calleePath, alternate); + callee = { + kind: 'MethodCall', + receiver: object, + property: value, + }; + } + else if (calleePath.isMemberExpression()) { + const memberExpr = lowerMemberExpression(builder, calleePath); + const propertyPlace = lowerValueToTemporary(builder, memberExpr.value); + callee = { + kind: 'MethodCall', + receiver: memberExpr.object, + property: propertyPlace, + }; + } + else { + callee = { + kind: 'CallExpression', + callee: lowerExpressionToTemporary(builder, calleePath), + }; + } + const testPlace = callee.kind === 'CallExpression' ? callee.callee : callee.property; + return { + kind: 'branch', + test: Object.assign({}, testPlace), + consequent: consequent.id, + alternate, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + builder.enterReserved(consequent, () => { + const args = lowerArguments(builder, expr.get('arguments')); + const temp = buildTemporaryPlace(builder, loc); + if (callee.kind === 'CallExpression') { + builder.push({ + id: makeInstructionId(0), + lvalue: Object.assign({}, temp), + value: { + kind: 'CallExpression', + callee: Object.assign({}, callee.callee), + args, + loc, + }, + effects: null, + loc, + }); + } + else { + builder.push({ + id: makeInstructionId(0), + lvalue: Object.assign({}, temp), + value: { + kind: 'MethodCall', + receiver: Object.assign({}, callee.receiver), + property: Object.assign({}, callee.property), + args, + loc, + }, + effects: null, + loc, + }); + } + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, temp), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + builder.terminateWithContinuation({ + kind: 'optional', + optional, + test: testBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }, continuationBlock); + return { kind: 'LoadLocal', place, loc: place.loc }; +} +function lowerReorderableExpression(builder, expr) { + var _a; + if (!isReorderableExpression(builder, expr, true)) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::node.lowerReorderableExpression) Expression type \`${expr.type}\` cannot be safely reordered`, + category: ErrorCategory.Todo, + loc: (_a = expr.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + } + return lowerExpressionToTemporary(builder, expr); +} +function isReorderableExpression(builder, expr, allowLocalIdentifiers) { + switch (expr.node.type) { + case 'Identifier': { + const binding = builder.resolveIdentifier(expr); + if (binding.kind === 'Identifier') { + return allowLocalIdentifiers; + } + else { + return true; + } + } + case 'TSInstantiationExpression': { + const innerExpr = expr.get('expression'); + return isReorderableExpression(builder, innerExpr, allowLocalIdentifiers); + } + case 'RegExpLiteral': + case 'StringLiteral': + case 'NumericLiteral': + case 'NullLiteral': + case 'BooleanLiteral': + case 'BigIntLiteral': { + return true; + } + case 'UnaryExpression': { + const unary = expr; + switch (expr.node.operator) { + case '!': + case '+': + case '-': { + return isReorderableExpression(builder, unary.get('argument'), allowLocalIdentifiers); + } + default: { + return false; + } + } + } + case 'TSAsExpression': + case 'TSNonNullExpression': + case 'TypeCastExpression': { + return isReorderableExpression(builder, expr.get('expression'), allowLocalIdentifiers); + } + case 'LogicalExpression': { + const logical = expr; + return (isReorderableExpression(builder, logical.get('left'), allowLocalIdentifiers) && + isReorderableExpression(builder, logical.get('right'), allowLocalIdentifiers)); + } + case 'ConditionalExpression': { + const conditional = expr; + return (isReorderableExpression(builder, conditional.get('test'), allowLocalIdentifiers) && + isReorderableExpression(builder, conditional.get('consequent'), allowLocalIdentifiers) && + isReorderableExpression(builder, conditional.get('alternate'), allowLocalIdentifiers)); + } + case 'ArrayExpression': { + return expr + .get('elements') + .every(element => element.isExpression() && + isReorderableExpression(builder, element, allowLocalIdentifiers)); + } + case 'ObjectExpression': { + return expr + .get('properties') + .every(property => { + if (!property.isObjectProperty() || property.node.computed) { + return false; + } + const value = property.get('value'); + return (value.isExpression() && + isReorderableExpression(builder, value, allowLocalIdentifiers)); + }); + } + case 'MemberExpression': { + const test = expr; + let innerObject = test; + while (innerObject.isMemberExpression()) { + innerObject = innerObject.get('object'); + } + if (innerObject.isIdentifier() && + builder.resolveIdentifier(innerObject).kind !== 'Identifier') { + return true; + } + else { + return false; + } + } + case 'ArrowFunctionExpression': { + const fn = expr; + const body = fn.get('body'); + if (body.node.type === 'BlockStatement') { + return body.node.body.length === 0; + } + else { + invariant(body.isExpression(), 'Expected an expression'); + return isReorderableExpression(builder, body, false); + } + } + case 'CallExpression': { + const call = expr; + const callee = call.get('callee'); + return (callee.isExpression() && + isReorderableExpression(builder, callee, allowLocalIdentifiers) && + call + .get('arguments') + .every(arg => arg.isExpression() && + isReorderableExpression(builder, arg, allowLocalIdentifiers))); + } + case 'NewExpression': { + const newExpr = expr; + const callee = newExpr.get('callee'); + return (callee.isExpression() && + isReorderableExpression(builder, callee, allowLocalIdentifiers) && + newExpr + .get('arguments') + .every(arg => arg.isExpression() && + isReorderableExpression(builder, arg, allowLocalIdentifiers))); + } + default: { + return false; + } + } +} +function lowerArguments(builder, expr) { + var _a; + let args = []; + for (const argPath of expr) { + if (argPath.isSpreadElement()) { + args.push({ + kind: 'Spread', + place: lowerExpressionToTemporary(builder, argPath.get('argument')), + }); + } + else if (argPath.isExpression()) { + args.push(lowerExpressionToTemporary(builder, argPath)); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${argPath.type} arguments in CallExpression`, + category: ErrorCategory.Todo, + loc: (_a = argPath.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + } + } + return args; +} +function lowerMemberExpression(builder, expr, loweredObject = null) { + var _a, _b, _c; + const exprNode = expr.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const objectNode = expr.get('object'); + const propertyNode = expr.get('property'); + const object = loweredObject !== null && loweredObject !== void 0 ? loweredObject : lowerExpressionToTemporary(builder, objectNode); + if (!expr.node.computed || expr.node.property.type === 'NumericLiteral') { + let property; + if (propertyNode.isIdentifier()) { + property = makePropertyLiteral(propertyNode.node.name); + } + else if (propertyNode.isNumericLiteral()) { + property = makePropertyLiteral(propertyNode.node.value); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerMemberExpression) Handle ${propertyNode.type} property`, + category: ErrorCategory.Todo, + loc: (_b = propertyNode.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + return { + object, + property: propertyNode.toString(), + value: { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }, + }; + } + const value = { + kind: 'PropertyLoad', + object: Object.assign({}, object), + property, + loc: exprLoc, + }; + return { object, property, value }; + } + else { + if (!propertyNode.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerMemberExpression) Expected Expression, got ${propertyNode.type} property`, + category: ErrorCategory.Todo, + loc: (_c = propertyNode.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + return { + object, + property: propertyNode.toString(), + value: { + kind: 'UnsupportedNode', + node: exprNode, + loc: exprLoc, + }, + }; + } + const property = lowerExpressionToTemporary(builder, propertyNode); + const value = { + kind: 'ComputedLoad', + object: Object.assign({}, object), + property: Object.assign({}, property), + loc: exprLoc, + }; + return { object, property, value }; + } +} +function lowerJsxElementName(builder, exprPath) { + var _a, _b, _c; + const exprNode = exprPath.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + if (exprPath.isJSXIdentifier()) { + const tag = exprPath.node.name; + if (tag.match(/^[A-Z]/)) { + const kind = getLoadKind(builder, exprPath); + return lowerValueToTemporary(builder, { + kind: kind, + place: lowerIdentifier(builder, exprPath), + loc: exprLoc, + }); + } + else { + return { + kind: 'BuiltinTag', + name: tag, + loc: exprLoc, + }; + } + } + else if (exprPath.isJSXMemberExpression()) { + return lowerJsxMemberExpression(builder, exprPath); + } + else if (exprPath.isJSXNamespacedName()) { + const namespace = exprPath.node.namespace.name; + const name = exprPath.node.name.name; + const tag = `${namespace}:${name}`; + if (namespace.indexOf(':') !== -1 || name.indexOf(':') !== -1) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected JSXNamespacedName to have no colons in the namespace or name`, + description: `Got \`${namespace}\` : \`${name}\``, + category: ErrorCategory.Syntax, + loc: (_b = exprPath.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + } + const place = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: tag, + loc: exprLoc, + }); + return place; + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerJsxElementName) Handle ${exprPath.type} tags`, + category: ErrorCategory.Todo, + loc: (_c = exprPath.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + return lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + node: exprNode, + loc: exprLoc, + }); + } +} +function lowerJsxMemberExpression(builder, exprPath) { + var _a, _b, _c; + const loc = (_a = exprPath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const object = exprPath.get('object'); + let objectPlace; + if (object.isJSXMemberExpression()) { + objectPlace = lowerJsxMemberExpression(builder, object); + } + else { + CompilerError.invariant(object.isJSXIdentifier(), { + reason: `TypeScript refinement fail: expected 'JsxIdentifier', got \`${object.node.type}\``, + loc: (_b = object.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + const kind = getLoadKind(builder, object); + objectPlace = lowerValueToTemporary(builder, { + kind: kind, + place: lowerIdentifier(builder, object), + loc: (_c = exprPath.node.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + }); + } + const property = exprPath.get('property').node.name; + return lowerValueToTemporary(builder, { + kind: 'PropertyLoad', + object: objectPlace, + property: makePropertyLiteral(property), + loc, + }); +} +function lowerJsxElement(builder, exprPath) { + var _a, _b, _c; + const exprNode = exprPath.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + if (exprPath.isJSXElement() || exprPath.isJSXFragment()) { + return lowerExpressionToTemporary(builder, exprPath); + } + else if (exprPath.isJSXExpressionContainer()) { + const expression = exprPath.get('expression'); + if (expression.isJSXEmptyExpression()) { + return null; + } + else { + CompilerError.invariant(expression.isExpression(), { + reason: `(BuildHIR::lowerJsxElement) Expected Expression but found ${expression.type}!`, + loc: (_b = expression.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + return lowerExpressionToTemporary(builder, expression); + } + } + else if (exprPath.isJSXText()) { + let text; + if (builder.fbtDepth > 0) { + text = exprPath.node.value; + } + else { + text = trimJsxText(exprPath.node.value); + } + if (text === null) { + return null; + } + const place = lowerValueToTemporary(builder, { + kind: 'JSXText', + value: text, + loc: exprLoc, + }); + return place; + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerJsxElement) Unhandled JsxElement, got: ${exprPath.type}`, + category: ErrorCategory.Todo, + loc: (_c = exprPath.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + const place = lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + node: exprNode, + loc: exprLoc, + }); + return place; + } +} +function trimJsxText(original) { + const lines = original.split(/\r\n|\n|\r/); + let lastNonEmptyLine = 0; + for (let i = 0; i < lines.length; i++) { + if (lines[i].match(/[^ \t]/)) { + lastNonEmptyLine = i; + } + } + let str = ''; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const isFirstLine = i === 0; + const isLastLine = i === lines.length - 1; + const isLastNonEmptyLine = i === lastNonEmptyLine; + let trimmedLine = line.replace(/\t/g, ' '); + if (!isFirstLine) { + trimmedLine = trimmedLine.replace(/^[ ]+/, ''); + } + if (!isLastLine) { + trimmedLine = trimmedLine.replace(/[ ]+$/, ''); + } + if (trimmedLine) { + if (!isLastNonEmptyLine) { + trimmedLine += ' '; + } + str += trimmedLine; + } + } + if (str.length !== 0) { + return str; + } + else { + return null; + } +} +function lowerFunctionToValue(builder, expr) { + var _a; + const exprNode = expr.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const loweredFunc = lowerFunction(builder, expr); + return { + kind: 'FunctionExpression', + name: loweredFunc.func.id, + nameHint: null, + type: expr.node.type, + loc: exprLoc, + loweredFunc, + }; +} +function lowerFunction(builder, expr) { + const componentScope = builder.environment.parentFunction.scope; + const capturedContext = gatherCapturedContext(expr, componentScope); + const loweredFunc = lower(expr, builder.environment, builder.bindings, new Map([...builder.context, ...capturedContext])); + return { + func: loweredFunc, + }; +} +function lowerExpressionToTemporary(builder, exprPath) { + const value = lowerExpression(builder, exprPath); + return lowerValueToTemporary(builder, value); +} +function lowerValueToTemporary(builder, value) { + if (value.kind === 'LoadLocal' && value.place.identifier.name === null) { + return value.place; + } + const place = buildTemporaryPlace(builder, value.loc); + builder.push({ + id: makeInstructionId(0), + lvalue: Object.assign({}, place), + value: value, + effects: null, + loc: value.loc, + }); + return place; +} +function lowerIdentifier(builder, exprPath) { + var _a, _b; + const exprNode = exprPath.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const binding = builder.resolveIdentifier(exprPath); + switch (binding.kind) { + case 'Identifier': { + const place = { + kind: 'Identifier', + identifier: binding.identifier, + effect: Effect.Unknown, + reactive: false, + loc: exprLoc, + }; + return place; + } + default: { + if (binding.kind === 'Global' && binding.name === 'eval') { + builder.recordError(new CompilerErrorDetail({ + reason: `The 'eval' function is not supported`, + description: 'Eval is an anti-pattern in JavaScript, and the code executed cannot be evaluated by React Compiler', + category: ErrorCategory.UnsupportedSyntax, + loc: (_b = exprPath.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + } + return lowerValueToTemporary(builder, { + kind: 'LoadGlobal', + binding, + loc: exprLoc, + }); + } + } +} +function buildTemporaryPlace(builder, loc) { + const place = { + kind: 'Identifier', + identifier: builder.makeTemporary(loc), + effect: Effect.Unknown, + reactive: false, + loc, + }; + return place; +} +function getStoreKind(builder, identifier) { + const isContext = builder.isContextIdentifier(identifier); + return isContext ? 'StoreContext' : 'StoreLocal'; +} +function getLoadKind(builder, identifier) { + const isContext = builder.isContextIdentifier(identifier); + return isContext ? 'LoadContext' : 'LoadLocal'; +} +function lowerIdentifierForAssignment(builder, loc, kind, path) { + var _a, _b; + const binding = builder.resolveIdentifier(path); + if (binding.kind !== 'Identifier') { + if (kind === InstructionKind.Reassign) { + return { kind: 'Global', name: path.node.name }; + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Could not find binding for declaration.`, + category: ErrorCategory.Invariant, + loc: (_a = path.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + return null; + } + } + else if (binding.bindingKind === 'const' && + kind === InstructionKind.Reassign) { + builder.recordError(new CompilerErrorDetail({ + reason: `Cannot reassign a \`const\` variable`, + category: ErrorCategory.Syntax, + loc: (_b = path.node.loc) !== null && _b !== void 0 ? _b : null, + description: binding.identifier.name != null + ? `\`${binding.identifier.name.value}\` is declared as const` + : null, + })); + return null; + } + const place = { + kind: 'Identifier', + identifier: binding.identifier, + effect: Effect.Unknown, + reactive: false, + loc, + }; + return place; +} +function lowerAssignment(builder, loc, kind, lvaluePath, value, assignmentKind) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4; + const lvalueNode = lvaluePath.node; + switch (lvalueNode.type) { + case 'Identifier': { + const lvalue = lvaluePath; + const place = lowerIdentifierForAssignment(builder, loc, kind, lvalue); + if (place === null) { + return { + kind: 'UnsupportedNode', + loc: (_a = lvalue.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + node: lvalue.node, + }; + } + else if (place.kind === 'Global') { + const temporary = lowerValueToTemporary(builder, { + kind: 'StoreGlobal', + name: place.name, + value, + loc, + }); + return { kind: 'LoadLocal', place: temporary, loc: temporary.loc }; + } + const isHoistedIdentifier = builder.environment.isHoistedIdentifier(lvalue.node); + let temporary; + if (builder.isContextIdentifier(lvalue)) { + if (kind === InstructionKind.Const && !isHoistedIdentifier) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected \`const\` declaration not to be reassigned`, + category: ErrorCategory.Syntax, + loc: (_b = lvalue.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + } + if (kind !== InstructionKind.Const && + kind !== InstructionKind.Reassign && + kind !== InstructionKind.Let && + kind !== InstructionKind.Function) { + builder.recordError(new CompilerErrorDetail({ + reason: `Unexpected context variable kind`, + category: ErrorCategory.Syntax, + loc: (_c = lvalue.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + temporary = lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + node: lvalueNode, + loc: (_d = lvalueNode.loc) !== null && _d !== void 0 ? _d : GeneratedSource, + }); + } + else { + temporary = lowerValueToTemporary(builder, { + kind: 'StoreContext', + lvalue: { place: Object.assign({}, place), kind }, + value, + loc, + }); + } + } + else { + const typeAnnotation = lvalue.get('typeAnnotation'); + let type; + if (typeAnnotation.isTSTypeAnnotation()) { + const typePath = typeAnnotation.get('typeAnnotation'); + type = typePath.node; + } + else if (typeAnnotation.isTypeAnnotation()) { + const typePath = typeAnnotation.get('typeAnnotation'); + type = typePath.node; + } + else { + type = null; + } + temporary = lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { place: Object.assign({}, place), kind }, + value, + type, + loc, + }); + } + return { kind: 'LoadLocal', place: temporary, loc: temporary.loc }; + } + case 'MemberExpression': { + CompilerError.invariant(kind === InstructionKind.Reassign, { + reason: 'MemberExpression may only appear in an assignment expression', + loc: (_e = lvaluePath.node.loc) !== null && _e !== void 0 ? _e : GeneratedSource, + }); + const lvalue = lvaluePath; + const property = lvalue.get('property'); + const object = lowerExpressionToTemporary(builder, lvalue.get('object')); + if (!lvalue.node.computed || lvalue.get('property').isNumericLiteral()) { + let temporary; + if (property.isIdentifier()) { + temporary = lowerValueToTemporary(builder, { + kind: 'PropertyStore', + object, + property: makePropertyLiteral(property.node.name), + value, + loc, + }); + } + else if (property.isNumericLiteral()) { + temporary = lowerValueToTemporary(builder, { + kind: 'PropertyStore', + object, + property: makePropertyLiteral(property.node.value), + value, + loc, + }); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle ${property.type} properties in MemberExpression`, + category: ErrorCategory.Todo, + loc: (_f = property.node.loc) !== null && _f !== void 0 ? _f : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: lvalueNode, loc }; + } + return { kind: 'LoadLocal', place: temporary, loc: temporary.loc }; + } + else { + if (!property.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: '(BuildHIR::lowerAssignment) Expected private name to appear as a non-computed property', + category: ErrorCategory.Todo, + loc: (_g = property.node.loc) !== null && _g !== void 0 ? _g : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: lvalueNode, loc }; + } + const propertyPlace = lowerExpressionToTemporary(builder, property); + const temporary = lowerValueToTemporary(builder, { + kind: 'ComputedStore', + object, + property: propertyPlace, + value, + loc, + }); + return { kind: 'LoadLocal', place: temporary, loc: temporary.loc }; + } + } + case 'ArrayPattern': { + const lvalue = lvaluePath; + const elements = lvalue.get('elements'); + const items = []; + const followups = []; + const forceTemporaries = kind === InstructionKind.Reassign && + (elements.some(element => !element.isIdentifier()) || + elements.some(element => element.isIdentifier() && + (getStoreKind(builder, element) !== 'StoreLocal' || + builder.resolveIdentifier(element).kind !== 'Identifier'))); + for (let i = 0; i < elements.length; i++) { + const element = elements[i]; + if (element.node == null) { + items.push({ + kind: 'Hole', + }); + continue; + } + if (element.isRestElement()) { + const argument = element.get('argument'); + if (argument.isIdentifier() && + !forceTemporaries && + (assignmentKind === 'Assignment' || + getStoreKind(builder, argument) === 'StoreLocal')) { + const identifier = lowerIdentifierForAssignment(builder, (_h = element.node.loc) !== null && _h !== void 0 ? _h : GeneratedSource, kind, argument); + if (identifier === null) { + continue; + } + else if (identifier.kind === 'Global') { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Expected reassignment of globals to enable forceTemporaries', + loc: (_j = element.node.loc) !== null && _j !== void 0 ? _j : GeneratedSource, + })); + continue; + } + items.push({ + kind: 'Spread', + place: identifier, + }); + } + else { + const temp = buildTemporaryPlace(builder, (_k = element.node.loc) !== null && _k !== void 0 ? _k : GeneratedSource); + promoteTemporary(temp.identifier); + items.push({ + kind: 'Spread', + place: Object.assign({}, temp), + }); + followups.push({ place: temp, path: argument }); + } + } + else if (element.isIdentifier() && + !forceTemporaries && + (assignmentKind === 'Assignment' || + getStoreKind(builder, element) === 'StoreLocal')) { + const identifier = lowerIdentifierForAssignment(builder, (_l = element.node.loc) !== null && _l !== void 0 ? _l : GeneratedSource, kind, element); + if (identifier === null) { + continue; + } + else if (identifier.kind === 'Global') { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Expected reassignment of globals to enable forceTemporaries', + loc: (_m = element.node.loc) !== null && _m !== void 0 ? _m : GeneratedSource, + })); + continue; + } + items.push(identifier); + } + else { + const temp = buildTemporaryPlace(builder, (_o = element.node.loc) !== null && _o !== void 0 ? _o : GeneratedSource); + promoteTemporary(temp.identifier); + items.push(Object.assign({}, temp)); + followups.push({ place: temp, path: element }); + } + } + const temporary = lowerValueToTemporary(builder, { + kind: 'Destructure', + lvalue: { + kind, + pattern: { + kind: 'ArrayPattern', + items, + loc: (_p = lvalue.node.loc) !== null && _p !== void 0 ? _p : GeneratedSource, + }, + }, + value, + loc, + }); + for (const { place, path } of followups) { + lowerAssignment(builder, (_q = path.node.loc) !== null && _q !== void 0 ? _q : loc, kind, path, place, assignmentKind); + } + return { kind: 'LoadLocal', place: temporary, loc: value.loc }; + } + case 'ObjectPattern': { + const lvalue = lvaluePath; + const propertiesPaths = lvalue.get('properties'); + const properties = []; + const followups = []; + const forceTemporaries = kind === InstructionKind.Reassign && + propertiesPaths.some(property => property.isRestElement() || + (property.isObjectProperty() && + (!property.get('value').isIdentifier() || + builder.resolveIdentifier(property.get('value')).kind !== 'Identifier'))); + for (let i = 0; i < propertiesPaths.length; i++) { + const property = propertiesPaths[i]; + if (property.isRestElement()) { + const argument = property.get('argument'); + if (!argument.isIdentifier()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle ${argument.node.type} rest element in ObjectPattern`, + category: ErrorCategory.Todo, + loc: (_r = argument.node.loc) !== null && _r !== void 0 ? _r : null, + suggestions: null, + })); + continue; + } + if (forceTemporaries || + getStoreKind(builder, argument) === 'StoreContext') { + const temp = buildTemporaryPlace(builder, (_s = property.node.loc) !== null && _s !== void 0 ? _s : GeneratedSource); + promoteTemporary(temp.identifier); + properties.push({ + kind: 'Spread', + place: Object.assign({}, temp), + }); + followups.push({ place: temp, path: argument }); + } + else { + const identifier = lowerIdentifierForAssignment(builder, (_t = property.node.loc) !== null && _t !== void 0 ? _t : GeneratedSource, kind, argument); + if (identifier === null) { + continue; + } + else if (identifier.kind === 'Global') { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Expected reassignment of globals to enable forceTemporaries', + loc: (_u = property.node.loc) !== null && _u !== void 0 ? _u : GeneratedSource, + })); + continue; + } + properties.push({ + kind: 'Spread', + place: identifier, + }); + } + } + else { + if (!property.isObjectProperty()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle ${property.type} properties in ObjectPattern`, + category: ErrorCategory.Todo, + loc: (_v = property.node.loc) !== null && _v !== void 0 ? _v : null, + suggestions: null, + })); + continue; + } + if (property.node.computed) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle computed properties in ObjectPattern`, + category: ErrorCategory.Todo, + loc: (_w = property.node.loc) !== null && _w !== void 0 ? _w : null, + suggestions: null, + })); + continue; + } + const loweredKey = lowerObjectPropertyKey(builder, property); + if (!loweredKey) { + continue; + } + const element = property.get('value'); + if (!element.isLVal()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Expected object property value to be an LVal, got: ${element.type}`, + category: ErrorCategory.Todo, + loc: (_x = element.node.loc) !== null && _x !== void 0 ? _x : null, + suggestions: null, + })); + continue; + } + if (element.isIdentifier() && + !forceTemporaries && + (assignmentKind === 'Assignment' || + getStoreKind(builder, element) === 'StoreLocal')) { + const identifier = lowerIdentifierForAssignment(builder, (_y = element.node.loc) !== null && _y !== void 0 ? _y : GeneratedSource, kind, element); + if (identifier === null) { + continue; + } + else if (identifier.kind === 'Global') { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Expected reassignment of globals to enable forceTemporaries', + loc: (_z = element.node.loc) !== null && _z !== void 0 ? _z : GeneratedSource, + })); + continue; + } + properties.push({ + kind: 'ObjectProperty', + type: 'property', + place: identifier, + key: loweredKey, + }); + } + else { + const temp = buildTemporaryPlace(builder, (_0 = element.node.loc) !== null && _0 !== void 0 ? _0 : GeneratedSource); + promoteTemporary(temp.identifier); + properties.push({ + kind: 'ObjectProperty', + type: 'property', + place: Object.assign({}, temp), + key: loweredKey, + }); + followups.push({ place: temp, path: element }); + } + } + } + const temporary = lowerValueToTemporary(builder, { + kind: 'Destructure', + lvalue: { + kind, + pattern: { + kind: 'ObjectPattern', + properties, + loc: (_1 = lvalue.node.loc) !== null && _1 !== void 0 ? _1 : GeneratedSource, + }, + }, + value, + loc, + }); + for (const { place, path } of followups) { + lowerAssignment(builder, (_2 = path.node.loc) !== null && _2 !== void 0 ? _2 : loc, kind, path, place, assignmentKind); + } + return { kind: 'LoadLocal', place: temporary, loc: value.loc }; + } + case 'AssignmentPattern': { + const lvalue = lvaluePath; + const loc = (_3 = lvalue.node.loc) !== null && _3 !== void 0 ? _3 : GeneratedSource; + const temp = buildTemporaryPlace(builder, loc); + const testBlock = builder.reserve('value'); + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const consequent = builder.enter('value', () => { + const defaultValue = lowerReorderableExpression(builder, lvalue.get('right')); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, temp) }, + value: Object.assign({}, defaultValue), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + const alternate = builder.enter('value', () => { + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, temp) }, + value: Object.assign({}, value), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + builder.terminateWithContinuation({ + kind: 'ternary', + test: testBlock.id, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }, testBlock); + const undef = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc, + }); + const test = lowerValueToTemporary(builder, { + kind: 'BinaryExpression', + left: Object.assign({}, value), + operator: '===', + right: Object.assign({}, undef), + loc, + }); + builder.terminateWithContinuation({ + kind: 'branch', + test: Object.assign({}, test), + consequent, + alternate, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }, continuationBlock); + return lowerAssignment(builder, loc, kind, lvalue.get('left'), temp, assignmentKind); + } + default: { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle ${lvaluePath.type} assignments`, + category: ErrorCategory.Todo, + loc: (_4 = lvaluePath.node.loc) !== null && _4 !== void 0 ? _4 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: lvalueNode, loc }; + } + } +} +function captureScopes({ from, to }) { + let scopes = new Set(); + while (from) { + scopes.add(from); + if (from === to) { + break; + } + from = from.parent; + } + return scopes; +} +function gatherCapturedContext(fn, componentScope) { + const capturedIds = new Map(); + const pureScopes = captureScopes({ + from: fn.scope.parent, + to: componentScope, + }); + function handleMaybeDependency(path) { + var _a, _b; + let baseIdentifier; + if (path.isJSXOpeningElement()) { + const name = path.get('name'); + if (!(name.isJSXMemberExpression() || name.isJSXIdentifier())) { + return; + } + let current = name; + while (current.isJSXMemberExpression()) { + current = current.get('object'); + } + invariant(current.isJSXIdentifier(), 'Invalid logic in gatherCapturedDeps'); + baseIdentifier = current; + } + else { + baseIdentifier = path; + } + path.skip(); + const binding = baseIdentifier.scope.getBinding(baseIdentifier.node.name); + if (binding !== undefined && + pureScopes.has(binding.scope) && + !capturedIds.has(binding.identifier)) { + capturedIds.set(binding.identifier, (_b = (_a = path.node.loc) !== null && _a !== void 0 ? _a : binding.identifier.loc) !== null && _b !== void 0 ? _b : GeneratedSource); + } + } + fn.traverse({ + TypeAnnotation(path) { + path.skip(); + }, + TSTypeAnnotation(path) { + path.skip(); + }, + TypeAlias(path) { + path.skip(); + }, + TSTypeAliasDeclaration(path) { + path.skip(); + }, + Expression(path) { + if (path.isAssignmentExpression()) { + const left = path.get('left'); + if (left.isIdentifier()) { + handleMaybeDependency(left); + } + return; + } + else if (path.isJSXElement()) { + handleMaybeDependency(path.get('openingElement')); + } + else if (path.isIdentifier()) { + handleMaybeDependency(path); + } + }, + }); + return capturedIds; +} +function notNull(value) { + return value !== null; +} +function lowerType(node) { + switch (node.type) { + case 'GenericTypeAnnotation': { + const id = node.id; + if (id.type === 'Identifier' && id.name === 'Array') { + return { kind: 'Object', shapeId: BuiltInArrayId }; + } + return makeType(); + } + case 'TSTypeReference': { + const typeName = node.typeName; + if (typeName.type === 'Identifier' && typeName.name === 'Array') { + return { kind: 'Object', shapeId: BuiltInArrayId }; + } + return makeType(); + } + case 'ArrayTypeAnnotation': + case 'TSArrayType': { + return { kind: 'Object', shapeId: BuiltInArrayId }; + } + case 'BooleanLiteralTypeAnnotation': + case 'BooleanTypeAnnotation': + case 'NullLiteralTypeAnnotation': + case 'NumberLiteralTypeAnnotation': + case 'NumberTypeAnnotation': + case 'StringLiteralTypeAnnotation': + case 'StringTypeAnnotation': + case 'TSBooleanKeyword': + case 'TSNullKeyword': + case 'TSNumberKeyword': + case 'TSStringKeyword': + case 'TSSymbolKeyword': + case 'TSUndefinedKeyword': + case 'TSVoidKeyword': + case 'VoidTypeAnnotation': { + return { kind: 'Primitive' }; + } + default: { + return makeType(); + } + } +} + +function buildReactiveScopeTerminalsHIR(fn) { + const queuedRewrites = []; + recursivelyTraverseItems([...getScopes(fn)], scope => scope.range, { + fallthroughs: new Map(), + rewrites: queuedRewrites, + env: fn.env, + }, pushStartScopeTerminal, pushEndScopeTerminal); + const rewrittenFinalBlocks = new Map(); + const nextBlocks = new Map(); + queuedRewrites.reverse(); + for (const [, block] of fn.body.blocks) { + const context = { + nextBlockId: block.id, + rewrites: [], + nextPreds: block.preds, + instrSliceIdx: 0, + source: block, + }; + for (let i = 0; i < block.instructions.length + 1; i++) { + const instrId = i < block.instructions.length + ? block.instructions[i].id + : block.terminal.id; + let rewrite = queuedRewrites.at(-1); + while (rewrite != null && rewrite.instrId <= instrId) { + handleRewrite(rewrite, i, context); + queuedRewrites.pop(); + rewrite = queuedRewrites.at(-1); + } + } + if (context.rewrites.length > 0) { + const finalBlock = { + id: context.nextBlockId, + kind: block.kind, + preds: context.nextPreds, + terminal: block.terminal, + instructions: block.instructions.slice(context.instrSliceIdx), + phis: new Set(), + }; + context.rewrites.push(finalBlock); + for (const b of context.rewrites) { + nextBlocks.set(b.id, b); + } + rewrittenFinalBlocks.set(block.id, finalBlock.id); + } + else { + nextBlocks.set(block.id, block); + } + } + const originalBlocks = fn.body.blocks; + fn.body.blocks = nextBlocks; + for (const [, block] of originalBlocks) { + for (const phi of block.phis) { + for (const [originalId, value] of phi.operands) { + const newId = rewrittenFinalBlocks.get(originalId); + if (newId != null) { + phi.operands.delete(originalId); + phi.operands.set(newId, value); + } + } + } + } + reversePostorderBlocks(fn.body); + markPredecessors(fn.body); + markInstructionIds(fn.body); + fixScopeAndIdentifierRanges(fn.body); +} +function pushStartScopeTerminal(scope, context) { + const blockId = context.env.nextBlockId; + const fallthroughId = context.env.nextBlockId; + context.rewrites.push({ + kind: 'StartScope', + blockId, + fallthroughId, + instrId: scope.range.start, + scope, + }); + context.fallthroughs.set(scope.id, fallthroughId); +} +function pushEndScopeTerminal(scope, context) { + const fallthroughId = context.fallthroughs.get(scope.id); + CompilerError.invariant(fallthroughId != null, { + reason: 'Expected scope to exist', + loc: GeneratedSource, + }); + context.rewrites.push({ + kind: 'EndScope', + fallthroughId, + instrId: scope.range.end, + }); +} +function handleRewrite(terminalInfo, idx, context) { + const terminal = terminalInfo.kind === 'StartScope' + ? { + kind: 'scope', + fallthrough: terminalInfo.fallthroughId, + block: terminalInfo.blockId, + scope: terminalInfo.scope, + id: terminalInfo.instrId, + loc: GeneratedSource, + } + : { + kind: 'goto', + variant: GotoVariant.Break, + block: terminalInfo.fallthroughId, + id: terminalInfo.instrId, + loc: GeneratedSource, + }; + const currBlockId = context.nextBlockId; + context.rewrites.push({ + kind: context.source.kind, + id: currBlockId, + instructions: context.source.instructions.slice(context.instrSliceIdx, idx), + preds: context.nextPreds, + phis: context.rewrites.length === 0 ? context.source.phis : new Set(), + terminal, + }); + context.nextPreds = new Set([currBlockId]); + context.nextBlockId = + terminalInfo.kind === 'StartScope' + ? terminalInfo.blockId + : terminalInfo.fallthroughId; + context.instrSliceIdx = idx; +} + +var ansiStylesExports = {}; +var ansiStyles = { + get exports(){ return ansiStylesExports; }, + set exports(v){ ansiStylesExports = v; }, +}; + +var conversionsExports = {}; +var conversions = { + get exports(){ return conversionsExports; }, + set exports(v){ conversionsExports = v; }, +}; + +var colorName; +var hasRequiredColorName; + +function requireColorName () { + if (hasRequiredColorName) return colorName; + hasRequiredColorName = 1; + + colorName = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + return colorName; +} + +var hasRequiredConversions; + +function requireConversions () { + if (hasRequiredConversions) return conversionsExports; + hasRequiredConversions = 1; + var cssKeywords = requireColorName(); + + // NOTE: conversions should only return primitive values (i.e. arrays, or + // values that give correct `typeof` results). + // do not use box values types (i.e. Number(), String(), etc.) + + var reverseKeywords = {}; + for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } + } + + var convert = conversions.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} + }; + + // hide .channels and .labels properties + for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } + } + + convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; + }; + + convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; + }; + + convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; + }; + + convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; + }; + + /** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ + function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); + } + + convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; + }; + + convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; + }; + + convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; + }; + + convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; + }; + + convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; + }; + + convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } + }; + + convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; + }; + + // http://dev.w3.org/csswg/css-color/#hwb-to-rgb + convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; + }; + + convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; + }; + + convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + + return [l, c, h]; + }; + + convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + + return [l, a, b]; + }; + + convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; + }; + + convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + + convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; + }; + + convert.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; + }; + + convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; + + return [r, g, b]; + }; + + convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; + + return [r, g, b]; + }; + + convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; + }; + + convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; + }; + + convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; + }; + + convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; + }; + + convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; + }; + + convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + + convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; + }; + + convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; + }; + + convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; + }; + + convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; + }; + + convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; + return conversionsExports; +} + +var route; +var hasRequiredRoute; + +function requireRoute () { + if (hasRequiredRoute) return route; + hasRequiredRoute = 1; + var conversions = requireConversions(); + + /* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. + */ + + function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; + } + + // https://en.wikipedia.org/wiki/Breadth-first_search + function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; + } + + function link(from, to) { + return function (args) { + return to(from(args)); + }; + } + + function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; + } + + route = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; + }; + return route; +} + +var colorConvert; +var hasRequiredColorConvert; + +function requireColorConvert () { + if (hasRequiredColorConvert) return colorConvert; + hasRequiredColorConvert = 1; + var conversions = requireConversions(); + var route = requireRoute(); + + var convert = {}; + + var models = Object.keys(conversions); + + function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + models.forEach(function (fromModel) { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + var routes = route(fromModel); + var routeModels = Object.keys(routes); + + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); + }); + + colorConvert = convert; + return colorConvert; +} + +var hasRequiredAnsiStyles; + +function requireAnsiStyles () { + if (hasRequiredAnsiStyles) return ansiStylesExports; + hasRequiredAnsiStyles = 1; + (function (module) { + const colorConvert = requireColorConvert(); + + const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; + }; + + const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; + }; + + const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + + function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; + } + + // Make the export immutable + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); +} (ansiStyles)); + return ansiStylesExports; +} + +var collections = {}; + +var hasRequiredCollections; + +function requireCollections () { + if (hasRequiredCollections) return collections; + hasRequiredCollections = 1; + + Object.defineProperty(collections, '__esModule', { + value: true + }); + collections.printIteratorEntries = printIteratorEntries; + collections.printIteratorValues = printIteratorValues; + collections.printListItems = printListItems; + collections.printObjectProperties = printObjectProperties; + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + const getKeysOfEnumerableProperties = object => { + const keys = Object.keys(object).sort(); + + if (Object.getOwnPropertySymbols) { + Object.getOwnPropertySymbols(object).forEach(symbol => { + if (Object.getOwnPropertyDescriptor(object, symbol).enumerable) { + keys.push(symbol); + } + }); + } + + return keys; + }; + /** + * Return entries (for example, of a map) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ + + function printIteratorEntries( // Flow 0.51.0: property `@@iterator` of $Iterator not found in Object + // To allow simplistic getRecordIterator in immutable.js + iterator, + config, + indentation, + depth, + refs, + printer, // Too bad, so sad that separator for ECMAScript Map has been ' => ' + // What a distracting diff if you change a data structure to/from + separator = ': ' + ) { + let result = ''; + let current = iterator.next(); + + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + while (!current.done) { + const name = printer( + current.value[0], + config, + indentationNext, + depth, + refs + ); + const value = printer( + current.value[1], + config, + indentationNext, + depth, + refs + ); + result += indentationNext + name + separator + value; + current = iterator.next(); + + if (!current.done) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; + } + /** + * Return values (for example, of a set) + * with spacing, indentation, and comma + * without surrounding punctuation (braces or brackets) + */ + + function printIteratorValues( + iterator, + config, + indentation, + depth, + refs, + printer + ) { + let result = ''; + let current = iterator.next(); + + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + while (!current.done) { + result += + indentationNext + + printer(current.value, config, indentationNext, depth, refs); + current = iterator.next(); + + if (!current.done) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; + } + /** + * Return items (for example, of an array) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, brackets) + **/ + + function printListItems(list, config, indentation, depth, refs, printer) { + let result = ''; + + if (list.length) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + for (let i = 0; i < list.length; i++) { + result += + indentationNext + + printer(list[i], config, indentationNext, depth, refs); + + if (i < list.length - 1) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; + } + /** + * Return properties of an object + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ + + function printObjectProperties(val, config, indentation, depth, refs, printer) { + let result = ''; + const keys = getKeysOfEnumerableProperties(val); + + if (keys.length) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const name = printer(key, config, indentationNext, depth, refs); + const value = printer(val[key], config, indentationNext, depth, refs); + result += indentationNext + name + ': ' + value; + + if (i < keys.length - 1) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; + } + return collections; +} + +var AsymmetricMatcher = {}; + +var hasRequiredAsymmetricMatcher; + +function requireAsymmetricMatcher () { + if (hasRequiredAsymmetricMatcher) return AsymmetricMatcher; + hasRequiredAsymmetricMatcher = 1; + + Object.defineProperty(AsymmetricMatcher, '__esModule', { + value: true + }); + AsymmetricMatcher.default = AsymmetricMatcher.test = AsymmetricMatcher.serialize = void 0; + + var _collections = requireCollections(); + + var Symbol = commonjsGlobal['jest-symbol-do-not-touch'] || commonjsGlobal.Symbol; + const asymmetricMatcher = Symbol.for('jest.asymmetricMatcher'); + const SPACE = ' '; + + const serialize = (val, config, indentation, depth, refs, printer) => { + const stringedValue = val.toString(); + + if ( + stringedValue === 'ArrayContaining' || + stringedValue === 'ArrayNotContaining' + ) { + if (++depth > config.maxDepth) { + return '[' + stringedValue + ']'; + } + + return ( + stringedValue + + SPACE + + '[' + + (0, _collections.printListItems)( + val.sample, + config, + indentation, + depth, + refs, + printer + ) + + ']' + ); + } + + if ( + stringedValue === 'ObjectContaining' || + stringedValue === 'ObjectNotContaining' + ) { + if (++depth > config.maxDepth) { + return '[' + stringedValue + ']'; + } + + return ( + stringedValue + + SPACE + + '{' + + (0, _collections.printObjectProperties)( + val.sample, + config, + indentation, + depth, + refs, + printer + ) + + '}' + ); + } + + if ( + stringedValue === 'StringMatching' || + stringedValue === 'StringNotMatching' + ) { + return ( + stringedValue + + SPACE + + printer(val.sample, config, indentation, depth, refs) + ); + } + + if ( + stringedValue === 'StringContaining' || + stringedValue === 'StringNotContaining' + ) { + return ( + stringedValue + + SPACE + + printer(val.sample, config, indentation, depth, refs) + ); + } + + return val.toAsymmetricMatcher(); + }; + + AsymmetricMatcher.serialize = serialize; + + const test = val => val && val.$$typeof === asymmetricMatcher; + + AsymmetricMatcher.test = test; + const plugin = { + serialize, + test + }; + var _default = plugin; + AsymmetricMatcher.default = _default; + return AsymmetricMatcher; +} + +var ConvertAnsi = {}; + +var ansiRegex; +var hasRequiredAnsiRegex; + +function requireAnsiRegex () { + if (hasRequiredAnsiRegex) return ansiRegex; + hasRequiredAnsiRegex = 1; + + ansiRegex = options => { + options = Object.assign({ + onlyFirst: false + }, options); + + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, options.onlyFirst ? undefined : 'g'); + }; + return ansiRegex; +} + +var hasRequiredConvertAnsi; + +function requireConvertAnsi () { + if (hasRequiredConvertAnsi) return ConvertAnsi; + hasRequiredConvertAnsi = 1; + + Object.defineProperty(ConvertAnsi, '__esModule', { + value: true + }); + ConvertAnsi.default = ConvertAnsi.serialize = ConvertAnsi.test = void 0; + + var _ansiRegex = _interopRequireDefault(requireAnsiRegex()); + + var _ansiStyles = _interopRequireDefault(requireAnsiStyles()); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; + } + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + const toHumanReadableAnsi = text => + text.replace((0, _ansiRegex.default)(), match => { + switch (match) { + case _ansiStyles.default.red.close: + case _ansiStyles.default.green.close: + case _ansiStyles.default.cyan.close: + case _ansiStyles.default.gray.close: + case _ansiStyles.default.white.close: + case _ansiStyles.default.yellow.close: + case _ansiStyles.default.bgRed.close: + case _ansiStyles.default.bgGreen.close: + case _ansiStyles.default.bgYellow.close: + case _ansiStyles.default.inverse.close: + case _ansiStyles.default.dim.close: + case _ansiStyles.default.bold.close: + case _ansiStyles.default.reset.open: + case _ansiStyles.default.reset.close: + return ''; + + case _ansiStyles.default.red.open: + return ''; + + case _ansiStyles.default.green.open: + return ''; + + case _ansiStyles.default.cyan.open: + return ''; + + case _ansiStyles.default.gray.open: + return ''; + + case _ansiStyles.default.white.open: + return ''; + + case _ansiStyles.default.yellow.open: + return ''; + + case _ansiStyles.default.bgRed.open: + return ''; + + case _ansiStyles.default.bgGreen.open: + return ''; + + case _ansiStyles.default.bgYellow.open: + return ''; + + case _ansiStyles.default.inverse.open: + return ''; + + case _ansiStyles.default.dim.open: + return ''; + + case _ansiStyles.default.bold.open: + return ''; + + default: + return ''; + } + }); + + const test = val => + typeof val === 'string' && !!val.match((0, _ansiRegex.default)()); + + ConvertAnsi.test = test; + + const serialize = (val, config, indentation, depth, refs, printer) => + printer(toHumanReadableAnsi(val), config, indentation, depth, refs); + + ConvertAnsi.serialize = serialize; + const plugin = { + serialize, + test + }; + var _default = plugin; + ConvertAnsi.default = _default; + return ConvertAnsi; +} + +var DOMCollection = {}; + +var hasRequiredDOMCollection; + +function requireDOMCollection () { + if (hasRequiredDOMCollection) return DOMCollection; + hasRequiredDOMCollection = 1; + + Object.defineProperty(DOMCollection, '__esModule', { + value: true + }); + DOMCollection.default = DOMCollection.serialize = DOMCollection.test = void 0; + + var _collections = requireCollections(); + + function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + var ownKeys = Object.keys(source); + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys = ownKeys.concat( + Object.getOwnPropertySymbols(source).filter(function(sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + }) + ); + } + ownKeys.forEach(function(key) { + _defineProperty(target, key, source[key]); + }); + } + return target; + } + + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; + } + + const SPACE = ' '; + const OBJECT_NAMES = ['DOMStringMap', 'NamedNodeMap']; + const ARRAY_REGEXP = /^(HTML\w*Collection|NodeList)$/; + + const testName = name => + OBJECT_NAMES.indexOf(name) !== -1 || ARRAY_REGEXP.test(name); + + const test = val => + val && + val.constructor && + val.constructor.name && + testName(val.constructor.name); // Convert array of attribute objects to props object. + + DOMCollection.test = test; + + const propsReducer = (props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }; + + const serialize = (collection, config, indentation, depth, refs, printer) => { + const name = collection.constructor.name; + + if (++depth > config.maxDepth) { + return '[' + name + ']'; + } + + return ( + (config.min ? '' : name + SPACE) + + (OBJECT_NAMES.indexOf(name) !== -1 + ? '{' + + (0, _collections.printObjectProperties)( + name === 'NamedNodeMap' + ? Array.prototype.reduce.call(collection, propsReducer, {}) + : _objectSpread({}, collection), + config, + indentation, + depth, + refs, + printer + ) + + '}' + : '[' + + (0, _collections.printListItems)( + Array.from(collection), + config, + indentation, + depth, + refs, + printer + ) + + ']') + ); + }; + + DOMCollection.serialize = serialize; + const plugin = { + serialize, + test + }; + var _default = plugin; + DOMCollection.default = _default; + return DOMCollection; +} + +var DOMElement = {}; + +var markup = {}; + +var escapeHTML = {}; + +var hasRequiredEscapeHTML; + +function requireEscapeHTML () { + if (hasRequiredEscapeHTML) return escapeHTML; + hasRequiredEscapeHTML = 1; + + Object.defineProperty(escapeHTML, '__esModule', { + value: true + }); + escapeHTML.default = escapeHTML$1; + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + function escapeHTML$1(str) { + return str.replace(//g, '>'); + } + return escapeHTML; +} + +var hasRequiredMarkup; + +function requireMarkup () { + if (hasRequiredMarkup) return markup; + hasRequiredMarkup = 1; + + Object.defineProperty(markup, '__esModule', { + value: true + }); + markup.printElementAsLeaf = markup.printElement = markup.printComment = markup.printText = markup.printChildren = markup.printProps = void 0; + + var _escapeHTML = _interopRequireDefault(requireEscapeHTML()); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; + } + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + // Return empty string if keys is empty. + const printProps = (keys, props, config, indentation, depth, refs, printer) => { + const indentationNext = indentation + config.indent; + const colors = config.colors; + return keys + .map(key => { + const value = props[key]; + let printed = printer(value, config, indentationNext, depth, refs); + + if (typeof value !== 'string') { + if (printed.indexOf('\n') !== -1) { + printed = + config.spacingOuter + + indentationNext + + printed + + config.spacingOuter + + indentation; + } + + printed = '{' + printed + '}'; + } + + return ( + config.spacingInner + + indentation + + colors.prop.open + + key + + colors.prop.close + + '=' + + colors.value.open + + printed + + colors.value.close + ); + }) + .join(''); + }; // Return empty string if children is empty. + + markup.printProps = printProps; + + const printChildren = (children, config, indentation, depth, refs, printer) => + children + .map( + child => + config.spacingOuter + + indentation + + (typeof child === 'string' + ? printText(child, config) + : printer(child, config, indentation, depth, refs)) + ) + .join(''); + + markup.printChildren = printChildren; + + const printText = (text, config) => { + const contentColor = config.colors.content; + return ( + contentColor.open + (0, _escapeHTML.default)(text) + contentColor.close + ); + }; + + markup.printText = printText; + + const printComment = (comment, config) => { + const commentColor = config.colors.comment; + return ( + commentColor.open + + '' + + commentColor.close + ); + }; // Separate the functions to format props, children, and element, + // so a plugin could override a particular function, if needed. + // Too bad, so sad: the traditional (but unnecessary) space + // in a self-closing tagColor requires a second test of printedProps. + + markup.printComment = printComment; + + const printElement = ( + type, + printedProps, + printedChildren, + config, + indentation + ) => { + const tagColor = config.colors.tag; + return ( + tagColor.open + + '<' + + type + + (printedProps && + tagColor.close + + printedProps + + config.spacingOuter + + indentation + + tagColor.open) + + (printedChildren + ? '>' + + tagColor.close + + printedChildren + + config.spacingOuter + + indentation + + tagColor.open + + '' + + tagColor.close + ); + }; + + markup.printElement = printElement; + + const printElementAsLeaf = (type, config) => { + const tagColor = config.colors.tag; + return ( + tagColor.open + + '<' + + type + + tagColor.close + + ' …' + + tagColor.open + + ' />' + + tagColor.close + ); + }; + + markup.printElementAsLeaf = printElementAsLeaf; + return markup; +} + +var hasRequiredDOMElement; + +function requireDOMElement () { + if (hasRequiredDOMElement) return DOMElement; + hasRequiredDOMElement = 1; + + Object.defineProperty(DOMElement, '__esModule', { + value: true + }); + DOMElement.default = DOMElement.serialize = DOMElement.test = void 0; + + var _markup = requireMarkup(); + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + const ELEMENT_NODE = 1; + const TEXT_NODE = 3; + const COMMENT_NODE = 8; + const FRAGMENT_NODE = 11; + const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/; + + const testNode = (nodeType, name) => + (nodeType === ELEMENT_NODE && ELEMENT_REGEXP.test(name)) || + (nodeType === TEXT_NODE && name === 'Text') || + (nodeType === COMMENT_NODE && name === 'Comment') || + (nodeType === FRAGMENT_NODE && name === 'DocumentFragment'); + + const test = val => + val && + val.constructor && + val.constructor.name && + testNode(val.nodeType, val.constructor.name); + + DOMElement.test = test; + + function nodeIsText(node) { + return node.nodeType === TEXT_NODE; + } + + function nodeIsComment(node) { + return node.nodeType === COMMENT_NODE; + } + + function nodeIsFragment(node) { + return node.nodeType === FRAGMENT_NODE; + } + + const serialize = (node, config, indentation, depth, refs, printer) => { + if (nodeIsText(node)) { + return (0, _markup.printText)(node.data, config); + } + + if (nodeIsComment(node)) { + return (0, _markup.printComment)(node.data, config); + } + + const type = nodeIsFragment(node) + ? `DocumentFragment` + : node.tagName.toLowerCase(); + + if (++depth > config.maxDepth) { + return (0, _markup.printElementAsLeaf)(type, config); + } + + return (0, _markup.printElement)( + type, + (0, _markup.printProps)( + nodeIsFragment(node) + ? [] + : Array.from(node.attributes) + .map(attr => attr.name) + .sort(), + nodeIsFragment(node) + ? [] + : Array.from(node.attributes).reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}), + config, + indentation + config.indent, + depth, + refs, + printer + ), + (0, _markup.printChildren)( + Array.prototype.slice.call(node.childNodes || node.children), + config, + indentation + config.indent, + depth, + refs, + printer + ), + config, + indentation + ); + }; + + DOMElement.serialize = serialize; + const plugin = { + serialize, + test + }; + var _default = plugin; + DOMElement.default = _default; + return DOMElement; +} + +var Immutable = {}; + +var hasRequiredImmutable; + +function requireImmutable () { + if (hasRequiredImmutable) return Immutable; + hasRequiredImmutable = 1; + + Object.defineProperty(Immutable, '__esModule', { + value: true + }); + Immutable.default = Immutable.test = Immutable.serialize = void 0; + + var _collections = requireCollections(); + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + // SENTINEL constants are from https://github.com/facebook/immutable-js + const IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; + const IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; + const IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; + const IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; + const IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; + const IS_RECORD_SENTINEL = '@@__IMMUTABLE_RECORD__@@'; // immutable v4 + + const IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; + const IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; + const IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; + + const getImmutableName = name => 'Immutable.' + name; + + const printAsLeaf = name => '[' + name + ']'; + + const SPACE = ' '; + const LAZY = '…'; // Seq is lazy if it calls a method like filter + + const printImmutableEntries = ( + val, + config, + indentation, + depth, + refs, + printer, + type + ) => + ++depth > config.maxDepth + ? printAsLeaf(getImmutableName(type)) + : getImmutableName(type) + + SPACE + + '{' + + (0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer + ) + + '}'; // Record has an entries method because it is a collection in immutable v3. + // Return an iterator for Immutable Record from version v3 or v4. + + const getRecordEntries = val => { + let i = 0; + return { + next() { + if (i < val._keys.length) { + const key = val._keys[i++]; + return { + done: false, + value: [key, val.get(key)] + }; + } + + return { + done: true + }; + } + }; + }; + + const printImmutableRecord = ( + val, + config, + indentation, + depth, + refs, + printer + ) => { + // _name property is defined only for an Immutable Record instance + // which was constructed with a second optional descriptive name arg + const name = getImmutableName(val._name || 'Record'); + return ++depth > config.maxDepth + ? printAsLeaf(name) + : name + + SPACE + + '{' + + (0, _collections.printIteratorEntries)( + getRecordEntries(val), + config, + indentation, + depth, + refs, + printer + ) + + '}'; + }; + + const printImmutableSeq = (val, config, indentation, depth, refs, printer) => { + const name = getImmutableName('Seq'); + + if (++depth > config.maxDepth) { + return printAsLeaf(name); + } + + if (val[IS_KEYED_SENTINEL]) { + return ( + name + + SPACE + + '{' + // from Immutable collection of entries or from ECMAScript object + (val._iter || val._object + ? (0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer + ) + : LAZY) + + '}' + ); + } + + return ( + name + + SPACE + + '[' + + (val._iter || // from Immutable collection of values + val._array || // from ECMAScript array + val._collection || // from ECMAScript collection in immutable v4 + val._iterable // from ECMAScript collection in immutable v3 + ? (0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + : LAZY) + + ']' + ); + }; + + const printImmutableValues = ( + val, + config, + indentation, + depth, + refs, + printer, + type + ) => + ++depth > config.maxDepth + ? printAsLeaf(getImmutableName(type)) + : getImmutableName(type) + + SPACE + + '[' + + (0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + + ']'; + + const serialize = (val, config, indentation, depth, refs, printer) => { + if (val[IS_MAP_SENTINEL]) { + return printImmutableEntries( + val, + config, + indentation, + depth, + refs, + printer, + val[IS_ORDERED_SENTINEL] ? 'OrderedMap' : 'Map' + ); + } + + if (val[IS_LIST_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + 'List' + ); + } + + if (val[IS_SET_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + val[IS_ORDERED_SENTINEL] ? 'OrderedSet' : 'Set' + ); + } + + if (val[IS_STACK_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + 'Stack' + ); + } + + if (val[IS_SEQ_SENTINEL]) { + return printImmutableSeq(val, config, indentation, depth, refs, printer); + } // For compatibility with immutable v3 and v4, let record be the default. + + return printImmutableRecord(val, config, indentation, depth, refs, printer); + }; // Explicitly comparing sentinel properties to true avoids false positive + // when mock identity-obj-proxy returns the key as the value for any key. + + Immutable.serialize = serialize; + + const test = val => + val && + (val[IS_ITERABLE_SENTINEL] === true || val[IS_RECORD_SENTINEL] === true); + + Immutable.test = test; + const plugin = { + serialize, + test + }; + var _default = plugin; + Immutable.default = _default; + return Immutable; +} + +var ReactElement = {}; + +var reactIsExports = {}; +var reactIs = { + get exports(){ return reactIsExports; }, + set exports(v){ reactIsExports = v; }, +}; + +var reactIs_development = {}; + +var hasRequiredReactIs_development; + +function requireReactIs_development () { + if (hasRequiredReactIs_development) return reactIs_development; + hasRequiredReactIs_development = 1; + + + + { + (function() { + + // The Symbol used to tag the ReactElement-like types. If there is no native Symbol + // nor polyfill, then a plain number is used for performance. + var hasSymbol = typeof Symbol === 'function' && Symbol.for; + var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; + var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; + var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; + var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; + var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; + var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; + var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary + // (unstable) APIs that have been removed. Can we remove the symbols? + + var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf; + var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; + var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; + var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; + var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8; + var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; + var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; + var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9; + var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5; + var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6; + var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7; + + function isValidElementType(type) { + return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. + type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE); + } + + function typeOf(object) { + if (typeof object === 'object' && object !== null) { + var $$typeof = object.$$typeof; + + switch ($$typeof) { + case REACT_ELEMENT_TYPE: + var type = object.type; + + switch (type) { + case REACT_ASYNC_MODE_TYPE: + case REACT_CONCURRENT_MODE_TYPE: + case REACT_FRAGMENT_TYPE: + case REACT_PROFILER_TYPE: + case REACT_STRICT_MODE_TYPE: + case REACT_SUSPENSE_TYPE: + return type; + + default: + var $$typeofType = type && type.$$typeof; + + switch ($$typeofType) { + case REACT_CONTEXT_TYPE: + case REACT_FORWARD_REF_TYPE: + case REACT_LAZY_TYPE: + case REACT_MEMO_TYPE: + case REACT_PROVIDER_TYPE: + return $$typeofType; + + default: + return $$typeof; + } + + } + + case REACT_PORTAL_TYPE: + return $$typeof; + } + } + + return undefined; + } // AsyncMode is deprecated along with isAsyncMode + + var AsyncMode = REACT_ASYNC_MODE_TYPE; + var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; + var ContextConsumer = REACT_CONTEXT_TYPE; + var ContextProvider = REACT_PROVIDER_TYPE; + var Element = REACT_ELEMENT_TYPE; + var ForwardRef = REACT_FORWARD_REF_TYPE; + var Fragment = REACT_FRAGMENT_TYPE; + var Lazy = REACT_LAZY_TYPE; + var Memo = REACT_MEMO_TYPE; + var Portal = REACT_PORTAL_TYPE; + var Profiler = REACT_PROFILER_TYPE; + var StrictMode = REACT_STRICT_MODE_TYPE; + var Suspense = REACT_SUSPENSE_TYPE; + var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated + + function isAsyncMode(object) { + { + if (!hasWarnedAboutDeprecatedIsAsyncMode) { + hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint + + console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.'); + } + } + + return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE; + } + function isConcurrentMode(object) { + return typeOf(object) === REACT_CONCURRENT_MODE_TYPE; + } + function isContextConsumer(object) { + return typeOf(object) === REACT_CONTEXT_TYPE; + } + function isContextProvider(object) { + return typeOf(object) === REACT_PROVIDER_TYPE; + } + function isElement(object) { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + function isForwardRef(object) { + return typeOf(object) === REACT_FORWARD_REF_TYPE; + } + function isFragment(object) { + return typeOf(object) === REACT_FRAGMENT_TYPE; + } + function isLazy(object) { + return typeOf(object) === REACT_LAZY_TYPE; + } + function isMemo(object) { + return typeOf(object) === REACT_MEMO_TYPE; + } + function isPortal(object) { + return typeOf(object) === REACT_PORTAL_TYPE; + } + function isProfiler(object) { + return typeOf(object) === REACT_PROFILER_TYPE; + } + function isStrictMode(object) { + return typeOf(object) === REACT_STRICT_MODE_TYPE; + } + function isSuspense(object) { + return typeOf(object) === REACT_SUSPENSE_TYPE; + } + + reactIs_development.AsyncMode = AsyncMode; + reactIs_development.ConcurrentMode = ConcurrentMode; + reactIs_development.ContextConsumer = ContextConsumer; + reactIs_development.ContextProvider = ContextProvider; + reactIs_development.Element = Element; + reactIs_development.ForwardRef = ForwardRef; + reactIs_development.Fragment = Fragment; + reactIs_development.Lazy = Lazy; + reactIs_development.Memo = Memo; + reactIs_development.Portal = Portal; + reactIs_development.Profiler = Profiler; + reactIs_development.StrictMode = StrictMode; + reactIs_development.Suspense = Suspense; + reactIs_development.isAsyncMode = isAsyncMode; + reactIs_development.isConcurrentMode = isConcurrentMode; + reactIs_development.isContextConsumer = isContextConsumer; + reactIs_development.isContextProvider = isContextProvider; + reactIs_development.isElement = isElement; + reactIs_development.isForwardRef = isForwardRef; + reactIs_development.isFragment = isFragment; + reactIs_development.isLazy = isLazy; + reactIs_development.isMemo = isMemo; + reactIs_development.isPortal = isPortal; + reactIs_development.isProfiler = isProfiler; + reactIs_development.isStrictMode = isStrictMode; + reactIs_development.isSuspense = isSuspense; + reactIs_development.isValidElementType = isValidElementType; + reactIs_development.typeOf = typeOf; + })(); + } + return reactIs_development; +} + +var hasRequiredReactIs; + +function requireReactIs () { + if (hasRequiredReactIs) return reactIsExports; + hasRequiredReactIs = 1; + (function (module) { + + { + module.exports = requireReactIs_development(); + } +} (reactIs)); + return reactIsExports; +} + +var hasRequiredReactElement; + +function requireReactElement () { + if (hasRequiredReactElement) return ReactElement; + hasRequiredReactElement = 1; + + Object.defineProperty(ReactElement, '__esModule', { + value: true + }); + ReactElement.default = ReactElement.test = ReactElement.serialize = void 0; + + var ReactIs = _interopRequireWildcard(requireReactIs()); + + var _markup = requireMarkup(); + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = + Object.defineProperty && Object.getOwnPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : {}; + if (desc.get || desc.set) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } + newObj.default = obj; + return newObj; + } + } + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + // Given element.props.children, or subtree during recursive traversal, + // return flattened array of children. + const getChildren = (arg, children = []) => { + if (Array.isArray(arg)) { + arg.forEach(item => { + getChildren(item, children); + }); + } else if (arg != null && arg !== false) { + children.push(arg); + } + + return children; + }; + + const getType = element => { + const type = element.type; + + if (typeof type === 'string') { + return type; + } + + if (typeof type === 'function') { + return type.displayName || type.name || 'Unknown'; + } + + if (ReactIs.isFragment(element)) { + return 'React.Fragment'; + } + + if (ReactIs.isSuspense(element)) { + return 'React.Suspense'; + } + + if (typeof type === 'object' && type !== null) { + if (ReactIs.isContextProvider(element)) { + return 'Context.Provider'; + } + + if (ReactIs.isContextConsumer(element)) { + return 'Context.Consumer'; + } + + if (ReactIs.isForwardRef(element)) { + const functionName = type.render.displayName || type.render.name || ''; + return functionName !== '' + ? 'ForwardRef(' + functionName + ')' + : 'ForwardRef'; + } + + if (ReactIs.isMemo(type)) { + const functionName = + type.displayName || type.type.displayName || type.type.name || ''; + return functionName !== '' ? 'Memo(' + functionName + ')' : 'Memo'; + } + } + + return 'UNDEFINED'; + }; + + const getPropKeys = element => { + const props = element.props; + return Object.keys(props) + .filter(key => key !== 'children' && props[key] !== undefined) + .sort(); + }; + + const serialize = (element, config, indentation, depth, refs, printer) => + ++depth > config.maxDepth + ? (0, _markup.printElementAsLeaf)(getType(element), config) + : (0, _markup.printElement)( + getType(element), + (0, _markup.printProps)( + getPropKeys(element), + element.props, + config, + indentation + config.indent, + depth, + refs, + printer + ), + (0, _markup.printChildren)( + getChildren(element.props.children), + config, + indentation + config.indent, + depth, + refs, + printer + ), + config, + indentation + ); + + ReactElement.serialize = serialize; + + const test = val => val && ReactIs.isElement(val); + + ReactElement.test = test; + const plugin = { + serialize, + test + }; + var _default = plugin; + ReactElement.default = _default; + return ReactElement; +} + +var ReactTestComponent = {}; + +var hasRequiredReactTestComponent; + +function requireReactTestComponent () { + if (hasRequiredReactTestComponent) return ReactTestComponent; + hasRequiredReactTestComponent = 1; + + Object.defineProperty(ReactTestComponent, '__esModule', { + value: true + }); + ReactTestComponent.default = ReactTestComponent.test = ReactTestComponent.serialize = void 0; + + var _markup = requireMarkup(); + + var Symbol = commonjsGlobal['jest-symbol-do-not-touch'] || commonjsGlobal.Symbol; + const testSymbol = Symbol.for('react.test.json'); + + const getPropKeys = object => { + const props = object.props; + return props + ? Object.keys(props) + .filter(key => props[key] !== undefined) + .sort() + : []; + }; + + const serialize = (object, config, indentation, depth, refs, printer) => + ++depth > config.maxDepth + ? (0, _markup.printElementAsLeaf)(object.type, config) + : (0, _markup.printElement)( + object.type, + object.props + ? (0, _markup.printProps)( + getPropKeys(object), + object.props, + config, + indentation + config.indent, + depth, + refs, + printer + ) + : '', + object.children + ? (0, _markup.printChildren)( + object.children, + config, + indentation + config.indent, + depth, + refs, + printer + ) + : '', + config, + indentation + ); + + ReactTestComponent.serialize = serialize; + + const test = val => val && val.$$typeof === testSymbol; + + ReactTestComponent.test = test; + const plugin = { + serialize, + test + }; + var _default = plugin; + ReactTestComponent.default = _default; + return ReactTestComponent; +} + +var build; +var hasRequiredBuild; + +function requireBuild () { + if (hasRequiredBuild) return build; + hasRequiredBuild = 1; + + var _ansiStyles = _interopRequireDefault(requireAnsiStyles()); + + var _collections = requireCollections(); + + var _AsymmetricMatcher = _interopRequireDefault( + requireAsymmetricMatcher() + ); + + var _ConvertAnsi = _interopRequireDefault(requireConvertAnsi()); + + var _DOMCollection = _interopRequireDefault(requireDOMCollection()); + + var _DOMElement = _interopRequireDefault(requireDOMElement()); + + var _Immutable = _interopRequireDefault(requireImmutable()); + + var _ReactElement = _interopRequireDefault(requireReactElement()); + + var _ReactTestComponent = _interopRequireDefault( + requireReactTestComponent() + ); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; + } + + var Symbol = commonjsGlobal['jest-symbol-do-not-touch'] || commonjsGlobal.Symbol; + const toString = Object.prototype.toString; + const toISOString = Date.prototype.toISOString; + const errorToString = Error.prototype.toString; + const regExpToString = RegExp.prototype.toString; + const symbolToString = Symbol.prototype.toString; + /** + * Explicitly comparing typeof constructor to function avoids undefined as name + * when mock identity-obj-proxy returns the key as the value for any key. + */ + + const getConstructorName = val => + (typeof val.constructor === 'function' && val.constructor.name) || 'Object'; + /* global window */ + + /** Is val is equal to global window object? Works even if it does not exist :) */ + + const isWindow = val => typeof window !== 'undefined' && val === window; + + const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; + const NEWLINE_REGEXP = /\n/gi; + + class PrettyFormatPluginError extends Error { + constructor(message, stack) { + super(message); + this.stack = stack; + this.name = this.constructor.name; + } + } + + function isToStringedArrayType(toStringed) { + return ( + toStringed === '[object Array]' || + toStringed === '[object ArrayBuffer]' || + toStringed === '[object DataView]' || + toStringed === '[object Float32Array]' || + toStringed === '[object Float64Array]' || + toStringed === '[object Int8Array]' || + toStringed === '[object Int16Array]' || + toStringed === '[object Int32Array]' || + toStringed === '[object Uint8Array]' || + toStringed === '[object Uint8ClampedArray]' || + toStringed === '[object Uint16Array]' || + toStringed === '[object Uint32Array]' + ); + } + + function printNumber(val) { + return Object.is(val, -0) ? '-0' : String(val); + } + + function printBigInt(val) { + return String(`${val}n`); + } + + function printFunction(val, printFunctionName) { + if (!printFunctionName) { + return '[Function]'; + } + + return '[Function ' + (val.name || 'anonymous') + ']'; + } + + function printSymbol(val) { + return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)'); + } + + function printError(val) { + return '[' + errorToString.call(val) + ']'; + } + /** + * The first port of call for printing an object, handles most of the + * data-types in JS. + */ + + function printBasicValue(val, printFunctionName, escapeRegex, escapeString) { + if (val === true || val === false) { + return '' + val; + } + + if (val === undefined) { + return 'undefined'; + } + + if (val === null) { + return 'null'; + } + + const typeOf = typeof val; + + if (typeOf === 'number') { + return printNumber(val); + } + + if (typeOf === 'bigint') { + return printBigInt(val); + } + + if (typeOf === 'string') { + if (escapeString) { + return '"' + val.replace(/"|\\/g, '\\$&') + '"'; + } + + return '"' + val + '"'; + } + + if (typeOf === 'function') { + return printFunction(val, printFunctionName); + } + + if (typeOf === 'symbol') { + return printSymbol(val); + } + + const toStringed = toString.call(val); + + if (toStringed === '[object WeakMap]') { + return 'WeakMap {}'; + } + + if (toStringed === '[object WeakSet]') { + return 'WeakSet {}'; + } + + if ( + toStringed === '[object Function]' || + toStringed === '[object GeneratorFunction]' + ) { + return printFunction(val, printFunctionName); + } + + if (toStringed === '[object Symbol]') { + return printSymbol(val); + } + + if (toStringed === '[object Date]') { + return isNaN(+val) ? 'Date { NaN }' : toISOString.call(val); + } + + if (toStringed === '[object Error]') { + return printError(val); + } + + if (toStringed === '[object RegExp]') { + if (escapeRegex) { + // https://github.com/benjamingr/RegExp.escape/blob/master/polyfill.js + return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); + } + + return regExpToString.call(val); + } + + if (val instanceof Error) { + return printError(val); + } + + return null; + } + /** + * Handles more complex objects ( such as objects with circular references. + * maps and sets etc ) + */ + + function printComplexValue( + val, + config, + indentation, + depth, + refs, + hasCalledToJSON + ) { + if (refs.indexOf(val) !== -1) { + return '[Circular]'; + } + + refs = refs.slice(); + refs.push(val); + const hitMaxDepth = ++depth > config.maxDepth; + const min = config.min; + + if ( + config.callToJSON && + !hitMaxDepth && + val.toJSON && + typeof val.toJSON === 'function' && + !hasCalledToJSON + ) { + return printer(val.toJSON(), config, indentation, depth, refs, true); + } + + const toStringed = toString.call(val); + + if (toStringed === '[object Arguments]') { + return hitMaxDepth + ? '[Arguments]' + : (min ? '' : 'Arguments ') + + '[' + + (0, _collections.printListItems)( + val, + config, + indentation, + depth, + refs, + printer + ) + + ']'; + } + + if (isToStringedArrayType(toStringed)) { + return hitMaxDepth + ? '[' + val.constructor.name + ']' + : (min ? '' : val.constructor.name + ' ') + + '[' + + (0, _collections.printListItems)( + val, + config, + indentation, + depth, + refs, + printer + ) + + ']'; + } + + if (toStringed === '[object Map]') { + return hitMaxDepth + ? '[Map]' + : 'Map {' + + (0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer, + ' => ' + ) + + '}'; + } + + if (toStringed === '[object Set]') { + return hitMaxDepth + ? '[Set]' + : 'Set {' + + (0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + + '}'; + } // Avoid failure to serialize global window object in jsdom test environment. + // For example, not even relevant if window is prop of React element. + + return hitMaxDepth || isWindow(val) + ? '[' + getConstructorName(val) + ']' + : (min ? '' : getConstructorName(val) + ' ') + + '{' + + (0, _collections.printObjectProperties)( + val, + config, + indentation, + depth, + refs, + printer + ) + + '}'; + } + + function isNewPlugin(plugin) { + return plugin.serialize != null; + } + + function printPlugin(plugin, val, config, indentation, depth, refs) { + let printed; + + try { + printed = isNewPlugin(plugin) + ? plugin.serialize(val, config, indentation, depth, refs, printer) + : plugin.print( + val, + valChild => printer(valChild, config, indentation, depth, refs), + str => { + const indentationNext = indentation + config.indent; + return ( + indentationNext + + str.replace(NEWLINE_REGEXP, '\n' + indentationNext) + ); + }, + { + edgeSpacing: config.spacingOuter, + min: config.min, + spacing: config.spacingInner + }, + config.colors + ); + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + + if (typeof printed !== 'string') { + throw new Error( + `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".` + ); + } + + return printed; + } + + function findPlugin(plugins, val) { + for (let p = 0; p < plugins.length; p++) { + try { + if (plugins[p].test(val)) { + return plugins[p]; + } + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + } + + return null; + } + + function printer(val, config, indentation, depth, refs, hasCalledToJSON) { + const plugin = findPlugin(config.plugins, val); + + if (plugin !== null) { + return printPlugin(plugin, val, config, indentation, depth, refs); + } + + const basicResult = printBasicValue( + val, + config.printFunctionName, + config.escapeRegex, + config.escapeString + ); + + if (basicResult !== null) { + return basicResult; + } + + return printComplexValue( + val, + config, + indentation, + depth, + refs, + hasCalledToJSON + ); + } + + const DEFAULT_THEME = { + comment: 'gray', + content: 'reset', + prop: 'yellow', + tag: 'cyan', + value: 'green' + }; + const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME); + const DEFAULT_OPTIONS = { + callToJSON: true, + escapeRegex: false, + escapeString: true, + highlight: false, + indent: 2, + maxDepth: Infinity, + min: false, + plugins: [], + printFunctionName: true, + theme: DEFAULT_THEME + }; + + function validateOptions(options) { + Object.keys(options).forEach(key => { + if (!DEFAULT_OPTIONS.hasOwnProperty(key)) { + throw new Error(`pretty-format: Unknown option "${key}".`); + } + }); + + if (options.min && options.indent !== undefined && options.indent !== 0) { + throw new Error( + 'pretty-format: Options "min" and "indent" cannot be used together.' + ); + } + + if (options.theme !== undefined) { + if (options.theme === null) { + throw new Error(`pretty-format: Option "theme" must not be null.`); + } + + if (typeof options.theme !== 'object') { + throw new Error( + `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".` + ); + } + } + } + + const getColorsHighlight = options => + DEFAULT_THEME_KEYS.reduce((colors, key) => { + const value = + options.theme && options.theme[key] !== undefined + ? options.theme[key] + : DEFAULT_THEME[key]; + const color = value && _ansiStyles.default[value]; + + if ( + color && + typeof color.close === 'string' && + typeof color.open === 'string' + ) { + colors[key] = color; + } else { + throw new Error( + `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.` + ); + } + + return colors; + }, Object.create(null)); + + const getColorsEmpty = () => + DEFAULT_THEME_KEYS.reduce((colors, key) => { + colors[key] = { + close: '', + open: '' + }; + return colors; + }, Object.create(null)); + + const getPrintFunctionName = options => + options && options.printFunctionName !== undefined + ? options.printFunctionName + : DEFAULT_OPTIONS.printFunctionName; + + const getEscapeRegex = options => + options && options.escapeRegex !== undefined + ? options.escapeRegex + : DEFAULT_OPTIONS.escapeRegex; + + const getEscapeString = options => + options && options.escapeString !== undefined + ? options.escapeString + : DEFAULT_OPTIONS.escapeString; + + const getConfig = options => ({ + callToJSON: + options && options.callToJSON !== undefined + ? options.callToJSON + : DEFAULT_OPTIONS.callToJSON, + colors: + options && options.highlight + ? getColorsHighlight(options) + : getColorsEmpty(), + escapeRegex: getEscapeRegex(options), + escapeString: getEscapeString(options), + indent: + options && options.min + ? '' + : createIndent( + options && options.indent !== undefined + ? options.indent + : DEFAULT_OPTIONS.indent + ), + maxDepth: + options && options.maxDepth !== undefined + ? options.maxDepth + : DEFAULT_OPTIONS.maxDepth, + min: options && options.min !== undefined ? options.min : DEFAULT_OPTIONS.min, + plugins: + options && options.plugins !== undefined + ? options.plugins + : DEFAULT_OPTIONS.plugins, + printFunctionName: getPrintFunctionName(options), + spacingInner: options && options.min ? ' ' : '\n', + spacingOuter: options && options.min ? '' : '\n' + }); + + function createIndent(indent) { + return new Array(indent + 1).join(' '); + } + /** + * Returns a presentation string of your `val` object + * @param val any potential JavaScript object + * @param options Custom settings + */ + + function prettyFormat(val, options) { + if (options) { + validateOptions(options); + + if (options.plugins) { + const plugin = findPlugin(options.plugins, val); + + if (plugin !== null) { + return printPlugin(plugin, val, getConfig(options), '', 0, []); + } + } + } + + const basicResult = printBasicValue( + val, + getPrintFunctionName(options), + getEscapeRegex(options), + getEscapeString(options) + ); + + if (basicResult !== null) { + return basicResult; + } + + return printComplexValue(val, getConfig(options), '', 0, []); + } + + prettyFormat.plugins = { + AsymmetricMatcher: _AsymmetricMatcher.default, + ConvertAnsi: _ConvertAnsi.default, + DOMCollection: _DOMCollection.default, + DOMElement: _DOMElement.default, + Immutable: _Immutable.default, + ReactElement: _ReactElement.default, + ReactTestComponent: _ReactTestComponent.default + }; + /* eslint-disable-next-line no-redeclare */ + + build = prettyFormat; + return build; +} + +var buildExports = requireBuild(); +var prettyFormat = /*@__PURE__*/getDefaultExportFromCjs(buildExports); + +var _PostDominator_exit, _PostDominator_nodes; +function computePostDominatorTree(fn, options) { + const graph = buildReverseGraph(fn, options.includeThrowsAsExitNode); + const nodes = computeImmediateDominators(graph); + if (!options.includeThrowsAsExitNode) { + for (const [id] of fn.body.blocks) { + if (!nodes.has(id)) { + nodes.set(id, id); + } + } + } + return new PostDominator(graph.entry, nodes); +} +class PostDominator { + constructor(exit, nodes) { + _PostDominator_exit.set(this, void 0); + _PostDominator_nodes.set(this, void 0); + __classPrivateFieldSet(this, _PostDominator_exit, exit, "f"); + __classPrivateFieldSet(this, _PostDominator_nodes, nodes, "f"); + } + get exit() { + return __classPrivateFieldGet(this, _PostDominator_exit, "f"); + } + get(id) { + const dominator = __classPrivateFieldGet(this, _PostDominator_nodes, "f").get(id); + CompilerError.invariant(dominator !== undefined, { + reason: 'Unknown node', + loc: GeneratedSource, + }); + return dominator === id ? null : dominator; + } + debug() { + const postDominators = new Map(); + for (const [key, value] of __classPrivateFieldGet(this, _PostDominator_nodes, "f")) { + postDominators.set(`bb${key}`, `bb${value}`); + } + return prettyFormat({ + exit: `bb${this.exit}`, + postDominators, + }); + } +} +_PostDominator_exit = new WeakMap(), _PostDominator_nodes = new WeakMap(); +function computeImmediateDominators(graph) { + const nodes = new Map(); + nodes.set(graph.entry, graph.entry); + let changed = true; + while (changed) { + changed = false; + for (const [id, node] of graph.nodes) { + if (node.id === graph.entry) { + continue; + } + let newIdom = null; + for (const pred of node.preds) { + if (nodes.has(pred)) { + newIdom = pred; + break; + } + } + CompilerError.invariant(newIdom !== null, { + reason: `At least one predecessor must have been visited for block ${id}`, + loc: GeneratedSource, + }); + for (const pred of node.preds) { + if (pred === newIdom) { + continue; + } + const predDom = nodes.get(pred); + if (predDom !== undefined) { + newIdom = intersect(pred, newIdom, graph, nodes); + } + } + if (nodes.get(id) !== newIdom) { + nodes.set(id, newIdom); + changed = true; + } + } + } + return nodes; +} +function intersect(a, b, graph, nodes) { + let block1 = graph.nodes.get(a); + let block2 = graph.nodes.get(b); + while (block1 !== block2) { + while (block1.index > block2.index) { + const dom = nodes.get(block1.id); + block1 = graph.nodes.get(dom); + } + while (block2.index > block1.index) { + const dom = nodes.get(block2.id); + block2 = graph.nodes.get(dom); + } + } + return block1.id; +} +function buildReverseGraph(fn, includeThrowsAsExitNode) { + const nodes = new Map(); + const exitId = fn.env.nextBlockId; + const exit = { + id: exitId, + index: 0, + preds: new Set(), + succs: new Set(), + }; + nodes.set(exitId, exit); + for (const [id, block] of fn.body.blocks) { + const node = { + id, + index: 0, + preds: new Set(eachTerminalSuccessor(block.terminal)), + succs: new Set(block.preds), + }; + if (block.terminal.kind === 'return') { + node.preds.add(exitId); + exit.succs.add(id); + } + else if (block.terminal.kind === 'throw' && includeThrowsAsExitNode) { + node.preds.add(exitId); + exit.succs.add(id); + } + nodes.set(id, node); + } + const visited = new Set(); + const postorder = []; + function visit(id) { + if (visited.has(id)) { + return; + } + visited.add(id); + const node = nodes.get(id); + for (const successor of node.succs) { + visit(successor); + } + postorder.push(id); + } + visit(exitId); + const rpo = { entry: exitId, nodes: new Map() }; + let index = 0; + for (const id of postorder.reverse()) { + const node = nodes.get(id); + node.index = index++; + rpo.nodes.set(id, node); + } + return rpo; +} + +const DEFAULT_SHAPES = new Map(BUILTIN_SHAPES); +const UNTYPED_GLOBALS = new Set([ + 'Object', + 'Function', + 'RegExp', + 'Date', + 'Error', + 'TypeError', + 'RangeError', + 'ReferenceError', + 'SyntaxError', + 'URIError', + 'EvalError', + 'DataView', + 'Float32Array', + 'Float64Array', + 'Int8Array', + 'Int16Array', + 'Int32Array', + 'WeakMap', + 'Uint8Array', + 'Uint8ClampedArray', + 'Uint16Array', + 'Uint32Array', + 'ArrayBuffer', + 'JSON', + 'console', + 'eval', +]); +const TYPED_GLOBALS = [ + [ + 'Object', + addObject(DEFAULT_SHAPES, 'Object', [ + [ + 'keys', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'fromEntries', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.ConditionallyMutate], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInObjectId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'entries', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + aliasing: { + receiver: '@receiver', + params: ['@object'], + rest: null, + returns: '@returns', + temporaries: [], + effects: [ + { + kind: 'Create', + into: '@returns', + reason: ValueReason.KnownReturnSignature, + value: ValueKind.Mutable, + }, + { + kind: 'Capture', + from: '@object', + into: '@returns', + }, + ], + }, + }), + ], + [ + 'keys', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + aliasing: { + receiver: '@receiver', + params: ['@object'], + rest: null, + returns: '@returns', + temporaries: [], + effects: [ + { + kind: 'Create', + into: '@returns', + reason: ValueReason.KnownReturnSignature, + value: ValueKind.Mutable, + }, + { + kind: 'ImmutableCapture', + from: '@object', + into: '@returns', + }, + ], + }, + }), + ], + [ + 'values', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + aliasing: { + receiver: '@receiver', + params: ['@object'], + rest: null, + returns: '@returns', + temporaries: [], + effects: [ + { + kind: 'Create', + into: '@returns', + reason: ValueReason.KnownReturnSignature, + value: ValueKind.Mutable, + }, + { + kind: 'Capture', + from: '@object', + into: '@returns', + }, + ], + }, + }), + ], + ]), + ], + [ + 'Array', + addObject(DEFAULT_SHAPES, 'Array', [ + [ + 'isArray', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'from', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [ + Effect.ConditionallyMutateIterator, + Effect.ConditionallyMutate, + Effect.ConditionallyMutate, + ], + restParam: Effect.Read, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'of', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }), + ], + ]), + ], + [ + 'performance', + addObject(DEFAULT_SHAPES, 'performance', [ + [ + 'now', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + impure: true, + canonicalName: 'performance.now', + }), + ], + ]), + ], + [ + 'Date', + addObject(DEFAULT_SHAPES, 'Date', [ + [ + 'now', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + impure: true, + canonicalName: 'Date.now', + }), + ], + ]), + ], + [ + 'Math', + addObject(DEFAULT_SHAPES, 'Math', [ + ['PI', { kind: 'Primitive' }], + [ + 'max', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'min', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'trunc', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'ceil', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'floor', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'pow', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'random', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + impure: true, + canonicalName: 'Math.random', + }), + ], + ]), + ], + ['Infinity', { kind: 'Primitive' }], + ['NaN', { kind: 'Primitive' }], + [ + 'console', + addObject(DEFAULT_SHAPES, 'console', [ + [ + 'error', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'info', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'log', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'table', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'trace', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'warn', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + ]), + ], + [ + 'Boolean', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'Number', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'String', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'parseInt', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'parseFloat', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'isNaN', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'isFinite', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'encodeURI', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'encodeURIComponent', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'decodeURI', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'decodeURIComponent', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'Map', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.ConditionallyMutateIterator], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInMapId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }, null, true), + ], + [ + 'Set', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.ConditionallyMutateIterator], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInSetId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }, null, true), + ], + [ + 'WeakMap', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.ConditionallyMutateIterator], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInWeakMapId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }, null, true), + ], + [ + 'WeakSet', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.ConditionallyMutateIterator], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInWeakSetId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }, null, true), + ], +]; +const REACT_APIS = [ + [ + 'useContext', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'useContext', + returnValueKind: ValueKind.Frozen, + returnValueReason: ValueReason.Context, + }, BuiltInUseContextHookId), + ], + [ + 'useState', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Object', shapeId: BuiltInUseStateId }, + calleeEffect: Effect.Read, + hookKind: 'useState', + returnValueKind: ValueKind.Frozen, + returnValueReason: ValueReason.State, + }), + ], + [ + 'useActionState', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Object', shapeId: BuiltInUseActionStateId }, + calleeEffect: Effect.Read, + hookKind: 'useActionState', + returnValueKind: ValueKind.Frozen, + returnValueReason: ValueReason.State, + }), + ], + [ + 'useReducer', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Object', shapeId: BuiltInUseReducerId }, + calleeEffect: Effect.Read, + hookKind: 'useReducer', + returnValueKind: ValueKind.Frozen, + returnValueReason: ValueReason.ReducerState, + }), + ], + [ + 'useRef', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Capture, + returnType: { kind: 'Object', shapeId: BuiltInUseRefId }, + calleeEffect: Effect.Read, + hookKind: 'useRef', + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'useImperativeHandle', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + hookKind: 'useImperativeHandle', + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'useMemo', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'useMemo', + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'useCallback', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'useCallback', + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'useEffect', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + hookKind: 'useEffect', + returnValueKind: ValueKind.Frozen, + aliasing: { + receiver: '@receiver', + params: [], + rest: '@rest', + returns: '@returns', + temporaries: ['@effect'], + effects: [ + { + kind: 'Freeze', + value: '@rest', + reason: ValueReason.Effect, + }, + { + kind: 'Create', + into: '@effect', + value: ValueKind.Frozen, + reason: ValueReason.KnownReturnSignature, + }, + { + kind: 'Capture', + from: '@rest', + into: '@effect', + }, + { + kind: 'Create', + into: '@returns', + value: ValueKind.Primitive, + reason: ValueReason.KnownReturnSignature, + }, + ], + }, + }, BuiltInUseEffectHookId), + ], + [ + 'useLayoutEffect', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'useLayoutEffect', + returnValueKind: ValueKind.Frozen, + }, BuiltInUseLayoutEffectHookId), + ], + [ + 'useInsertionEffect', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'useInsertionEffect', + returnValueKind: ValueKind.Frozen, + }, BuiltInUseInsertionEffectHookId), + ], + [ + 'useTransition', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInUseTransitionId }, + calleeEffect: Effect.Read, + hookKind: 'useTransition', + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'useOptimistic', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Object', shapeId: BuiltInUseOptimisticId }, + calleeEffect: Effect.Read, + hookKind: 'useOptimistic', + returnValueKind: ValueKind.Frozen, + returnValueReason: ValueReason.State, + }), + ], + [ + 'use', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Frozen, + }, BuiltInUseOperatorId), + ], + [ + 'useEffectEvent', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { + kind: 'Function', + return: { kind: 'Poly' }, + shapeId: BuiltInEffectEventId, + isConstructor: false, + }, + calleeEffect: Effect.Read, + hookKind: 'useEffectEvent', + returnValueKind: ValueKind.Frozen, + }, BuiltInUseEffectEventId), + ], +]; +TYPED_GLOBALS.push([ + 'React', + addObject(DEFAULT_SHAPES, null, [ + ...REACT_APIS, + [ + 'createElement', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'cloneElement', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'createRef', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Capture, + returnType: { kind: 'Object', shapeId: BuiltInUseRefId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }), + ], + ]), +], [ + '_jsx', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Frozen, + }), +]); +const DEFAULT_GLOBALS = new Map(REACT_APIS); +for (const name of UNTYPED_GLOBALS) { + DEFAULT_GLOBALS.set(name, { + kind: 'Poly', + }); +} +for (const [name, type_] of TYPED_GLOBALS) { + DEFAULT_GLOBALS.set(name, type_); +} +DEFAULT_GLOBALS.set('globalThis', addObject(DEFAULT_SHAPES, 'globalThis', TYPED_GLOBALS)); +DEFAULT_GLOBALS.set('global', addObject(DEFAULT_SHAPES, 'global', TYPED_GLOBALS)); +function installTypeConfig(globals, shapes, typeConfig, moduleName, loc) { + var _a, _b, _c, _d, _e, _f; + switch (typeConfig.kind) { + case 'type': { + switch (typeConfig.name) { + case 'Array': { + return { kind: 'Object', shapeId: BuiltInArrayId }; + } + case 'MixedReadonly': { + return { kind: 'Object', shapeId: BuiltInMixedReadonlyId }; + } + case 'Primitive': { + return { kind: 'Primitive' }; + } + case 'Ref': { + return { kind: 'Object', shapeId: BuiltInUseRefId }; + } + case 'Any': { + return { kind: 'Poly' }; + } + default: { + assertExhaustive$1(typeConfig.name, `Unexpected type '${typeConfig.name}'`); + } + } + } + case 'function': { + return addFunction(shapes, [], { + positionalParams: typeConfig.positionalParams, + restParam: typeConfig.restParam, + calleeEffect: typeConfig.calleeEffect, + returnType: installTypeConfig(globals, shapes, typeConfig.returnType, moduleName, loc), + returnValueKind: typeConfig.returnValueKind, + noAlias: typeConfig.noAlias === true, + mutableOnlyIfOperandsAreMutable: typeConfig.mutableOnlyIfOperandsAreMutable === true, + aliasing: typeConfig.aliasing, + knownIncompatible: (_a = typeConfig.knownIncompatible) !== null && _a !== void 0 ? _a : null, + }); + } + case 'hook': { + return addHook(shapes, { + hookKind: 'Custom', + positionalParams: (_b = typeConfig.positionalParams) !== null && _b !== void 0 ? _b : [], + restParam: (_c = typeConfig.restParam) !== null && _c !== void 0 ? _c : Effect.Freeze, + calleeEffect: Effect.Read, + returnType: installTypeConfig(globals, shapes, typeConfig.returnType, moduleName, loc), + returnValueKind: (_d = typeConfig.returnValueKind) !== null && _d !== void 0 ? _d : ValueKind.Frozen, + noAlias: typeConfig.noAlias === true, + aliasing: typeConfig.aliasing, + knownIncompatible: (_e = typeConfig.knownIncompatible) !== null && _e !== void 0 ? _e : null, + }); + } + case 'object': { + return addObject(shapes, null, Object.entries((_f = typeConfig.properties) !== null && _f !== void 0 ? _f : {}).map(([key, value]) => { + var _a; + const type = installTypeConfig(globals, shapes, value, moduleName, loc); + const expectHook = isHookName$2(key); + let isHook = false; + if (type.kind === 'Function' && type.shapeId !== null) { + const functionType = shapes.get(type.shapeId); + if (((_a = functionType === null || functionType === void 0 ? void 0 : functionType.functionType) === null || _a === void 0 ? void 0 : _a.hookKind) !== null) { + isHook = true; + } + } + if (expectHook !== isHook) { + CompilerError.throwInvalidConfig({ + reason: `Invalid type configuration for module`, + description: `Expected type for object property '${key}' from module '${moduleName}' ${expectHook ? 'to be a hook' : 'not to be a hook'} based on the property name`, + loc, + }); + } + return [key, type]; + })); + } + default: { + assertExhaustive$1(typeConfig, `Unexpected type kind '${typeConfig.kind}'`); + } + } +} +function getReanimatedModuleType(registry) { + const frozenHooks = [ + 'useFrameCallback', + 'useAnimatedStyle', + 'useAnimatedProps', + 'useAnimatedScrollHandler', + 'useAnimatedReaction', + 'useWorkletCallback', + ]; + const reanimatedType = []; + for (const hook of frozenHooks) { + reanimatedType.push([ + hook, + addHook(registry, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + returnValueKind: ValueKind.Frozen, + noAlias: true, + calleeEffect: Effect.Read, + hookKind: 'Custom', + }), + ]); + } + const mutableHooks = ['useSharedValue', 'useDerivedValue']; + for (const hook of mutableHooks) { + reanimatedType.push([ + hook, + addHook(registry, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Object', shapeId: ReanimatedSharedValueId }, + returnValueKind: ValueKind.Mutable, + noAlias: true, + calleeEffect: Effect.Read, + hookKind: 'Custom', + }), + ]); + } + const funcs = [ + 'withTiming', + 'withSpring', + 'createAnimatedPropAdapter', + 'withDecay', + 'withRepeat', + 'runOnUI', + 'executeOnUIRuntimeSync', + ]; + for (const fn of funcs) { + reanimatedType.push([ + fn, + addFunction(registry, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + noAlias: true, + }), + ]); + } + return addObject(registry, null, reanimatedType); +} + +const ObjectPropertiesSchema = v4.z + .record(v4.z.string(), v4.z.lazy(() => TypeSchema)) + .refine(record => { + return Object.keys(record).every(key => key === '*' || key === 'default' || libExports$1.isValidIdentifier(key)); +}, 'Expected all "object" property names to be valid identifier, `*` to match any property, of `default` to define a module default export'); +const ObjectTypeSchema = v4.z.object({ + kind: v4.z.literal('object'), + properties: ObjectPropertiesSchema.nullable(), +}); +const LifetimeIdSchema = v4.z.string().refine(id => id.startsWith('@'), { + message: "Placeholder names must start with '@'", +}); +const FreezeEffectSchema = v4.z.object({ + kind: v4.z.literal('Freeze'), + value: LifetimeIdSchema, + reason: ValueReasonSchema, +}); +const MutateEffectSchema = v4.z.object({ + kind: v4.z.literal('Mutate'), + value: LifetimeIdSchema, +}); +const MutateTransitiveConditionallySchema = v4.z.object({ + kind: v4.z.literal('MutateTransitiveConditionally'), + value: LifetimeIdSchema, +}); +const CreateEffectSchema = v4.z.object({ + kind: v4.z.literal('Create'), + into: LifetimeIdSchema, + value: ValueKindSchema, + reason: ValueReasonSchema, +}); +const AssignEffectSchema = v4.z.object({ + kind: v4.z.literal('Assign'), + from: LifetimeIdSchema, + into: LifetimeIdSchema, +}); +const AliasEffectSchema = v4.z.object({ + kind: v4.z.literal('Alias'), + from: LifetimeIdSchema, + into: LifetimeIdSchema, +}); +const ImmutableCaptureEffectSchema = v4.z.object({ + kind: v4.z.literal('ImmutableCapture'), + from: LifetimeIdSchema, + into: LifetimeIdSchema, +}); +const CaptureEffectSchema = v4.z.object({ + kind: v4.z.literal('Capture'), + from: LifetimeIdSchema, + into: LifetimeIdSchema, +}); +const CreateFromEffectSchema = v4.z.object({ + kind: v4.z.literal('CreateFrom'), + from: LifetimeIdSchema, + into: LifetimeIdSchema, +}); +const ApplyArgSchema = v4.z.union([ + LifetimeIdSchema, + v4.z.object({ + kind: v4.z.literal('Spread'), + place: LifetimeIdSchema, + }), + v4.z.object({ + kind: v4.z.literal('Hole'), + }), +]); +const ApplyEffectSchema = v4.z.object({ + kind: v4.z.literal('Apply'), + receiver: LifetimeIdSchema, + function: LifetimeIdSchema, + mutatesFunction: v4.z.boolean(), + args: v4.z.array(ApplyArgSchema), + into: LifetimeIdSchema, +}); +const ImpureEffectSchema = v4.z.object({ + kind: v4.z.literal('Impure'), + place: LifetimeIdSchema, +}); +const AliasingEffectSchema = v4.z.union([ + FreezeEffectSchema, + CreateEffectSchema, + CreateFromEffectSchema, + AssignEffectSchema, + AliasEffectSchema, + CaptureEffectSchema, + ImmutableCaptureEffectSchema, + ImpureEffectSchema, + MutateEffectSchema, + MutateTransitiveConditionallySchema, + ApplyEffectSchema, +]); +const AliasingSignatureSchema = v4.z.object({ + receiver: LifetimeIdSchema, + params: v4.z.array(LifetimeIdSchema), + rest: LifetimeIdSchema.nullable(), + returns: LifetimeIdSchema, + effects: v4.z.array(AliasingEffectSchema), + temporaries: v4.z.array(LifetimeIdSchema), +}); +const FunctionTypeSchema = v4.z.object({ + kind: v4.z.literal('function'), + positionalParams: v4.z.array(EffectSchema), + restParam: EffectSchema.nullable(), + calleeEffect: EffectSchema, + returnType: v4.z.lazy(() => TypeSchema), + returnValueKind: ValueKindSchema, + noAlias: v4.z.boolean().nullable().optional(), + mutableOnlyIfOperandsAreMutable: v4.z.boolean().nullable().optional(), + impure: v4.z.boolean().nullable().optional(), + canonicalName: v4.z.string().nullable().optional(), + aliasing: AliasingSignatureSchema.nullable().optional(), + knownIncompatible: v4.z.string().nullable().optional(), +}); +const HookTypeSchema = v4.z.object({ + kind: v4.z.literal('hook'), + positionalParams: v4.z.array(EffectSchema).nullable().optional(), + restParam: EffectSchema.nullable().optional(), + returnType: v4.z.lazy(() => TypeSchema), + returnValueKind: ValueKindSchema.nullable().optional(), + noAlias: v4.z.boolean().nullable().optional(), + aliasing: AliasingSignatureSchema.nullable().optional(), + knownIncompatible: v4.z.string().nullable().optional(), +}); +const BuiltInTypeSchema = v4.z.union([ + v4.z.literal('Any'), + v4.z.literal('Ref'), + v4.z.literal('Array'), + v4.z.literal('Primitive'), + v4.z.literal('MixedReadonly'), +]); +const TypeReferenceSchema = v4.z.object({ + kind: v4.z.literal('type'), + name: BuiltInTypeSchema, +}); +const TypeSchema = v4.z.union([ + ObjectTypeSchema, + FunctionTypeSchema, + HookTypeSchema, + TypeReferenceSchema, +]); + +function unsupportedTypeAnnotation(desc, loc) { + CompilerError.throwInvalidJS({ + reason: `Typedchecker does not currently support type annotation: ${desc}`, + loc, + }); +} + +var _FlowTypeEnv_nextNominalId, _FlowTypeEnv_nextTypeParameterId, _FlowTypeEnv_types, _FlowTypeEnv_bindings, _FlowTypeEnv_generics, _FlowTypeEnv_flowTypes; +function makeTypeParameterId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected TypeParameterId to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function makeNominalId(id) { + return id; +} +const DUMMY_NOMINAL = makeNominalId(0); +function convertFlowType(flowType, loc) { + let nextGenericId = 0; + function convertFlowTypeImpl(flowType, loc, genericEnv, platform, poly = null) { + var _a, _b, _c; + switch (flowType.kind) { + case 'TypeApp': { + if (flowType.type.kind === 'Def' && + flowType.type.def.kind === 'Poly' && + flowType.type.def.t_out.kind === 'Def' && + flowType.type.def.t_out.def.kind === 'Type' && + flowType.type.def.t_out.def.type.kind === 'Opaque' && + flowType.type.def.t_out.def.type.opaquetype.opaque_name === + 'Client' && + flowType.targs.length === 1) { + return convertFlowTypeImpl(flowType.targs[0], loc, genericEnv, 'client'); + } + else if (flowType.type.kind === 'Def' && + flowType.type.def.kind === 'Poly' && + flowType.type.def.t_out.kind === 'Def' && + flowType.type.def.t_out.def.kind === 'Type' && + flowType.type.def.t_out.def.type.kind === 'Opaque' && + flowType.type.def.t_out.def.type.opaquetype.opaque_name === + 'Server' && + flowType.targs.length === 1) { + return convertFlowTypeImpl(flowType.targs[0], loc, genericEnv, 'server'); + } + return Resolved.todo(platform); + } + case 'Open': + return Resolved.mixed(platform); + case 'Any': + return Resolved.todo(platform); + case 'Annot': + return convertFlowTypeImpl(flowType.type, loc, genericEnv, platform, poly); + case 'Opaque': { + if (flowType.opaquetype.opaque_name === 'Client' && + flowType.opaquetype.super_t != null) { + return convertFlowTypeImpl(flowType.opaquetype.super_t, loc, genericEnv, 'client'); + } + if (flowType.opaquetype.opaque_name === 'Server' && + flowType.opaquetype.super_t != null) { + return convertFlowTypeImpl(flowType.opaquetype.super_t, loc, genericEnv, 'server'); + } + const t = (_a = flowType.opaquetype.underlying_t) !== null && _a !== void 0 ? _a : flowType.opaquetype.super_t; + if (t != null) { + return convertFlowTypeImpl(t, loc, genericEnv, platform, poly); + } + else { + return Resolved.todo(platform); + } + } + case 'Def': { + switch (flowType.def.kind) { + case 'EnumValue': + return convertFlowTypeImpl(flowType.def.enum_info.representation_t, loc, genericEnv, platform, poly); + case 'EnumObject': + return Resolved.enum(platform); + case 'Empty': + return Resolved.todo(platform); + case 'Instance': { + const members = new Map(); + for (const key in flowType.def.instance.inst.own_props) { + const prop = flowType.def.instance.inst.own_props[key]; + if (prop.kind === 'Field') { + members.set(key, convertFlowTypeImpl(prop.type, loc, genericEnv, platform)); + } + else { + CompilerError.invariant(false, { + reason: `Unsupported property kind ${prop.kind}`, + loc: GeneratedSource, + }); + } + } + return Resolved.class((_b = flowType.def.instance.inst.class_name) !== null && _b !== void 0 ? _b : '[anonymous class]', members, platform); + } + case 'Type': + return convertFlowTypeImpl(flowType.def.type, loc, genericEnv, platform, poly); + case 'NumGeneral': + case 'SingletonNum': + return Resolved.number(platform); + case 'StrGeneral': + case 'SingletonStr': + return Resolved.string(platform); + case 'BoolGeneral': + case 'SingletonBool': + return Resolved.boolean(platform); + case 'Void': + return Resolved.void(platform); + case 'Null': + return Resolved.void(platform); + case 'Mixed': + return Resolved.mixed(platform); + case 'Arr': { + if (flowType.def.arrtype.kind === 'ArrayAT' || + flowType.def.arrtype.kind === 'ROArrayAT') { + return Resolved.array(convertFlowTypeImpl(flowType.def.arrtype.elem_t, loc, genericEnv, platform), platform); + } + else { + return Resolved.tuple(DUMMY_NOMINAL, flowType.def.arrtype.elements.map(t => convertFlowTypeImpl(t.t, loc, genericEnv, platform)), platform); + } + } + case 'Obj': { + const members = new Map(); + for (const key in flowType.def.objtype.props) { + const prop = flowType.def.objtype.props[key]; + if (prop.kind === 'Field') { + members.set(key, convertFlowTypeImpl(prop.type, loc, genericEnv, platform)); + } + else { + CompilerError.invariant(false, { + reason: `Unsupported property kind ${prop.kind}`, + loc: GeneratedSource, + }); + } + } + return Resolved.object(DUMMY_NOMINAL, members, platform); + } + case 'Class': { + if (flowType.def.type.kind === 'ThisInstance') { + const members = new Map(); + for (const key in flowType.def.type.instance.inst.own_props) { + const prop = flowType.def.type.instance.inst.own_props[key]; + if (prop.kind === 'Field') { + members.set(key, convertFlowTypeImpl(prop.type, loc, genericEnv, platform)); + } + else { + CompilerError.invariant(false, { + reason: `Unsupported property kind ${prop.kind}`, + loc: GeneratedSource, + }); + } + } + return Resolved.class((_c = flowType.def.type.instance.inst.class_name) !== null && _c !== void 0 ? _c : '[anonymous class]', members, platform); + } + CompilerError.invariant(false, { + reason: `Unsupported class instance type ${flowType.def.type.kind}`, + loc: GeneratedSource, + }); + } + case 'Fun': + return Resolved.function(poly, flowType.def.funtype.params.map(p => convertFlowTypeImpl(p.type, loc, genericEnv, platform)), convertFlowTypeImpl(flowType.def.funtype.return_t, loc, genericEnv, platform), platform); + case 'Poly': { + let newEnv = genericEnv; + const poly = flowType.def.tparams.map(p => { + const id = makeTypeParameterId(nextGenericId++); + const bound = convertFlowTypeImpl(p.bound, loc, newEnv, platform); + newEnv = new Map(newEnv); + newEnv.set(p.name, id); + return { + name: p.name, + id, + bound, + }; + }); + return convertFlowTypeImpl(flowType.def.t_out, loc, newEnv, platform, poly); + } + case 'ReactAbstractComponent': { + const props = new Map(); + let children = null; + const propsType = convertFlowTypeImpl(flowType.def.config, loc, genericEnv, platform); + if (propsType.type.kind === 'Object') { + propsType.type.members.forEach((v, k) => { + if (k === 'children') { + children = v; + } + else { + props.set(k, v); + } + }); + } + else { + CompilerError.invariant(false, { + reason: `Unsupported component props type ${propsType.type.kind}`, + loc: GeneratedSource, + }); + } + return Resolved.component(props, children, platform); + } + case 'Renders': + return Resolved.todo(platform); + default: + unsupportedTypeAnnotation('Renders', GeneratedSource); + } + } + case 'Generic': { + const id = genericEnv.get(flowType.name); + if (id == null) { + unsupportedTypeAnnotation(flowType.name, GeneratedSource); + } + return Resolved.generic(id, platform, convertFlowTypeImpl(flowType.bound, loc, genericEnv, platform)); + } + case 'Union': { + const members = flowType.members.map(t => convertFlowTypeImpl(t, loc, genericEnv, platform)); + if (members.length === 1) { + return members[0]; + } + if (members[0].type.kind === 'Number' || + members[0].type.kind === 'String' || + members[0].type.kind === 'Boolean') { + const dupes = members.filter(t => t.type.kind === members[0].type.kind); + if (dupes.length === members.length) { + return members[0]; + } + } + if (members[0].type.kind === 'Array' && + (members[0].type.element.type.kind === 'Number' || + members[0].type.element.type.kind === 'String' || + members[0].type.element.type.kind === 'Boolean')) { + const first = members[0].type.element; + const dupes = members.filter(t => t.type.kind === 'Array' && + t.type.element.type.kind === first.type.kind); + if (dupes.length === members.length) { + return members[0]; + } + } + return Resolved.union(members, platform); + } + case 'Eval': { + if (flowType.destructor.kind === 'ReactDRO' || + flowType.destructor.kind === 'ReactCheckComponentConfig') { + return convertFlowTypeImpl(flowType.type, loc, genericEnv, platform, poly); + } + unsupportedTypeAnnotation(`EvalT(${flowType.destructor.kind})`, GeneratedSource); + } + case 'Optional': { + return Resolved.union([ + convertFlowTypeImpl(flowType.type, loc, genericEnv, platform), + Resolved.void(platform), + ], platform); + } + default: + unsupportedTypeAnnotation(flowType.kind, GeneratedSource); + } + } + return convertFlowTypeImpl(flowType, loc, new Map(), 'shared'); +} +function serializeLoc(location) { + return `${location.start.line}:${location.start.column}-${location.end.line}:${location.end.column}`; +} +function buildTypeEnvironment(flowOutput) { + const result = new Map(); + for (const item of flowOutput) { + const loc = { + start: { + line: item.loc.start.line, + column: item.loc.start.column - 1, + index: item.loc.start.index, + }, + end: item.loc.end, + filename: item.loc.filename, + identifierName: item.loc.identifierName, + }; + result.set(serializeLoc(loc), item.type); + } + return result; +} +let lastFlowSource = null; +let lastFlowResult = null; +class FlowTypeEnv { + constructor() { + this.moduleEnv = new Map(); + _FlowTypeEnv_nextNominalId.set(this, 0); + _FlowTypeEnv_nextTypeParameterId.set(this, 0); + _FlowTypeEnv_types.set(this, new Map()); + _FlowTypeEnv_bindings.set(this, new Map()); + _FlowTypeEnv_generics.set(this, []); + _FlowTypeEnv_flowTypes.set(this, new Map()); + } + init(env, source) { + CompilerError.invariant(env.config.flowTypeProvider != null, { + reason: 'Expected flowDumpTypes to be defined in environment config', + loc: GeneratedSource, + }); + let stdout; + if (source === lastFlowSource) { + stdout = lastFlowResult; + } + else { + lastFlowSource = source; + lastFlowResult = env.config.flowTypeProvider(source); + stdout = lastFlowResult; + } + const flowTypes = buildTypeEnvironment(stdout); + const resolvedFlowTypes = new Map(); + for (const [loc, type] of flowTypes) { + if (typeof loc === 'symbol') + continue; + resolvedFlowTypes.set(loc, convertFlowType(JSON.parse(type), loc)); + } + __classPrivateFieldSet(this, _FlowTypeEnv_flowTypes, resolvedFlowTypes, "f"); + } + setType(identifier, type) { + if (typeof identifier.loc !== 'symbol' && + __classPrivateFieldGet(this, _FlowTypeEnv_flowTypes, "f").has(serializeLoc(identifier.loc))) { + return; + } + __classPrivateFieldGet(this, _FlowTypeEnv_types, "f").set(identifier.id, type); + } + getType(identifier) { + const result = this.getTypeOrNull(identifier); + if (result == null) { + throw new Error(`Type not found for ${identifier.id}, ${typeof identifier.loc === 'symbol' ? 'generated loc' : serializeLoc(identifier.loc)}`); + } + return result; + } + getTypeOrNull(identifier) { + var _a; + const result = (_a = __classPrivateFieldGet(this, _FlowTypeEnv_types, "f").get(identifier.id)) !== null && _a !== void 0 ? _a : null; + if (result == null && typeof identifier.loc !== 'symbol') { + const flowType = __classPrivateFieldGet(this, _FlowTypeEnv_flowTypes, "f").get(serializeLoc(identifier.loc)); + return flowType !== null && flowType !== void 0 ? flowType : null; + } + return result; + } + getTypeByLoc(loc) { + if (typeof loc === 'symbol') { + return null; + } + const flowType = __classPrivateFieldGet(this, _FlowTypeEnv_flowTypes, "f").get(serializeLoc(loc)); + return flowType !== null && flowType !== void 0 ? flowType : null; + } + nextNominalId() { + var _a, _b; + return makeNominalId((__classPrivateFieldSet(this, _FlowTypeEnv_nextNominalId, (_b = __classPrivateFieldGet(this, _FlowTypeEnv_nextNominalId, "f"), _a = _b++, _b), "f"), _a)); + } + nextTypeParameterId() { + var _a, _b; + return makeTypeParameterId((__classPrivateFieldSet(this, _FlowTypeEnv_nextTypeParameterId, (_b = __classPrivateFieldGet(this, _FlowTypeEnv_nextTypeParameterId, "f"), _a = _b++, _b), "f"), _a)); + } + addBinding(bindingIdentifier, type) { + __classPrivateFieldGet(this, _FlowTypeEnv_bindings, "f").set(bindingIdentifier, type); + } + resolveBinding(bindingIdentifier) { + var _a; + return (_a = __classPrivateFieldGet(this, _FlowTypeEnv_bindings, "f").get(bindingIdentifier)) !== null && _a !== void 0 ? _a : null; + } + pushGeneric(name, generic) { + __classPrivateFieldGet(this, _FlowTypeEnv_generics, "f").unshift([name, generic]); + } + popGeneric(name) { + for (let i = 0; i < __classPrivateFieldGet(this, _FlowTypeEnv_generics, "f").length; i++) { + if (__classPrivateFieldGet(this, _FlowTypeEnv_generics, "f")[i][0] === name) { + __classPrivateFieldGet(this, _FlowTypeEnv_generics, "f").splice(i, 1); + return; + } + } + } + getGeneric(name) { + for (const [eltName, param] of __classPrivateFieldGet(this, _FlowTypeEnv_generics, "f")) { + if (name === eltName) { + return param; + } + } + return null; + } +} +_FlowTypeEnv_nextNominalId = new WeakMap(), _FlowTypeEnv_nextTypeParameterId = new WeakMap(), _FlowTypeEnv_types = new WeakMap(), _FlowTypeEnv_bindings = new WeakMap(), _FlowTypeEnv_generics = new WeakMap(), _FlowTypeEnv_flowTypes = new WeakMap(); +const Primitives = { + number(platform) { + return { kind: 'Concrete', type: { kind: 'Number' }, platform }; + }, + string(platform) { + return { kind: 'Concrete', type: { kind: 'String' }, platform }; + }, + boolean(platform) { + return { kind: 'Concrete', type: { kind: 'Boolean' }, platform }; + }, + void(platform) { + return { kind: 'Concrete', type: { kind: 'Void' }, platform }; + }, + mixed(platform) { + return { kind: 'Concrete', type: { kind: 'Mixed' }, platform }; + }, + enum(platform) { + return { kind: 'Concrete', type: { kind: 'Enum' }, platform }; + }, + todo(platform) { + return { kind: 'Concrete', type: { kind: 'Mixed' }, platform }; + }, +}; +const Resolved = Object.assign(Object.assign({}, Primitives), { nullable(type, platform) { + return { kind: 'Concrete', type: { kind: 'Nullable', type }, platform }; + }, + array(element, platform) { + return { kind: 'Concrete', type: { kind: 'Array', element }, platform }; + }, + set(element, platform) { + return { kind: 'Concrete', type: { kind: 'Set', element }, platform }; + }, + map(key, value, platform) { + return { kind: 'Concrete', type: { kind: 'Map', key, value }, platform }; + }, + function(typeParameters, params, returnType, platform) { + return { + kind: 'Concrete', + type: { kind: 'Function', typeParameters, params, returnType }, + platform, + }; + }, + component(props, children, platform) { + return { + kind: 'Concrete', + type: { kind: 'Component', props, children }, + platform, + }; + }, + object(id, members, platform) { + return { + kind: 'Concrete', + type: { + kind: 'Object', + id, + members, + }, + platform, + }; + }, + class(name, members, platform) { + return { + kind: 'Concrete', + type: { + kind: 'Instance', + name, + members, + }, + platform, + }; + }, + tuple(id, members, platform) { + return { + kind: 'Concrete', + type: { + kind: 'Tuple', + id, + members, + }, + platform, + }; + }, + generic(id, platform, bound = Primitives.mixed(platform)) { + return { + kind: 'Concrete', + type: { + kind: 'Generic', + id, + bound, + }, + platform, + }; + }, + union(members, platform) { + return { + kind: 'Concrete', + type: { + kind: 'Union', + members, + }, + platform, + }; + } }); + +function defaultModuleTypeProvider(moduleName) { + switch (moduleName) { + case 'react-hook-form': { + return { + kind: 'object', + properties: { + useForm: { + kind: 'hook', + returnType: { + kind: 'object', + properties: { + watch: { + kind: 'function', + positionalParams: [], + restParam: Effect.Read, + calleeEffect: Effect.Read, + returnType: { kind: 'type', name: 'Any' }, + returnValueKind: ValueKind.Mutable, + knownIncompatible: `React Hook Form's \`useForm()\` API returns a \`watch()\` function which cannot be memoized safely.`, + }, + }, + }, + }, + }, + }; + } + case '@tanstack/react-table': { + return { + kind: 'object', + properties: { + useReactTable: { + kind: 'hook', + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'type', name: 'Any' }, + knownIncompatible: `TanStack Table's \`useReactTable()\` API returns functions that cannot be memoized safely`, + }, + }, + }; + } + case '@tanstack/react-virtual': { + return { + kind: 'object', + properties: { + useVirtualizer: { + kind: 'hook', + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'type', name: 'Any' }, + knownIncompatible: `TanStack Virtual's \`useVirtualizer()\` API returns functions that cannot be memoized safely`, + }, + }, + }; + } + } + return null; +} + +var _Environment_instances, _Environment_globals, _Environment_shapes, _Environment_moduleTypes, _Environment_nextIdentifer, _Environment_nextBlock, _Environment_nextScope, _Environment_scope, _Environment_outlinedFunctions, _Environment_contextIdentifiers, _Environment_hoistedIdentifiers, _Environment_flowTypeEnvironment, _Environment_errors, _Environment_resolveModuleType, _Environment_isKnownReactModule, _Environment_getCustomHookType; +const ExternalFunctionSchema = v4.z.object({ + source: v4.z.string(), + importSpecifierName: v4.z.string(), +}); +const InstrumentationSchema = v4.z + .object({ + fn: ExternalFunctionSchema, + gating: ExternalFunctionSchema.nullable(), + globalGating: v4.z.string().nullable(), +}) + .refine(opts => opts.gating != null || opts.globalGating != null, 'Expected at least one of gating or globalGating'); +const MacroSchema = v4.z.string(); +const HookSchema = v4.z.object({ + effectKind: v4.z.nativeEnum(Effect), + valueKind: v4.z.nativeEnum(ValueKind), + noAlias: v4.z.boolean().default(false), + transitiveMixedData: v4.z.boolean().default(false), +}); +const EnvironmentConfigSchema = v4.z.object({ + customHooks: v4.z.map(v4.z.string(), HookSchema).default(new Map()), + moduleTypeProvider: v4.z.nullable(v4.z.any()).default(null), + customMacros: v4.z.nullable(v4.z.array(MacroSchema)).default(null), + enableResetCacheOnSourceFileChanges: v4.z.nullable(v4.z.boolean()).default(null), + enablePreserveExistingMemoizationGuarantees: v4.z.boolean().default(true), + validatePreserveExistingMemoizationGuarantees: v4.z.boolean().default(true), + validateExhaustiveMemoizationDependencies: v4.z.boolean().default(true), + validateExhaustiveEffectDependencies: v4.z + .enum(['off', 'all', 'missing-only', 'extra-only']) + .default('off'), + enableForest: v4.z.boolean().default(false), + flowTypeProvider: v4.z.nullable(v4.z.any()).default(null), + enableOptionalDependencies: v4.z.boolean().default(true), + enableNameAnonymousFunctions: v4.z.boolean().default(false), + validateHooksUsage: v4.z.boolean().default(true), + validateRefAccessDuringRender: v4.z.boolean().default(true), + validateNoSetStateInRender: v4.z.boolean().default(true), + enableUseKeyedState: v4.z.boolean().default(false), + validateNoSetStateInEffects: v4.z.boolean().default(false), + validateNoDerivedComputationsInEffects: v4.z.boolean().default(false), + validateNoDerivedComputationsInEffects_exp: v4.z.boolean().default(false), + validateNoJSXInTryStatements: v4.z.boolean().default(false), + validateStaticComponents: v4.z.boolean().default(false), + validateNoCapitalizedCalls: v4.z.nullable(v4.z.array(v4.z.string())).default(null), + validateBlocklistedImports: v4.z.nullable(v4.z.array(v4.z.string())).default(null), + validateSourceLocations: v4.z.boolean().default(false), + validateNoImpureFunctionsInRender: v4.z.boolean().default(false), + validateNoFreezingKnownMutableFunctions: v4.z.boolean().default(false), + enableAssumeHooksFollowRulesOfReact: v4.z.boolean().default(true), + enableTransitivelyFreezeFunctionExpressions: v4.z.boolean().default(true), + enableEmitHookGuards: ExternalFunctionSchema.nullable().default(null), + enableFunctionOutlining: v4.z.boolean().default(true), + enableJsxOutlining: v4.z.boolean().default(false), + enableEmitInstrumentForget: InstrumentationSchema.nullable().default(null), + assertValidMutableRanges: v4.z.boolean().default(false), + throwUnknownException__testonly: v4.z.boolean().default(false), + enableCustomTypeDefinitionForReanimated: v4.z.boolean().default(false), + enableTreatRefLikeIdentifiersAsRefs: v4.z.boolean().default(true), + enableTreatSetIdentifiersAsStateSetters: v4.z.boolean().default(false), + validateNoVoidUseMemo: v4.z.boolean().default(true), + enableAllowSetStateFromRefsInEffects: v4.z.boolean().default(true), + enableVerboseNoSetStateInEffect: v4.z.boolean().default(false), +}); +class Environment { + constructor(scope, fnType, outputMode, config, contextIdentifiers, parentFunction, logger, filename, code, programContext) { + _Environment_instances.add(this); + _Environment_globals.set(this, void 0); + _Environment_shapes.set(this, void 0); + _Environment_moduleTypes.set(this, new Map()); + _Environment_nextIdentifer.set(this, 0); + _Environment_nextBlock.set(this, 0); + _Environment_nextScope.set(this, 0); + _Environment_scope.set(this, void 0); + _Environment_outlinedFunctions.set(this, []); + _Environment_contextIdentifiers.set(this, void 0); + _Environment_hoistedIdentifiers.set(this, void 0); + _Environment_flowTypeEnvironment.set(this, void 0); + _Environment_errors.set(this, new CompilerError()); + __classPrivateFieldSet(this, _Environment_scope, scope, "f"); + this.fnType = fnType; + this.outputMode = outputMode; + this.config = config; + this.filename = filename; + this.code = code; + this.logger = logger; + this.programContext = programContext; + __classPrivateFieldSet(this, _Environment_shapes, new Map(DEFAULT_SHAPES), "f"); + __classPrivateFieldSet(this, _Environment_globals, new Map(DEFAULT_GLOBALS), "f"); + for (const [hookName, hook] of this.config.customHooks) { + CompilerError.invariant(!__classPrivateFieldGet(this, _Environment_globals, "f").has(hookName), { + reason: `[Globals] Found existing definition in global registry for custom hook ${hookName}`, + loc: GeneratedSource, + }); + __classPrivateFieldGet(this, _Environment_globals, "f").set(hookName, addHook(__classPrivateFieldGet(this, _Environment_shapes, "f"), { + positionalParams: [], + restParam: hook.effectKind, + returnType: hook.transitiveMixedData + ? { kind: 'Object', shapeId: BuiltInMixedReadonlyId } + : { kind: 'Poly' }, + returnValueKind: hook.valueKind, + calleeEffect: Effect.Read, + hookKind: 'Custom', + noAlias: hook.noAlias, + })); + } + if (config.enableCustomTypeDefinitionForReanimated) { + const reanimatedModuleType = getReanimatedModuleType(__classPrivateFieldGet(this, _Environment_shapes, "f")); + __classPrivateFieldGet(this, _Environment_moduleTypes, "f").set(REANIMATED_MODULE_NAME, reanimatedModuleType); + } + this.parentFunction = parentFunction; + __classPrivateFieldSet(this, _Environment_contextIdentifiers, contextIdentifiers, "f"); + __classPrivateFieldSet(this, _Environment_hoistedIdentifiers, new Set(), "f"); + if (config.flowTypeProvider != null) { + __classPrivateFieldSet(this, _Environment_flowTypeEnvironment, new FlowTypeEnv(), "f"); + CompilerError.invariant(code != null, { + reason: 'Expected Environment to be initialized with source code when a Flow type provider is specified', + loc: GeneratedSource, + }); + __classPrivateFieldGet(this, _Environment_flowTypeEnvironment, "f").init(this, code); + } + else { + __classPrivateFieldSet(this, _Environment_flowTypeEnvironment, null, "f"); + } + } + get typeContext() { + CompilerError.invariant(__classPrivateFieldGet(this, _Environment_flowTypeEnvironment, "f") != null, { + reason: 'Flow type environment not initialized', + loc: GeneratedSource, + }); + return __classPrivateFieldGet(this, _Environment_flowTypeEnvironment, "f"); + } + get enableDropManualMemoization() { + switch (this.outputMode) { + case 'lint': { + return true; + } + case 'client': + case 'ssr': { + return true; + } + default: { + assertExhaustive$1(this.outputMode, `Unexpected output mode '${this.outputMode}'`); + } + } + } + get enableMemoization() { + switch (this.outputMode) { + case 'client': + case 'lint': { + return true; + } + case 'ssr': { + return false; + } + default: { + assertExhaustive$1(this.outputMode, `Unexpected output mode '${this.outputMode}'`); + } + } + } + get enableValidations() { + switch (this.outputMode) { + case 'client': + case 'lint': + case 'ssr': { + return true; + } + default: { + assertExhaustive$1(this.outputMode, `Unexpected output mode '${this.outputMode}'`); + } + } + } + get nextIdentifierId() { + var _a, _b; + return makeIdentifierId((__classPrivateFieldSet(this, _Environment_nextIdentifer, (_b = __classPrivateFieldGet(this, _Environment_nextIdentifer, "f"), _a = _b++, _b), "f"), _a)); + } + get nextBlockId() { + var _a, _b; + return makeBlockId((__classPrivateFieldSet(this, _Environment_nextBlock, (_b = __classPrivateFieldGet(this, _Environment_nextBlock, "f"), _a = _b++, _b), "f"), _a)); + } + get nextScopeId() { + var _a, _b; + return makeScopeId((__classPrivateFieldSet(this, _Environment_nextScope, (_b = __classPrivateFieldGet(this, _Environment_nextScope, "f"), _a = _b++, _b), "f"), _a)); + } + get scope() { + return __classPrivateFieldGet(this, _Environment_scope, "f"); + } + logErrors(errors) { + if (errors.isOk() || this.logger == null) { + return; + } + for (const error of errors.unwrapErr().details) { + this.logger.logEvent(this.filename, { + kind: 'CompileError', + detail: error, + fnLoc: null, + }); + } + } + recordError(error) { + if (error.category === ErrorCategory.Invariant) { + const compilerError = new CompilerError(); + if (error instanceof CompilerDiagnostic) { + compilerError.pushDiagnostic(error); + } + else { + compilerError.pushErrorDetail(error); + } + throw compilerError; + } + if (error instanceof CompilerDiagnostic) { + __classPrivateFieldGet(this, _Environment_errors, "f").pushDiagnostic(error); + } + else { + __classPrivateFieldGet(this, _Environment_errors, "f").pushErrorDetail(error); + } + } + recordErrors(error) { + for (const detail of error.details) { + this.recordError(detail); + } + } + hasErrors() { + return __classPrivateFieldGet(this, _Environment_errors, "f").hasAnyErrors(); + } + aggregateErrors() { + return __classPrivateFieldGet(this, _Environment_errors, "f"); + } + isContextIdentifier(node) { + return __classPrivateFieldGet(this, _Environment_contextIdentifiers, "f").has(node); + } + isHoistedIdentifier(node) { + return __classPrivateFieldGet(this, _Environment_hoistedIdentifiers, "f").has(node); + } + generateGloballyUniqueIdentifierName(name) { + const identifierNode = __classPrivateFieldGet(this, _Environment_scope, "f").generateUidIdentifier(name !== null && name !== void 0 ? name : undefined); + return makeIdentifierName(identifierNode.name); + } + outlineFunction(fn, type) { + __classPrivateFieldGet(this, _Environment_outlinedFunctions, "f").push({ fn, type }); + } + getOutlinedFunctions() { + return __classPrivateFieldGet(this, _Environment_outlinedFunctions, "f"); + } + getGlobalDeclaration(binding, loc) { + var _a, _b, _c; + switch (binding.kind) { + case 'ModuleLocal': { + return isHookName$2(binding.name) ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) : null; + } + case 'Global': { + return ((_a = __classPrivateFieldGet(this, _Environment_globals, "f").get(binding.name)) !== null && _a !== void 0 ? _a : (isHookName$2(binding.name) ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) : null)); + } + case 'ImportSpecifier': { + if (__classPrivateFieldGet(this, _Environment_instances, "m", _Environment_isKnownReactModule).call(this, binding.module)) { + return ((_b = __classPrivateFieldGet(this, _Environment_globals, "f").get(binding.imported)) !== null && _b !== void 0 ? _b : (isHookName$2(binding.imported) || isHookName$2(binding.name) + ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) + : null)); + } + else { + const moduleType = __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_resolveModuleType).call(this, binding.module, loc); + if (moduleType !== null) { + const importedType = this.getPropertyType(moduleType, binding.imported); + if (importedType != null) { + const expectHook = isHookName$2(binding.imported); + const isHook = getHookKindForType(this, importedType) != null; + if (expectHook !== isHook) { + CompilerError.throwInvalidConfig({ + reason: `Invalid type configuration for module`, + description: `Expected type for \`import {${binding.imported}} from '${binding.module}'\` ${expectHook ? 'to be a hook' : 'not to be a hook'} based on the exported name`, + loc, + }); + } + return importedType; + } + } + return isHookName$2(binding.imported) || isHookName$2(binding.name) + ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) + : null; + } + } + case 'ImportDefault': + case 'ImportNamespace': { + if (__classPrivateFieldGet(this, _Environment_instances, "m", _Environment_isKnownReactModule).call(this, binding.module)) { + return ((_c = __classPrivateFieldGet(this, _Environment_globals, "f").get(binding.name)) !== null && _c !== void 0 ? _c : (isHookName$2(binding.name) ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) : null)); + } + else { + const moduleType = __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_resolveModuleType).call(this, binding.module, loc); + if (moduleType !== null) { + let importedType = null; + if (binding.kind === 'ImportDefault') { + const defaultType = this.getPropertyType(moduleType, 'default'); + if (defaultType !== null) { + importedType = defaultType; + } + } + else { + importedType = moduleType; + } + if (importedType !== null) { + const expectHook = isHookName$2(binding.module); + const isHook = getHookKindForType(this, importedType) != null; + if (expectHook !== isHook) { + CompilerError.throwInvalidConfig({ + reason: `Invalid type configuration for module`, + description: `Expected type for \`import ... from '${binding.module}'\` ${expectHook ? 'to be a hook' : 'not to be a hook'} based on the module name`, + loc, + }); + } + return importedType; + } + } + return isHookName$2(binding.name) ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) : null; + } + } + } + } + getFallthroughPropertyType(receiver, _property) { + var _a; + let shapeId = null; + if (receiver.kind === 'Object' || receiver.kind === 'Function') { + shapeId = receiver.shapeId; + } + if (shapeId !== null) { + const shape = __classPrivateFieldGet(this, _Environment_shapes, "f").get(shapeId); + CompilerError.invariant(shape !== undefined, { + reason: `[HIR] Forget internal error: cannot resolve shape ${shapeId}`, + loc: GeneratedSource, + }); + return (_a = shape.properties.get('*')) !== null && _a !== void 0 ? _a : null; + } + return null; + } + getPropertyType(receiver, property) { + var _a, _b, _c; + let shapeId = null; + if (receiver.kind === 'Object' || receiver.kind === 'Function') { + shapeId = receiver.shapeId; + } + if (shapeId !== null) { + const shape = __classPrivateFieldGet(this, _Environment_shapes, "f").get(shapeId); + CompilerError.invariant(shape !== undefined, { + reason: `[HIR] Forget internal error: cannot resolve shape ${shapeId}`, + loc: GeneratedSource, + }); + if (typeof property === 'string') { + return ((_b = (_a = shape.properties.get(property)) !== null && _a !== void 0 ? _a : shape.properties.get('*')) !== null && _b !== void 0 ? _b : (isHookName$2(property) ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) : null)); + } + else { + return (_c = shape.properties.get('*')) !== null && _c !== void 0 ? _c : null; + } + } + else if (typeof property === 'string' && isHookName$2(property)) { + return __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this); + } + return null; + } + getFunctionSignature(type) { + const { shapeId } = type; + if (shapeId !== null) { + const shape = __classPrivateFieldGet(this, _Environment_shapes, "f").get(shapeId); + CompilerError.invariant(shape !== undefined, { + reason: `[HIR] Forget internal error: cannot resolve shape ${shapeId}`, + loc: GeneratedSource, + }); + return shape.functionType; + } + return null; + } + addHoistedIdentifier(node) { + __classPrivateFieldGet(this, _Environment_contextIdentifiers, "f").add(node); + __classPrivateFieldGet(this, _Environment_hoistedIdentifiers, "f").add(node); + } +} +_Environment_globals = new WeakMap(), _Environment_shapes = new WeakMap(), _Environment_moduleTypes = new WeakMap(), _Environment_nextIdentifer = new WeakMap(), _Environment_nextBlock = new WeakMap(), _Environment_nextScope = new WeakMap(), _Environment_scope = new WeakMap(), _Environment_outlinedFunctions = new WeakMap(), _Environment_contextIdentifiers = new WeakMap(), _Environment_hoistedIdentifiers = new WeakMap(), _Environment_flowTypeEnvironment = new WeakMap(), _Environment_errors = new WeakMap(), _Environment_instances = new WeakSet(), _Environment_resolveModuleType = function _Environment_resolveModuleType(moduleName, loc) { + var _a; + let moduleType = __classPrivateFieldGet(this, _Environment_moduleTypes, "f").get(moduleName); + if (moduleType === undefined) { + const moduleTypeProvider = (_a = this.config.moduleTypeProvider) !== null && _a !== void 0 ? _a : defaultModuleTypeProvider; + if (moduleTypeProvider == null) { + return null; + } + if (typeof moduleTypeProvider !== 'function') { + CompilerError.throwInvalidConfig({ + reason: `Expected a function for \`moduleTypeProvider\``, + loc, + }); + } + const unparsedModuleConfig = moduleTypeProvider(moduleName); + if (unparsedModuleConfig != null) { + const parsedModuleConfig = TypeSchema.safeParse(unparsedModuleConfig); + if (!parsedModuleConfig.success) { + CompilerError.throwInvalidConfig({ + reason: `Could not parse module type, the configured \`moduleTypeProvider\` function returned an invalid module description`, + description: parsedModuleConfig.error.toString(), + loc, + }); + } + const moduleConfig = parsedModuleConfig.data; + moduleType = installTypeConfig(__classPrivateFieldGet(this, _Environment_globals, "f"), __classPrivateFieldGet(this, _Environment_shapes, "f"), moduleConfig, moduleName, loc); + } + else { + moduleType = null; + } + __classPrivateFieldGet(this, _Environment_moduleTypes, "f").set(moduleName, moduleType); + } + return moduleType; +}, _Environment_isKnownReactModule = function _Environment_isKnownReactModule(moduleName) { + return (moduleName.toLowerCase() === 'react' || + moduleName.toLowerCase() === 'react-dom'); +}, _Environment_getCustomHookType = function _Environment_getCustomHookType() { + if (this.config.enableAssumeHooksFollowRulesOfReact) { + return DefaultNonmutatingHook; + } + else { + return DefaultMutatingHook; + } +}; +Environment.knownReactModules = ['react', 'react-dom']; +const REANIMATED_MODULE_NAME = 'react-native-reanimated'; +function isHookName$2(name) { + return /^use[A-Z0-9]/.test(name); +} +function parseEnvironmentConfig(partialConfig) { + const config = EnvironmentConfigSchema.safeParse(partialConfig); + if (config.success) { + return Ok(config.data); + } + else { + return Err(config.error); + } +} +function validateEnvironmentConfig(partialConfig) { + const config = EnvironmentConfigSchema.safeParse(partialConfig); + if (config.success) { + return config.data; + } + CompilerError.throwInvalidConfig({ + reason: 'Could not validate environment config. Update React Compiler config to fix the error', + description: `${v4$1.fromZodError(config.error)}`, + loc: null, + suggestions: null, + }); +} +function tryParseExternalFunction(maybeExternalFunction) { + const externalFunction = ExternalFunctionSchema.safeParse(maybeExternalFunction); + if (externalFunction.success) { + return externalFunction.data; + } + CompilerError.throwInvalidConfig({ + reason: 'Could not parse external function. Update React Compiler config to fix the error', + description: `${v4$1.fromZodError(externalFunction.error)}`, + loc: null, + suggestions: null, + }); +} + +var _MergedBlocks_map; +function mergeConsecutiveBlocks(fn) { + const merged = new MergedBlocks(); + const fallthroughBlocks = new Set(); + for (const [, block] of fn.body.blocks) { + const fallthrough = terminalFallthrough(block.terminal); + if (fallthrough !== null) { + fallthroughBlocks.add(fallthrough); + } + for (const instr of block.instructions) { + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + mergeConsecutiveBlocks(instr.value.loweredFunc.func); + } + } + if (block.preds.size !== 1 || + block.kind !== 'block' || + fallthroughBlocks.has(block.id)) { + continue; + } + const originalPredecessorId = Array.from(block.preds)[0]; + const predecessorId = merged.get(originalPredecessorId); + const predecessor = fn.body.blocks.get(predecessorId); + CompilerError.invariant(predecessor !== undefined, { + reason: `Expected predecessor ${predecessorId} to exist`, + loc: GeneratedSource, + }); + if (predecessor.terminal.kind !== 'goto' || predecessor.kind !== 'block') { + continue; + } + for (const phi of block.phis) { + CompilerError.invariant(phi.operands.size === 1, { + reason: `Found a block with a single predecessor but where a phi has multiple (${phi.operands.size}) operands`, + loc: GeneratedSource, + }); + const operand = Array.from(phi.operands.values())[0]; + const lvalue = { + kind: 'Identifier', + identifier: phi.place.identifier, + effect: Effect.ConditionallyMutate, + reactive: false, + loc: GeneratedSource, + }; + const instr = { + id: predecessor.terminal.id, + lvalue: Object.assign({}, lvalue), + value: { + kind: 'LoadLocal', + place: Object.assign({}, operand), + loc: GeneratedSource, + }, + effects: [{ kind: 'Alias', from: Object.assign({}, operand), into: Object.assign({}, lvalue) }], + loc: GeneratedSource, + }; + predecessor.instructions.push(instr); + } + predecessor.instructions.push(...block.instructions); + predecessor.terminal = block.terminal; + merged.merge(block.id, predecessorId); + fn.body.blocks.delete(block.id); + } + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + for (const [predecessorId, operand] of phi.operands) { + const mapped = merged.get(predecessorId); + if (mapped !== predecessorId) { + phi.operands.delete(predecessorId); + phi.operands.set(mapped, operand); + } + } + } + } + markPredecessors(fn.body); + for (const [, { terminal }] of fn.body.blocks) { + if (terminalHasFallthrough(terminal)) { + terminal.fallthrough = merged.get(terminal.fallthrough); + } + } +} +class MergedBlocks { + constructor() { + _MergedBlocks_map.set(this, new Map()); + } + merge(block, into) { + const target = this.get(into); + __classPrivateFieldGet(this, _MergedBlocks_map, "f").set(block, target); + } + get(block) { + var _a; + let current = block; + while (__classPrivateFieldGet(this, _MergedBlocks_map, "f").has(current)) { + current = (_a = __classPrivateFieldGet(this, _MergedBlocks_map, "f").get(current)) !== null && _a !== void 0 ? _a : current; + } + return current; + } +} +_MergedBlocks_map = new WeakMap(); + +var _DisjointSet_entries; +class DisjointSet { + constructor() { + _DisjointSet_entries.set(this, new Map()); + } + union(items) { + const first = items.shift(); + CompilerError.invariant(first != null, { + reason: 'Expected set to be non-empty', + loc: GeneratedSource, + }); + let root = this.find(first); + if (root == null) { + root = first; + __classPrivateFieldGet(this, _DisjointSet_entries, "f").set(first, first); + } + for (const item of items) { + let itemParent = __classPrivateFieldGet(this, _DisjointSet_entries, "f").get(item); + if (itemParent == null) { + __classPrivateFieldGet(this, _DisjointSet_entries, "f").set(item, root); + continue; + } + else if (itemParent === root) { + continue; + } + else { + let current = item; + while (itemParent !== root) { + __classPrivateFieldGet(this, _DisjointSet_entries, "f").set(current, root); + current = itemParent; + itemParent = __classPrivateFieldGet(this, _DisjointSet_entries, "f").get(current); + } + } + } + } + find(item) { + if (!__classPrivateFieldGet(this, _DisjointSet_entries, "f").has(item)) { + return null; + } + const parent = __classPrivateFieldGet(this, _DisjointSet_entries, "f").get(item); + if (parent === item) { + return item; + } + const root = this.find(parent); + __classPrivateFieldGet(this, _DisjointSet_entries, "f").set(item, root); + return root; + } + has(item) { + return __classPrivateFieldGet(this, _DisjointSet_entries, "f").has(item); + } + canonicalize() { + const entries = new Map(); + for (const item of __classPrivateFieldGet(this, _DisjointSet_entries, "f").keys()) { + const root = this.find(item); + entries.set(item, root); + } + return entries; + } + forEach(fn) { + for (const item of __classPrivateFieldGet(this, _DisjointSet_entries, "f").keys()) { + const group = this.find(item); + fn(item, group); + } + } + buildSets() { + const ids = new Map(); + const sets = new Map(); + this.forEach((identifier, groupIdentifier) => { + let id = ids.get(groupIdentifier); + if (id == null) { + id = ids.size; + ids.set(groupIdentifier, id); + } + let set = sets.get(id); + if (set === undefined) { + set = new Set(); + sets.set(id, set); + } + set.add(identifier); + }); + return [...sets.values()]; + } + get size() { + return __classPrivateFieldGet(this, _DisjointSet_entries, "f").size; + } +} +_DisjointSet_entries = new WeakMap(); + +function inferReactiveScopeVariables(fn) { + var _a, _b; + const scopeIdentifiers = findDisjointMutableValues(fn); + const scopes = new Map(); + scopeIdentifiers.forEach((identifier, groupIdentifier) => { + let scope = scopes.get(groupIdentifier); + if (scope === undefined) { + scope = { + id: fn.env.nextScopeId, + range: identifier.mutableRange, + dependencies: new Set(), + declarations: new Map(), + reassignments: new Set(), + earlyReturnValue: null, + merged: new Set(), + loc: identifier.loc, + }; + scopes.set(groupIdentifier, scope); + } + else { + if (scope.range.start === 0) { + scope.range.start = identifier.mutableRange.start; + } + else if (identifier.mutableRange.start !== 0) { + scope.range.start = makeInstructionId(Math.min(scope.range.start, identifier.mutableRange.start)); + } + scope.range.end = makeInstructionId(Math.max(scope.range.end, identifier.mutableRange.end)); + scope.loc = mergeLocation(scope.loc, identifier.loc); + } + identifier.scope = scope; + identifier.mutableRange = scope.range; + }); + let maxInstruction = 0; + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + maxInstruction = makeInstructionId(Math.max(maxInstruction, instr.id)); + } + maxInstruction = makeInstructionId(Math.max(maxInstruction, block.terminal.id)); + } + for (const [, scope] of scopes) { + if (scope.range.start === 0 || + scope.range.end === 0 || + maxInstruction === 0 || + scope.range.end > maxInstruction + 1) { + (_b = (_a = fn.env.logger) === null || _a === void 0 ? void 0 : _a.debugLogIRs) === null || _b === void 0 ? void 0 : _b.call(_a, { + kind: 'hir', + name: 'InferReactiveScopeVariables (invalid scope)', + value: fn, + }); + CompilerError.invariant(false, { + reason: `Invalid mutable range for scope`, + description: `Scope @${scope.id} has range [${scope.range.start}:${scope.range.end}] but the valid range is [1:${maxInstruction + 1}]`, + loc: GeneratedSource, + }); + } + } +} +function mergeLocation(l, r) { + if (l === GeneratedSource) { + return r; + } + else if (r === GeneratedSource) { + return l; + } + else { + return { + filename: l.filename, + identifierName: l.identifierName, + start: { + index: Math.min(l.start.index, r.start.index), + line: Math.min(l.start.line, r.start.line), + column: Math.min(l.start.column, r.start.column), + }, + end: { + index: Math.max(l.end.index, r.end.index), + line: Math.max(l.end.line, r.end.line), + column: Math.max(l.end.column, r.end.column), + }, + }; + } +} +function isMutable(instr, place) { + return inRange(instr, place.identifier.mutableRange); +} +function inRange({ id }, range) { + return id >= range.start && id < range.end; +} +function mayAllocate(_env, instruction) { + const { value } = instruction; + switch (value.kind) { + case 'Destructure': { + return doesPatternContainSpreadElement(value.lvalue.pattern); + } + case 'PostfixUpdate': + case 'PrefixUpdate': + case 'Await': + case 'DeclareLocal': + case 'DeclareContext': + case 'StoreLocal': + case 'LoadGlobal': + case 'MetaProperty': + case 'TypeCastExpression': + case 'LoadLocal': + case 'LoadContext': + case 'StoreContext': + case 'PropertyDelete': + case 'ComputedLoad': + case 'ComputedDelete': + case 'JSXText': + case 'TemplateLiteral': + case 'Primitive': + case 'GetIterator': + case 'IteratorNext': + case 'NextPropertyOf': + case 'Debugger': + case 'StartMemoize': + case 'FinishMemoize': + case 'UnaryExpression': + case 'BinaryExpression': + case 'PropertyLoad': + case 'StoreGlobal': { + return false; + } + case 'TaggedTemplateExpression': + case 'CallExpression': + case 'MethodCall': { + return instruction.lvalue.identifier.type.kind !== 'Primitive'; + } + case 'RegExpLiteral': + case 'PropertyStore': + case 'ComputedStore': + case 'ArrayExpression': + case 'JsxExpression': + case 'JsxFragment': + case 'NewExpression': + case 'ObjectExpression': + case 'UnsupportedNode': + case 'ObjectMethod': + case 'FunctionExpression': { + return true; + } + default: { + assertExhaustive$1(value, `Unexpected value kind \`${value.kind}\``); + } + } +} +function findDisjointMutableValues(fn) { + var _a, _b; + const scopeIdentifiers = new DisjointSet(); + const declarations = new Map(); + function declareIdentifier(lvalue) { + if (!declarations.has(lvalue.identifier.declarationId)) { + declarations.set(lvalue.identifier.declarationId, lvalue.identifier); + } + } + for (const [_, block] of fn.body.blocks) { + for (const phi of block.phis) { + if (phi.place.identifier.mutableRange.start + 1 !== + phi.place.identifier.mutableRange.end && + phi.place.identifier.mutableRange.end > + ((_b = (_a = block.instructions.at(0)) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : block.terminal.id)) { + const operands = [phi.place.identifier]; + const declaration = declarations.get(phi.place.identifier.declarationId); + if (declaration !== undefined) { + operands.push(declaration); + } + for (const [_, phiId] of phi.operands) { + operands.push(phiId.identifier); + } + scopeIdentifiers.union(operands); + } + else if (fn.env.config.enableForest) { + for (const [, phiId] of phi.operands) { + scopeIdentifiers.union([phi.place.identifier, phiId.identifier]); + } + } + } + for (const instr of block.instructions) { + const operands = []; + const range = instr.lvalue.identifier.mutableRange; + if (range.end > range.start + 1 || mayAllocate(fn.env, instr)) { + operands.push(instr.lvalue.identifier); + } + if (instr.value.kind === 'DeclareLocal' || + instr.value.kind === 'DeclareContext') { + declareIdentifier(instr.value.lvalue.place); + } + else if (instr.value.kind === 'StoreLocal' || + instr.value.kind === 'StoreContext') { + declareIdentifier(instr.value.lvalue.place); + if (instr.value.lvalue.place.identifier.mutableRange.end > + instr.value.lvalue.place.identifier.mutableRange.start + 1) { + operands.push(instr.value.lvalue.place.identifier); + } + if (isMutable(instr, instr.value.value) && + instr.value.value.identifier.mutableRange.start > 0) { + operands.push(instr.value.value.identifier); + } + } + else if (instr.value.kind === 'Destructure') { + for (const place of eachPatternOperand(instr.value.lvalue.pattern)) { + declareIdentifier(place); + if (place.identifier.mutableRange.end > + place.identifier.mutableRange.start + 1) { + operands.push(place.identifier); + } + } + if (isMutable(instr, instr.value.value) && + instr.value.value.identifier.mutableRange.start > 0) { + operands.push(instr.value.value.identifier); + } + } + else if (instr.value.kind === 'MethodCall') { + for (const operand of eachInstructionOperand(instr)) { + if (isMutable(instr, operand) && + operand.identifier.mutableRange.start > 0) { + operands.push(operand.identifier); + } + } + operands.push(instr.value.property.identifier); + } + else { + for (const operand of eachInstructionOperand(instr)) { + if (isMutable(instr, operand) && + operand.identifier.mutableRange.start > 0) { + operands.push(operand.identifier); + } + } + } + if (operands.length !== 0) { + scopeIdentifiers.union(operands); + } + } + } + return scopeIdentifiers; +} + +function mergeOverlappingReactiveScopesHIR(fn) { + const scopesInfo = collectScopeInfo(fn); + const joinedScopes = getOverlappingReactiveScopes(fn, scopesInfo); + joinedScopes.forEach((scope, groupScope) => { + if (scope !== groupScope) { + groupScope.range.start = makeInstructionId(Math.min(groupScope.range.start, scope.range.start)); + groupScope.range.end = makeInstructionId(Math.max(groupScope.range.end, scope.range.end)); + } + }); + for (const [place, originalScope] of scopesInfo.placeScopes) { + const nextScope = joinedScopes.find(originalScope); + if (nextScope !== null && nextScope !== originalScope) { + place.identifier.scope = nextScope; + } + } +} +function collectScopeInfo(fn) { + const scopeStarts = new Map(); + const scopeEnds = new Map(); + const placeScopes = new Map(); + function collectPlaceScope(place) { + const scope = place.identifier.scope; + if (scope != null) { + placeScopes.set(place, scope); + if (scope.range.start !== scope.range.end) { + getOrInsertDefault(scopeStarts, scope.range.start, new Set()).add(scope); + getOrInsertDefault(scopeEnds, scope.range.end, new Set()).add(scope); + } + } + } + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + for (const operand of eachInstructionLValue(instr)) { + collectPlaceScope(operand); + } + for (const operand of eachInstructionOperand(instr)) { + collectPlaceScope(operand); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + collectPlaceScope(operand); + } + } + return { + scopeStarts: [...scopeStarts.entries()] + .map(([id, scopes]) => ({ id, scopes })) + .sort((a, b) => b.id - a.id), + scopeEnds: [...scopeEnds.entries()] + .map(([id, scopes]) => ({ id, scopes })) + .sort((a, b) => b.id - a.id), + placeScopes, + }; +} +function visitInstructionId(id, { scopeEnds, scopeStarts }, { activeScopes, joined }) { + const scopeEndTop = scopeEnds.at(-1); + if (scopeEndTop != null && scopeEndTop.id <= id) { + scopeEnds.pop(); + const scopesSortedStartDescending = [...scopeEndTop.scopes].sort((a, b) => b.range.start - a.range.start); + for (const scope of scopesSortedStartDescending) { + const idx = activeScopes.indexOf(scope); + if (idx !== -1) { + if (idx !== activeScopes.length - 1) { + joined.union([scope, ...activeScopes.slice(idx + 1)]); + } + activeScopes.splice(idx, 1); + } + } + } + const scopeStartTop = scopeStarts.at(-1); + if (scopeStartTop != null && scopeStartTop.id <= id) { + scopeStarts.pop(); + const scopesSortedEndDescending = [...scopeStartTop.scopes].sort((a, b) => b.range.end - a.range.end); + activeScopes.push(...scopesSortedEndDescending); + for (let i = 1; i < scopesSortedEndDescending.length; i++) { + const prev = scopesSortedEndDescending[i - 1]; + const curr = scopesSortedEndDescending[i]; + if (prev.range.end === curr.range.end) { + joined.union([prev, curr]); + } + } + } +} +function visitPlace(id, place, { activeScopes, joined }) { + const placeScope = getPlaceScope(id, place); + if (placeScope != null && isMutable({ id }, place)) { + const placeScopeIdx = activeScopes.indexOf(placeScope); + if (placeScopeIdx !== -1 && placeScopeIdx !== activeScopes.length - 1) { + joined.union([placeScope, ...activeScopes.slice(placeScopeIdx + 1)]); + } + } +} +function getOverlappingReactiveScopes(fn, context) { + const state = { + joined: new DisjointSet(), + activeScopes: [], + }; + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + visitInstructionId(instr.id, context, state); + for (const place of eachInstructionOperand(instr)) { + if ((instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') && + place.identifier.type.kind === 'Primitive') { + continue; + } + visitPlace(instr.id, place, state); + } + for (const place of eachInstructionLValue(instr)) { + visitPlace(instr.id, place, state); + } + } + visitInstructionId(block.terminal.id, context, state); + for (const place of eachTerminalOperand(block.terminal)) { + visitPlace(block.terminal.id, place, state); + } + } + return state.joined; +} + +function pruneUnusedLabelsHIR(fn) { + var _a; + const merged = []; + const rewrites = new Map(); + for (const [blockId, block] of fn.body.blocks) { + const terminal = block.terminal; + if (terminal.kind === 'label') { + const { block: nextId, fallthrough: fallthroughId } = terminal; + const next = fn.body.blocks.get(nextId); + const fallthrough = fn.body.blocks.get(fallthroughId); + if (next.terminal.kind === 'goto' && + next.terminal.variant === GotoVariant.Break && + next.terminal.block === fallthroughId) { + if (next.kind === 'block' && fallthrough.kind === 'block') { + merged.push({ + label: blockId, + next: nextId, + fallthrough: fallthroughId, + }); + } + } + } + } + for (const { label: originalLabelId, next: nextId, fallthrough: fallthroughId, } of merged) { + const labelId = (_a = rewrites.get(originalLabelId)) !== null && _a !== void 0 ? _a : originalLabelId; + const label = fn.body.blocks.get(labelId); + const next = fn.body.blocks.get(nextId); + const fallthrough = fn.body.blocks.get(fallthroughId); + CompilerError.invariant(next.phis.size === 0 && fallthrough.phis.size === 0, { + reason: 'Unexpected phis when merging label blocks', + loc: label.terminal.loc, + }); + CompilerError.invariant(next.preds.size === 1 && + fallthrough.preds.size === 1 && + next.preds.has(originalLabelId) && + fallthrough.preds.has(nextId), { + reason: 'Unexpected block predecessors when merging label blocks', + loc: label.terminal.loc, + }); + label.instructions.push(...next.instructions, ...fallthrough.instructions); + label.terminal = fallthrough.terminal; + fn.body.blocks.delete(nextId); + fn.body.blocks.delete(fallthroughId); + rewrites.set(fallthroughId, labelId); + } + for (const [_, block] of fn.body.blocks) { + for (const pred of block.preds) { + const rewritten = rewrites.get(pred); + if (rewritten != null) { + block.preds.delete(pred); + block.preds.add(rewritten); + } + } + } +} + +function insertAdditionalFunctionDeclaration(fnPath, compiled, programContext, gatingFunctionIdentifierName) { + var _a, _b; + const originalFnName = fnPath.node.id; + const originalFnParams = fnPath.node.params; + const compiledParams = fnPath.node.params; + CompilerError.invariant(originalFnName != null && compiled.id != null, { + reason: 'Expected function declarations that are referenced elsewhere to have a named identifier', + loc: (_a = fnPath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + CompilerError.invariant(originalFnParams.length === compiledParams.length, { + reason: 'Expected React Compiler optimized function declarations to have the same number of parameters as source', + loc: (_b = fnPath.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + const gatingCondition = libExports$1.identifier(programContext.newUid(`${gatingFunctionIdentifierName}_result`)); + const unoptimizedFnName = libExports$1.identifier(programContext.newUid(`${originalFnName.name}_unoptimized`)); + const optimizedFnName = libExports$1.identifier(programContext.newUid(`${originalFnName.name}_optimized`)); + compiled.id.name = optimizedFnName.name; + fnPath.get('id').replaceInline(unoptimizedFnName); + const newParams = []; + const genNewArgs = []; + for (let i = 0; i < originalFnParams.length; i++) { + const argName = `arg${i}`; + if (originalFnParams[i].type === 'RestElement') { + newParams.push(libExports$1.restElement(libExports$1.identifier(argName))); + genNewArgs.push(() => libExports$1.spreadElement(libExports$1.identifier(argName))); + } + else { + newParams.push(libExports$1.identifier(argName)); + genNewArgs.push(() => libExports$1.identifier(argName)); + } + } + fnPath.insertAfter(libExports$1.functionDeclaration(originalFnName, newParams, libExports$1.blockStatement([ + libExports$1.ifStatement(gatingCondition, libExports$1.returnStatement(libExports$1.callExpression(compiled.id, genNewArgs.map(fn => fn()))), libExports$1.returnStatement(libExports$1.callExpression(unoptimizedFnName, genNewArgs.map(fn => fn())))), + ]))); + fnPath.insertBefore(libExports$1.variableDeclaration('const', [ + libExports$1.variableDeclarator(gatingCondition, libExports$1.callExpression(libExports$1.identifier(gatingFunctionIdentifierName), [])), + ])); + fnPath.insertBefore(compiled); +} +function insertGatedFunctionDeclaration(fnPath, compiled, programContext, gating, referencedBeforeDeclaration) { + var _a; + const gatingImportedName = programContext.addImportSpecifier(gating).name; + if (referencedBeforeDeclaration && fnPath.isFunctionDeclaration()) { + CompilerError.invariant(compiled.type === 'FunctionDeclaration', { + reason: 'Expected compiled node type to match input type', + description: `Got ${compiled.type} but expected FunctionDeclaration`, + loc: (_a = fnPath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + insertAdditionalFunctionDeclaration(fnPath, compiled, programContext, gatingImportedName); + } + else { + const gatingExpression = libExports$1.conditionalExpression(libExports$1.callExpression(libExports$1.identifier(gatingImportedName), []), buildFunctionExpression(compiled), buildFunctionExpression(fnPath.node)); + if (fnPath.parentPath.node.type !== 'ExportDefaultDeclaration' && + fnPath.node.type === 'FunctionDeclaration' && + fnPath.node.id != null) { + fnPath.replaceWith(libExports$1.variableDeclaration('const', [ + libExports$1.variableDeclarator(fnPath.node.id, gatingExpression), + ])); + } + else if (fnPath.parentPath.node.type === 'ExportDefaultDeclaration' && + fnPath.node.type !== 'ArrowFunctionExpression' && + fnPath.node.id != null) { + fnPath.insertAfter(libExports$1.exportDefaultDeclaration(libExports$1.identifier(fnPath.node.id.name))); + fnPath.parentPath.replaceWith(libExports$1.variableDeclaration('const', [ + libExports$1.variableDeclarator(libExports$1.identifier(fnPath.node.id.name), gatingExpression), + ])); + } + else { + fnPath.replaceWith(gatingExpression); + } + } +} +function buildFunctionExpression(node) { + var _a, _b; + if (node.type === 'ArrowFunctionExpression' || + node.type === 'FunctionExpression') { + return node; + } + else { + const fn = { + type: 'FunctionExpression', + async: node.async, + generator: node.generator, + loc: (_a = node.loc) !== null && _a !== void 0 ? _a : null, + id: (_b = node.id) !== null && _b !== void 0 ? _b : null, + params: node.params, + body: node.body, + }; + return fn; + } +} + +function isComponentDeclaration(node) { + return Object.prototype.hasOwnProperty.call(node, '__componentDeclaration'); +} + +function isHookDeclaration(node) { + return Object.prototype.hasOwnProperty.call(node, '__hookDeclaration'); +} + +const DEFAULT_IDENTIFIER_INFO = { + reassigned: false, + reassignedByInnerFn: false, + referencedByInnerFn: false, +}; +const withFunctionScope = { + enter: function (path, state) { + state.currentFn.push(path); + }, + exit: function (_, state) { + state.currentFn.pop(); + }, +}; +function findContextIdentifiers(func) { + const state = { + currentFn: [], + identifiers: new Map(), + }; + func.traverse({ + FunctionDeclaration: withFunctionScope, + FunctionExpression: withFunctionScope, + ArrowFunctionExpression: withFunctionScope, + ObjectMethod: withFunctionScope, + AssignmentExpression(path, state) { + var _a, _b; + const left = path.get('left'); + if (left.isLVal()) { + const currentFn = (_a = state.currentFn.at(-1)) !== null && _a !== void 0 ? _a : null; + handleAssignment(currentFn, state.identifiers, left); + } + else { + CompilerError.throwTodo({ + reason: `Unsupported syntax on the left side of an AssignmentExpression`, + description: `Expected an LVal, got: ${left.type}`, + loc: (_b = left.node.loc) !== null && _b !== void 0 ? _b : null, + }); + } + }, + UpdateExpression(path, state) { + var _a; + const argument = path.get('argument'); + const currentFn = (_a = state.currentFn.at(-1)) !== null && _a !== void 0 ? _a : null; + if (argument.isLVal()) { + handleAssignment(currentFn, state.identifiers, argument); + } + }, + Identifier(path, state) { + var _a; + const currentFn = (_a = state.currentFn.at(-1)) !== null && _a !== void 0 ? _a : null; + if (path.isReferencedIdentifier()) { + handleIdentifier(currentFn, state.identifiers, path); + } + }, + }, state); + const result = new Set(); + for (const [id, info] of state.identifiers.entries()) { + if (info.reassignedByInnerFn) { + result.add(id); + } + else if (info.reassigned && info.referencedByInnerFn) { + result.add(id); + } + } + return result; +} +function handleIdentifier(currentFn, identifiers, path) { + const name = path.node.name; + const binding = path.scope.getBinding(name); + if (binding == null) { + return; + } + const identifier = getOrInsertDefault(identifiers, binding.identifier, Object.assign({}, DEFAULT_IDENTIFIER_INFO)); + if (currentFn != null) { + const bindingAboveLambdaScope = currentFn.scope.parent.getBinding(name); + if (binding === bindingAboveLambdaScope) { + identifier.referencedByInnerFn = true; + } + } +} +function handleAssignment(currentFn, identifiers, lvalPath) { + var _a, _b, _c; + const lvalNode = lvalPath.node; + switch (lvalNode.type) { + case 'Identifier': { + const path = lvalPath; + const name = path.node.name; + const binding = path.scope.getBinding(name); + if (binding == null) { + break; + } + const state = getOrInsertDefault(identifiers, binding.identifier, Object.assign({}, DEFAULT_IDENTIFIER_INFO)); + state.reassigned = true; + if (currentFn != null) { + const bindingAboveLambdaScope = currentFn.scope.parent.getBinding(name); + if (binding === bindingAboveLambdaScope) { + state.reassignedByInnerFn = true; + } + } + break; + } + case 'ArrayPattern': { + const path = lvalPath; + for (const element of path.get('elements')) { + if (nonNull(element)) { + handleAssignment(currentFn, identifiers, element); + } + } + break; + } + case 'ObjectPattern': { + const path = lvalPath; + for (const property of path.get('properties')) { + if (property.isObjectProperty()) { + const valuePath = property.get('value'); + CompilerError.invariant(valuePath.isLVal(), { + reason: `[FindContextIdentifiers] Expected object property value to be an LVal, got: ${valuePath.type}`, + loc: (_a = valuePath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + handleAssignment(currentFn, identifiers, valuePath); + } + else { + CompilerError.invariant(property.isRestElement(), { + reason: `[FindContextIdentifiers] Invalid assumptions for babel types.`, + loc: (_b = property.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + handleAssignment(currentFn, identifiers, property); + } + } + break; + } + case 'AssignmentPattern': { + const path = lvalPath; + const left = path.get('left'); + handleAssignment(currentFn, identifiers, left); + break; + } + case 'RestElement': { + const path = lvalPath; + handleAssignment(currentFn, identifiers, path.get('argument')); + break; + } + case 'MemberExpression': { + break; + } + default: { + CompilerError.throwTodo({ + reason: `[FindContextIdentifiers] Cannot handle Object destructuring assignment target ${lvalNode.type}`, + description: null, + loc: (_c = lvalNode.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + suggestions: null, + }); + } + } +} +function nonNull(t) { + return t.node != null; +} + +function eliminateRedundantPhi(fn, sharedRewrites) { + const ir = fn.body; + const rewrites = sharedRewrites != null ? sharedRewrites : new Map(); + let hasBackEdge = false; + const visited = new Set(); + let size = rewrites.size; + do { + size = rewrites.size; + for (const [blockId, block] of ir.blocks) { + if (!hasBackEdge) { + for (const predId of block.preds) { + if (!visited.has(predId)) { + hasBackEdge = true; + } + } + } + visited.add(blockId); + phis: for (const phi of block.phis) { + phi.operands.forEach((place, _) => rewritePlace(place, rewrites)); + let same = null; + for (const [_, operand] of phi.operands) { + if ((same !== null && operand.identifier.id === same.id) || + operand.identifier.id === phi.place.identifier.id) { + continue; + } + else if (same !== null) { + continue phis; + } + else { + same = operand.identifier; + } + } + CompilerError.invariant(same !== null, { + reason: 'Expected phis to be non-empty', + loc: GeneratedSource, + }); + rewrites.set(phi.place.identifier, same); + block.phis.delete(phi); + } + for (const instr of block.instructions) { + for (const place of eachInstructionLValue(instr)) { + rewritePlace(place, rewrites); + } + for (const place of eachInstructionOperand(instr)) { + rewritePlace(place, rewrites); + } + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + const { context } = instr.value.loweredFunc.func; + for (const place of context) { + rewritePlace(place, rewrites); + } + eliminateRedundantPhi(instr.value.loweredFunc.func, rewrites); + } + } + const { terminal } = block; + for (const place of eachTerminalOperand(terminal)) { + rewritePlace(place, rewrites); + } + } + } while (rewrites.size > size && hasBackEdge); +} +function rewritePlace(place, rewrites) { + const rewrite = rewrites.get(place.identifier); + if (rewrite != null) { + place.identifier = rewrite; + } +} + +var _SSABuilder_states, _SSABuilder_current, _SSABuilder_blocks, _SSABuilder_env, _SSABuilder_unknown, _SSABuilder_context; +class SSABuilder { + constructor(env, blocks) { + _SSABuilder_states.set(this, new Map()); + _SSABuilder_current.set(this, null); + this.unsealedPreds = new Map(); + _SSABuilder_blocks.set(this, void 0); + _SSABuilder_env.set(this, void 0); + _SSABuilder_unknown.set(this, new Set()); + _SSABuilder_context.set(this, new Set()); + __classPrivateFieldSet(this, _SSABuilder_blocks, new Map(blocks), "f"); + __classPrivateFieldSet(this, _SSABuilder_env, env, "f"); + } + get nextSsaId() { + return __classPrivateFieldGet(this, _SSABuilder_env, "f").nextIdentifierId; + } + defineFunction(func) { + for (const [id, block] of func.body.blocks) { + __classPrivateFieldGet(this, _SSABuilder_blocks, "f").set(id, block); + } + } + enter(fn) { + const current = __classPrivateFieldGet(this, _SSABuilder_current, "f"); + fn(); + __classPrivateFieldSet(this, _SSABuilder_current, current, "f"); + } + state() { + CompilerError.invariant(__classPrivateFieldGet(this, _SSABuilder_current, "f") !== null, { + reason: 'we need to be in a block to access state!', + loc: GeneratedSource, + }); + return __classPrivateFieldGet(this, _SSABuilder_states, "f").get(__classPrivateFieldGet(this, _SSABuilder_current, "f")); + } + makeId(oldId) { + return { + id: this.nextSsaId, + declarationId: oldId.declarationId, + name: oldId.name, + mutableRange: { + start: makeInstructionId(0), + end: makeInstructionId(0), + }, + scope: null, + type: makeType(), + loc: oldId.loc, + }; + } + defineContext(oldPlace) { + const newPlace = this.definePlace(oldPlace); + __classPrivateFieldGet(this, _SSABuilder_context, "f").add(oldPlace.identifier); + return newPlace; + } + definePlace(oldPlace) { + const oldId = oldPlace.identifier; + if (__classPrivateFieldGet(this, _SSABuilder_unknown, "f").has(oldId)) { + CompilerError.throwTodo({ + reason: `[hoisting] EnterSSA: Expected identifier to be defined before being used`, + description: `Identifier ${printIdentifier(oldId)} is undefined`, + loc: oldPlace.loc, + suggestions: null, + }); + } + if (__classPrivateFieldGet(this, _SSABuilder_context, "f").has(oldId)) { + return this.getPlace(oldPlace); + } + const newId = this.makeId(oldId); + this.state().defs.set(oldId, newId); + return Object.assign(Object.assign({}, oldPlace), { identifier: newId }); + } + getPlace(oldPlace) { + const newId = this.getIdAt(oldPlace, __classPrivateFieldGet(this, _SSABuilder_current, "f").id); + return Object.assign(Object.assign({}, oldPlace), { identifier: newId }); + } + getIdAt(oldPlace, blockId) { + const block = __classPrivateFieldGet(this, _SSABuilder_blocks, "f").get(blockId); + const state = __classPrivateFieldGet(this, _SSABuilder_states, "f").get(block); + if (state.defs.has(oldPlace.identifier)) { + return state.defs.get(oldPlace.identifier); + } + if (block.preds.size == 0) { + __classPrivateFieldGet(this, _SSABuilder_unknown, "f").add(oldPlace.identifier); + return oldPlace.identifier; + } + if (this.unsealedPreds.get(block) > 0) { + const newId = this.makeId(oldPlace.identifier); + state.incompletePhis.push({ + oldPlace, + newPlace: Object.assign(Object.assign({}, oldPlace), { identifier: newId }), + }); + state.defs.set(oldPlace.identifier, newId); + return newId; + } + if (block.preds.size == 1) { + const [pred] = block.preds; + const newId = this.getIdAt(oldPlace, pred); + state.defs.set(oldPlace.identifier, newId); + return newId; + } + const newId = this.makeId(oldPlace.identifier); + state.defs.set(oldPlace.identifier, newId); + return this.addPhi(block, oldPlace, Object.assign(Object.assign({}, oldPlace), { identifier: newId })); + } + addPhi(block, oldPlace, newPlace) { + const predDefs = new Map(); + for (const predBlockId of block.preds) { + const predId = this.getIdAt(oldPlace, predBlockId); + predDefs.set(predBlockId, Object.assign(Object.assign({}, oldPlace), { identifier: predId })); + } + const phi = { + kind: 'Phi', + place: newPlace, + operands: predDefs, + }; + block.phis.add(phi); + return newPlace.identifier; + } + fixIncompletePhis(block) { + const state = __classPrivateFieldGet(this, _SSABuilder_states, "f").get(block); + for (const phi of state.incompletePhis) { + this.addPhi(block, phi.oldPlace, phi.newPlace); + } + } + startBlock(block) { + __classPrivateFieldSet(this, _SSABuilder_current, block, "f"); + __classPrivateFieldGet(this, _SSABuilder_states, "f").set(block, { + defs: new Map(), + incompletePhis: [], + }); + } + print() { + var _a; + const text = []; + for (const [block, state] of __classPrivateFieldGet(this, _SSABuilder_states, "f")) { + text.push(`bb${block.id}:`); + for (const [oldId, newId] of state.defs) { + text.push(` \$${printIdentifier(oldId)}: \$${printIdentifier(newId)}`); + } + for (const incompletePhi of state.incompletePhis) { + text.push(` iphi \$${printPlace(incompletePhi.newPlace)} = \$${printPlace(incompletePhi.oldPlace)}`); + } + } + text.push(`current block: bb${(_a = __classPrivateFieldGet(this, _SSABuilder_current, "f")) === null || _a === void 0 ? void 0 : _a.id}`); + console.log(text.join('\n')); + } +} +_SSABuilder_states = new WeakMap(), _SSABuilder_current = new WeakMap(), _SSABuilder_blocks = new WeakMap(), _SSABuilder_env = new WeakMap(), _SSABuilder_unknown = new WeakMap(), _SSABuilder_context = new WeakMap(); +function enterSSA(func) { + const builder = new SSABuilder(func.env, func.body.blocks); + enterSSAImpl(func, builder, func.body.entry); +} +function enterSSAImpl(func, builder, rootEntry) { + const visitedBlocks = new Set(); + for (const [blockId, block] of func.body.blocks) { + CompilerError.invariant(!visitedBlocks.has(block), { + reason: `found a cycle! visiting bb${block.id} again`, + loc: GeneratedSource, + }); + visitedBlocks.add(block); + builder.startBlock(block); + if (blockId === rootEntry) { + CompilerError.invariant(func.context.length === 0, { + reason: `Expected function context to be empty for outer function declarations`, + loc: func.loc, + }); + func.params = func.params.map(param => { + if (param.kind === 'Identifier') { + return builder.definePlace(param); + } + else { + return { + kind: 'Spread', + place: builder.definePlace(param.place), + }; + } + }); + } + for (const instr of block.instructions) { + mapInstructionOperands(instr, place => builder.getPlace(place)); + mapInstructionLValues(instr, lvalue => builder.definePlace(lvalue)); + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + const loweredFunc = instr.value.loweredFunc.func; + const entry = loweredFunc.body.blocks.get(loweredFunc.body.entry); + CompilerError.invariant(entry.preds.size === 0, { + reason: 'Expected function expression entry block to have zero predecessors', + loc: GeneratedSource, + }); + entry.preds.add(blockId); + builder.defineFunction(loweredFunc); + builder.enter(() => { + loweredFunc.params = loweredFunc.params.map(param => { + if (param.kind === 'Identifier') { + return builder.definePlace(param); + } + else { + return { + kind: 'Spread', + place: builder.definePlace(param.place), + }; + } + }); + enterSSAImpl(loweredFunc, builder, rootEntry); + }); + entry.preds.clear(); + } + } + mapTerminalOperands(block.terminal, place => builder.getPlace(place)); + for (const outputId of eachTerminalSuccessor(block.terminal)) { + const output = func.body.blocks.get(outputId); + let count; + if (builder.unsealedPreds.has(output)) { + count = builder.unsealedPreds.get(output) - 1; + } + else { + count = output.preds.size - 1; + } + builder.unsealedPreds.set(output, count); + if (count === 0 && visitedBlocks.has(output)) { + builder.fixIncompletePhis(output); + } + } + } +} + +function rewriteInstructionKindsBasedOnReassignment(fn) { + const declarations = new Map(); + for (const param of fn.params) { + let place = param.kind === 'Identifier' ? param : param.place; + if (place.identifier.name !== null) { + declarations.set(place.identifier.declarationId, { + kind: InstructionKind.Let, + place, + }); + } + } + for (const place of fn.context) { + if (place.identifier.name !== null) { + declarations.set(place.identifier.declarationId, { + kind: InstructionKind.Let, + place, + }); + } + } + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'DeclareLocal': { + const lvalue = value.lvalue; + CompilerError.invariant(!declarations.has(lvalue.place.identifier.declarationId), { + reason: `Expected variable not to be defined prior to declaration`, + description: `${printPlace(lvalue.place)} was already defined`, + loc: lvalue.place.loc, + }); + declarations.set(lvalue.place.identifier.declarationId, lvalue); + break; + } + case 'StoreLocal': { + const lvalue = value.lvalue; + if (lvalue.place.identifier.name !== null) { + const declaration = declarations.get(lvalue.place.identifier.declarationId); + if (declaration === undefined) { + CompilerError.invariant(!declarations.has(lvalue.place.identifier.declarationId), { + reason: `Expected variable not to be defined prior to declaration`, + description: `${printPlace(lvalue.place)} was already defined`, + loc: lvalue.place.loc, + }); + declarations.set(lvalue.place.identifier.declarationId, lvalue); + lvalue.kind = InstructionKind.Const; + } + else { + declaration.kind = InstructionKind.Let; + lvalue.kind = InstructionKind.Reassign; + } + } + break; + } + case 'Destructure': { + const lvalue = value.lvalue; + let kind = null; + for (const place of eachPatternOperand(lvalue.pattern)) { + if (place.identifier.name === null) { + CompilerError.invariant(kind === null || kind === InstructionKind.Const, { + reason: `Expected consistent kind for destructuring`, + description: `other places were \`${kind}\` but '${printPlace(place)}' is const`, + loc: place.loc, + }); + kind = InstructionKind.Const; + } + else { + const declaration = declarations.get(place.identifier.declarationId); + if (declaration === undefined) { + CompilerError.invariant(block.kind !== 'value', { + reason: `TODO: Handle reassignment in a value block where the original declaration was removed by dead code elimination (DCE)`, + loc: place.loc, + }); + declarations.set(place.identifier.declarationId, lvalue); + CompilerError.invariant(kind === null || kind === InstructionKind.Const, { + reason: `Expected consistent kind for destructuring`, + description: `Other places were \`${kind}\` but '${printPlace(place)}' is const`, + loc: place.loc, + }); + kind = InstructionKind.Const; + } + else { + CompilerError.invariant(kind === null || kind === InstructionKind.Reassign, { + reason: `Expected consistent kind for destructuring`, + description: `Other places were \`${kind}\` but '${printPlace(place)}' is reassigned`, + loc: place.loc, + }); + kind = InstructionKind.Reassign; + declaration.kind = InstructionKind.Let; + } + } + } + CompilerError.invariant(kind !== null, { + reason: 'Expected at least one operand', + loc: GeneratedSource, + }); + lvalue.kind = kind; + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + const lvalue = value.lvalue; + const declaration = declarations.get(lvalue.identifier.declarationId); + CompilerError.invariant(declaration !== undefined, { + reason: `Expected variable to have been defined`, + description: `No declaration for ${printPlace(lvalue)}`, + loc: lvalue.loc, + }); + declaration.kind = InstructionKind.Let; + break; + } + } + } + } +} + +function constantPropagation(fn) { + const constants = new Map(); + constantPropagationImpl(fn, constants); +} +function constantPropagationImpl(fn, constants) { + while (true) { + const haveTerminalsChanged = applyConstantPropagation(fn, constants); + if (!haveTerminalsChanged) { + break; + } + reversePostorderBlocks(fn.body); + removeUnreachableForUpdates(fn.body); + removeDeadDoWhileStatements(fn.body); + removeUnnecessaryTryCatch(fn.body); + markInstructionIds(fn.body); + markPredecessors(fn.body); + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + for (const [predecessor] of phi.operands) { + if (!block.preds.has(predecessor)) { + phi.operands.delete(predecessor); + } + } + } + } + eliminateRedundantPhi(fn); + mergeConsecutiveBlocks(fn); + assertConsistentIdentifiers(fn); + assertTerminalSuccessorsExist(fn); + } +} +function applyConstantPropagation(fn, constants) { + let hasChanges = false; + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + let value = evaluatePhi(phi, constants); + if (value !== null) { + constants.set(phi.place.identifier.id, value); + } + } + for (let i = 0; i < block.instructions.length; i++) { + if (block.kind === 'sequence' && i === block.instructions.length - 1) { + continue; + } + const instr = block.instructions[i]; + const value = evaluateInstruction(constants, instr); + if (value !== null) { + constants.set(instr.lvalue.identifier.id, value); + } + } + const terminal = block.terminal; + switch (terminal.kind) { + case 'if': { + const testValue = read(constants, terminal.test); + if (testValue !== null && testValue.kind === 'Primitive') { + hasChanges = true; + const targetBlockId = testValue.value + ? terminal.consequent + : terminal.alternate; + block.terminal = { + kind: 'goto', + variant: GotoVariant.Break, + block: targetBlockId, + id: terminal.id, + loc: terminal.loc, + }; + } + break; + } + } + } + return hasChanges; +} +function evaluatePhi(phi, constants) { + var _a; + let value = null; + for (const [, operand] of phi.operands) { + const operandValue = (_a = constants.get(operand.identifier.id)) !== null && _a !== void 0 ? _a : null; + if (operandValue === null) { + return null; + } + if (value === null) { + value = operandValue; + continue; + } + if (operandValue.kind !== value.kind) { + return null; + } + switch (operandValue.kind) { + case 'Primitive': { + CompilerError.invariant(value.kind === 'Primitive', { + reason: 'value kind expected to be Primitive', + loc: GeneratedSource, + }); + if (operandValue.value !== value.value) { + return null; + } + break; + } + case 'LoadGlobal': { + CompilerError.invariant(value.kind === 'LoadGlobal', { + reason: 'value kind expected to be LoadGlobal', + loc: GeneratedSource, + }); + if (operandValue.binding.name !== value.binding.name) { + return null; + } + break; + } + default: + return null; + } + } + return value; +} +function evaluateInstruction(constants, instr) { + const value = instr.value; + switch (value.kind) { + case 'Primitive': { + return value; + } + case 'LoadGlobal': { + return value; + } + case 'ComputedLoad': { + const property = read(constants, value.property); + if (property !== null && + property.kind === 'Primitive' && + ((typeof property.value === 'string' && + libExports$1.isValidIdentifier(property.value)) || + typeof property.value === 'number')) { + const nextValue = { + kind: 'PropertyLoad', + loc: value.loc, + property: makePropertyLiteral(property.value), + object: value.object, + }; + instr.value = nextValue; + } + return null; + } + case 'ComputedStore': { + const property = read(constants, value.property); + if (property !== null && + property.kind === 'Primitive' && + ((typeof property.value === 'string' && + libExports$1.isValidIdentifier(property.value)) || + typeof property.value === 'number')) { + const nextValue = { + kind: 'PropertyStore', + loc: value.loc, + property: makePropertyLiteral(property.value), + object: value.object, + value: value.value, + }; + instr.value = nextValue; + } + return null; + } + case 'PostfixUpdate': { + const previous = read(constants, value.value); + if (previous !== null && + previous.kind === 'Primitive' && + typeof previous.value === 'number') { + const next = value.operation === '++' ? previous.value + 1 : previous.value - 1; + constants.set(value.lvalue.identifier.id, { + kind: 'Primitive', + value: next, + loc: value.loc, + }); + return previous; + } + return null; + } + case 'PrefixUpdate': { + const previous = read(constants, value.value); + if (previous !== null && + previous.kind === 'Primitive' && + typeof previous.value === 'number') { + const next = { + kind: 'Primitive', + value: value.operation === '++' ? previous.value + 1 : previous.value - 1, + loc: value.loc, + }; + constants.set(value.lvalue.identifier.id, next); + return next; + } + return null; + } + case 'UnaryExpression': { + switch (value.operator) { + case '!': { + const operand = read(constants, value.value); + if (operand !== null && operand.kind === 'Primitive') { + const result = { + kind: 'Primitive', + value: !operand.value, + loc: value.loc, + }; + instr.value = result; + return result; + } + return null; + } + case '-': { + const operand = read(constants, value.value); + if (operand !== null && + operand.kind === 'Primitive' && + typeof operand.value === 'number') { + const result = { + kind: 'Primitive', + value: operand.value * -1, + loc: value.loc, + }; + instr.value = result; + return result; + } + return null; + } + default: + return null; + } + } + case 'BinaryExpression': { + const lhsValue = read(constants, value.left); + const rhsValue = read(constants, value.right); + if (lhsValue !== null && + rhsValue !== null && + lhsValue.kind === 'Primitive' && + rhsValue.kind === 'Primitive') { + const lhs = lhsValue.value; + const rhs = rhsValue.value; + let result = null; + switch (value.operator) { + case '+': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs + rhs, loc: value.loc }; + } + else if (typeof lhs === 'string' && typeof rhs === 'string') { + result = { kind: 'Primitive', value: lhs + rhs, loc: value.loc }; + } + break; + } + case '-': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs - rhs, loc: value.loc }; + } + break; + } + case '*': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs * rhs, loc: value.loc }; + } + break; + } + case '/': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs / rhs, loc: value.loc }; + } + break; + } + case '|': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs | rhs, loc: value.loc }; + } + break; + } + case '&': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs & rhs, loc: value.loc }; + } + break; + } + case '^': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs ^ rhs, loc: value.loc }; + } + break; + } + case '<<': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs << rhs, loc: value.loc }; + } + break; + } + case '>>': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs >> rhs, loc: value.loc }; + } + break; + } + case '>>>': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { + kind: 'Primitive', + value: lhs >>> rhs, + loc: value.loc, + }; + } + break; + } + case '%': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs % rhs, loc: value.loc }; + } + break; + } + case '**': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: Math.pow(lhs, rhs), loc: value.loc }; + } + break; + } + case '<': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs < rhs, loc: value.loc }; + } + break; + } + case '<=': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs <= rhs, loc: value.loc }; + } + break; + } + case '>': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs > rhs, loc: value.loc }; + } + break; + } + case '>=': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs >= rhs, loc: value.loc }; + } + break; + } + case '==': { + result = { kind: 'Primitive', value: lhs == rhs, loc: value.loc }; + break; + } + case '===': { + result = { kind: 'Primitive', value: lhs === rhs, loc: value.loc }; + break; + } + case '!=': { + result = { kind: 'Primitive', value: lhs != rhs, loc: value.loc }; + break; + } + case '!==': { + result = { kind: 'Primitive', value: lhs !== rhs, loc: value.loc }; + break; + } + } + if (result !== null) { + instr.value = result; + return result; + } + } + return null; + } + case 'PropertyLoad': { + const objectValue = read(constants, value.object); + if (objectValue !== null) { + if (objectValue.kind === 'Primitive' && + typeof objectValue.value === 'string' && + value.property === 'length') { + const result = { + kind: 'Primitive', + value: objectValue.value.length, + loc: value.loc, + }; + instr.value = result; + return result; + } + } + return null; + } + case 'TemplateLiteral': { + if (value.subexprs.length === 0) { + const result = { + kind: 'Primitive', + value: value.quasis.map(q => q.cooked).join(''), + loc: value.loc, + }; + instr.value = result; + return result; + } + if (value.subexprs.length !== value.quasis.length - 1) { + return null; + } + if (value.quasis.some(q => q.cooked === undefined)) { + return null; + } + let quasiIndex = 0; + let resultString = value.quasis[quasiIndex].cooked; + ++quasiIndex; + for (const subExpr of value.subexprs) { + const subExprValue = read(constants, subExpr); + if (!subExprValue || subExprValue.kind !== 'Primitive') { + return null; + } + const expressionValue = subExprValue.value; + if (typeof expressionValue !== 'number' && + typeof expressionValue !== 'string' && + typeof expressionValue !== 'boolean' && + !(typeof expressionValue === 'object' && expressionValue === null)) { + return null; + } + const suffix = value.quasis[quasiIndex].cooked; + ++quasiIndex; + if (suffix === undefined) { + return null; + } + resultString = resultString.concat(expressionValue, suffix); + } + const result = { + kind: 'Primitive', + value: resultString, + loc: value.loc, + }; + instr.value = result; + return result; + } + case 'LoadLocal': { + const placeValue = read(constants, value.place); + if (placeValue !== null) { + instr.value = placeValue; + } + return placeValue; + } + case 'StoreLocal': { + const placeValue = read(constants, value.value); + if (placeValue !== null) { + constants.set(value.lvalue.place.identifier.id, placeValue); + } + return placeValue; + } + case 'ObjectMethod': + case 'FunctionExpression': { + constantPropagationImpl(value.loweredFunc.func, constants); + return null; + } + case 'StartMemoize': { + if (value.deps != null) { + for (const dep of value.deps) { + if (dep.root.kind === 'NamedLocal') { + const placeValue = read(constants, dep.root.value); + if (placeValue != null && placeValue.kind === 'Primitive') { + dep.root.constant = true; + } + } + } + } + return null; + } + default: { + return null; + } + } +} +function read(constants, place) { + var _a; + return (_a = constants.get(place.identifier.id)) !== null && _a !== void 0 ? _a : null; +} + +function deadCodeElimination(fn) { + const state = findReferencedIdentifiers(fn); + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + if (!state.isIdOrNameUsed(phi.place.identifier)) { + block.phis.delete(phi); + } + } + retainWhere(block.instructions, instr => state.isIdOrNameUsed(instr.lvalue.identifier)); + for (let i = 0; i < block.instructions.length; i++) { + const isBlockValue = block.kind !== 'block' && i === block.instructions.length - 1; + if (!isBlockValue) { + rewriteInstruction(block.instructions[i], state); + } + } + } + retainWhere(fn.context, contextVar => state.isIdOrNameUsed(contextVar.identifier)); +} +let State$2 = class State { + constructor(env) { + this.named = new Set(); + this.identifiers = new Set(); + this.env = env; + } + reference(identifier) { + this.identifiers.add(identifier.id); + if (identifier.name !== null) { + this.named.add(identifier.name.value); + } + } + isIdOrNameUsed(identifier) { + return (this.identifiers.has(identifier.id) || + (identifier.name !== null && this.named.has(identifier.name.value))); + } + isIdUsed(identifier) { + return this.identifiers.has(identifier.id); + } + get count() { + return this.identifiers.size; + } +}; +function findReferencedIdentifiers(fn) { + const hasLoop = hasBackEdge(fn); + const reversedBlocks = [...fn.body.blocks.values()].reverse(); + const state = new State$2(fn.env); + let size = state.count; + do { + size = state.count; + for (const block of reversedBlocks) { + for (const operand of eachTerminalOperand(block.terminal)) { + state.reference(operand.identifier); + } + for (let i = block.instructions.length - 1; i >= 0; i--) { + const instr = block.instructions[i]; + const isBlockValue = block.kind !== 'block' && i === block.instructions.length - 1; + if (isBlockValue) { + state.reference(instr.lvalue.identifier); + for (const place of eachInstructionValueOperand(instr.value)) { + state.reference(place.identifier); + } + } + else if (state.isIdOrNameUsed(instr.lvalue.identifier) || + !pruneableValue(instr.value, state)) { + state.reference(instr.lvalue.identifier); + if (instr.value.kind === 'StoreLocal') { + if (instr.value.lvalue.kind === InstructionKind.Reassign || + state.isIdUsed(instr.value.lvalue.place.identifier)) { + state.reference(instr.value.value.identifier); + } + } + else { + for (const operand of eachInstructionValueOperand(instr.value)) { + state.reference(operand.identifier); + } + } + } + } + for (const phi of block.phis) { + if (state.isIdOrNameUsed(phi.place.identifier)) { + for (const [_pred, operand] of phi.operands) { + state.reference(operand.identifier); + } + } + } + } + } while (state.count > size && hasLoop); + return state; +} +function rewriteInstruction(instr, state) { + if (instr.value.kind === 'Destructure') { + switch (instr.value.lvalue.pattern.kind) { + case 'ArrayPattern': { + let lastEntryIndex = 0; + const items = instr.value.lvalue.pattern.items; + for (let i = 0; i < items.length; i++) { + const item = items[i]; + if (item.kind === 'Identifier') { + if (!state.isIdOrNameUsed(item.identifier)) { + items[i] = { kind: 'Hole' }; + } + else { + lastEntryIndex = i; + } + } + else if (item.kind === 'Spread') { + if (!state.isIdOrNameUsed(item.place.identifier)) { + items[i] = { kind: 'Hole' }; + } + else { + lastEntryIndex = i; + } + } + } + items.length = lastEntryIndex + 1; + break; + } + case 'ObjectPattern': { + let nextProperties = null; + for (const property of instr.value.lvalue.pattern.properties) { + if (property.kind === 'ObjectProperty') { + if (state.isIdOrNameUsed(property.place.identifier)) { + nextProperties !== null && nextProperties !== void 0 ? nextProperties : (nextProperties = []); + nextProperties.push(property); + } + } + else { + if (state.isIdOrNameUsed(property.place.identifier)) { + nextProperties = null; + break; + } + } + } + if (nextProperties !== null) { + instr.value.lvalue.pattern.properties = nextProperties; + } + break; + } + default: { + assertExhaustive$1(instr.value.lvalue.pattern, `Unexpected pattern kind '${instr.value.lvalue.pattern.kind}'`); + } + } + } + else if (instr.value.kind === 'StoreLocal') { + if (instr.value.lvalue.kind !== InstructionKind.Reassign && + !state.isIdUsed(instr.value.lvalue.place.identifier)) { + instr.value = { + kind: 'DeclareLocal', + lvalue: instr.value.lvalue, + type: instr.value.type, + loc: instr.value.loc, + }; + } + } +} +function pruneableValue(value, state) { + switch (value.kind) { + case 'DeclareLocal': { + return !state.isIdOrNameUsed(value.lvalue.place.identifier); + } + case 'StoreLocal': { + if (value.lvalue.kind === InstructionKind.Reassign) { + return !state.isIdUsed(value.lvalue.place.identifier); + } + return !state.isIdOrNameUsed(value.lvalue.place.identifier); + } + case 'Destructure': { + let isIdOrNameUsed = false; + let isIdUsed = false; + for (const place of eachPatternOperand(value.lvalue.pattern)) { + if (state.isIdUsed(place.identifier)) { + isIdOrNameUsed = true; + isIdUsed = true; + } + else if (state.isIdOrNameUsed(place.identifier)) { + isIdOrNameUsed = true; + } + } + if (value.lvalue.kind === InstructionKind.Reassign) { + return !isIdUsed; + } + else { + return !isIdOrNameUsed; + } + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + return !state.isIdUsed(value.lvalue.identifier); + } + case 'Debugger': { + return false; + } + case 'CallExpression': + case 'MethodCall': { + if (state.env.outputMode === 'ssr') { + const calleee = value.kind === 'CallExpression' ? value.callee : value.property; + const hookKind = getHookKind(state.env, calleee.identifier); + switch (hookKind) { + case 'useState': + case 'useReducer': + case 'useRef': { + return true; + } + } + } + return false; + } + case 'Await': + case 'ComputedDelete': + case 'ComputedStore': + case 'PropertyDelete': + case 'PropertyStore': + case 'StoreGlobal': { + return false; + } + case 'NewExpression': + case 'UnsupportedNode': + case 'TaggedTemplateExpression': { + return false; + } + case 'GetIterator': + case 'NextPropertyOf': + case 'IteratorNext': { + return false; + } + case 'LoadContext': + case 'DeclareContext': + case 'StoreContext': { + return false; + } + case 'StartMemoize': + case 'FinishMemoize': { + return false; + } + case 'RegExpLiteral': + case 'MetaProperty': + case 'LoadGlobal': + case 'ArrayExpression': + case 'BinaryExpression': + case 'ComputedLoad': + case 'ObjectMethod': + case 'FunctionExpression': + case 'LoadLocal': + case 'JsxExpression': + case 'JsxFragment': + case 'JSXText': + case 'ObjectExpression': + case 'Primitive': + case 'PropertyLoad': + case 'TemplateLiteral': + case 'TypeCastExpression': + case 'UnaryExpression': { + return true; + } + default: { + assertExhaustive$1(value, `Unexepcted value kind \`${value.kind}\``); + } + } +} +function hasBackEdge(fn) { + return findBlocksWithBackEdges(fn).size > 0; +} +function findBlocksWithBackEdges(fn) { + const visited = new Set(); + const blocks = new Set(); + for (const [blockId, block] of fn.body.blocks) { + for (const predId of block.preds) { + if (!visited.has(predId)) { + blocks.add(blockId); + } + } + visited.add(blockId); + } + return blocks; +} + +function pruneMaybeThrows(fn) { + const terminalMapping = pruneMaybeThrowsImpl(fn); + if (terminalMapping) { + reversePostorderBlocks(fn.body); + removeUnreachableForUpdates(fn.body); + removeDeadDoWhileStatements(fn.body); + removeUnnecessaryTryCatch(fn.body); + markInstructionIds(fn.body); + mergeConsecutiveBlocks(fn); + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + for (const [predecessor, operand] of phi.operands) { + if (!block.preds.has(predecessor)) { + const mappedTerminal = terminalMapping.get(predecessor); + CompilerError.invariant(mappedTerminal != null, { + reason: `Expected non-existing phi operand's predecessor to have been mapped to a new terminal`, + description: `Could not find mapping for predecessor bb${predecessor} in block bb${block.id} for phi ${printPlace(phi.place)}`, + loc: GeneratedSource, + }); + phi.operands.delete(predecessor); + phi.operands.set(mappedTerminal, operand); + } + } + } + } + assertConsistentIdentifiers(fn); + assertTerminalSuccessorsExist(fn); + } +} +function pruneMaybeThrowsImpl(fn) { + var _a; + const terminalMapping = new Map(); + for (const [_, block] of fn.body.blocks) { + const terminal = block.terminal; + if (terminal.kind !== 'maybe-throw') { + continue; + } + const canThrow = block.instructions.some(instr => instructionMayThrow(instr)); + if (!canThrow) { + const source = (_a = terminalMapping.get(block.id)) !== null && _a !== void 0 ? _a : block.id; + terminalMapping.set(terminal.continuation, source); + terminal.handler = null; + } + } + return terminalMapping.size > 0 ? terminalMapping : null; +} +function instructionMayThrow(instr) { + switch (instr.value.kind) { + case 'Primitive': + case 'ArrayExpression': + case 'ObjectExpression': { + return false; + } + default: { + return true; + } + } +} + +function findScopesToMerge(fn) { + const objectMethodDecls = new Set(); + const mergeScopesBuilder = new DisjointSet(); + for (const [_, block] of fn.body.blocks) { + for (const { lvalue, value } of block.instructions) { + if (value.kind === 'ObjectMethod') { + objectMethodDecls.add(lvalue.identifier); + } + else if (value.kind === 'ObjectExpression') { + for (const operand of eachInstructionValueOperand(value)) { + if (objectMethodDecls.has(operand.identifier)) { + const operandScope = operand.identifier.scope; + const lvalueScope = lvalue.identifier.scope; + CompilerError.invariant(operandScope != null && lvalueScope != null, { + reason: 'Internal error: Expected all ObjectExpressions and ObjectMethods to have non-null scope.', + loc: GeneratedSource, + }); + mergeScopesBuilder.union([operandScope, lvalueScope]); + } + } + } + } + } + return mergeScopesBuilder; +} +function alignObjectMethodScopes(fn) { + for (const [_, block] of fn.body.blocks) { + for (const { value } of block.instructions) { + if (value.kind === 'ObjectMethod' || + value.kind === 'FunctionExpression') { + alignObjectMethodScopes(value.loweredFunc.func); + } + } + } + const scopeGroupsMap = findScopesToMerge(fn).canonicalize(); + for (const [scope, root] of scopeGroupsMap) { + if (scope !== root) { + root.range.start = makeInstructionId(Math.min(scope.range.start, root.range.start)); + root.range.end = makeInstructionId(Math.max(scope.range.end, root.range.end)); + } + } + for (const [_, block] of fn.body.blocks) { + for (const { lvalue: { identifier }, } of block.instructions) { + if (identifier.scope != null) { + const root = scopeGroupsMap.get(identifier.scope); + if (root != null) { + identifier.scope = root; + } + } + } + } +} + +function visitReactiveFunction(fn, visitor, state) { + visitor.visitBlock(fn.body, state); +} +class ReactiveFunctionVisitor { + visitID(_id, _state) { } + visitParam(_place, _state) { } + visitLValue(_id, _lvalue, _state) { } + visitPlace(_id, _place, _state) { } + visitReactiveFunctionValue(_id, _dependencies, _fn, _state) { } + visitValue(id, value, state) { + this.traverseValue(id, value, state); + } + traverseValue(id, value, state) { + switch (value.kind) { + case 'OptionalExpression': { + this.visitValue(id, value.value, state); + break; + } + case 'LogicalExpression': { + this.visitValue(id, value.left, state); + this.visitValue(id, value.right, state); + break; + } + case 'ConditionalExpression': { + this.visitValue(id, value.test, state); + this.visitValue(id, value.consequent, state); + this.visitValue(id, value.alternate, state); + break; + } + case 'SequenceExpression': { + for (const instr of value.instructions) { + this.visitInstruction(instr, state); + } + this.visitValue(value.id, value.value, state); + break; + } + default: { + for (const place of eachInstructionValueOperand(value)) { + this.visitPlace(id, place, state); + } + } + } + } + visitInstruction(instruction, state) { + this.traverseInstruction(instruction, state); + } + traverseInstruction(instruction, state) { + this.visitID(instruction.id, state); + for (const operand of eachInstructionLValue(instruction)) { + this.visitLValue(instruction.id, operand, state); + } + this.visitValue(instruction.id, instruction.value, state); + } + visitTerminal(stmt, state) { + this.traverseTerminal(stmt, state); + } + traverseTerminal(stmt, state) { + const { terminal } = stmt; + if (terminal.id !== null) { + this.visitID(terminal.id, state); + } + switch (terminal.kind) { + case 'break': + case 'continue': { + break; + } + case 'return': { + this.visitPlace(terminal.id, terminal.value, state); + break; + } + case 'throw': { + this.visitPlace(terminal.id, terminal.value, state); + break; + } + case 'for': { + this.visitValue(terminal.id, terminal.init, state); + this.visitValue(terminal.id, terminal.test, state); + this.visitBlock(terminal.loop, state); + if (terminal.update !== null) { + this.visitValue(terminal.id, terminal.update, state); + } + break; + } + case 'for-of': { + this.visitValue(terminal.id, terminal.init, state); + this.visitValue(terminal.id, terminal.test, state); + this.visitBlock(terminal.loop, state); + break; + } + case 'for-in': { + this.visitValue(terminal.id, terminal.init, state); + this.visitBlock(terminal.loop, state); + break; + } + case 'do-while': { + this.visitBlock(terminal.loop, state); + this.visitValue(terminal.id, terminal.test, state); + break; + } + case 'while': { + this.visitValue(terminal.id, terminal.test, state); + this.visitBlock(terminal.loop, state); + break; + } + case 'if': { + this.visitPlace(terminal.id, terminal.test, state); + this.visitBlock(terminal.consequent, state); + if (terminal.alternate !== null) { + this.visitBlock(terminal.alternate, state); + } + break; + } + case 'switch': { + this.visitPlace(terminal.id, terminal.test, state); + for (const case_ of terminal.cases) { + if (case_.test !== null) { + this.visitPlace(terminal.id, case_.test, state); + } + if (case_.block !== undefined) { + this.visitBlock(case_.block, state); + } + } + break; + } + case 'label': { + this.visitBlock(terminal.block, state); + break; + } + case 'try': { + this.visitBlock(terminal.block, state); + this.visitBlock(terminal.handler, state); + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } + } + visitScope(scope, state) { + this.traverseScope(scope, state); + } + traverseScope(scope, state) { + this.visitBlock(scope.instructions, state); + } + visitPrunedScope(scopeBlock, state) { + this.traversePrunedScope(scopeBlock, state); + } + traversePrunedScope(scopeBlock, state) { + this.visitBlock(scopeBlock.instructions, state); + } + visitBlock(block, state) { + this.traverseBlock(block, state); + } + traverseBlock(block, state) { + for (const instr of block) { + switch (instr.kind) { + case 'instruction': { + this.visitInstruction(instr.instruction, state); + break; + } + case 'scope': { + this.visitScope(instr, state); + break; + } + case 'pruned-scope': { + this.visitPrunedScope(instr, state); + break; + } + case 'terminal': { + this.visitTerminal(instr, state); + break; + } + default: { + assertExhaustive$1(instr, `Unexpected instruction kind \`${instr.kind}\``); + } + } + } + } + visitHirFunction(fn, state) { + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + this.visitParam(place, state); + } + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + this.visitInstruction(instr, state); + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + this.visitHirFunction(instr.value.loweredFunc.func, state); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + this.visitPlace(block.terminal.id, operand, state); + } + } + } +} +class ReactiveFunctionTransform extends ReactiveFunctionVisitor { + traverseBlock(block, state) { + let nextBlock = null; + for (let i = 0; i < block.length; i++) { + const instr = block[i]; + let transformed; + switch (instr.kind) { + case 'instruction': { + transformed = this.transformInstruction(instr.instruction, state); + break; + } + case 'scope': { + transformed = this.transformScope(instr, state); + break; + } + case 'pruned-scope': { + transformed = this.transformPrunedScope(instr, state); + break; + } + case 'terminal': { + transformed = this.transformTerminal(instr, state); + break; + } + default: { + assertExhaustive$1(instr, `Unexpected instruction kind \`${instr.kind}\``); + } + } + switch (transformed.kind) { + case 'keep': { + if (nextBlock !== null) { + nextBlock.push(instr); + } + break; + } + case 'remove': { + if (nextBlock === null) { + nextBlock = block.slice(0, i); + } + break; + } + case 'replace': { + nextBlock !== null && nextBlock !== void 0 ? nextBlock : (nextBlock = block.slice(0, i)); + nextBlock.push(transformed.value); + break; + } + case 'replace-many': { + nextBlock !== null && nextBlock !== void 0 ? nextBlock : (nextBlock = block.slice(0, i)); + nextBlock.push(...transformed.value); + break; + } + } + } + if (nextBlock !== null) { + block.length = 0; + block.push(...nextBlock); + } + } + transformInstruction(instruction, state) { + this.visitInstruction(instruction, state); + return { kind: 'keep' }; + } + transformTerminal(stmt, state) { + this.visitTerminal(stmt, state); + return { kind: 'keep' }; + } + transformScope(scope, state) { + this.visitScope(scope, state); + return { kind: 'keep' }; + } + transformPrunedScope(scope, state) { + this.visitPrunedScope(scope, state); + return { kind: 'keep' }; + } + transformValue(id, value, state) { + this.visitValue(id, value, state); + return { kind: 'keep' }; + } + transformReactiveFunctionValue(id, dependencies, fn, state) { + this.visitReactiveFunctionValue(id, dependencies, fn, state); + return { kind: 'keep' }; + } + traverseValue(id, value, state) { + switch (value.kind) { + case 'OptionalExpression': { + const nextValue = this.transformValue(id, value.value, state); + if (nextValue.kind === 'replace') { + value.value = nextValue.value; + } + break; + } + case 'LogicalExpression': { + const left = this.transformValue(id, value.left, state); + if (left.kind === 'replace') { + value.left = left.value; + } + const right = this.transformValue(id, value.right, state); + if (right.kind === 'replace') { + value.right = right.value; + } + break; + } + case 'ConditionalExpression': { + const test = this.transformValue(id, value.test, state); + if (test.kind === 'replace') { + value.test = test.value; + } + const consequent = this.transformValue(id, value.consequent, state); + if (consequent.kind === 'replace') { + value.consequent = consequent.value; + } + const alternate = this.transformValue(id, value.alternate, state); + if (alternate.kind === 'replace') { + value.alternate = alternate.value; + } + break; + } + case 'SequenceExpression': { + for (const instr of value.instructions) { + this.visitInstruction(instr, state); + } + const nextValue = this.transformValue(value.id, value.value, state); + if (nextValue.kind === 'replace') { + value.value = nextValue.value; + } + break; + } + default: { + for (const place of eachInstructionValueOperand(value)) { + this.visitPlace(id, place, state); + } + } + } + } + traverseInstruction(instruction, state) { + this.visitID(instruction.id, state); + for (const operand of eachInstructionLValue(instruction)) { + this.visitLValue(instruction.id, operand, state); + } + const nextValue = this.transformValue(instruction.id, instruction.value, state); + if (nextValue.kind === 'replace') { + instruction.value = nextValue.value; + } + } + traverseTerminal(stmt, state) { + const { terminal } = stmt; + if (terminal.id !== null) { + this.visitID(terminal.id, state); + } + switch (terminal.kind) { + case 'break': + case 'continue': { + break; + } + case 'return': { + this.visitPlace(terminal.id, terminal.value, state); + break; + } + case 'throw': { + this.visitPlace(terminal.id, terminal.value, state); + break; + } + case 'for': { + const init = this.transformValue(terminal.id, terminal.init, state); + if (init.kind === 'replace') { + terminal.init = init.value; + } + const test = this.transformValue(terminal.id, terminal.test, state); + if (test.kind === 'replace') { + terminal.test = test.value; + } + if (terminal.update !== null) { + const update = this.transformValue(terminal.id, terminal.update, state); + if (update.kind === 'replace') { + terminal.update = update.value; + } + } + this.visitBlock(terminal.loop, state); + break; + } + case 'for-of': { + const init = this.transformValue(terminal.id, terminal.init, state); + if (init.kind === 'replace') { + terminal.init = init.value; + } + const test = this.transformValue(terminal.id, terminal.test, state); + if (test.kind === 'replace') { + terminal.test = test.value; + } + this.visitBlock(terminal.loop, state); + break; + } + case 'for-in': { + const init = this.transformValue(terminal.id, terminal.init, state); + if (init.kind === 'replace') { + terminal.init = init.value; + } + this.visitBlock(terminal.loop, state); + break; + } + case 'do-while': { + this.visitBlock(terminal.loop, state); + const test = this.transformValue(terminal.id, terminal.test, state); + if (test.kind === 'replace') { + terminal.test = test.value; + } + break; + } + case 'while': { + const test = this.transformValue(terminal.id, terminal.test, state); + if (test.kind === 'replace') { + terminal.test = test.value; + } + this.visitBlock(terminal.loop, state); + break; + } + case 'if': { + this.visitPlace(terminal.id, terminal.test, state); + this.visitBlock(terminal.consequent, state); + if (terminal.alternate !== null) { + this.visitBlock(terminal.alternate, state); + } + break; + } + case 'switch': { + this.visitPlace(terminal.id, terminal.test, state); + for (const case_ of terminal.cases) { + if (case_.test !== null) { + this.visitPlace(terminal.id, case_.test, state); + } + if (case_.block !== undefined) { + this.visitBlock(case_.block, state); + } + } + break; + } + case 'label': { + this.visitBlock(terminal.block, state); + break; + } + case 'try': { + this.visitBlock(terminal.block, state); + if (terminal.handlerBinding !== null) { + this.visitPlace(terminal.id, terminal.handlerBinding, state); + } + this.visitBlock(terminal.handler, state); + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } + } +} +function* eachReactiveValueOperand(instrValue) { + switch (instrValue.kind) { + case 'OptionalExpression': { + yield* eachReactiveValueOperand(instrValue.value); + break; + } + case 'LogicalExpression': { + yield* eachReactiveValueOperand(instrValue.left); + yield* eachReactiveValueOperand(instrValue.right); + break; + } + case 'SequenceExpression': { + for (const instr of instrValue.instructions) { + yield* eachReactiveValueOperand(instr.value); + } + yield* eachReactiveValueOperand(instrValue.value); + break; + } + case 'ConditionalExpression': { + yield* eachReactiveValueOperand(instrValue.test); + yield* eachReactiveValueOperand(instrValue.consequent); + yield* eachReactiveValueOperand(instrValue.alternate); + break; + } + default: { + yield* eachInstructionValueOperand(instrValue); + } + } +} + +function assertScopeInstructionsWithinScopes(fn) { + const existingScopes = new Set(); + visitReactiveFunction(fn, new FindAllScopesVisitor(), existingScopes); + visitReactiveFunction(fn, new CheckInstructionsAgainstScopesVisitor(), existingScopes); +} +class FindAllScopesVisitor extends ReactiveFunctionVisitor { + visitScope(block, state) { + this.traverseScope(block, state); + state.add(block.scope.id); + } +} +class CheckInstructionsAgainstScopesVisitor extends ReactiveFunctionVisitor { + constructor() { + super(...arguments); + this.activeScopes = new Set(); + } + visitPlace(id, place, state) { + const scope = getPlaceScope(id, place); + if (scope !== null && + state.has(scope.id) && + !this.activeScopes.has(scope.id)) { + CompilerError.invariant(false, { + reason: 'Encountered an instruction that should be part of a scope, but where that scope has already completed', + description: `Instruction [${id}] is part of scope @${scope.id}, but that scope has already completed`, + loc: place.loc, + }); + } + } + visitScope(block, state) { + this.activeScopes.add(block.scope.id); + this.traverseScope(block, state); + this.activeScopes.delete(block.scope.id); + } +} + +function assertWellFormedBreakTargets(fn) { + visitReactiveFunction(fn, new Visitor$8(), new Set()); +} +let Visitor$8 = class Visitor extends ReactiveFunctionVisitor { + visitTerminal(stmt, seenLabels) { + if (stmt.label != null) { + seenLabels.add(stmt.label.id); + } + const terminal = stmt.terminal; + if (terminal.kind === 'break' || terminal.kind === 'continue') { + CompilerError.invariant(seenLabels.has(terminal.target), { + reason: 'Unexpected break to invalid label', + loc: stmt.terminal.loc, + }); + } + } +}; + +var _Context_nextScheduleId, _Context_scheduled, _Context_catchHandlers, _Context_controlFlowStack; +function buildReactiveFunction(fn) { + const cx = new Context$2(fn.body); + const driver = new Driver(cx); + const body = driver.traverseBlock(cx.block(fn.body.entry)); + return { + loc: fn.loc, + id: fn.id, + nameHint: fn.nameHint, + params: fn.params, + generator: fn.generator, + async: fn.async, + body, + env: fn.env, + directives: fn.directives, + }; +} +class Driver { + constructor(cx) { + this.cx = cx; + } + wrapWithSequence(instructions, continuation, loc) { + if (instructions.length === 0) { + return continuation; + } + const sequence = { + kind: 'SequenceExpression', + instructions, + id: continuation.id, + value: continuation.value, + loc, + }; + return { + block: continuation.block, + value: sequence, + place: continuation.place, + id: continuation.id, + }; + } + extractValueBlockResult(instructions, blockId, loc) { + CompilerError.invariant(instructions.length !== 0, { + reason: `Expected non-empty instructions in extractValueBlockResult`, + description: null, + loc, + }); + const instr = instructions.at(-1); + let place = instr.lvalue; + let value = instr.value; + if (value.kind === 'StoreLocal' && + value.lvalue.place.identifier.name === null) { + place = value.lvalue.place; + value = { + kind: 'LoadLocal', + place: value.value, + loc: value.value.loc, + }; + } + if (instructions.length === 1) { + return { block: blockId, place, value, id: instr.id }; + } + const sequence = { + kind: 'SequenceExpression', + instructions: instructions.slice(0, -1), + id: instr.id, + value, + loc, + }; + return { block: blockId, place, value: sequence, id: instr.id }; + } + valueBlockResultToSequence(result, loc) { + const instructions = []; + let innerValue = result.value; + while (innerValue.kind === 'SequenceExpression') { + instructions.push(...innerValue.instructions); + innerValue = innerValue.value; + } + const isLoadOfSamePlace = innerValue.kind === 'LoadLocal' && + innerValue.place.identifier.id === result.place.identifier.id; + if (!isLoadOfSamePlace) { + instructions.push({ + id: result.id, + lvalue: result.place, + value: innerValue, + loc, + }); + } + return { + kind: 'SequenceExpression', + instructions, + id: result.id, + value: { kind: 'Primitive', value: undefined, loc }, + loc, + }; + } + traverseBlock(block) { + const blockValue = []; + this.visitBlock(block, blockValue); + return blockValue; + } + visitBlock(block, blockValue) { + var _a; + CompilerError.invariant(!this.cx.emitted.has(block.id), { + reason: `Cannot emit the same block twice: bb${block.id}`, + loc: GeneratedSource, + }); + this.cx.emitted.add(block.id); + for (const instruction of block.instructions) { + blockValue.push({ + kind: 'instruction', + instruction, + }); + } + const terminal = block.terminal; + const scheduleIds = []; + switch (terminal.kind) { + case 'return': { + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'return', + loc: terminal.loc, + value: terminal.value, + id: terminal.id, + }, + label: null, + }); + break; + } + case 'throw': { + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'throw', + loc: terminal.loc, + value: terminal.value, + id: terminal.id, + }, + label: null, + }); + break; + } + case 'if': { + const fallthroughId = this.cx.reachable(terminal.fallthrough) && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const alternateId = terminal.alternate !== terminal.fallthrough + ? terminal.alternate + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'if'); + scheduleIds.push(scheduleId); + } + let consequent = null; + if (this.cx.isScheduled(terminal.consequent)) { + CompilerError.invariant(false, { + reason: `Unexpected 'if' where the consequent is already scheduled`, + loc: terminal.loc, + }); + } + else { + consequent = this.traverseBlock(this.cx.ir.blocks.get(terminal.consequent)); + } + let alternate = null; + if (alternateId !== null) { + if (this.cx.isScheduled(alternateId)) { + CompilerError.invariant(false, { + reason: `Unexpected 'if' where the alternate is already scheduled`, + loc: terminal.loc, + }); + } + else { + alternate = this.traverseBlock(this.cx.ir.blocks.get(alternateId)); + } + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'if', + loc: terminal.loc, + test: terminal.test, + consequent: consequent !== null && consequent !== void 0 ? consequent : this.emptyBlock(), + alternate: alternate, + id: terminal.id, + }, + label: fallthroughId == null + ? null + : { + id: fallthroughId, + implicit: false, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'switch': { + const fallthroughId = this.cx.reachable(terminal.fallthrough) && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'switch'); + scheduleIds.push(scheduleId); + } + const cases = []; + [...terminal.cases].reverse().forEach((case_, _index) => { + const test = case_.test; + let consequent; + if (this.cx.isScheduled(case_.block)) { + CompilerError.invariant(case_.block === terminal.fallthrough, { + reason: `Unexpected 'switch' where a case is already scheduled and block is not the fallthrough`, + loc: terminal.loc, + }); + return; + } + else { + consequent = this.traverseBlock(this.cx.ir.blocks.get(case_.block)); + const scheduleId = this.cx.schedule(case_.block, 'case'); + scheduleIds.push(scheduleId); + } + cases.push({ test, block: consequent }); + }); + cases.reverse(); + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'switch', + loc: terminal.loc, + test: terminal.test, + cases, + id: terminal.id, + }, + label: fallthroughId == null + ? null + : { + id: fallthroughId, + implicit: false, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'do-while': { + const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const loopId = !this.cx.isScheduled(terminal.loop) && + terminal.loop !== terminal.fallthrough + ? terminal.loop + : null; + const scheduleId = this.cx.scheduleLoop(terminal.fallthrough, terminal.test, terminal.loop); + scheduleIds.push(scheduleId); + let loopBody; + if (loopId) { + loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); + } + else { + CompilerError.invariant(false, { + reason: `Unexpected 'do-while' where the loop is already scheduled`, + loc: terminal.loc, + }); + } + const testValue = this.visitValueBlock(terminal.test, terminal.loc).value; + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'do-while', + loc: terminal.loc, + test: testValue, + loop: loopBody, + id: terminal.id, + }, + label: fallthroughId == null + ? null + : { + id: fallthroughId, + implicit: false, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'while': { + const fallthroughId = this.cx.reachable(terminal.fallthrough) && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const loopId = !this.cx.isScheduled(terminal.loop) && + terminal.loop !== terminal.fallthrough + ? terminal.loop + : null; + const scheduleId = this.cx.scheduleLoop(terminal.fallthrough, terminal.test, terminal.loop); + scheduleIds.push(scheduleId); + const testValue = this.visitValueBlock(terminal.test, terminal.loc).value; + let loopBody; + if (loopId) { + loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); + } + else { + CompilerError.invariant(false, { + reason: `Unexpected 'while' where the loop is already scheduled`, + loc: terminal.loc, + }); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'while', + loc: terminal.loc, + test: testValue, + loop: loopBody, + id: terminal.id, + }, + label: fallthroughId == null + ? null + : { + id: fallthroughId, + implicit: false, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'for': { + const loopId = !this.cx.isScheduled(terminal.loop) && + terminal.loop !== terminal.fallthrough + ? terminal.loop + : null; + const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const scheduleId = this.cx.scheduleLoop(terminal.fallthrough, (_a = terminal.update) !== null && _a !== void 0 ? _a : terminal.test, terminal.loop); + scheduleIds.push(scheduleId); + const init = this.visitValueBlock(terminal.init, terminal.loc); + const initValue = this.valueBlockResultToSequence(init, terminal.loc); + const testValue = this.visitValueBlock(terminal.test, terminal.loc).value; + const updateValue = terminal.update !== null + ? this.visitValueBlock(terminal.update, terminal.loc).value + : null; + let loopBody; + if (loopId) { + loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); + } + else { + CompilerError.invariant(false, { + reason: `Unexpected 'for' where the loop is already scheduled`, + loc: terminal.loc, + }); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'for', + loc: terminal.loc, + init: initValue, + test: testValue, + update: updateValue, + loop: loopBody, + id: terminal.id, + }, + label: fallthroughId == null ? null : { id: fallthroughId, implicit: false }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'for-of': { + const loopId = !this.cx.isScheduled(terminal.loop) && + terminal.loop !== terminal.fallthrough + ? terminal.loop + : null; + const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const scheduleId = this.cx.scheduleLoop(terminal.fallthrough, terminal.init, terminal.loop); + scheduleIds.push(scheduleId); + const init = this.visitValueBlock(terminal.init, terminal.loc); + const initValue = this.valueBlockResultToSequence(init, terminal.loc); + const test = this.visitValueBlock(terminal.test, terminal.loc); + const testValue = this.valueBlockResultToSequence(test, terminal.loc); + let loopBody; + if (loopId) { + loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); + } + else { + CompilerError.invariant(false, { + reason: `Unexpected 'for-of' where the loop is already scheduled`, + loc: terminal.loc, + }); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'for-of', + loc: terminal.loc, + init: initValue, + test: testValue, + loop: loopBody, + id: terminal.id, + }, + label: fallthroughId == null ? null : { id: fallthroughId, implicit: false }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'for-in': { + const loopId = !this.cx.isScheduled(terminal.loop) && + terminal.loop !== terminal.fallthrough + ? terminal.loop + : null; + const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const scheduleId = this.cx.scheduleLoop(terminal.fallthrough, terminal.init, terminal.loop); + scheduleIds.push(scheduleId); + const init = this.visitValueBlock(terminal.init, terminal.loc); + const initValue = this.valueBlockResultToSequence(init, terminal.loc); + let loopBody; + if (loopId) { + loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); + } + else { + CompilerError.invariant(false, { + reason: `Unexpected 'for-in' where the loop is already scheduled`, + loc: terminal.loc, + }); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'for-in', + loc: terminal.loc, + init: initValue, + loop: loopBody, + id: terminal.id, + }, + label: fallthroughId == null ? null : { id: fallthroughId, implicit: false }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'branch': { + let consequent = null; + if (this.cx.isScheduled(terminal.consequent)) { + const break_ = this.visitBreak(terminal.consequent, terminal.id, terminal.loc); + if (break_ !== null) { + consequent = [break_]; + } + } + else { + consequent = this.traverseBlock(this.cx.ir.blocks.get(terminal.consequent)); + } + let alternate = null; + if (this.cx.isScheduled(terminal.alternate)) { + CompilerError.invariant(false, { + reason: `Unexpected 'branch' where the alternate is already scheduled`, + loc: terminal.loc, + }); + } + else { + alternate = this.traverseBlock(this.cx.ir.blocks.get(terminal.alternate)); + } + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'if', + loc: terminal.loc, + test: terminal.test, + consequent: consequent !== null && consequent !== void 0 ? consequent : this.emptyBlock(), + alternate: alternate, + id: terminal.id, + }, + label: null, + }); + break; + } + case 'label': { + const fallthroughId = this.cx.reachable(terminal.fallthrough) && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'if'); + scheduleIds.push(scheduleId); + } + let block; + if (this.cx.isScheduled(terminal.block)) { + CompilerError.invariant(false, { + reason: `Unexpected 'label' where the block is already scheduled`, + loc: terminal.loc, + }); + } + else { + block = this.traverseBlock(this.cx.ir.blocks.get(terminal.block)); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'label', + loc: terminal.loc, + block, + id: terminal.id, + }, + label: fallthroughId == null ? null : { id: fallthroughId, implicit: false }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'sequence': + case 'optional': + case 'ternary': + case 'logical': { + const fallthroughId = terminal.fallthrough !== null && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'if'); + scheduleIds.push(scheduleId); + } + const { place, value } = this.visitValueBlockTerminal(terminal); + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'instruction', + instruction: { + id: terminal.id, + lvalue: place, + value, + loc: terminal.loc, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'goto': { + switch (terminal.variant) { + case GotoVariant.Break: { + const break_ = this.visitBreak(terminal.block, terminal.id, terminal.loc); + if (break_ !== null) { + blockValue.push(break_); + } + break; + } + case GotoVariant.Continue: { + const continue_ = this.visitContinue(terminal.block, terminal.id, terminal.loc); + if (continue_ !== null) { + blockValue.push(continue_); + } + break; + } + case GotoVariant.Try: { + break; + } + default: { + assertExhaustive$1(terminal.variant, `Unexpected goto variant \`${terminal.variant}\``); + } + } + break; + } + case 'maybe-throw': { + if (!this.cx.isScheduled(terminal.continuation)) { + this.visitBlock(this.cx.ir.blocks.get(terminal.continuation), blockValue); + } + break; + } + case 'try': { + const fallthroughId = this.cx.reachable(terminal.fallthrough) && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'if'); + scheduleIds.push(scheduleId); + } + this.cx.scheduleCatchHandler(terminal.handler); + const block = this.traverseBlock(this.cx.ir.blocks.get(terminal.block)); + const handler = this.traverseBlock(this.cx.ir.blocks.get(terminal.handler)); + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + label: fallthroughId == null ? null : { id: fallthroughId, implicit: false }, + terminal: { + kind: 'try', + loc: terminal.loc, + block, + handlerBinding: terminal.handlerBinding, + handler, + id: terminal.id, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'pruned-scope': + case 'scope': { + const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'if'); + scheduleIds.push(scheduleId); + this.cx.scopeFallthroughs.add(fallthroughId); + } + let block; + if (this.cx.isScheduled(terminal.block)) { + CompilerError.invariant(false, { + reason: `Unexpected 'scope' where the block is already scheduled`, + loc: terminal.loc, + }); + } + else { + block = this.traverseBlock(this.cx.ir.blocks.get(terminal.block)); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: terminal.kind, + instructions: block, + scope: terminal.scope, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'unreachable': { + break; + } + case 'unsupported': { + CompilerError.invariant(false, { + reason: 'Unexpected unsupported terminal', + loc: terminal.loc, + }); + } + default: { + assertExhaustive$1(terminal, 'Unexpected terminal'); + } + } + } + visitValueBlock(blockId, loc, fallthrough = null) { + const block = this.cx.ir.blocks.get(blockId); + if (fallthrough !== null && blockId === fallthrough) { + CompilerError.invariant(false, { + reason: 'Did not expect to reach the fallthrough of a value block', + description: `Reached bb${blockId}, which is the fallthrough for this value block`, + loc, + }); + } + if (block.terminal.kind === 'branch') { + if (block.instructions.length === 0) { + return { + block: block.id, + place: block.terminal.test, + value: { + kind: 'LoadLocal', + place: block.terminal.test, + loc: block.terminal.test.loc, + }, + id: block.terminal.id, + }; + } + return this.extractValueBlockResult(block.instructions, block.id, loc); + } + else if (block.terminal.kind === 'goto') { + if (block.instructions.length === 0) { + CompilerError.invariant(false, { + reason: 'Unexpected empty block with `goto` terminal', + description: `Block bb${block.id} is empty`, + loc, + }); + } + return this.extractValueBlockResult(block.instructions, block.id, loc); + } + else if (block.terminal.kind === 'maybe-throw') { + const continuationId = block.terminal.continuation; + const continuationBlock = this.cx.ir.blocks.get(continuationId); + if (continuationBlock.instructions.length === 0 && + continuationBlock.terminal.kind === 'goto') { + return this.extractValueBlockResult(block.instructions, continuationBlock.id, loc); + } + const continuation = this.visitValueBlock(continuationId, loc, fallthrough); + return this.wrapWithSequence(block.instructions, continuation, loc); + } + else { + const init = this.visitValueBlockTerminal(block.terminal); + const final = this.visitValueBlock(init.fallthrough, loc); + return this.wrapWithSequence([ + ...block.instructions, + { id: init.id, loc, lvalue: init.place, value: init.value }, + ], final, loc); + } + } + visitTestBlock(testBlockId, loc, terminalKind) { + const test = this.visitValueBlock(testBlockId, loc); + const testBlock = this.cx.ir.blocks.get(test.block); + if (testBlock.terminal.kind !== 'branch') { + CompilerError.invariant(false, { + reason: `Expected a branch terminal for ${terminalKind} test block`, + description: `Got \`${testBlock.terminal.kind}\``, + loc: testBlock.terminal.loc, + }); + } + return { + test, + branch: { + consequent: testBlock.terminal.consequent, + alternate: testBlock.terminal.alternate, + loc: testBlock.terminal.loc, + }, + }; + } + visitValueBlockTerminal(terminal) { + switch (terminal.kind) { + case 'sequence': { + const block = this.visitValueBlock(terminal.block, terminal.loc, terminal.fallthrough); + return { + value: block.value, + place: block.place, + fallthrough: terminal.fallthrough, + id: terminal.id, + }; + } + case 'optional': { + const { test, branch } = this.visitTestBlock(terminal.test, terminal.loc, 'optional'); + const consequent = this.visitValueBlock(branch.consequent, terminal.loc, terminal.fallthrough); + const call = { + kind: 'SequenceExpression', + instructions: [ + { + id: test.id, + loc: branch.loc, + lvalue: test.place, + value: test.value, + }, + ], + id: consequent.id, + value: consequent.value, + loc: terminal.loc, + }; + return { + place: Object.assign({}, consequent.place), + value: { + kind: 'OptionalExpression', + optional: terminal.optional, + value: call, + id: terminal.id, + loc: terminal.loc, + }, + fallthrough: terminal.fallthrough, + id: terminal.id, + }; + } + case 'logical': { + const { test, branch } = this.visitTestBlock(terminal.test, terminal.loc, 'logical'); + const leftFinal = this.visitValueBlock(branch.consequent, terminal.loc, terminal.fallthrough); + const left = { + kind: 'SequenceExpression', + instructions: [ + { + id: test.id, + loc: terminal.loc, + lvalue: test.place, + value: test.value, + }, + ], + id: leftFinal.id, + value: leftFinal.value, + loc: terminal.loc, + }; + const right = this.visitValueBlock(branch.alternate, terminal.loc, terminal.fallthrough); + const value = { + kind: 'LogicalExpression', + operator: terminal.operator, + left: left, + right: right.value, + loc: terminal.loc, + }; + return { + place: Object.assign({}, leftFinal.place), + value, + fallthrough: terminal.fallthrough, + id: terminal.id, + }; + } + case 'ternary': { + const { test, branch } = this.visitTestBlock(terminal.test, terminal.loc, 'ternary'); + const consequent = this.visitValueBlock(branch.consequent, terminal.loc, terminal.fallthrough); + const alternate = this.visitValueBlock(branch.alternate, terminal.loc, terminal.fallthrough); + const value = { + kind: 'ConditionalExpression', + test: test.value, + consequent: consequent.value, + alternate: alternate.value, + loc: terminal.loc, + }; + return { + place: Object.assign({}, consequent.place), + value, + fallthrough: terminal.fallthrough, + id: terminal.id, + }; + } + case 'maybe-throw': { + CompilerError.invariant(false, { + reason: `Unexpected maybe-throw in visitValueBlockTerminal - should be handled in visitValueBlock`, + description: null, + loc: terminal.loc, + }); + } + case 'label': { + CompilerError.throwTodo({ + reason: `Support labeled statements combined with value blocks (conditional, logical, optional chaining, etc)`, + description: null, + loc: terminal.loc, + suggestions: null, + }); + } + default: { + CompilerError.throwTodo({ + reason: `Support \`${terminal.kind}\` as a value block terminal (conditional, logical, optional chaining, etc)`, + description: null, + loc: terminal.loc, + suggestions: null, + }); + } + } + } + emptyBlock() { + return []; + } + visitBreak(block, id, loc) { + const target = this.cx.getBreakTarget(block); + if (target === null) { + CompilerError.invariant(false, { + reason: 'Expected a break target', + loc: GeneratedSource, + }); + } + if (this.cx.scopeFallthroughs.has(target.block)) { + CompilerError.invariant(target.type === 'implicit', { + reason: 'Expected reactive scope to implicitly break to fallthrough', + loc, + }); + return null; + } + return { + kind: 'terminal', + terminal: { + kind: 'break', + loc, + target: target.block, + id, + targetKind: target.type, + }, + label: null, + }; + } + visitContinue(block, id, loc) { + const target = this.cx.getContinueTarget(block); + CompilerError.invariant(target !== null, { + reason: `Expected continue target to be scheduled for bb${block}`, + loc: GeneratedSource, + }); + return { + kind: 'terminal', + terminal: { + kind: 'continue', + loc, + target: target.block, + id, + targetKind: target.type, + }, + label: null, + }; + } +} +let Context$2 = class Context { + constructor(ir) { + _Context_nextScheduleId.set(this, 0); + this.emitted = new Set(); + this.scopeFallthroughs = new Set(); + _Context_scheduled.set(this, new Set()); + _Context_catchHandlers.set(this, new Set()); + _Context_controlFlowStack.set(this, []); + this.ir = ir; + } + block(id) { + return this.ir.blocks.get(id); + } + scheduleCatchHandler(block) { + __classPrivateFieldGet(this, _Context_catchHandlers, "f").add(block); + } + reachable(id) { + const block = this.ir.blocks.get(id); + return block.terminal.kind !== 'unreachable'; + } + schedule(block, type) { + var _a, _b; + const id = (__classPrivateFieldSet(this, _Context_nextScheduleId, (_b = __classPrivateFieldGet(this, _Context_nextScheduleId, "f"), _a = _b++, _b), "f"), _a); + CompilerError.invariant(!__classPrivateFieldGet(this, _Context_scheduled, "f").has(block), { + reason: `Break block is already scheduled: bb${block}`, + loc: GeneratedSource, + }); + __classPrivateFieldGet(this, _Context_scheduled, "f").add(block); + __classPrivateFieldGet(this, _Context_controlFlowStack, "f").push({ block, id, type }); + return id; + } + scheduleLoop(fallthroughBlock, continueBlock, loopBlock) { + var _a, _b; + const id = (__classPrivateFieldSet(this, _Context_nextScheduleId, (_b = __classPrivateFieldGet(this, _Context_nextScheduleId, "f"), _a = _b++, _b), "f"), _a); + const ownsBlock = !__classPrivateFieldGet(this, _Context_scheduled, "f").has(fallthroughBlock); + __classPrivateFieldGet(this, _Context_scheduled, "f").add(fallthroughBlock); + CompilerError.invariant(!__classPrivateFieldGet(this, _Context_scheduled, "f").has(continueBlock), { + reason: `Continue block is already scheduled: bb${continueBlock}`, + loc: GeneratedSource, + }); + __classPrivateFieldGet(this, _Context_scheduled, "f").add(continueBlock); + let ownsLoop = false; + if (loopBlock !== null) { + ownsLoop = !__classPrivateFieldGet(this, _Context_scheduled, "f").has(loopBlock); + __classPrivateFieldGet(this, _Context_scheduled, "f").add(loopBlock); + } + __classPrivateFieldGet(this, _Context_controlFlowStack, "f").push({ + block: fallthroughBlock, + ownsBlock, + id, + type: 'loop', + continueBlock, + loopBlock, + ownsLoop, + }); + return id; + } + unschedule(scheduleId) { + const last = __classPrivateFieldGet(this, _Context_controlFlowStack, "f").pop(); + CompilerError.invariant(last !== undefined && last.id === scheduleId, { + reason: 'Can only unschedule the last target', + loc: GeneratedSource, + }); + if (last.type !== 'loop' || last.ownsBlock !== null) { + __classPrivateFieldGet(this, _Context_scheduled, "f").delete(last.block); + } + if (last.type === 'loop') { + __classPrivateFieldGet(this, _Context_scheduled, "f").delete(last.continueBlock); + if (last.ownsLoop && last.loopBlock !== null) { + __classPrivateFieldGet(this, _Context_scheduled, "f").delete(last.loopBlock); + } + } + } + unscheduleAll(scheduleIds) { + for (let i = scheduleIds.length - 1; i >= 0; i--) { + this.unschedule(scheduleIds[i]); + } + } + isScheduled(block) { + return __classPrivateFieldGet(this, _Context_scheduled, "f").has(block) || __classPrivateFieldGet(this, _Context_catchHandlers, "f").has(block); + } + getBreakTarget(block) { + let hasPrecedingLoop = false; + for (let i = __classPrivateFieldGet(this, _Context_controlFlowStack, "f").length - 1; i >= 0; i--) { + const target = __classPrivateFieldGet(this, _Context_controlFlowStack, "f")[i]; + if (target.block === block) { + let type; + if (target.type === 'loop') { + type = hasPrecedingLoop ? 'labeled' : 'unlabeled'; + } + else if (i === __classPrivateFieldGet(this, _Context_controlFlowStack, "f").length - 1) { + type = 'implicit'; + } + else { + type = 'labeled'; + } + return { + block: target.block, + type, + }; + } + hasPrecedingLoop || (hasPrecedingLoop = target.type === 'loop'); + } + CompilerError.invariant(false, { + reason: 'Expected a break target', + loc: GeneratedSource, + }); + } + getContinueTarget(block) { + let hasPrecedingLoop = false; + for (let i = __classPrivateFieldGet(this, _Context_controlFlowStack, "f").length - 1; i >= 0; i--) { + const target = __classPrivateFieldGet(this, _Context_controlFlowStack, "f")[i]; + if (target.type == 'loop' && target.continueBlock === block) { + let type; + if (hasPrecedingLoop) { + type = 'labeled'; + } + else if (i === __classPrivateFieldGet(this, _Context_controlFlowStack, "f").length - 1) { + type = 'implicit'; + } + else { + type = 'unlabeled'; + } + return { + block: target.block, + type, + }; + } + hasPrecedingLoop || (hasPrecedingLoop = target.type === 'loop'); + } + return null; + } + debugBreakTargets() { + return __classPrivateFieldGet(this, _Context_controlFlowStack, "f").map(target => (Object.assign({}, target))); + } +}; +_Context_nextScheduleId = new WeakMap(), _Context_scheduled = new WeakMap(), _Context_catchHandlers = new WeakMap(), _Context_controlFlowStack = new WeakMap(); + +var GuardKind; +(function (GuardKind) { + GuardKind[GuardKind["PushHookGuard"] = 0] = "PushHookGuard"; + GuardKind[GuardKind["PopHookGuard"] = 1] = "PopHookGuard"; + GuardKind[GuardKind["AllowHook"] = 2] = "AllowHook"; + GuardKind[GuardKind["DisallowHook"] = 3] = "DisallowHook"; +})(GuardKind || (GuardKind = {})); + +var InlineLevel; +(function (InlineLevel) { + InlineLevel["Transitive"] = "Transitive"; + InlineLevel["Shallow"] = "Shallow"; +})(InlineLevel || (InlineLevel = {})); +const SHALLOW_MACRO = { + level: InlineLevel.Shallow, + properties: null, +}; +const TRANSITIVE_MACRO = { + level: InlineLevel.Transitive, + properties: null, +}; +const FBT_MACRO = { + level: InlineLevel.Transitive, + properties: new Map([['*', SHALLOW_MACRO]]), +}; +FBT_MACRO.properties.set('enum', FBT_MACRO); +function memoizeFbtAndMacroOperandsInSameScope(fn) { + var _a; + const macroKinds = new Map([ + ...Array.from(FBT_TAGS.entries()), + ...((_a = fn.env.config.customMacros) !== null && _a !== void 0 ? _a : []).map(name => [name, TRANSITIVE_MACRO]), + ]); + const macroTags = populateMacroTags(fn, macroKinds); + const macroValues = mergeMacroArguments(fn, macroTags, macroKinds); + return macroValues; +} +const FBT_TAGS = new Map([ + ['fbt', FBT_MACRO], + ['fbt:param', SHALLOW_MACRO], + ['fbt:enum', FBT_MACRO], + ['fbt:plural', SHALLOW_MACRO], + ['fbs', FBT_MACRO], + ['fbs:param', SHALLOW_MACRO], + ['fbs:enum', FBT_MACRO], + ['fbs:plural', SHALLOW_MACRO], +]); +const SINGLE_CHILD_FBT_TAGS = new Set([ + 'fbt:param', + 'fbs:param', +]); +function populateMacroTags(fn, macroKinds) { + var _a; + const macroTags = new Map(); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'Primitive': { + if (typeof value.value === 'string') { + const macroDefinition = macroKinds.get(value.value); + if (macroDefinition != null) { + macroTags.set(lvalue.identifier.id, macroDefinition); + } + } + break; + } + case 'LoadGlobal': { + let macroDefinition = macroKinds.get(value.binding.name); + if (macroDefinition != null) { + macroTags.set(lvalue.identifier.id, macroDefinition); + } + break; + } + case 'PropertyLoad': { + if (typeof value.property === 'string') { + const macroDefinition = macroTags.get(value.object.identifier.id); + if (macroDefinition != null) { + const propertyDefinition = macroDefinition.properties != null + ? ((_a = macroDefinition.properties.get(value.property)) !== null && _a !== void 0 ? _a : macroDefinition.properties.get('*')) + : null; + const propertyMacro = propertyDefinition !== null && propertyDefinition !== void 0 ? propertyDefinition : macroDefinition; + macroTags.set(lvalue.identifier.id, propertyMacro); + } + } + break; + } + } + } + } + return macroTags; +} +function mergeMacroArguments(fn, macroTags, macroKinds) { + var _a; + const macroValues = new Set(macroTags.keys()); + for (const block of Array.from(fn.body.blocks.values()).reverse()) { + for (let i = block.instructions.length - 1; i >= 0; i--) { + const instr = block.instructions[i]; + const { lvalue, value } = instr; + switch (value.kind) { + case 'DeclareContext': + case 'DeclareLocal': + case 'Destructure': + case 'LoadContext': + case 'LoadLocal': + case 'PostfixUpdate': + case 'PrefixUpdate': + case 'StoreContext': + case 'StoreLocal': { + break; + } + case 'CallExpression': + case 'MethodCall': { + const scope = lvalue.identifier.scope; + if (scope == null) { + continue; + } + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + const macroDefinition = (_a = macroTags.get(callee.identifier.id)) !== null && _a !== void 0 ? _a : macroTags.get(lvalue.identifier.id); + if (macroDefinition != null) { + visitOperands(macroDefinition, scope, lvalue, value, macroValues, macroTags); + } + break; + } + case 'JsxExpression': { + const scope = lvalue.identifier.scope; + if (scope == null) { + continue; + } + let macroDefinition; + if (value.tag.kind === 'Identifier') { + macroDefinition = macroTags.get(value.tag.identifier.id); + } + else { + macroDefinition = macroKinds.get(value.tag.name); + } + macroDefinition !== null && macroDefinition !== void 0 ? macroDefinition : (macroDefinition = macroTags.get(lvalue.identifier.id)); + if (macroDefinition != null) { + visitOperands(macroDefinition, scope, lvalue, value, macroValues, macroTags); + } + break; + } + default: { + const scope = lvalue.identifier.scope; + if (scope == null) { + continue; + } + const macroDefinition = macroTags.get(lvalue.identifier.id); + if (macroDefinition != null) { + visitOperands(macroDefinition, scope, lvalue, value, macroValues, macroTags); + } + break; + } + } + } + for (const phi of block.phis) { + const scope = phi.place.identifier.scope; + if (scope == null) { + continue; + } + const macroDefinition = macroTags.get(phi.place.identifier.id); + if (macroDefinition == null || + macroDefinition.level === InlineLevel.Shallow) { + continue; + } + macroValues.add(phi.place.identifier.id); + for (const operand of phi.operands.values()) { + operand.identifier.scope = scope; + expandFbtScopeRange(scope.range, operand.identifier.mutableRange); + macroTags.set(operand.identifier.id, macroDefinition); + macroValues.add(operand.identifier.id); + } + } + } + return macroValues; +} +function expandFbtScopeRange(fbtRange, extendWith) { + if (extendWith.start !== 0) { + fbtRange.start = makeInstructionId(Math.min(fbtRange.start, extendWith.start)); + } +} +function visitOperands(macroDefinition, scope, lvalue, value, macroValues, macroTags) { + macroValues.add(lvalue.identifier.id); + for (const operand of eachInstructionValueOperand(value)) { + if (macroDefinition.level === InlineLevel.Transitive) { + operand.identifier.scope = scope; + expandFbtScopeRange(scope.range, operand.identifier.mutableRange); + macroTags.set(operand.identifier.id, macroDefinition); + } + macroValues.add(operand.identifier.id); + } +} + +var _Context_nextCacheIndex, _Context_declarations; +const MEMO_CACHE_SENTINEL = 'react.memo_cache_sentinel'; +const EARLY_RETURN_SENTINEL = 'react.early_return_sentinel'; +function codegenFunction(fn, { uniqueIdentifiers, fbtOperands, }) { + var _a, _b, _c; + const cx = new Context$1(fn.env, (_a = fn.id) !== null && _a !== void 0 ? _a : '[[ anonymous ]]', uniqueIdentifiers, fbtOperands, null); + let fastRefreshState = null; + if (fn.env.config.enableResetCacheOnSourceFileChanges && + fn.env.code !== null) { + const hash = crypto.createHmac('sha256', fn.env.code).digest('hex'); + fastRefreshState = { + cacheIndex: cx.nextCacheIndex, + hash, + }; + } + const compiled = codegenReactiveFunction(cx, fn); + const hookGuard = fn.env.config.enableEmitHookGuards; + if (hookGuard != null && fn.env.outputMode === 'client') { + compiled.body = libExports$1.blockStatement([ + createHookGuard(hookGuard, fn.env.programContext, compiled.body.body, GuardKind.PushHookGuard, GuardKind.PopHookGuard), + ]); + } + const cacheCount = compiled.memoSlotsUsed; + if (cacheCount !== 0) { + const preface = []; + const useMemoCacheIdentifier = fn.env.programContext.addMemoCacheImport().name; + preface.push(libExports$1.variableDeclaration('const', [ + libExports$1.variableDeclarator(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.callExpression(libExports$1.identifier(useMemoCacheIdentifier), [ + libExports$1.numericLiteral(cacheCount), + ])), + ])); + if (fastRefreshState !== null) { + const index = cx.synthesizeName('$i'); + preface.push(libExports$1.ifStatement(libExports$1.binaryExpression('!==', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(fastRefreshState.cacheIndex), true), libExports$1.stringLiteral(fastRefreshState.hash)), libExports$1.blockStatement([ + libExports$1.forStatement(libExports$1.variableDeclaration('let', [ + libExports$1.variableDeclarator(libExports$1.identifier(index), libExports$1.numericLiteral(0)), + ]), libExports$1.binaryExpression('<', libExports$1.identifier(index), libExports$1.numericLiteral(cacheCount)), libExports$1.assignmentExpression('+=', libExports$1.identifier(index), libExports$1.numericLiteral(1)), libExports$1.blockStatement([ + libExports$1.expressionStatement(libExports$1.assignmentExpression('=', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.identifier(index), true), libExports$1.callExpression(libExports$1.memberExpression(libExports$1.identifier('Symbol'), libExports$1.identifier('for')), [libExports$1.stringLiteral(MEMO_CACHE_SENTINEL)]))), + ])), + libExports$1.expressionStatement(libExports$1.assignmentExpression('=', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(fastRefreshState.cacheIndex), true), libExports$1.stringLiteral(fastRefreshState.hash))), + ]))); + } + compiled.body.body.unshift(...preface); + } + const emitInstrumentForget = fn.env.config.enableEmitInstrumentForget; + if (emitInstrumentForget != null && + fn.id != null && + fn.env.outputMode === 'client') { + const gating = emitInstrumentForget.gating != null + ? libExports$1.identifier(fn.env.programContext.addImportSpecifier(emitInstrumentForget.gating).name) + : null; + const globalGating = emitInstrumentForget.globalGating != null + ? libExports$1.identifier(emitInstrumentForget.globalGating) + : null; + if (emitInstrumentForget.globalGating != null) { + const assertResult = fn.env.programContext.assertGlobalBinding(emitInstrumentForget.globalGating); + if (assertResult.isErr()) { + fn.env.recordErrors(assertResult.unwrapErr()); + } + } + let ifTest; + if (gating != null && globalGating != null) { + ifTest = libExports$1.logicalExpression('&&', globalGating, gating); + } + else if (gating != null) { + ifTest = gating; + } + else { + CompilerError.invariant(globalGating != null, { + reason: 'Bad config not caught! Expected at least one of gating or globalGating', + loc: GeneratedSource, + }); + ifTest = globalGating; + } + const instrumentFnIdentifier = fn.env.programContext.addImportSpecifier(emitInstrumentForget.fn).name; + const test = libExports$1.ifStatement(ifTest, libExports$1.expressionStatement(libExports$1.callExpression(libExports$1.identifier(instrumentFnIdentifier), [ + libExports$1.stringLiteral(fn.id), + libExports$1.stringLiteral((_b = fn.env.filename) !== null && _b !== void 0 ? _b : ''), + ]))); + compiled.body.body.unshift(test); + } + const outlined = []; + for (const { fn: outlinedFunction, type } of cx.env.getOutlinedFunctions()) { + const reactiveFunction = buildReactiveFunction(outlinedFunction); + pruneUnusedLabels(reactiveFunction); + pruneUnusedLValues(reactiveFunction); + pruneHoistedContexts(reactiveFunction); + const identifiers = renameVariables(reactiveFunction); + const codegen = codegenReactiveFunction(new Context$1(cx.env, (_c = reactiveFunction.id) !== null && _c !== void 0 ? _c : '[[ anonymous ]]', identifiers, cx.fbtOperands), reactiveFunction); + outlined.push({ fn: codegen, type }); + } + compiled.outlined = outlined; + return compiled; +} +function codegenReactiveFunction(cx, fn) { + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + cx.temp.set(place.identifier.declarationId, null); + cx.declare(place.identifier); + } + const params = fn.params.map(param => convertParameter(param)); + const body = codegenBlock(cx, fn.body); + body.directives = fn.directives.map(d => libExports$1.directive(libExports$1.directiveLiteral(d))); + const statements = body.body; + if (statements.length !== 0) { + const last = statements[statements.length - 1]; + if (last.type === 'ReturnStatement' && last.argument == null) { + statements.pop(); + } + } + const countMemoBlockVisitor = new CountMemoBlockVisitor(fn.env); + visitReactiveFunction(fn, countMemoBlockVisitor, undefined); + return { + type: 'CodegenFunction', + loc: fn.loc, + id: fn.id !== null ? libExports$1.identifier(fn.id) : null, + nameHint: fn.nameHint, + params, + body, + generator: fn.generator, + async: fn.async, + memoSlotsUsed: cx.nextCacheIndex, + memoBlocks: countMemoBlockVisitor.memoBlocks, + memoValues: countMemoBlockVisitor.memoValues, + prunedMemoBlocks: countMemoBlockVisitor.prunedMemoBlocks, + prunedMemoValues: countMemoBlockVisitor.prunedMemoValues, + outlined: [], + }; +} +class CountMemoBlockVisitor extends ReactiveFunctionVisitor { + constructor(env) { + super(); + this.memoBlocks = 0; + this.memoValues = 0; + this.prunedMemoBlocks = 0; + this.prunedMemoValues = 0; + this.env = env; + } + visitScope(scopeBlock, state) { + this.memoBlocks += 1; + this.memoValues += scopeBlock.scope.declarations.size; + this.traverseScope(scopeBlock, state); + } + visitPrunedScope(scopeBlock, state) { + this.prunedMemoBlocks += 1; + this.prunedMemoValues += scopeBlock.scope.declarations.size; + this.traversePrunedScope(scopeBlock, state); + } +} +function convertParameter(param) { + if (param.kind === 'Identifier') { + return convertIdentifier(param.identifier); + } + else { + return libExports$1.restElement(convertIdentifier(param.place.identifier)); + } +} +let Context$1 = class Context { + constructor(env, fnName, uniqueIdentifiers, fbtOperands, temporaries = null) { + _Context_nextCacheIndex.set(this, 0); + _Context_declarations.set(this, new Set()); + this.objectMethods = new Map(); + this.synthesizedNames = new Map(); + this.env = env; + this.fnName = fnName; + this.uniqueIdentifiers = uniqueIdentifiers; + this.fbtOperands = fbtOperands; + this.temp = temporaries !== null ? new Map(temporaries) : new Map(); + } + recordError(error) { + this.env.recordError(error); + } + get nextCacheIndex() { + var _a, _b; + return __classPrivateFieldSet(this, _Context_nextCacheIndex, (_b = __classPrivateFieldGet(this, _Context_nextCacheIndex, "f"), _a = _b++, _b), "f"), _a; + } + declare(identifier) { + __classPrivateFieldGet(this, _Context_declarations, "f").add(identifier.declarationId); + } + hasDeclared(identifier) { + return __classPrivateFieldGet(this, _Context_declarations, "f").has(identifier.declarationId); + } + synthesizeName(name) { + const previous = this.synthesizedNames.get(name); + if (previous !== undefined) { + return previous; + } + let validated = makeIdentifierName(name).value; + let index = 0; + while (this.uniqueIdentifiers.has(validated)) { + validated = makeIdentifierName(`${name}${index++}`).value; + } + this.uniqueIdentifiers.add(validated); + this.synthesizedNames.set(name, validated); + return validated; + } +}; +_Context_nextCacheIndex = new WeakMap(), _Context_declarations = new WeakMap(); +function codegenBlock(cx, block) { + const temp = new Map(cx.temp); + const result = codegenBlockNoReset(cx, block); + for (const [key, value] of cx.temp) { + if (!temp.has(key)) { + continue; + } + CompilerError.invariant(temp.get(key) === value, { + reason: 'Expected temporary value to be unchanged', + loc: GeneratedSource, + }); + } + cx.temp = temp; + return result; +} +function codegenBlockNoReset(cx, block) { + const statements = []; + for (const item of block) { + switch (item.kind) { + case 'instruction': { + const statement = codegenInstructionNullable(cx, item.instruction); + if (statement !== null) { + statements.push(statement); + } + break; + } + case 'pruned-scope': { + const scopeBlock = codegenBlockNoReset(cx, item.instructions); + statements.push(...scopeBlock.body); + break; + } + case 'scope': { + const temp = new Map(cx.temp); + codegenReactiveScope(cx, statements, item.scope, item.instructions); + cx.temp = temp; + break; + } + case 'terminal': { + const statement = codegenTerminal(cx, item.terminal); + if (statement === null) { + break; + } + if (item.label !== null && !item.label.implicit) { + const block = statement.type === 'BlockStatement' && statement.body.length === 1 + ? statement.body[0] + : statement; + statements.push(libExports$1.labeledStatement(libExports$1.identifier(codegenLabel(item.label.id)), block)); + } + else if (statement.type === 'BlockStatement') { + statements.push(...statement.body); + } + else { + statements.push(statement); + } + break; + } + default: { + assertExhaustive$1(item, `Unexpected item kind \`${item.kind}\``); + } + } + } + return libExports$1.blockStatement(statements); +} +function codegenReactiveScope(cx, statements, scope, block) { + const cacheStoreStatements = []; + const cacheLoadStatements = []; + const cacheLoads = []; + const changeExpressions = []; + for (const dep of [...scope.dependencies].sort(compareScopeDependency)) { + const index = cx.nextCacheIndex; + const comparison = libExports$1.binaryExpression('!==', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(index), true), codegenDependency(cx, dep)); + changeExpressions.push(comparison); + cacheStoreStatements.push(libExports$1.expressionStatement(libExports$1.assignmentExpression('=', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(index), true), codegenDependency(cx, dep)))); + } + let firstOutputIndex = null; + for (const [, { identifier }] of [...scope.declarations].sort(([, a], [, b]) => compareScopeDeclaration(a, b))) { + const index = cx.nextCacheIndex; + if (firstOutputIndex === null) { + firstOutputIndex = index; + } + CompilerError.invariant(identifier.name != null, { + reason: `Expected scope declaration identifier to be named`, + description: `Declaration \`${printIdentifier(identifier)}\` is unnamed in scope @${scope.id}`, + loc: GeneratedSource, + }); + const name = convertIdentifier(identifier); + if (!cx.hasDeclared(identifier)) { + statements.push(libExports$1.variableDeclaration('let', [createVariableDeclarator(name, null)])); + } + cacheLoads.push({ name, index, value: name }); + cx.declare(identifier); + } + for (const reassignment of scope.reassignments) { + const index = cx.nextCacheIndex; + if (firstOutputIndex === null) { + firstOutputIndex = index; + } + const name = convertIdentifier(reassignment); + cacheLoads.push({ name, index, value: name }); + } + let testCondition = changeExpressions.reduce((acc, ident) => { + if (acc == null) { + return ident; + } + return libExports$1.logicalExpression('||', acc, ident); + }, null); + if (testCondition === null) { + CompilerError.invariant(firstOutputIndex !== null, { + reason: `Expected scope to have at least one declaration`, + description: `Scope '@${scope.id}' has no declarations`, + loc: GeneratedSource, + }); + testCondition = libExports$1.binaryExpression('===', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(firstOutputIndex), true), libExports$1.callExpression(libExports$1.memberExpression(libExports$1.identifier('Symbol'), libExports$1.identifier('for')), [libExports$1.stringLiteral(MEMO_CACHE_SENTINEL)])); + } + let computationBlock = codegenBlock(cx, block); + let memoStatement; + for (const { name, index, value } of cacheLoads) { + cacheStoreStatements.push(libExports$1.expressionStatement(libExports$1.assignmentExpression('=', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(index), true), value))); + cacheLoadStatements.push(libExports$1.expressionStatement(libExports$1.assignmentExpression('=', name, libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(index), true)))); + } + computationBlock.body.push(...cacheStoreStatements); + memoStatement = libExports$1.ifStatement(testCondition, computationBlock, libExports$1.blockStatement(cacheLoadStatements)); + statements.push(memoStatement); + const earlyReturnValue = scope.earlyReturnValue; + if (earlyReturnValue !== null) { + CompilerError.invariant(earlyReturnValue.value.name !== null && + earlyReturnValue.value.name.kind === 'named', { + reason: `Expected early return value to be promoted to a named variable`, + loc: earlyReturnValue.loc, + }); + const name = earlyReturnValue.value.name.value; + statements.push(libExports$1.ifStatement(libExports$1.binaryExpression('!==', libExports$1.identifier(name), libExports$1.callExpression(libExports$1.memberExpression(libExports$1.identifier('Symbol'), libExports$1.identifier('for')), [libExports$1.stringLiteral(EARLY_RETURN_SENTINEL)])), libExports$1.blockStatement([libExports$1.returnStatement(libExports$1.identifier(name))]))); + } +} +function codegenTerminal(cx, terminal) { + switch (terminal.kind) { + case 'break': { + if (terminal.targetKind === 'implicit') { + return null; + } + return createBreakStatement(terminal.loc, terminal.targetKind === 'labeled' + ? libExports$1.identifier(codegenLabel(terminal.target)) + : null); + } + case 'continue': { + if (terminal.targetKind === 'implicit') { + return null; + } + return createContinueStatement(terminal.loc, terminal.targetKind === 'labeled' + ? libExports$1.identifier(codegenLabel(terminal.target)) + : null); + } + case 'for': { + return createForStatement(terminal.loc, codegenForInit(cx, terminal.init), codegenInstructionValueToExpression(cx, terminal.test), terminal.update !== null + ? codegenInstructionValueToExpression(cx, terminal.update) + : null, codegenBlock(cx, terminal.loop)); + } + case 'for-in': { + CompilerError.invariant(terminal.init.kind === 'SequenceExpression', { + reason: `Expected a sequence expression init for for..in`, + description: `Got \`${terminal.init.kind}\` expression instead`, + loc: terminal.init.loc, + }); + if (terminal.init.instructions.length !== 2) { + cx.recordError(new CompilerErrorDetail({ + reason: 'Support non-trivial for..in inits', + category: ErrorCategory.Todo, + loc: terminal.init.loc, + suggestions: null, + })); + return libExports$1.emptyStatement(); + } + const iterableCollection = terminal.init.instructions[0]; + const iterableItem = terminal.init.instructions[1]; + let lval; + switch (iterableItem.value.kind) { + case 'StoreLocal': { + lval = codegenLValue(cx, iterableItem.value.lvalue.place); + break; + } + case 'Destructure': { + lval = codegenLValue(cx, iterableItem.value.lvalue.pattern); + break; + } + case 'StoreContext': { + cx.recordError(new CompilerErrorDetail({ + reason: 'Support non-trivial for..in inits', + category: ErrorCategory.Todo, + loc: terminal.init.loc, + suggestions: null, + })); + return libExports$1.emptyStatement(); + } + default: + CompilerError.invariant(false, { + reason: `Expected a StoreLocal or Destructure to be assigned to the collection`, + description: `Found ${iterableItem.value.kind}`, + loc: iterableItem.value.loc, + }); + } + let varDeclKind; + switch (iterableItem.value.lvalue.kind) { + case InstructionKind.Const: + varDeclKind = 'const'; + break; + case InstructionKind.Let: + varDeclKind = 'let'; + break; + case InstructionKind.Reassign: + CompilerError.invariant(false, { + reason: 'Destructure should never be Reassign as it would be an Object/ArrayPattern', + loc: iterableItem.loc, + }); + case InstructionKind.Catch: + case InstructionKind.HoistedConst: + case InstructionKind.HoistedLet: + case InstructionKind.HoistedFunction: + case InstructionKind.Function: + CompilerError.invariant(false, { + reason: `Unexpected ${iterableItem.value.lvalue.kind} variable in for..in collection`, + loc: iterableItem.loc, + }); + default: + assertExhaustive$1(iterableItem.value.lvalue.kind, `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}`); + } + return createForInStatement(terminal.loc, createVariableDeclaration(iterableItem.value.loc, varDeclKind, [ + libExports$1.variableDeclarator(lval, null), + ]), codegenInstructionValueToExpression(cx, iterableCollection.value), codegenBlock(cx, terminal.loop)); + } + case 'for-of': { + CompilerError.invariant(terminal.init.kind === 'SequenceExpression' && + terminal.init.instructions.length === 1 && + terminal.init.instructions[0].value.kind === 'GetIterator', { + reason: `Expected a single-expression sequence expression init for for..of`, + description: `Got \`${terminal.init.kind}\` expression instead`, + loc: terminal.init.loc, + }); + const iterableCollection = terminal.init.instructions[0].value; + CompilerError.invariant(terminal.test.kind === 'SequenceExpression', { + reason: `Expected a sequence expression test for for..of`, + description: `Got \`${terminal.init.kind}\` expression instead`, + loc: terminal.test.loc, + }); + if (terminal.test.instructions.length !== 2) { + cx.recordError(new CompilerErrorDetail({ + reason: 'Support non-trivial for..of inits', + category: ErrorCategory.Todo, + loc: terminal.init.loc, + suggestions: null, + })); + return libExports$1.emptyStatement(); + } + const iterableItem = terminal.test.instructions[1]; + let lval; + switch (iterableItem.value.kind) { + case 'StoreLocal': { + lval = codegenLValue(cx, iterableItem.value.lvalue.place); + break; + } + case 'Destructure': { + lval = codegenLValue(cx, iterableItem.value.lvalue.pattern); + break; + } + case 'StoreContext': { + cx.recordError(new CompilerErrorDetail({ + reason: 'Support non-trivial for..of inits', + category: ErrorCategory.Todo, + loc: terminal.init.loc, + suggestions: null, + })); + return libExports$1.emptyStatement(); + } + default: + CompilerError.invariant(false, { + reason: `Expected a StoreLocal or Destructure to be assigned to the collection`, + description: `Found ${iterableItem.value.kind}`, + loc: iterableItem.value.loc, + }); + } + let varDeclKind; + switch (iterableItem.value.lvalue.kind) { + case InstructionKind.Const: + varDeclKind = 'const'; + break; + case InstructionKind.Let: + varDeclKind = 'let'; + break; + case InstructionKind.Reassign: + case InstructionKind.Catch: + case InstructionKind.HoistedConst: + case InstructionKind.HoistedLet: + case InstructionKind.HoistedFunction: + case InstructionKind.Function: + CompilerError.invariant(false, { + reason: `Unexpected ${iterableItem.value.lvalue.kind} variable in for..of collection`, + loc: iterableItem.loc, + }); + default: + assertExhaustive$1(iterableItem.value.lvalue.kind, `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}`); + } + return createForOfStatement(terminal.loc, createVariableDeclaration(iterableItem.value.loc, varDeclKind, [ + libExports$1.variableDeclarator(lval, null), + ]), codegenInstructionValueToExpression(cx, iterableCollection), codegenBlock(cx, terminal.loop)); + } + case 'if': { + const test = codegenPlaceToExpression(cx, terminal.test); + const consequent = codegenBlock(cx, terminal.consequent); + let alternate = null; + if (terminal.alternate !== null) { + const block = codegenBlock(cx, terminal.alternate); + if (block.body.length !== 0) { + alternate = block; + } + } + return createIfStatement(terminal.loc, test, consequent, alternate); + } + case 'return': { + const value = codegenPlaceToExpression(cx, terminal.value); + if (value.type === 'Identifier' && value.name === 'undefined') { + return createReturnStatement(terminal.loc); + } + return createReturnStatement(terminal.loc, value); + } + case 'switch': { + return createSwitchStatement(terminal.loc, codegenPlaceToExpression(cx, terminal.test), terminal.cases.map(case_ => { + const test = case_.test !== null + ? codegenPlaceToExpression(cx, case_.test) + : null; + const block = codegenBlock(cx, case_.block); + return libExports$1.switchCase(test, block.body.length === 0 ? [] : [block]); + })); + } + case 'throw': { + return createThrowStatement(terminal.loc, codegenPlaceToExpression(cx, terminal.value)); + } + case 'do-while': { + const test = codegenInstructionValueToExpression(cx, terminal.test); + return createDoWhileStatement(terminal.loc, test, codegenBlock(cx, terminal.loop)); + } + case 'while': { + const test = codegenInstructionValueToExpression(cx, terminal.test); + return createWhileStatement(terminal.loc, test, codegenBlock(cx, terminal.loop)); + } + case 'label': { + return codegenBlock(cx, terminal.block); + } + case 'try': { + let catchParam = null; + if (terminal.handlerBinding !== null) { + catchParam = convertIdentifier(terminal.handlerBinding.identifier); + cx.temp.set(terminal.handlerBinding.identifier.declarationId, null); + } + return createTryStatement(terminal.loc, codegenBlock(cx, terminal.block), libExports$1.catchClause(catchParam, codegenBlock(cx, terminal.handler))); + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +function codegenInstructionNullable(cx, instr) { + if (instr.value.kind === 'StoreLocal' || + instr.value.kind === 'StoreContext' || + instr.value.kind === 'Destructure' || + instr.value.kind === 'DeclareLocal' || + instr.value.kind === 'DeclareContext') { + let kind = instr.value.lvalue.kind; + let lvalue; + let value; + if (instr.value.kind === 'StoreLocal') { + kind = cx.hasDeclared(instr.value.lvalue.place.identifier) + ? InstructionKind.Reassign + : kind; + lvalue = instr.value.lvalue.place; + value = codegenPlaceToExpression(cx, instr.value.value); + } + else if (instr.value.kind === 'StoreContext') { + lvalue = instr.value.lvalue.place; + value = codegenPlaceToExpression(cx, instr.value.value); + } + else if (instr.value.kind === 'DeclareLocal' || + instr.value.kind === 'DeclareContext') { + if (cx.hasDeclared(instr.value.lvalue.place.identifier)) { + return null; + } + kind = instr.value.lvalue.kind; + lvalue = instr.value.lvalue.place; + value = null; + } + else { + lvalue = instr.value.lvalue.pattern; + for (const place of eachPatternOperand(lvalue)) { + if (kind !== InstructionKind.Reassign && + place.identifier.name === null) { + cx.temp.set(place.identifier.declarationId, null); + } + } + value = codegenPlaceToExpression(cx, instr.value.value); + } + switch (kind) { + case InstructionKind.Const: { + CompilerError.invariant(instr.lvalue === null, { + reason: `Const declaration cannot be referenced as an expression`, + message: `this is ${kind}`, + loc: instr.value.loc, + }); + return createVariableDeclaration(instr.loc, 'const', [ + createVariableDeclarator(codegenLValue(cx, lvalue), value), + ]); + } + case InstructionKind.Function: { + CompilerError.invariant(instr.lvalue === null, { + reason: `Function declaration cannot be referenced as an expression`, + loc: instr.value.loc, + }); + const genLvalue = codegenLValue(cx, lvalue); + CompilerError.invariant(genLvalue.type === 'Identifier', { + reason: 'Expected an identifier as a function declaration lvalue', + loc: instr.value.loc, + }); + CompilerError.invariant((value === null || value === void 0 ? void 0 : value.type) === 'FunctionExpression', { + reason: 'Expected a function as a function declaration value', + description: `Got ${value == null ? String(value) : value.type} at ${printInstruction(instr)}`, + loc: instr.value.loc, + }); + return createFunctionDeclaration(instr.loc, genLvalue, value.params, value.body, value.generator, value.async); + } + case InstructionKind.Let: { + CompilerError.invariant(instr.lvalue === null, { + reason: `Const declaration cannot be referenced as an expression`, + message: `this is ${kind}`, + loc: instr.value.loc, + }); + return createVariableDeclaration(instr.loc, 'let', [ + createVariableDeclarator(codegenLValue(cx, lvalue), value), + ]); + } + case InstructionKind.Reassign: { + CompilerError.invariant(value !== null, { + reason: 'Expected a value for reassignment', + loc: instr.value.loc, + }); + const expr = libExports$1.assignmentExpression('=', codegenLValue(cx, lvalue), value); + if (instr.lvalue !== null) { + if (instr.value.kind !== 'StoreContext') { + cx.temp.set(instr.lvalue.identifier.declarationId, expr); + return null; + } + else { + const statement = codegenInstruction(cx, instr, expr); + if (statement.type === 'EmptyStatement') { + return null; + } + return statement; + } + } + else { + return createExpressionStatement(instr.loc, expr); + } + } + case InstructionKind.Catch: { + return libExports$1.emptyStatement(); + } + case InstructionKind.HoistedLet: + case InstructionKind.HoistedConst: + case InstructionKind.HoistedFunction: { + CompilerError.invariant(false, { + reason: `Expected ${kind} to have been pruned in PruneHoistedContexts`, + loc: instr.loc, + }); + } + default: { + assertExhaustive$1(kind, `Unexpected instruction kind \`${kind}\``); + } + } + } + else if (instr.value.kind === 'StartMemoize' || + instr.value.kind === 'FinishMemoize') { + return null; + } + else if (instr.value.kind === 'Debugger') { + return libExports$1.debuggerStatement(); + } + else if (instr.value.kind === 'ObjectMethod') { + CompilerError.invariant(instr.lvalue, { + reason: 'Expected object methods to have a temp lvalue', + loc: GeneratedSource, + }); + cx.objectMethods.set(instr.lvalue.identifier.id, instr.value); + return null; + } + else { + const value = codegenInstructionValue(cx, instr.value); + const statement = codegenInstruction(cx, instr, value); + if (statement.type === 'EmptyStatement') { + return null; + } + return statement; + } +} +function codegenForInit(cx, init) { + if (init.kind === 'SequenceExpression') { + const body = codegenBlock(cx, init.instructions.map(instruction => ({ + kind: 'instruction', + instruction, + }))).body; + const declarators = []; + let kind = 'const'; + body.forEach(instr => { + var _a; + let top = undefined; + if (instr.type === 'ExpressionStatement' && + instr.expression.type === 'AssignmentExpression' && + instr.expression.operator === '=' && + instr.expression.left.type === 'Identifier' && + ((_a = (top = declarators.at(-1))) === null || _a === void 0 ? void 0 : _a.id.type) === 'Identifier' && + (top === null || top === void 0 ? void 0 : top.id.name) === instr.expression.left.name && + (top === null || top === void 0 ? void 0 : top.init) == null) { + top.init = instr.expression.right; + } + else { + CompilerError.invariant(instr.type === 'VariableDeclaration' && + (instr.kind === 'let' || instr.kind === 'const'), { + reason: 'Expected a variable declaration', + description: `Got ${instr.type}`, + loc: init.loc, + }); + if (instr.kind === 'let') { + kind = 'let'; + } + declarators.push(...instr.declarations); + } + }); + CompilerError.invariant(declarators.length > 0, { + reason: 'Expected a variable declaration', + loc: init.loc, + }); + return libExports$1.variableDeclaration(kind, declarators); + } + else { + return codegenInstructionValueToExpression(cx, init); + } +} +function codegenDependency(cx, dependency) { + let object = convertIdentifier(dependency.identifier); + if (dependency.path.length !== 0) { + const hasOptional = dependency.path.some(path => path.optional); + for (const path of dependency.path) { + const property = typeof path.property === 'string' + ? libExports$1.identifier(path.property) + : libExports$1.numericLiteral(path.property); + const isComputed = typeof path.property !== 'string'; + if (hasOptional) { + object = libExports$1.optionalMemberExpression(object, property, isComputed, path.optional); + } + else { + object = libExports$1.memberExpression(object, property, isComputed); + } + } + } + return object; +} +function withLoc(fn) { + return (loc, ...args) => { + const node = fn(...args); + if (loc != null && loc != GeneratedSource) { + node.loc = loc; + } + return node; + }; +} +const createIdentifier = withLoc(libExports$1.identifier); +const createArrayPattern = withLoc(libExports$1.arrayPattern); +const createObjectPattern = withLoc(libExports$1.objectPattern); +const createBinaryExpression = withLoc(libExports$1.binaryExpression); +const createExpressionStatement = withLoc(libExports$1.expressionStatement); +const createVariableDeclaration = withLoc(libExports$1.variableDeclaration); +const createFunctionDeclaration = withLoc(libExports$1.functionDeclaration); +const createWhileStatement = withLoc(libExports$1.whileStatement); +const createDoWhileStatement = withLoc(libExports$1.doWhileStatement); +const createSwitchStatement = withLoc(libExports$1.switchStatement); +const createIfStatement = withLoc(libExports$1.ifStatement); +const createForStatement = withLoc(libExports$1.forStatement); +const createForOfStatement = withLoc(libExports$1.forOfStatement); +const createForInStatement = withLoc(libExports$1.forInStatement); +const createTaggedTemplateExpression = withLoc(libExports$1.taggedTemplateExpression); +const createLogicalExpression = withLoc(libExports$1.logicalExpression); +const createSequenceExpression = withLoc(libExports$1.sequenceExpression); +const createConditionalExpression = withLoc(libExports$1.conditionalExpression); +const createTemplateLiteral = withLoc(libExports$1.templateLiteral); +const createJsxNamespacedName = withLoc(libExports$1.jsxNamespacedName); +const createJsxElement = withLoc(libExports$1.jsxElement); +const createJsxAttribute = withLoc(libExports$1.jsxAttribute); +const createJsxIdentifier = withLoc(libExports$1.jsxIdentifier); +const createJsxExpressionContainer = withLoc(libExports$1.jsxExpressionContainer); +const createJsxText = withLoc(libExports$1.jsxText); +const createJsxClosingElement = withLoc(libExports$1.jsxClosingElement); +const createJsxOpeningElement = withLoc(libExports$1.jsxOpeningElement); +const createStringLiteral = withLoc(libExports$1.stringLiteral); +const createThrowStatement = withLoc(libExports$1.throwStatement); +const createTryStatement = withLoc(libExports$1.tryStatement); +const createBreakStatement = withLoc(libExports$1.breakStatement); +const createContinueStatement = withLoc(libExports$1.continueStatement); +const createReturnStatement = withLoc(libExports$1.returnStatement); +function createVariableDeclarator(id, init) { + var _a, _b; + const node = libExports$1.variableDeclarator(id, init); + if (id.loc && (init === null || (init === null || init === void 0 ? void 0 : init.loc))) { + node.loc = { + start: id.loc.start, + end: (_b = (_a = init === null || init === void 0 ? void 0 : init.loc) === null || _a === void 0 ? void 0 : _a.end) !== null && _b !== void 0 ? _b : id.loc.end, + filename: id.loc.filename, + identifierName: undefined, + }; + } + return node; +} +function createHookGuard(guard, context, stmts, before, after) { + const guardFnName = context.addImportSpecifier(guard).name; + function createHookGuardImpl(kind) { + return libExports$1.expressionStatement(libExports$1.callExpression(libExports$1.identifier(guardFnName), [libExports$1.numericLiteral(kind)])); + } + return libExports$1.tryStatement(libExports$1.blockStatement([createHookGuardImpl(before), ...stmts]), null, libExports$1.blockStatement([createHookGuardImpl(after)])); +} +function createCallExpression(env, callee, args, loc, isHook) { + const callExpr = libExports$1.callExpression(callee, args); + if (loc != null && loc != GeneratedSource) { + callExpr.loc = loc; + } + const hookGuard = env.config.enableEmitHookGuards; + if (hookGuard != null && isHook && env.outputMode === 'client') { + const iife = libExports$1.functionExpression(null, [], libExports$1.blockStatement([ + createHookGuard(hookGuard, env.programContext, [libExports$1.returnStatement(callExpr)], GuardKind.AllowHook, GuardKind.DisallowHook), + ])); + return libExports$1.callExpression(iife, []); + } + else { + return callExpr; + } +} +function codegenLabel(id) { + return `bb${id}`; +} +function codegenInstruction(cx, instr, value) { + if (libExports$1.isStatement(value)) { + return value; + } + if (instr.lvalue === null) { + return libExports$1.expressionStatement(convertValueToExpression(value)); + } + if (instr.lvalue.identifier.name === null) { + cx.temp.set(instr.lvalue.identifier.declarationId, value); + return libExports$1.emptyStatement(); + } + else { + const expressionValue = convertValueToExpression(value); + if (cx.hasDeclared(instr.lvalue.identifier)) { + return createExpressionStatement(instr.loc, libExports$1.assignmentExpression('=', convertIdentifier(instr.lvalue.identifier), expressionValue)); + } + else { + return createVariableDeclaration(instr.loc, 'const', [ + createVariableDeclarator(convertIdentifier(instr.lvalue.identifier), expressionValue), + ]); + } + } +} +function convertValueToExpression(value) { + if (value.type === 'JSXText') { + return createStringLiteral(value.loc, value.value); + } + return value; +} +function codegenInstructionValueToExpression(cx, instrValue) { + const value = codegenInstructionValue(cx, instrValue); + return convertValueToExpression(value); +} +function codegenInstructionValue(cx, instrValue) { + var _a, _b, _c, _d, _e, _f, _g; + let value; + switch (instrValue.kind) { + case 'ArrayExpression': { + const elements = instrValue.elements.map(element => { + if (element.kind === 'Identifier') { + return codegenPlaceToExpression(cx, element); + } + else if (element.kind === 'Spread') { + return libExports$1.spreadElement(codegenPlaceToExpression(cx, element.place)); + } + else { + return null; + } + }); + value = libExports$1.arrayExpression(elements); + break; + } + case 'BinaryExpression': { + const left = codegenPlaceToExpression(cx, instrValue.left); + const right = codegenPlaceToExpression(cx, instrValue.right); + value = createBinaryExpression(instrValue.loc, instrValue.operator, left, right); + break; + } + case 'UnaryExpression': { + value = libExports$1.unaryExpression(instrValue.operator, codegenPlaceToExpression(cx, instrValue.value)); + break; + } + case 'Primitive': { + value = codegenValue(cx, instrValue.loc, instrValue.value); + break; + } + case 'CallExpression': { + if (cx.env.config.enableForest) { + const callee = codegenPlaceToExpression(cx, instrValue.callee); + const args = instrValue.args.map(arg => codegenArgument(cx, arg)); + value = libExports$1.callExpression(callee, args); + if (instrValue.typeArguments != null) { + value.typeArguments = libExports$1.typeParameterInstantiation(instrValue.typeArguments); + } + break; + } + const isHook = getHookKind(cx.env, instrValue.callee.identifier) != null; + const callee = codegenPlaceToExpression(cx, instrValue.callee); + const args = instrValue.args.map(arg => codegenArgument(cx, arg)); + value = createCallExpression(cx.env, callee, args, instrValue.loc, isHook); + break; + } + case 'OptionalExpression': { + const optionalValue = codegenInstructionValueToExpression(cx, instrValue.value); + switch (optionalValue.type) { + case 'OptionalCallExpression': + case 'CallExpression': { + CompilerError.invariant(libExports$1.isExpression(optionalValue.callee), { + reason: 'v8 intrinsics are validated during lowering', + loc: (_a = optionalValue.callee.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + value = libExports$1.optionalCallExpression(optionalValue.callee, optionalValue.arguments, instrValue.optional); + break; + } + case 'OptionalMemberExpression': + case 'MemberExpression': { + const property = optionalValue.property; + CompilerError.invariant(libExports$1.isExpression(property), { + reason: 'Private names are validated during lowering', + loc: (_b = property.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + value = libExports$1.optionalMemberExpression(optionalValue.object, property, optionalValue.computed, instrValue.optional); + break; + } + default: { + CompilerError.invariant(false, { + reason: 'Expected an optional value to resolve to a call expression or member expression', + description: `Got a \`${optionalValue.type}\``, + loc: instrValue.loc, + }); + } + } + break; + } + case 'MethodCall': { + const isHook = getHookKind(cx.env, instrValue.property.identifier) != null; + const memberExpr = codegenPlaceToExpression(cx, instrValue.property); + CompilerError.invariant(libExports$1.isMemberExpression(memberExpr) || + libExports$1.isOptionalMemberExpression(memberExpr), { + reason: '[Codegen] Internal error: MethodCall::property must be an unpromoted + unmemoized MemberExpression', + message: `Got: '${memberExpr.type}'`, + loc: (_c = memberExpr.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + }); + CompilerError.invariant(libExports$1.isNodesEquivalent(memberExpr.object, codegenPlaceToExpression(cx, instrValue.receiver)), { + reason: '[Codegen] Internal error: Forget should always generate MethodCall::property ' + + 'as a MemberExpression of MethodCall::receiver', + loc: (_d = memberExpr.loc) !== null && _d !== void 0 ? _d : GeneratedSource, + }); + const args = instrValue.args.map(arg => codegenArgument(cx, arg)); + value = createCallExpression(cx.env, memberExpr, args, instrValue.loc, isHook); + break; + } + case 'NewExpression': { + const callee = codegenPlaceToExpression(cx, instrValue.callee); + const args = instrValue.args.map(arg => codegenArgument(cx, arg)); + value = libExports$1.newExpression(callee, args); + break; + } + case 'ObjectExpression': { + const properties = []; + for (const property of instrValue.properties) { + if (property.kind === 'ObjectProperty') { + const key = codegenObjectPropertyKey(cx, property.key); + switch (property.type) { + case 'property': { + const value = codegenPlaceToExpression(cx, property.place); + properties.push(libExports$1.objectProperty(key, value, property.key.kind === 'computed', key.type === 'Identifier' && + value.type === 'Identifier' && + value.name === key.name)); + break; + } + case 'method': { + const method = cx.objectMethods.get(property.place.identifier.id); + CompilerError.invariant(method, { + reason: 'Expected ObjectMethod instruction', + loc: GeneratedSource, + }); + const loweredFunc = method.loweredFunc; + const reactiveFunction = buildReactiveFunction(loweredFunc.func); + pruneUnusedLabels(reactiveFunction); + pruneUnusedLValues(reactiveFunction); + const fn = codegenReactiveFunction(new Context$1(cx.env, (_e = reactiveFunction.id) !== null && _e !== void 0 ? _e : '[[ anonymous ]]', cx.uniqueIdentifiers, cx.fbtOperands, cx.temp), reactiveFunction); + const babelNode = libExports$1.objectMethod('method', key, fn.params, fn.body, false); + babelNode.async = fn.async; + babelNode.generator = fn.generator; + properties.push(babelNode); + break; + } + default: + assertExhaustive$1(property.type, `Unexpected property type: ${property.type}`); + } + } + else { + properties.push(libExports$1.spreadElement(codegenPlaceToExpression(cx, property.place))); + } + } + value = libExports$1.objectExpression(properties); + break; + } + case 'JSXText': { + value = createJsxText(instrValue.loc, instrValue.value); + break; + } + case 'JsxExpression': { + const attributes = []; + for (const attribute of instrValue.props) { + attributes.push(codegenJsxAttribute(cx, attribute)); + } + let tagValue = instrValue.tag.kind === 'Identifier' + ? codegenPlaceToExpression(cx, instrValue.tag) + : libExports$1.stringLiteral(instrValue.tag.name); + let tag; + if (tagValue.type === 'Identifier') { + tag = createJsxIdentifier(instrValue.tag.loc, tagValue.name); + } + else if (tagValue.type === 'MemberExpression') { + tag = convertMemberExpressionToJsx(tagValue); + } + else { + CompilerError.invariant(tagValue.type === 'StringLiteral', { + reason: `Expected JSX tag to be an identifier or string, got \`${tagValue.type}\``, + loc: (_f = tagValue.loc) !== null && _f !== void 0 ? _f : GeneratedSource, + }); + if (tagValue.value.indexOf(':') >= 0) { + const [namespace, name] = tagValue.value.split(':', 2); + tag = createJsxNamespacedName(instrValue.tag.loc, createJsxIdentifier(instrValue.tag.loc, namespace), createJsxIdentifier(instrValue.tag.loc, name)); + } + else { + tag = createJsxIdentifier(instrValue.loc, tagValue.value); + } + } + let children; + if (tagValue.type === 'StringLiteral' && + SINGLE_CHILD_FBT_TAGS.has(tagValue.value)) { + CompilerError.invariant(instrValue.children != null, { + reason: 'Expected fbt element to have children', + loc: instrValue.loc, + }); + children = instrValue.children.map(child => codegenJsxFbtChildElement(cx, child)); + } + else { + children = + instrValue.children !== null + ? instrValue.children.map(child => codegenJsxElement(cx, child)) + : []; + } + value = createJsxElement(instrValue.loc, createJsxOpeningElement(instrValue.openingLoc, tag, attributes, instrValue.children === null), instrValue.children !== null + ? createJsxClosingElement(instrValue.closingLoc, tag) + : null, children, instrValue.children === null); + break; + } + case 'JsxFragment': { + value = libExports$1.jsxFragment(libExports$1.jsxOpeningFragment(), libExports$1.jsxClosingFragment(), instrValue.children.map(child => codegenJsxElement(cx, child))); + break; + } + case 'UnsupportedNode': { + const node = instrValue.node; + if (!libExports$1.isExpression(node)) { + return node; + } + value = node; + break; + } + case 'PropertyStore': + case 'PropertyLoad': + case 'PropertyDelete': { + let memberExpr; + if (typeof instrValue.property === 'string') { + memberExpr = libExports$1.memberExpression(codegenPlaceToExpression(cx, instrValue.object), libExports$1.identifier(instrValue.property)); + } + else { + memberExpr = libExports$1.memberExpression(codegenPlaceToExpression(cx, instrValue.object), libExports$1.numericLiteral(instrValue.property), true); + } + if (instrValue.kind === 'PropertyStore') { + value = libExports$1.assignmentExpression('=', memberExpr, codegenPlaceToExpression(cx, instrValue.value)); + } + else if (instrValue.kind === 'PropertyLoad') { + value = memberExpr; + } + else { + value = libExports$1.unaryExpression('delete', memberExpr); + } + break; + } + case 'ComputedStore': { + value = libExports$1.assignmentExpression('=', libExports$1.memberExpression(codegenPlaceToExpression(cx, instrValue.object), codegenPlaceToExpression(cx, instrValue.property), true), codegenPlaceToExpression(cx, instrValue.value)); + break; + } + case 'ComputedLoad': { + const object = codegenPlaceToExpression(cx, instrValue.object); + const property = codegenPlaceToExpression(cx, instrValue.property); + value = libExports$1.memberExpression(object, property, true); + break; + } + case 'ComputedDelete': { + value = libExports$1.unaryExpression('delete', libExports$1.memberExpression(codegenPlaceToExpression(cx, instrValue.object), codegenPlaceToExpression(cx, instrValue.property), true)); + break; + } + case 'LoadLocal': + case 'LoadContext': { + value = codegenPlaceToExpression(cx, instrValue.place); + break; + } + case 'FunctionExpression': { + const loweredFunc = instrValue.loweredFunc.func; + const reactiveFunction = buildReactiveFunction(loweredFunc); + pruneUnusedLabels(reactiveFunction); + pruneUnusedLValues(reactiveFunction); + pruneHoistedContexts(reactiveFunction); + const fn = codegenReactiveFunction(new Context$1(cx.env, (_g = reactiveFunction.id) !== null && _g !== void 0 ? _g : '[[ anonymous ]]', cx.uniqueIdentifiers, cx.fbtOperands, cx.temp), reactiveFunction); + if (instrValue.type === 'ArrowFunctionExpression') { + let body = fn.body; + if (body.body.length === 1 && loweredFunc.directives.length == 0) { + const stmt = body.body[0]; + if (stmt.type === 'ReturnStatement' && stmt.argument != null) { + body = stmt.argument; + } + } + value = libExports$1.arrowFunctionExpression(fn.params, body, fn.async); + } + else { + value = libExports$1.functionExpression(instrValue.name != null ? libExports$1.identifier(instrValue.name) : null, fn.params, fn.body, fn.generator, fn.async); + } + if (cx.env.config.enableNameAnonymousFunctions && + instrValue.name == null && + instrValue.nameHint != null) { + const name = instrValue.nameHint; + value = libExports$1.memberExpression(libExports$1.objectExpression([libExports$1.objectProperty(libExports$1.stringLiteral(name), value)]), libExports$1.stringLiteral(name), true, false); + } + break; + } + case 'TaggedTemplateExpression': { + value = createTaggedTemplateExpression(instrValue.loc, codegenPlaceToExpression(cx, instrValue.tag), libExports$1.templateLiteral([libExports$1.templateElement(instrValue.value)], [])); + break; + } + case 'TypeCastExpression': { + if (libExports$1.isTSType(instrValue.typeAnnotation)) { + if (instrValue.typeAnnotationKind === 'satisfies') { + value = libExports$1.tsSatisfiesExpression(codegenPlaceToExpression(cx, instrValue.value), instrValue.typeAnnotation); + } + else { + value = libExports$1.tsAsExpression(codegenPlaceToExpression(cx, instrValue.value), instrValue.typeAnnotation); + } + } + else { + value = libExports$1.typeCastExpression(codegenPlaceToExpression(cx, instrValue.value), libExports$1.typeAnnotation(instrValue.typeAnnotation)); + } + break; + } + case 'LogicalExpression': { + value = createLogicalExpression(instrValue.loc, instrValue.operator, codegenInstructionValueToExpression(cx, instrValue.left), codegenInstructionValueToExpression(cx, instrValue.right)); + break; + } + case 'ConditionalExpression': { + value = createConditionalExpression(instrValue.loc, codegenInstructionValueToExpression(cx, instrValue.test), codegenInstructionValueToExpression(cx, instrValue.consequent), codegenInstructionValueToExpression(cx, instrValue.alternate)); + break; + } + case 'SequenceExpression': { + const body = codegenBlockNoReset(cx, instrValue.instructions.map(instruction => ({ + kind: 'instruction', + instruction, + }))).body; + const expressions = body.map(stmt => { + var _a, _b; + if (stmt.type === 'ExpressionStatement') { + return stmt.expression; + } + else { + if (libExports$1.isVariableDeclaration(stmt)) { + const declarator = stmt.declarations[0]; + cx.recordError(new CompilerErrorDetail({ + reason: `(CodegenReactiveFunction::codegenInstructionValue) Cannot declare variables in a value block, tried to declare '${declarator.id.name}'`, + category: ErrorCategory.Todo, + loc: (_a = declarator.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + return libExports$1.stringLiteral(`TODO handle ${declarator.id}`); + } + else { + cx.recordError(new CompilerErrorDetail({ + reason: `(CodegenReactiveFunction::codegenInstructionValue) Handle conversion of ${stmt.type} to expression`, + category: ErrorCategory.Todo, + loc: (_b = stmt.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + return libExports$1.stringLiteral(`TODO handle ${stmt.type}`); + } + } + }); + if (expressions.length === 0) { + value = codegenInstructionValueToExpression(cx, instrValue.value); + } + else { + value = createSequenceExpression(instrValue.loc, [ + ...expressions, + codegenInstructionValueToExpression(cx, instrValue.value), + ]); + } + break; + } + case 'TemplateLiteral': { + value = createTemplateLiteral(instrValue.loc, instrValue.quasis.map(q => libExports$1.templateElement(q)), instrValue.subexprs.map(p => codegenPlaceToExpression(cx, p))); + break; + } + case 'LoadGlobal': { + value = libExports$1.identifier(instrValue.binding.name); + break; + } + case 'RegExpLiteral': { + value = libExports$1.regExpLiteral(instrValue.pattern, instrValue.flags); + break; + } + case 'MetaProperty': { + value = libExports$1.metaProperty(libExports$1.identifier(instrValue.meta), libExports$1.identifier(instrValue.property)); + break; + } + case 'Await': { + value = libExports$1.awaitExpression(codegenPlaceToExpression(cx, instrValue.value)); + break; + } + case 'GetIterator': { + value = codegenPlaceToExpression(cx, instrValue.collection); + break; + } + case 'IteratorNext': { + value = codegenPlaceToExpression(cx, instrValue.iterator); + break; + } + case 'NextPropertyOf': { + value = codegenPlaceToExpression(cx, instrValue.value); + break; + } + case 'PostfixUpdate': { + value = libExports$1.updateExpression(instrValue.operation, codegenPlaceToExpression(cx, instrValue.lvalue), false); + break; + } + case 'PrefixUpdate': { + value = libExports$1.updateExpression(instrValue.operation, codegenPlaceToExpression(cx, instrValue.lvalue), true); + break; + } + case 'StoreLocal': { + CompilerError.invariant(instrValue.lvalue.kind === InstructionKind.Reassign, { + reason: `Unexpected StoreLocal in codegenInstructionValue`, + loc: instrValue.loc, + }); + value = libExports$1.assignmentExpression('=', codegenLValue(cx, instrValue.lvalue.place), codegenPlaceToExpression(cx, instrValue.value)); + break; + } + case 'StoreGlobal': { + value = libExports$1.assignmentExpression('=', libExports$1.identifier(instrValue.name), codegenPlaceToExpression(cx, instrValue.value)); + break; + } + case 'StartMemoize': + case 'FinishMemoize': + case 'Debugger': + case 'DeclareLocal': + case 'DeclareContext': + case 'Destructure': + case 'ObjectMethod': + case 'StoreContext': { + CompilerError.invariant(false, { + reason: `Unexpected ${instrValue.kind} in codegenInstructionValue`, + loc: instrValue.loc, + }); + } + default: { + assertExhaustive$1(instrValue, `Unexpected instruction value kind \`${instrValue.kind}\``); + } + } + if (instrValue.loc != null && instrValue.loc != GeneratedSource) { + value.loc = instrValue.loc; + } + return value; +} +const STRING_REQUIRES_EXPR_CONTAINER_PATTERN = /[\u{0000}-\u{001F}\u{007F}\u{0080}-\u{FFFF}\u{010000}-\u{10FFFF}]|"|\\/u; +function codegenJsxAttribute(cx, attribute) { + switch (attribute.kind) { + case 'JsxAttribute': { + let propName; + if (attribute.name.indexOf(':') === -1) { + propName = createJsxIdentifier(attribute.place.loc, attribute.name); + } + else { + const [namespace, name] = attribute.name.split(':', 2); + propName = createJsxNamespacedName(attribute.place.loc, createJsxIdentifier(attribute.place.loc, namespace), createJsxIdentifier(attribute.place.loc, name)); + } + const innerValue = codegenPlaceToExpression(cx, attribute.place); + let value; + switch (innerValue.type) { + case 'StringLiteral': { + value = innerValue; + if (STRING_REQUIRES_EXPR_CONTAINER_PATTERN.test(value.value) && + !cx.fbtOperands.has(attribute.place.identifier.id)) { + value = createJsxExpressionContainer(value.loc, value); + } + break; + } + default: { + value = createJsxExpressionContainer(attribute.place.loc, innerValue); + break; + } + } + return createJsxAttribute(attribute.place.loc, propName, value); + } + case 'JsxSpreadAttribute': { + return libExports$1.jsxSpreadAttribute(codegenPlaceToExpression(cx, attribute.argument)); + } + default: { + assertExhaustive$1(attribute, `Unexpected attribute kind \`${attribute.kind}\``); + } + } +} +const JSX_TEXT_CHILD_REQUIRES_EXPR_CONTAINER_PATTERN = /[<>&{}]/; +function codegenJsxElement(cx, place) { + const value = codegenPlace(cx, place); + switch (value.type) { + case 'JSXText': { + if (JSX_TEXT_CHILD_REQUIRES_EXPR_CONTAINER_PATTERN.test(value.value)) { + return createJsxExpressionContainer(place.loc, createStringLiteral(place.loc, value.value)); + } + return createJsxText(place.loc, value.value); + } + case 'JSXElement': + case 'JSXFragment': { + return value; + } + default: { + return createJsxExpressionContainer(place.loc, value); + } + } +} +function codegenJsxFbtChildElement(cx, place) { + const value = codegenPlace(cx, place); + switch (value.type) { + case 'JSXText': + case 'JSXElement': { + return value; + } + default: { + return createJsxExpressionContainer(place.loc, value); + } + } +} +function convertMemberExpressionToJsx(expr) { + var _a, _b; + CompilerError.invariant(expr.property.type === 'Identifier', { + reason: 'Expected JSX member expression property to be a string', + loc: (_a = expr.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + const property = libExports$1.jsxIdentifier(expr.property.name); + if (expr.object.type === 'Identifier') { + return libExports$1.jsxMemberExpression(libExports$1.jsxIdentifier(expr.object.name), property); + } + else { + CompilerError.invariant(expr.object.type === 'MemberExpression', { + reason: 'Expected JSX member expression to be an identifier or nested member expression', + loc: (_b = expr.object.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + const object = convertMemberExpressionToJsx(expr.object); + return libExports$1.jsxMemberExpression(object, property); + } +} +function codegenObjectPropertyKey(cx, key) { + switch (key.kind) { + case 'string': { + return libExports$1.stringLiteral(key.name); + } + case 'identifier': { + return libExports$1.identifier(key.name); + } + case 'computed': { + const expr = codegenPlace(cx, key.name); + CompilerError.invariant(libExports$1.isExpression(expr), { + reason: 'Expected object property key to be an expression', + loc: key.name.loc, + }); + return expr; + } + case 'number': { + return libExports$1.numericLiteral(key.name); + } + } +} +function codegenArrayPattern(cx, pattern) { + const hasHoles = !pattern.items.every(e => e.kind !== 'Hole'); + if (hasHoles) { + const result = createArrayPattern(pattern.loc, []); + for (const item of pattern.items) { + if (item.kind === 'Hole') { + result.elements.push(null); + } + else { + result.elements.push(codegenLValue(cx, item)); + } + } + return result; + } + else { + return createArrayPattern(pattern.loc, pattern.items.map(item => { + if (item.kind === 'Hole') { + return null; + } + return codegenLValue(cx, item); + })); + } +} +function codegenLValue(cx, pattern) { + switch (pattern.kind) { + case 'ArrayPattern': { + return codegenArrayPattern(cx, pattern); + } + case 'ObjectPattern': { + return createObjectPattern(pattern.loc, pattern.properties.map(property => { + if (property.kind === 'ObjectProperty') { + const key = codegenObjectPropertyKey(cx, property.key); + const value = codegenLValue(cx, property.place); + return libExports$1.objectProperty(key, value, property.key.kind === 'computed', key.type === 'Identifier' && + value.type === 'Identifier' && + value.name === key.name); + } + else { + return libExports$1.restElement(codegenLValue(cx, property.place)); + } + })); + } + case 'Spread': { + return libExports$1.restElement(codegenLValue(cx, pattern.place)); + } + case 'Identifier': { + return convertIdentifier(pattern.identifier); + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } +} +function codegenValue(cx, loc, value) { + if (typeof value === 'number') { + if (value < 0) { + return libExports$1.unaryExpression('-', libExports$1.numericLiteral(-value), false); + } + else { + return libExports$1.numericLiteral(value); + } + } + else if (typeof value === 'boolean') { + return libExports$1.booleanLiteral(value); + } + else if (typeof value === 'string') { + return createStringLiteral(loc, value); + } + else if (value === null) { + return libExports$1.nullLiteral(); + } + else if (value === undefined) { + return libExports$1.identifier('undefined'); + } + else { + assertExhaustive$1(value, 'Unexpected primitive value kind'); + } +} +function codegenArgument(cx, arg) { + if (arg.kind === 'Identifier') { + return codegenPlaceToExpression(cx, arg); + } + else { + return libExports$1.spreadElement(codegenPlaceToExpression(cx, arg.place)); + } +} +function codegenPlaceToExpression(cx, place) { + const value = codegenPlace(cx, place); + return convertValueToExpression(value); +} +function codegenPlace(cx, place) { + let tmp = cx.temp.get(place.identifier.declarationId); + if (tmp != null) { + return tmp; + } + CompilerError.invariant(place.identifier.name !== null || tmp !== undefined, { + reason: `[Codegen] No value found for temporary`, + description: `Value for '${printPlace(place)}' was not set in the codegen context`, + loc: place.loc, + }); + const identifier = convertIdentifier(place.identifier); + identifier.loc = place.loc; + return identifier; +} +function convertIdentifier(identifier) { + CompilerError.invariant(identifier.name !== null && identifier.name.kind === 'named', { + reason: `Expected temporaries to be promoted to named identifiers in an earlier pass`, + description: `identifier ${identifier.id} is unnamed`, + loc: GeneratedSource, + }); + return createIdentifier(identifier.loc, identifier.name.value); +} +function compareScopeDependency(a, b) { + var _a, _b; + CompilerError.invariant(((_a = a.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named' && ((_b = b.identifier.name) === null || _b === void 0 ? void 0 : _b.kind) === 'named', { + reason: '[Codegen] Expected named identifier for dependency', + loc: a.identifier.loc, + }); + const aName = [ + a.identifier.name.value, + ...a.path.map(entry => `${entry.optional ? '?' : ''}${entry.property}`), + ].join('.'); + const bName = [ + b.identifier.name.value, + ...b.path.map(entry => `${entry.optional ? '?' : ''}${entry.property}`), + ].join('.'); + if (aName < bName) + return -1; + else if (aName > bName) + return 1; + else + return 0; +} +function compareScopeDeclaration(a, b) { + var _a, _b; + CompilerError.invariant(((_a = a.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named' && ((_b = b.identifier.name) === null || _b === void 0 ? void 0 : _b.kind) === 'named', { + reason: '[Codegen] Expected named identifier for declaration', + loc: a.identifier.loc, + }); + const aName = a.identifier.name.value; + const bName = b.identifier.name.value; + if (aName < bName) + return -1; + else if (aName > bName) + return 1; + else + return 0; +} + +function extractScopeDeclarationsFromDestructuring(fn) { + const state = new State$1(fn.env); + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + state.declared.add(place.identifier.declarationId); + } + visitReactiveFunction(fn, new Visitor$7(), state); +} +let State$1 = class State { + constructor(env) { + this.declared = new Set(); + this.env = env; + } +}; +let Visitor$7 = class Visitor extends ReactiveFunctionTransform { + visitScope(scope, state) { + for (const [, declaration] of scope.scope.declarations) { + state.declared.add(declaration.identifier.declarationId); + } + this.traverseScope(scope, state); + } + transformInstruction(instruction, state) { + this.visitInstruction(instruction, state); + let instructionsToProcess = [instruction]; + let result = { kind: 'keep' }; + if (instruction.value.kind === 'Destructure') { + const transformed = transformDestructuring(state, instruction, instruction.value); + if (transformed) { + instructionsToProcess = transformed; + result = { + kind: 'replace-many', + value: transformed.map(instruction => ({ + kind: 'instruction', + instruction, + })), + }; + } + } + for (const instr of instructionsToProcess) { + for (const [place, kind] of eachInstructionLValueWithKind(instr)) { + if (kind !== InstructionKind.Reassign) { + state.declared.add(place.identifier.declarationId); + } + } + } + return result; + } +}; +function transformDestructuring(state, instr, destructure) { + let reassigned = new Set(); + let hasDeclaration = false; + for (const place of eachPatternOperand(destructure.lvalue.pattern)) { + const isDeclared = state.declared.has(place.identifier.declarationId); + if (isDeclared) { + reassigned.add(place.identifier.id); + } + else { + hasDeclaration = true; + } + } + if (!hasDeclaration) { + destructure.lvalue.kind = InstructionKind.Reassign; + return null; + } + const instructions = []; + const renamed = new Map(); + mapPatternOperands(destructure.lvalue.pattern, place => { + if (!reassigned.has(place.identifier.id)) { + return place; + } + const temporary = clonePlaceToTemporary(state.env, place); + promoteTemporary(temporary.identifier); + renamed.set(place, temporary); + return temporary; + }); + instructions.push(instr); + for (const [original, temporary] of renamed) { + instructions.push({ + id: instr.id, + lvalue: null, + value: { + kind: 'StoreLocal', + lvalue: { + kind: InstructionKind.Reassign, + place: original, + }, + value: temporary, + type: null, + loc: destructure.loc, + }, + loc: instr.loc, + }); + } + return instructions; +} + +function mergeReactiveScopesThatInvalidateTogether(fn) { + const lastUsageVisitor = new FindLastUsageVisitor(); + visitReactiveFunction(fn, lastUsageVisitor, undefined); + visitReactiveFunction(fn, new Transform$4(lastUsageVisitor.lastUsage), null); +} +function log(msg) { +} +class FindLastUsageVisitor extends ReactiveFunctionVisitor { + constructor() { + super(...arguments); + this.lastUsage = new Map(); + } + visitPlace(id, place, _state) { + const previousUsage = this.lastUsage.get(place.identifier.declarationId); + const lastUsage = previousUsage !== undefined + ? makeInstructionId(Math.max(previousUsage, id)) + : id; + this.lastUsage.set(place.identifier.declarationId, lastUsage); + } +} +let Transform$4 = class Transform extends ReactiveFunctionTransform { + constructor(lastUsage) { + super(); + this.temporaries = new Map(); + this.lastUsage = lastUsage; + } + transformScope(scopeBlock, state) { + this.visitScope(scopeBlock, scopeBlock.scope.dependencies); + if (state !== null && + areEqualDependencies(state, scopeBlock.scope.dependencies)) { + return { kind: 'replace-many', value: scopeBlock.instructions }; + } + else { + return { kind: 'keep' }; + } + } + visitBlock(block, state) { + var _a; + this.traverseBlock(block, state); + let current = null; + const merged = []; + function reset() { + CompilerError.invariant(current !== null, { + reason: 'MergeConsecutiveScopes: expected current scope to be non-null if reset()', + loc: GeneratedSource, + }); + if (current.to > current.from + 1) { + merged.push(current); + } + current = null; + } + for (let i = 0; i < block.length; i++) { + const instr = block[i]; + switch (instr.kind) { + case 'terminal': { + if (current !== null) { + reset(); + } + break; + } + case 'pruned-scope': { + if (current !== null) { + reset(); + } + break; + } + case 'instruction': { + switch (instr.instruction.value.kind) { + case 'BinaryExpression': + case 'ComputedLoad': + case 'JSXText': + case 'LoadGlobal': + case 'LoadLocal': + case 'Primitive': + case 'PropertyLoad': + case 'TemplateLiteral': + case 'UnaryExpression': { + if (current !== null && instr.instruction.lvalue !== null) { + current.lvalues.add(instr.instruction.lvalue.identifier.declarationId); + if (instr.instruction.value.kind === 'LoadLocal') { + this.temporaries.set(instr.instruction.lvalue.identifier.declarationId, instr.instruction.value.place.identifier.declarationId); + } + } + break; + } + case 'StoreLocal': { + if (current !== null) { + if (instr.instruction.value.lvalue.kind === InstructionKind.Const) { + for (const lvalue of eachInstructionLValue(instr.instruction)) { + current.lvalues.add(lvalue.identifier.declarationId); + } + this.temporaries.set(instr.instruction.value.lvalue.place.identifier + .declarationId, (_a = this.temporaries.get(instr.instruction.value.value.identifier.declarationId)) !== null && _a !== void 0 ? _a : instr.instruction.value.value.identifier.declarationId); + } + else { + reset(); + } + } + break; + } + default: { + if (current !== null) { + reset(); + } + } + } + break; + } + case 'scope': { + if (current !== null && + canMergeScopes(current.block, instr, this.temporaries) && + areLValuesLastUsedByScope(instr.scope, current.lvalues, this.lastUsage)) { + current.block.scope.range.end = makeInstructionId(Math.max(current.block.scope.range.end, instr.scope.range.end)); + for (const [key, value] of instr.scope.declarations) { + current.block.scope.declarations.set(key, value); + } + updateScopeDeclarations(current.block.scope, this.lastUsage); + current.to = i + 1; + current.lvalues.clear(); + if (!scopeIsEligibleForMerging(instr)) { + reset(); + } + } + else { + if (current !== null) { + reset(); + } + if (scopeIsEligibleForMerging(instr)) { + current = { + block: instr, + from: i, + to: i + 1, + lvalues: new Set(), + }; + } + } + break; + } + default: { + assertExhaustive$1(instr, `Unexpected instruction kind \`${instr.kind}\``); + } + } + } + if (current !== null) { + reset(); + } + if (merged.length) { + for (const entry of merged) { + log(printReactiveScopeSummary(entry.block.scope) + + ` from=${entry.from} to=${entry.to}`); + } + } + if (merged.length === 0) { + return; + } + const nextInstructions = []; + let index = 0; + for (const entry of merged) { + if (index < entry.from) { + nextInstructions.push(...block.slice(index, entry.from)); + index = entry.from; + } + const mergedScope = block[entry.from]; + CompilerError.invariant(mergedScope.kind === 'scope', { + reason: 'MergeConsecutiveScopes: Expected scope starting index to be a scope', + loc: GeneratedSource, + }); + nextInstructions.push(mergedScope); + index++; + while (index < entry.to) { + const instr = block[index++]; + if (instr.kind === 'scope') { + mergedScope.instructions.push(...instr.instructions); + mergedScope.scope.merged.add(instr.scope.id); + } + else { + mergedScope.instructions.push(instr); + } + } + } + while (index < block.length) { + nextInstructions.push(block[index++]); + } + block.length = 0; + block.push(...nextInstructions); + } +}; +function updateScopeDeclarations(scope, lastUsage) { + for (const [id, decl] of scope.declarations) { + const lastUsedAt = lastUsage.get(decl.identifier.declarationId); + if (lastUsedAt < scope.range.end) { + scope.declarations.delete(id); + } + } +} +function areLValuesLastUsedByScope(scope, lvalues, lastUsage) { + for (const lvalue of lvalues) { + const lastUsedAt = lastUsage.get(lvalue); + if (lastUsedAt >= scope.range.end) { + return false; + } + } + return true; +} +function canMergeScopes(current, next, temporaries) { + if (current.scope.reassignments.size !== 0 || + next.scope.reassignments.size !== 0) { + return false; + } + if (areEqualDependencies(current.scope.dependencies, next.scope.dependencies)) { + return true; + } + if (areEqualDependencies(new Set([...current.scope.declarations.values()].map(declaration => ({ + identifier: declaration.identifier, + reactive: true, + path: [], + loc: GeneratedSource, + }))), next.scope.dependencies) || + (next.scope.dependencies.size !== 0 && + [...next.scope.dependencies].every(dep => dep.path.length === 0 && + isAlwaysInvalidatingType(dep.identifier.type) && + Iterable_some(current.scope.declarations.values(), decl => decl.identifier.declarationId === dep.identifier.declarationId || + decl.identifier.declarationId === + temporaries.get(dep.identifier.declarationId))))) { + return true; + } + log(` ${printReactiveScopeSummary(current.scope)} ${[...current.scope.declarations.values()].map(decl => decl.identifier.declarationId)}`); + log(` ${printReactiveScopeSummary(next.scope)} ${[...next.scope.dependencies].map(dep => { var _a; return `${dep.identifier.declarationId} ${(_a = temporaries.get(dep.identifier.declarationId)) !== null && _a !== void 0 ? _a : dep.identifier.declarationId}`; })}`); + return false; +} +function isAlwaysInvalidatingType(type) { + switch (type.kind) { + case 'Object': { + switch (type.shapeId) { + case BuiltInArrayId: + case BuiltInObjectId: + case BuiltInFunctionId: + case BuiltInJsxId: { + return true; + } + } + break; + } + case 'Function': { + return true; + } + } + return false; +} +function areEqualDependencies(a, b) { + if (a.size !== b.size) { + return false; + } + for (const aValue of a) { + let found = false; + for (const bValue of b) { + if (aValue.identifier.declarationId === bValue.identifier.declarationId && + areEqualPaths(aValue.path, bValue.path)) { + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; +} +function scopeIsEligibleForMerging(scopeBlock) { + if (scopeBlock.scope.dependencies.size === 0) { + return true; + } + return [...scopeBlock.scope.declarations].some(([, decl]) => isAlwaysInvalidatingType(decl.identifier.type)); +} + +var _PromoteInterposedTemporaries_promotable, _PromoteInterposedTemporaries_consts, _PromoteInterposedTemporaries_globals; +class PromoteTemporaries extends ReactiveFunctionVisitor { + visitScope(scopeBlock, state) { + for (const dep of scopeBlock.scope.dependencies) { + const { identifier } = dep; + if (identifier.name == null) { + promoteIdentifier(identifier, state); + } + } + for (const [, declaration] of scopeBlock.scope.declarations) { + if (declaration.identifier.name == null) { + promoteIdentifier(declaration.identifier, state); + } + } + this.traverseScope(scopeBlock, state); + } + visitPrunedScope(scopeBlock, state) { + var _a; + for (const [, declaration] of scopeBlock.scope.declarations) { + if (declaration.identifier.name == null && + ((_a = state.pruned.get(declaration.identifier.declarationId)) === null || _a === void 0 ? void 0 : _a.usedOutsideScope) === true) { + promoteIdentifier(declaration.identifier, state); + } + } + this.traversePrunedScope(scopeBlock, state); + } + visitParam(place, state) { + if (place.identifier.name === null) { + promoteIdentifier(place.identifier, state); + } + } + visitValue(id, value, state) { + this.traverseValue(id, value, state); + if (value.kind === 'FunctionExpression' || value.kind === 'ObjectMethod') { + this.visitHirFunction(value.loweredFunc.func, state); + } + } + visitReactiveFunctionValue(_id, _dependencies, fn, state) { + for (const operand of fn.params) { + const place = operand.kind === 'Identifier' ? operand : operand.place; + if (place.identifier.name === null) { + promoteIdentifier(place.identifier, state); + } + } + visitReactiveFunction(fn, this, state); + } +} +class PromoteAllInstancedOfPromotedTemporaries extends ReactiveFunctionVisitor { + visitPlace(_id, place, state) { + if (place.identifier.name === null && + state.promoted.has(place.identifier.declarationId)) { + promoteIdentifier(place.identifier, state); + } + } + visitLValue(_id, _lvalue, _state) { + this.visitPlace(_id, _lvalue, _state); + } + traverseScopeIdentifiers(scope, state) { + for (const [, decl] of scope.declarations) { + if (decl.identifier.name === null && + state.promoted.has(decl.identifier.declarationId)) { + promoteIdentifier(decl.identifier, state); + } + } + for (const dep of scope.dependencies) { + if (dep.identifier.name === null && + state.promoted.has(dep.identifier.declarationId)) { + promoteIdentifier(dep.identifier, state); + } + } + for (const reassignment of scope.reassignments) { + if (reassignment.name === null && + state.promoted.has(reassignment.declarationId)) { + promoteIdentifier(reassignment, state); + } + } + } + visitScope(scope, state) { + this.traverseScope(scope, state); + this.traverseScopeIdentifiers(scope.scope, state); + } + visitPrunedScope(scopeBlock, state) { + this.traversePrunedScope(scopeBlock, state); + this.traverseScopeIdentifiers(scopeBlock.scope, state); + } + visitReactiveFunctionValue(_id, _dependencies, fn, state) { + visitReactiveFunction(fn, this, state); + } +} +class CollectPromotableTemporaries extends ReactiveFunctionVisitor { + constructor() { + super(...arguments); + this.activeScopes = []; + } + visitPlace(_id, place, state) { + if (this.activeScopes.length !== 0 && + state.pruned.has(place.identifier.declarationId)) { + const prunedPlace = state.pruned.get(place.identifier.declarationId); + if (prunedPlace.activeScopes.indexOf(this.activeScopes.at(-1)) === -1) { + prunedPlace.usedOutsideScope = true; + } + } + } + visitValue(id, value, state) { + this.traverseValue(id, value, state); + if (value.kind === 'JsxExpression' && value.tag.kind === 'Identifier') { + state.tags.add(value.tag.identifier.declarationId); + } + } + visitPrunedScope(scopeBlock, state) { + for (const [_id, decl] of scopeBlock.scope.declarations) { + state.pruned.set(decl.identifier.declarationId, { + activeScopes: [...this.activeScopes], + usedOutsideScope: false, + }); + } + this.visitBlock(scopeBlock.instructions, state); + } + visitScope(scopeBlock, state) { + this.activeScopes.push(scopeBlock.scope.id); + this.traverseScope(scopeBlock, state); + this.activeScopes.pop(); + } +} +class PromoteInterposedTemporaries extends ReactiveFunctionVisitor { + constructor(promotable, params) { + super(); + _PromoteInterposedTemporaries_promotable.set(this, void 0); + _PromoteInterposedTemporaries_consts.set(this, new Set()); + _PromoteInterposedTemporaries_globals.set(this, new Set()); + params.forEach(param => { + switch (param.kind) { + case 'Identifier': + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(param.identifier.id); + break; + case 'Spread': + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(param.place.identifier.id); + break; + } + }); + __classPrivateFieldSet(this, _PromoteInterposedTemporaries_promotable, promotable, "f"); + } + visitPlace(_id, place, state) { + const promo = state.get(place.identifier.id); + if (promo) { + const [identifier, needsPromotion] = promo; + if (needsPromotion && + identifier.name === null && + !__classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").has(identifier.id)) { + promoteIdentifier(identifier, __classPrivateFieldGet(this, _PromoteInterposedTemporaries_promotable, "f")); + } + } + } + visitInstruction(instruction, state) { + for (const lval of eachInstructionValueLValue(instruction.value)) { + CompilerError.invariant(lval.identifier.name != null, { + reason: 'PromoteInterposedTemporaries: Assignment targets not expected to be temporaries', + loc: instruction.loc, + }); + } + switch (instruction.value.kind) { + case 'CallExpression': + case 'MethodCall': + case 'Await': + case 'PropertyStore': + case 'PropertyDelete': + case 'ComputedStore': + case 'ComputedDelete': + case 'PostfixUpdate': + case 'PrefixUpdate': + case 'StoreLocal': + case 'StoreContext': + case 'StoreGlobal': + case 'Destructure': { + let constStore = false; + if ((instruction.value.kind === 'StoreContext' || + instruction.value.kind === 'StoreLocal') && + (instruction.value.lvalue.kind === 'Const' || + instruction.value.lvalue.kind === 'HoistedConst')) { + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(instruction.value.lvalue.place.identifier.id); + constStore = true; + } + if (instruction.value.kind === 'Destructure' && + (instruction.value.lvalue.kind === 'Const' || + instruction.value.lvalue.kind === 'HoistedConst')) { + [...eachPatternOperand(instruction.value.lvalue.pattern)].forEach(ident => __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(ident.identifier.id)); + constStore = true; + } + if (instruction.value.kind === 'MethodCall') { + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(instruction.value.property.identifier.id); + } + super.visitInstruction(instruction, state); + if (!constStore && + (instruction.lvalue == null || + instruction.lvalue.identifier.name != null)) { + for (const [key, [ident, _]] of state.entries()) { + state.set(key, [ident, true]); + } + } + if (instruction.lvalue && instruction.lvalue.identifier.name === null) { + state.set(instruction.lvalue.identifier.id, [ + instruction.lvalue.identifier, + false, + ]); + } + break; + } + case 'DeclareContext': + case 'DeclareLocal': { + if (instruction.value.lvalue.kind === 'Const' || + instruction.value.lvalue.kind === 'HoistedConst') { + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(instruction.value.lvalue.place.identifier.id); + } + super.visitInstruction(instruction, state); + break; + } + case 'LoadContext': + case 'LoadLocal': { + if (instruction.lvalue && instruction.lvalue.identifier.name === null) { + if (__classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").has(instruction.value.place.identifier.id)) { + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(instruction.lvalue.identifier.id); + } + state.set(instruction.lvalue.identifier.id, [ + instruction.lvalue.identifier, + false, + ]); + } + super.visitInstruction(instruction, state); + break; + } + case 'PropertyLoad': + case 'ComputedLoad': { + if (instruction.lvalue) { + if (__classPrivateFieldGet(this, _PromoteInterposedTemporaries_globals, "f").has(instruction.value.object.identifier.id)) { + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_globals, "f").add(instruction.lvalue.identifier.id); + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(instruction.lvalue.identifier.id); + } + if (instruction.lvalue.identifier.name === null) { + state.set(instruction.lvalue.identifier.id, [ + instruction.lvalue.identifier, + false, + ]); + } + } + super.visitInstruction(instruction, state); + break; + } + case 'LoadGlobal': { + instruction.lvalue && + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_globals, "f").add(instruction.lvalue.identifier.id); + super.visitInstruction(instruction, state); + break; + } + default: { + super.visitInstruction(instruction, state); + } + } + } +} +_PromoteInterposedTemporaries_promotable = new WeakMap(), _PromoteInterposedTemporaries_consts = new WeakMap(), _PromoteInterposedTemporaries_globals = new WeakMap(); +function promoteUsedTemporaries(fn) { + const state = { + tags: new Set(), + promoted: new Set(), + pruned: new Map(), + }; + visitReactiveFunction(fn, new CollectPromotableTemporaries(), state); + for (const operand of fn.params) { + const place = operand.kind === 'Identifier' ? operand : operand.place; + if (place.identifier.name === null) { + promoteIdentifier(place.identifier, state); + } + } + visitReactiveFunction(fn, new PromoteTemporaries(), state); + visitReactiveFunction(fn, new PromoteInterposedTemporaries(state, fn.params), new Map()); + visitReactiveFunction(fn, new PromoteAllInstancedOfPromotedTemporaries(), state); +} +function promoteIdentifier(identifier, state) { + CompilerError.invariant(identifier.name === null, { + reason: 'promoteTemporary: Expected to be called only for temporary variables', + loc: GeneratedSource, + }); + if (state.tags.has(identifier.declarationId)) { + promoteTemporaryJsxTag(identifier); + } + else { + promoteTemporary(identifier); + } + state.promoted.add(identifier.declarationId); +} + +function propagateEarlyReturns(fn) { + visitReactiveFunction(fn, new Transform$3(fn.env), { + withinReactiveScope: false, + earlyReturnValue: null, + }); +} +let Transform$3 = class Transform extends ReactiveFunctionTransform { + constructor(env) { + super(); + this.env = env; + } + visitScope(scopeBlock, parentState) { + if (scopeBlock.scope.earlyReturnValue !== null) { + return; + } + const innerState = { + withinReactiveScope: true, + earlyReturnValue: parentState.earlyReturnValue, + }; + this.traverseScope(scopeBlock, innerState); + const earlyReturnValue = innerState.earlyReturnValue; + if (earlyReturnValue !== null) { + if (!parentState.withinReactiveScope) { + scopeBlock.scope.earlyReturnValue = earlyReturnValue; + scopeBlock.scope.declarations.set(earlyReturnValue.value.id, { + identifier: earlyReturnValue.value, + scope: scopeBlock.scope, + }); + const instructions = scopeBlock.instructions; + const loc = earlyReturnValue.loc; + const sentinelTemp = createTemporaryPlace(this.env, loc); + const symbolTemp = createTemporaryPlace(this.env, loc); + const forTemp = createTemporaryPlace(this.env, loc); + const argTemp = createTemporaryPlace(this.env, loc); + scopeBlock.instructions = [ + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: Object.assign({}, symbolTemp), + value: { + kind: 'LoadGlobal', + binding: { + kind: 'Global', + name: 'Symbol', + }, + loc, + }, + }, + }, + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: Object.assign({}, forTemp), + value: { + kind: 'PropertyLoad', + object: Object.assign({}, symbolTemp), + property: makePropertyLiteral('for'), + loc, + }, + }, + }, + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: Object.assign({}, argTemp), + value: { + kind: 'Primitive', + value: EARLY_RETURN_SENTINEL, + loc, + }, + }, + }, + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: Object.assign({}, sentinelTemp), + value: { + kind: 'MethodCall', + receiver: symbolTemp, + property: forTemp, + args: [argTemp], + loc, + }, + }, + }, + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: null, + value: { + kind: 'StoreLocal', + loc, + type: null, + lvalue: { + kind: InstructionKind.Let, + place: { + kind: 'Identifier', + effect: Effect.ConditionallyMutate, + loc, + reactive: true, + identifier: earlyReturnValue.value, + }, + }, + value: Object.assign({}, sentinelTemp), + }, + }, + }, + { + kind: 'terminal', + label: { + id: earlyReturnValue.label, + implicit: false, + }, + terminal: { + kind: 'label', + id: makeInstructionId(0), + loc: GeneratedSource, + block: instructions, + }, + }, + ]; + } + else { + parentState.earlyReturnValue = earlyReturnValue; + } + } + } + transformTerminal(stmt, state) { + if (state.withinReactiveScope && stmt.terminal.kind === 'return') { + const loc = stmt.terminal.value.loc; + let earlyReturnValue; + if (state.earlyReturnValue !== null) { + earlyReturnValue = state.earlyReturnValue; + } + else { + const identifier = createTemporaryPlace(this.env, loc).identifier; + promoteTemporary(identifier); + earlyReturnValue = { + label: this.env.nextBlockId, + loc, + value: identifier, + }; + } + state.earlyReturnValue = earlyReturnValue; + return { + kind: 'replace-many', + value: [ + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: null, + value: { + kind: 'StoreLocal', + loc, + type: null, + lvalue: { + kind: InstructionKind.Reassign, + place: { + kind: 'Identifier', + identifier: earlyReturnValue.value, + effect: Effect.Capture, + loc, + reactive: true, + }, + }, + value: stmt.terminal.value, + }, + }, + }, + { + kind: 'terminal', + label: null, + terminal: { + kind: 'break', + id: makeInstructionId(0), + loc, + targetKind: 'labeled', + target: earlyReturnValue.label, + }, + }, + ], + }; + } + this.traverseTerminal(stmt, state); + return { kind: 'keep' }; + } +}; + +var _Node_value, _Node_next; +function empty() { + return EMPTY; +} +class Node { + constructor(value, next = EMPTY) { + _Node_value.set(this, void 0); + _Node_next.set(this, void 0); + __classPrivateFieldSet(this, _Node_value, value, "f"); + __classPrivateFieldSet(this, _Node_next, next, "f"); + } + push(value) { + return new Node(value, this); + } + pop() { + return __classPrivateFieldGet(this, _Node_next, "f"); + } + find(fn) { + return fn(__classPrivateFieldGet(this, _Node_value, "f")) ? true : __classPrivateFieldGet(this, _Node_next, "f").find(fn); + } + contains(value) { + return (value === __classPrivateFieldGet(this, _Node_value, "f") || + (__classPrivateFieldGet(this, _Node_next, "f") !== null && __classPrivateFieldGet(this, _Node_next, "f").contains(value))); + } + each(fn) { + fn(__classPrivateFieldGet(this, _Node_value, "f")); + __classPrivateFieldGet(this, _Node_next, "f").each(fn); + } + get value() { + return __classPrivateFieldGet(this, _Node_value, "f"); + } + print(fn) { + return fn(__classPrivateFieldGet(this, _Node_value, "f")) + __classPrivateFieldGet(this, _Node_next, "f").print(fn); + } +} +_Node_value = new WeakMap(), _Node_next = new WeakMap(); +class Empty { + push(value) { + return new Node(value, this); + } + pop() { + return this; + } + find(_fn) { + return false; + } + contains(_value) { + return false; + } + each(_fn) { + return; + } + get value() { + return null; + } + print(_) { + return ''; + } +} +const EMPTY = new Empty(); + +function pruneHoistedContexts(fn) { + visitReactiveFunction(fn, new Visitor$6(), { + activeScopes: empty(), + uninitialized: new Map(), + }); +} +let Visitor$6 = class Visitor extends ReactiveFunctionTransform { + visitScope(scope, state) { + state.activeScopes = state.activeScopes.push(new Set(scope.scope.declarations.keys())); + for (const decl of scope.scope.declarations.values()) { + state.uninitialized.set(decl.identifier.id, { kind: 'unknown-kind' }); + } + this.traverseScope(scope, state); + state.activeScopes.pop(); + for (const decl of scope.scope.declarations.values()) { + state.uninitialized.delete(decl.identifier.id); + } + } + visitPlace(_id, place, state) { + const maybeHoistedFn = state.uninitialized.get(place.identifier.id); + if ((maybeHoistedFn === null || maybeHoistedFn === void 0 ? void 0 : maybeHoistedFn.kind) === 'func' && + maybeHoistedFn.definition !== place) { + CompilerError.throwTodo({ + reason: '[PruneHoistedContexts] Rewrite hoisted function references', + loc: place.loc, + }); + } + } + transformInstruction(instruction, state) { + if (instruction.value.kind === 'DeclareContext') { + const maybeNonHoisted = convertHoistedLValueKind(instruction.value.lvalue.kind); + if (maybeNonHoisted != null) { + if (maybeNonHoisted === InstructionKind.Function && + state.uninitialized.has(instruction.value.lvalue.place.identifier.id)) { + state.uninitialized.set(instruction.value.lvalue.place.identifier.id, { + kind: 'func', + definition: null, + }); + } + return { kind: 'remove' }; + } + } + if (instruction.value.kind === 'StoreContext' && + instruction.value.lvalue.kind !== InstructionKind.Reassign) { + const lvalueId = instruction.value.lvalue.place.identifier.id; + const isDeclaredByScope = state.activeScopes.find(scope => scope.has(lvalueId)); + if (isDeclaredByScope) { + if (instruction.value.lvalue.kind === InstructionKind.Let || + instruction.value.lvalue.kind === InstructionKind.Const) { + instruction.value.lvalue.kind = InstructionKind.Reassign; + } + else if (instruction.value.lvalue.kind === InstructionKind.Function) { + const maybeHoistedFn = state.uninitialized.get(lvalueId); + if (maybeHoistedFn != null) { + CompilerError.invariant(maybeHoistedFn.kind === 'func', { + reason: '[PruneHoistedContexts] Unexpected hoisted function', + loc: instruction.loc, + }); + maybeHoistedFn.definition = instruction.value.lvalue.place; + state.uninitialized.delete(lvalueId); + } + } + else { + CompilerError.throwTodo({ + reason: '[PruneHoistedContexts] Unexpected kind', + description: `(${instruction.value.lvalue.kind})`, + loc: instruction.loc, + }); + } + } + } + this.visitInstruction(instruction, state); + return { kind: 'keep' }; + } +}; + +function hashEffect(effect) { + var _a; + switch (effect.kind) { + case 'Apply': { + return [ + effect.kind, + effect.receiver.identifier.id, + effect.function.identifier.id, + effect.mutatesFunction, + effect.args + .map(a => { + if (a.kind === 'Hole') { + return ''; + } + else if (a.kind === 'Identifier') { + return a.identifier.id; + } + else { + return `...${a.place.identifier.id}`; + } + }) + .join(','), + effect.into.identifier.id, + ].join(':'); + } + case 'CreateFrom': + case 'ImmutableCapture': + case 'Assign': + case 'Alias': + case 'Capture': + case 'MaybeAlias': { + return [ + effect.kind, + effect.from.identifier.id, + effect.into.identifier.id, + ].join(':'); + } + case 'Create': { + return [ + effect.kind, + effect.into.identifier.id, + effect.value, + effect.reason, + ].join(':'); + } + case 'Freeze': { + return [effect.kind, effect.value.identifier.id, effect.reason].join(':'); + } + case 'Impure': + case 'Render': { + return [effect.kind, effect.place.identifier.id].join(':'); + } + case 'MutateFrozen': + case 'MutateGlobal': { + return [ + effect.kind, + effect.place.identifier.id, + effect.error.severity, + effect.error.reason, + effect.error.description, + printSourceLocation((_a = effect.error.primaryLocation()) !== null && _a !== void 0 ? _a : GeneratedSource), + ].join(':'); + } + case 'Mutate': + case 'MutateConditionally': + case 'MutateTransitive': + case 'MutateTransitiveConditionally': { + return [effect.kind, effect.value.identifier.id].join(':'); + } + case 'CreateFunction': { + return [ + effect.kind, + effect.into.identifier.id, + effect.function.loweredFunc.func.returns.identifier.id, + effect.captures.map(p => p.identifier.id).join(','), + ].join(':'); + } + } +} + +var _InferenceState_isFunctionExpression, _InferenceState_values, _InferenceState_variables; +function inferMutationAliasingEffects(fn, { isFunctionExpression } = { + isFunctionExpression: false, +}) { + const initialState = InferenceState.empty(fn.env, isFunctionExpression); + const statesByBlock = new Map(); + for (const ref of fn.context) { + const value = { + kind: 'ObjectExpression', + properties: [], + loc: ref.loc, + }; + initialState.initialize(value, { + kind: ValueKind.Context, + reason: new Set([ValueReason.Other]), + }); + initialState.define(ref, value); + } + const paramKind = isFunctionExpression + ? { + kind: ValueKind.Mutable, + reason: new Set([ValueReason.Other]), + } + : { + kind: ValueKind.Frozen, + reason: new Set([ValueReason.ReactiveFunctionArgument]), + }; + if (fn.fnType === 'Component') { + CompilerError.invariant(fn.params.length <= 2, { + reason: 'Expected React component to have not more than two parameters: one for props and for ref', + loc: fn.loc, + }); + const [props, ref] = fn.params; + if (props != null) { + inferParam(props, initialState, paramKind); + } + if (ref != null) { + const place = ref.kind === 'Identifier' ? ref : ref.place; + const value = { + kind: 'ObjectExpression', + properties: [], + loc: place.loc, + }; + initialState.initialize(value, { + kind: ValueKind.Mutable, + reason: new Set([ValueReason.Other]), + }); + initialState.define(place, value); + } + } + else { + for (const param of fn.params) { + inferParam(param, initialState, paramKind); + } + } + const queuedStates = new Map(); + function queue(blockId, state) { + var _a; + let queuedState = queuedStates.get(blockId); + if (queuedState != null) { + state = (_a = queuedState.merge(state)) !== null && _a !== void 0 ? _a : queuedState; + queuedStates.set(blockId, state); + } + else { + const prevState = statesByBlock.get(blockId); + const nextState = prevState != null ? prevState.merge(state) : state; + if (nextState != null) { + queuedStates.set(blockId, nextState); + } + } + } + queue(fn.body.entry, initialState); + const hoistedContextDeclarations = findHoistedContextDeclarations(fn); + const context = new Context(isFunctionExpression, fn, hoistedContextDeclarations, findNonMutatedDestructureSpreads(fn)); + let iterationCount = 0; + while (queuedStates.size !== 0) { + iterationCount++; + if (iterationCount > 100) { + CompilerError.invariant(false, { + reason: `[InferMutationAliasingEffects] Potential infinite loop`, + description: `A value, temporary place, or effect was not cached properly`, + loc: fn.loc, + }); + } + for (const [blockId, block] of fn.body.blocks) { + const incomingState = queuedStates.get(blockId); + queuedStates.delete(blockId); + if (incomingState == null) { + continue; + } + statesByBlock.set(blockId, incomingState); + const state = incomingState.clone(); + inferBlock(context, state, block); + for (const nextBlockId of eachTerminalSuccessor(block.terminal)) { + queue(nextBlockId, state); + } + } + } + return; +} +function findHoistedContextDeclarations(fn) { + const hoisted = new Map(); + function visit(place) { + if (hoisted.has(place.identifier.declarationId) && + hoisted.get(place.identifier.declarationId) == null) { + hoisted.set(place.identifier.declarationId, place); + } + } + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + if (instr.value.kind === 'DeclareContext') { + const kind = instr.value.lvalue.kind; + if (kind == InstructionKind.HoistedConst || + kind == InstructionKind.HoistedFunction || + kind == InstructionKind.HoistedLet) { + hoisted.set(instr.value.lvalue.place.identifier.declarationId, null); + } + } + else { + for (const operand of eachInstructionValueOperand(instr.value)) { + visit(operand); + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + visit(operand); + } + } + return hoisted; +} +class Context { + constructor(isFunctionExpression, fn, hoistedContextDeclarations, nonMutatingSpreads) { + this.internedEffects = new Map(); + this.instructionSignatureCache = new Map(); + this.effectInstructionValueCache = new Map(); + this.applySignatureCache = new Map(); + this.catchHandlers = new Map(); + this.functionSignatureCache = new Map(); + this.isFuctionExpression = isFunctionExpression; + this.fn = fn; + this.hoistedContextDeclarations = hoistedContextDeclarations; + this.nonMutatingSpreads = nonMutatingSpreads; + } + cacheApplySignature(signature, effect, f) { + const inner = getOrInsertDefault(this.applySignatureCache, signature, new Map()); + return getOrInsertWith(inner, effect, f); + } + internEffect(effect) { + const hash = hashEffect(effect); + let interned = this.internedEffects.get(hash); + if (interned == null) { + this.internedEffects.set(hash, effect); + interned = effect; + } + return interned; + } +} +function findNonMutatedDestructureSpreads(fn) { + const knownFrozen = new Set(); + if (fn.fnType === 'Component') { + const [props] = fn.params; + if (props != null && props.kind === 'Identifier') { + knownFrozen.add(props.identifier.id); + } + } + else { + for (const param of fn.params) { + if (param.kind === 'Identifier') { + knownFrozen.add(param.identifier.id); + } + } + } + const candidateNonMutatingSpreads = new Map(); + for (const block of fn.body.blocks.values()) { + if (candidateNonMutatingSpreads.size !== 0) { + for (const phi of block.phis) { + for (const operand of phi.operands.values()) { + const spread = candidateNonMutatingSpreads.get(operand.identifier.id); + if (spread != null) { + candidateNonMutatingSpreads.delete(spread); + } + } + } + } + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'Destructure': { + if (!knownFrozen.has(value.value.identifier.id) || + !(value.lvalue.kind === InstructionKind.Let || + value.lvalue.kind === InstructionKind.Const) || + value.lvalue.pattern.kind !== 'ObjectPattern') { + continue; + } + for (const item of value.lvalue.pattern.properties) { + if (item.kind !== 'Spread') { + continue; + } + candidateNonMutatingSpreads.set(item.place.identifier.id, item.place.identifier.id); + } + break; + } + case 'LoadLocal': { + const spread = candidateNonMutatingSpreads.get(value.place.identifier.id); + if (spread != null) { + candidateNonMutatingSpreads.set(lvalue.identifier.id, spread); + } + break; + } + case 'StoreLocal': { + const spread = candidateNonMutatingSpreads.get(value.value.identifier.id); + if (spread != null) { + candidateNonMutatingSpreads.set(lvalue.identifier.id, spread); + candidateNonMutatingSpreads.set(value.lvalue.place.identifier.id, spread); + } + break; + } + case 'JsxFragment': + case 'JsxExpression': { + break; + } + case 'PropertyLoad': { + break; + } + case 'CallExpression': + case 'MethodCall': { + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + if (getHookKind(fn.env, callee.identifier) != null) { + if (!isRefOrRefValue(lvalue.identifier)) { + knownFrozen.add(lvalue.identifier.id); + } + } + else { + if (candidateNonMutatingSpreads.size !== 0) { + for (const operand of eachInstructionValueOperand(value)) { + const spread = candidateNonMutatingSpreads.get(operand.identifier.id); + if (spread != null) { + candidateNonMutatingSpreads.delete(spread); + } + } + } + } + break; + } + default: { + if (candidateNonMutatingSpreads.size !== 0) { + for (const operand of eachInstructionValueOperand(value)) { + const spread = candidateNonMutatingSpreads.get(operand.identifier.id); + if (spread != null) { + candidateNonMutatingSpreads.delete(spread); + } + } + } + } + } + } + } + const nonMutatingSpreads = new Set(); + for (const [key, value] of candidateNonMutatingSpreads) { + if (key === value) { + nonMutatingSpreads.add(key); + } + } + return nonMutatingSpreads; +} +function inferParam(param, initialState, paramKind) { + const place = param.kind === 'Identifier' ? param : param.place; + const value = { + kind: 'Primitive', + loc: place.loc, + value: undefined, + }; + initialState.initialize(value, paramKind); + initialState.define(place, value); +} +function inferBlock(context, state, block) { + for (const phi of block.phis) { + state.inferPhi(phi); + } + for (const instr of block.instructions) { + let instructionSignature = context.instructionSignatureCache.get(instr); + if (instructionSignature == null) { + instructionSignature = computeSignatureForInstruction(context, state.env, instr); + context.instructionSignatureCache.set(instr, instructionSignature); + } + const effects = applySignature(context, state, instructionSignature, instr); + instr.effects = effects; + } + const terminal = block.terminal; + if (terminal.kind === 'try' && terminal.handlerBinding != null) { + context.catchHandlers.set(terminal.handler, terminal.handlerBinding); + } + else if (terminal.kind === 'maybe-throw' && terminal.handler !== null) { + const handlerParam = context.catchHandlers.get(terminal.handler); + if (handlerParam != null) { + CompilerError.invariant(state.kind(handlerParam) != null, { + reason: 'Expected catch binding to be initialized with a DeclareLocal Catch instruction', + loc: terminal.loc, + }); + const effects = []; + for (const instr of block.instructions) { + if (instr.value.kind === 'CallExpression' || + instr.value.kind === 'MethodCall') { + state.appendAlias(handlerParam, instr.lvalue); + const kind = state.kind(instr.lvalue).kind; + if (kind === ValueKind.Mutable || kind == ValueKind.Context) { + effects.push(context.internEffect({ + kind: 'Alias', + from: instr.lvalue, + into: handlerParam, + })); + } + } + } + terminal.effects = effects.length !== 0 ? effects : null; + } + } + else if (terminal.kind === 'return') { + if (!context.isFuctionExpression) { + terminal.effects = [ + context.internEffect({ + kind: 'Freeze', + value: terminal.value, + reason: ValueReason.JsxCaptured, + }), + ]; + } + } +} +function applySignature(context, state, signature, instruction) { + var _a, _b; + const effects = []; + if (instruction.value.kind === 'FunctionExpression' || + instruction.value.kind === 'ObjectMethod') { + const aliasingEffects = (_a = instruction.value.loweredFunc.func.aliasingEffects) !== null && _a !== void 0 ? _a : []; + const context = new Set(instruction.value.loweredFunc.func.context.map(p => p.identifier.id)); + for (const effect of aliasingEffects) { + if (effect.kind === 'Mutate' || effect.kind === 'MutateTransitive') { + if (!context.has(effect.value.identifier.id)) { + continue; + } + const value = state.kind(effect.value); + switch (value.kind) { + case ValueKind.Frozen: { + const reason = getWriteErrorReason({ + kind: value.kind, + reason: value.reason, + }); + const variable = effect.value.identifier.name !== null && + effect.value.identifier.name.kind === 'named' + ? `\`${effect.value.identifier.name.value}\`` + : 'value'; + const diagnostic = CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'This value cannot be modified', + description: reason, + }).withDetails({ + kind: 'error', + loc: effect.value.loc, + message: `${variable} cannot be modified`, + }); + if (effect.kind === 'Mutate' && + ((_b = effect.reason) === null || _b === void 0 ? void 0 : _b.kind) === 'AssignCurrentProperty') { + diagnostic.withDetails({ + kind: 'hint', + message: `Hint: If this value is a Ref (value returned by \`useRef()\`), rename the variable to end in "Ref".`, + }); + } + effects.push({ + kind: 'MutateFrozen', + place: effect.value, + error: diagnostic, + }); + } + } + } + } + } + const initialized = new Set(); + for (const effect of signature.effects) { + applyEffect(context, state, effect, initialized, effects); + } + if (!(state.isDefined(instruction.lvalue) && state.kind(instruction.lvalue))) { + CompilerError.invariant(false, { + reason: `Expected instruction lvalue to be initialized`, + loc: instruction.loc, + }); + } + return effects.length !== 0 ? effects : null; +} +function applyEffect(context, state, _effect, initialized, effects) { + var _a, _b, _c, _d, _e; + const effect = context.internEffect(_effect); + switch (effect.kind) { + case 'Freeze': { + const didFreeze = state.freeze(effect.value, effect.reason); + if (didFreeze) { + effects.push(effect); + } + break; + } + case 'Create': { + CompilerError.invariant(!initialized.has(effect.into.identifier.id), { + reason: `Cannot re-initialize variable within an instruction`, + description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, + loc: effect.into.loc, + }); + initialized.add(effect.into.identifier.id); + let value = context.effectInstructionValueCache.get(effect); + if (value == null) { + value = { + kind: 'ObjectExpression', + properties: [], + loc: effect.into.loc, + }; + context.effectInstructionValueCache.set(effect, value); + } + state.initialize(value, { + kind: effect.value, + reason: new Set([effect.reason]), + }); + state.define(effect.into, value); + effects.push(effect); + break; + } + case 'ImmutableCapture': { + const kind = state.kind(effect.from).kind; + switch (kind) { + case ValueKind.Global: + case ValueKind.Primitive: { + break; + } + default: { + effects.push(effect); + } + } + break; + } + case 'CreateFrom': { + CompilerError.invariant(!initialized.has(effect.into.identifier.id), { + reason: `Cannot re-initialize variable within an instruction`, + description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, + loc: effect.into.loc, + }); + initialized.add(effect.into.identifier.id); + const fromValue = state.kind(effect.from); + let value = context.effectInstructionValueCache.get(effect); + if (value == null) { + value = { + kind: 'ObjectExpression', + properties: [], + loc: effect.into.loc, + }; + context.effectInstructionValueCache.set(effect, value); + } + state.initialize(value, { + kind: fromValue.kind, + reason: new Set(fromValue.reason), + }); + state.define(effect.into, value); + switch (fromValue.kind) { + case ValueKind.Primitive: + case ValueKind.Global: { + effects.push({ + kind: 'Create', + value: fromValue.kind, + into: effect.into, + reason: (_a = [...fromValue.reason][0]) !== null && _a !== void 0 ? _a : ValueReason.Other, + }); + break; + } + case ValueKind.Frozen: { + effects.push({ + kind: 'Create', + value: fromValue.kind, + into: effect.into, + reason: (_b = [...fromValue.reason][0]) !== null && _b !== void 0 ? _b : ValueReason.Other, + }); + applyEffect(context, state, { + kind: 'ImmutableCapture', + from: effect.from, + into: effect.into, + }, initialized, effects); + break; + } + default: { + effects.push(effect); + } + } + break; + } + case 'CreateFunction': { + CompilerError.invariant(!initialized.has(effect.into.identifier.id), { + reason: `Cannot re-initialize variable within an instruction`, + description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, + loc: effect.into.loc, + }); + initialized.add(effect.into.identifier.id); + effects.push(effect); + const hasCaptures = effect.captures.some(capture => { + switch (state.kind(capture).kind) { + case ValueKind.Context: + case ValueKind.Mutable: { + return true; + } + default: { + return false; + } + } + }); + const hasTrackedSideEffects = (_c = effect.function.loweredFunc.func.aliasingEffects) === null || _c === void 0 ? void 0 : _c.some(effect => effect.kind === 'MutateFrozen' || + effect.kind === 'MutateGlobal' || + effect.kind === 'Impure'); + const capturesRef = effect.function.loweredFunc.func.context.some(operand => isRefOrRefValue(operand.identifier)); + const isMutable = hasCaptures || hasTrackedSideEffects || capturesRef; + for (const operand of effect.function.loweredFunc.func.context) { + if (operand.effect !== Effect.Capture) { + continue; + } + const kind = state.kind(operand).kind; + if (kind === ValueKind.Primitive || + kind == ValueKind.Frozen || + kind == ValueKind.Global) { + operand.effect = Effect.Read; + } + } + state.initialize(effect.function, { + kind: isMutable ? ValueKind.Mutable : ValueKind.Frozen, + reason: new Set([]), + }); + state.define(effect.into, effect.function); + for (const capture of effect.captures) { + applyEffect(context, state, { + kind: 'Capture', + from: capture, + into: effect.into, + }, initialized, effects); + } + break; + } + case 'MaybeAlias': + case 'Alias': + case 'Capture': { + CompilerError.invariant(effect.kind === 'Capture' || + effect.kind === 'MaybeAlias' || + initialized.has(effect.into.identifier.id), { + reason: `Expected destination to already be initialized within this instruction`, + description: `Destination ${printPlace(effect.into)} is not initialized in this ` + + `instruction for effect ${printAliasingEffect(effect)}`, + loc: effect.into.loc, + }); + const intoKind = state.kind(effect.into).kind; + let destinationType = null; + switch (intoKind) { + case ValueKind.Context: { + destinationType = 'context'; + break; + } + case ValueKind.Mutable: + case ValueKind.MaybeFrozen: { + destinationType = 'mutable'; + break; + } + } + const fromKind = state.kind(effect.from).kind; + let sourceType = null; + switch (fromKind) { + case ValueKind.Context: { + sourceType = 'context'; + break; + } + case ValueKind.Global: + case ValueKind.Primitive: { + break; + } + case ValueKind.MaybeFrozen: + case ValueKind.Frozen: { + sourceType = 'frozen'; + break; + } + default: { + sourceType = 'mutable'; + break; + } + } + if (sourceType === 'frozen') { + applyEffect(context, state, { + kind: 'ImmutableCapture', + from: effect.from, + into: effect.into, + }, initialized, effects); + } + else if ((sourceType === 'mutable' && destinationType === 'mutable') || + effect.kind === 'MaybeAlias') { + effects.push(effect); + } + else if ((sourceType === 'context' && destinationType != null) || + (sourceType === 'mutable' && destinationType === 'context')) { + applyEffect(context, state, { kind: 'MaybeAlias', from: effect.from, into: effect.into }, initialized, effects); + } + break; + } + case 'Assign': { + CompilerError.invariant(!initialized.has(effect.into.identifier.id), { + reason: `Cannot re-initialize variable within an instruction`, + description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, + loc: effect.into.loc, + }); + initialized.add(effect.into.identifier.id); + const fromValue = state.kind(effect.from); + const fromKind = fromValue.kind; + switch (fromKind) { + case ValueKind.Frozen: { + applyEffect(context, state, { + kind: 'ImmutableCapture', + from: effect.from, + into: effect.into, + }, initialized, effects); + let value = context.effectInstructionValueCache.get(effect); + if (value == null) { + value = { + kind: 'Primitive', + value: undefined, + loc: effect.from.loc, + }; + context.effectInstructionValueCache.set(effect, value); + } + state.initialize(value, { + kind: fromKind, + reason: new Set(fromValue.reason), + }); + state.define(effect.into, value); + break; + } + case ValueKind.Global: + case ValueKind.Primitive: { + let value = context.effectInstructionValueCache.get(effect); + if (value == null) { + value = { + kind: 'Primitive', + value: undefined, + loc: effect.from.loc, + }; + context.effectInstructionValueCache.set(effect, value); + } + state.initialize(value, { + kind: fromKind, + reason: new Set(fromValue.reason), + }); + state.define(effect.into, value); + break; + } + default: { + state.assign(effect.into, effect.from); + effects.push(effect); + break; + } + } + break; + } + case 'Apply': { + const functionValues = state.values(effect.function); + if (functionValues.length === 1 && + functionValues[0].kind === 'FunctionExpression' && + functionValues[0].loweredFunc.func.aliasingEffects != null) { + const functionExpr = functionValues[0]; + let signature = context.functionSignatureCache.get(functionExpr); + if (signature == null) { + signature = buildSignatureFromFunctionExpression(state.env, functionExpr); + context.functionSignatureCache.set(functionExpr, signature); + } + const signatureEffects = context.cacheApplySignature(signature, effect, () => computeEffectsForSignature(state.env, signature, effect.into, effect.receiver, effect.args, functionExpr.loweredFunc.func.context, effect.loc)); + if (signatureEffects != null) { + applyEffect(context, state, { kind: 'MutateTransitiveConditionally', value: effect.function }, initialized, effects); + for (const signatureEffect of signatureEffects) { + applyEffect(context, state, signatureEffect, initialized, effects); + } + break; + } + } + let signatureEffects = null; + if (((_d = effect.signature) === null || _d === void 0 ? void 0 : _d.aliasing) != null) { + const signature = effect.signature.aliasing; + signatureEffects = context.cacheApplySignature(effect.signature.aliasing, effect, () => computeEffectsForSignature(state.env, signature, effect.into, effect.receiver, effect.args, [], effect.loc)); + } + if (signatureEffects != null) { + for (const signatureEffect of signatureEffects) { + applyEffect(context, state, signatureEffect, initialized, effects); + } + } + else if (effect.signature != null) { + const legacyEffects = computeEffectsForLegacySignature(state, effect.signature, effect.into, effect.receiver, effect.args, effect.loc); + for (const legacyEffect of legacyEffects) { + applyEffect(context, state, legacyEffect, initialized, effects); + } + } + else { + applyEffect(context, state, { + kind: 'Create', + into: effect.into, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }, initialized, effects); + for (const arg of [effect.receiver, effect.function, ...effect.args]) { + if (arg.kind === 'Hole') { + continue; + } + const operand = arg.kind === 'Identifier' ? arg : arg.place; + if (operand !== effect.function || effect.mutatesFunction) { + applyEffect(context, state, { + kind: 'MutateTransitiveConditionally', + value: operand, + }, initialized, effects); + } + const mutateIterator = arg.kind === 'Spread' ? conditionallyMutateIterator(operand) : null; + if (mutateIterator) { + applyEffect(context, state, mutateIterator, initialized, effects); + } + applyEffect(context, state, { kind: 'MaybeAlias', from: operand, into: effect.into }, initialized, effects); + for (const otherArg of [ + effect.receiver, + effect.function, + ...effect.args, + ]) { + if (otherArg.kind === 'Hole') { + continue; + } + const other = otherArg.kind === 'Identifier' ? otherArg : otherArg.place; + if (other === arg) { + continue; + } + applyEffect(context, state, { + kind: 'Capture', + from: operand, + into: other, + }, initialized, effects); + } + } + } + break; + } + case 'Mutate': + case 'MutateConditionally': + case 'MutateTransitive': + case 'MutateTransitiveConditionally': { + const mutationKind = state.mutate(effect.kind, effect.value); + if (mutationKind === 'mutate') { + effects.push(effect); + } + else if (mutationKind === 'mutate-ref') ; + else if (mutationKind !== 'none' && + (effect.kind === 'Mutate' || effect.kind === 'MutateTransitive')) { + const value = state.kind(effect.value); + if (mutationKind === 'mutate-frozen' && + context.hoistedContextDeclarations.has(effect.value.identifier.declarationId)) { + const variable = effect.value.identifier.name !== null && + effect.value.identifier.name.kind === 'named' + ? `\`${effect.value.identifier.name.value}\`` + : null; + const hoistedAccess = context.hoistedContextDeclarations.get(effect.value.identifier.declarationId); + const diagnostic = CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'Cannot access variable before it is declared', + description: `${variable !== null && variable !== void 0 ? variable : 'This variable'} is accessed before it is declared, which prevents the earlier access from updating when this value changes over time`, + }); + if (hoistedAccess != null && hoistedAccess.loc != effect.value.loc) { + diagnostic.withDetails({ + kind: 'error', + loc: hoistedAccess.loc, + message: `${variable !== null && variable !== void 0 ? variable : 'variable'} accessed before it is declared`, + }); + } + diagnostic.withDetails({ + kind: 'error', + loc: effect.value.loc, + message: `${variable !== null && variable !== void 0 ? variable : 'variable'} is declared here`, + }); + applyEffect(context, state, { + kind: 'MutateFrozen', + place: effect.value, + error: diagnostic, + }, initialized, effects); + } + else { + const reason = getWriteErrorReason({ + kind: value.kind, + reason: value.reason, + }); + const variable = effect.value.identifier.name !== null && + effect.value.identifier.name.kind === 'named' + ? `\`${effect.value.identifier.name.value}\`` + : 'value'; + const diagnostic = CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'This value cannot be modified', + description: reason, + }).withDetails({ + kind: 'error', + loc: effect.value.loc, + message: `${variable} cannot be modified`, + }); + if (effect.kind === 'Mutate' && + ((_e = effect.reason) === null || _e === void 0 ? void 0 : _e.kind) === 'AssignCurrentProperty') { + diagnostic.withDetails({ + kind: 'hint', + message: `Hint: If this value is a Ref (value returned by \`useRef()\`), rename the variable to end in "Ref".`, + }); + } + applyEffect(context, state, { + kind: value.kind === ValueKind.Frozen + ? 'MutateFrozen' + : 'MutateGlobal', + place: effect.value, + error: diagnostic, + }, initialized, effects); + } + } + break; + } + case 'Impure': + case 'Render': + case 'MutateFrozen': + case 'MutateGlobal': { + effects.push(effect); + break; + } + default: { + assertExhaustive$1(effect, `Unexpected effect kind '${effect.kind}'`); + } + } +} +class InferenceState { + constructor(env, isFunctionExpression, values, variables) { + _InferenceState_isFunctionExpression.set(this, void 0); + _InferenceState_values.set(this, void 0); + _InferenceState_variables.set(this, void 0); + this.env = env; + __classPrivateFieldSet(this, _InferenceState_isFunctionExpression, isFunctionExpression, "f"); + __classPrivateFieldSet(this, _InferenceState_values, values, "f"); + __classPrivateFieldSet(this, _InferenceState_variables, variables, "f"); + } + static empty(env, isFunctionExpression) { + return new InferenceState(env, isFunctionExpression, new Map(), new Map()); + } + get isFunctionExpression() { + return __classPrivateFieldGet(this, _InferenceState_isFunctionExpression, "f"); + } + initialize(value, kind) { + CompilerError.invariant(value.kind !== 'LoadLocal', { + reason: '[InferMutationAliasingEffects] Expected all top-level identifiers to be defined as variables, not values', + loc: value.loc, + }); + __classPrivateFieldGet(this, _InferenceState_values, "f").set(value, kind); + } + values(place) { + const values = __classPrivateFieldGet(this, _InferenceState_variables, "f").get(place.identifier.id); + CompilerError.invariant(values != null, { + reason: `[InferMutationAliasingEffects] Expected value kind to be initialized`, + description: `${printPlace(place)}`, + message: 'this is uninitialized', + loc: place.loc, + }); + return Array.from(values); + } + kind(place) { + const values = __classPrivateFieldGet(this, _InferenceState_variables, "f").get(place.identifier.id); + CompilerError.invariant(values != null, { + reason: `[InferMutationAliasingEffects] Expected value kind to be initialized`, + description: `${printPlace(place)}`, + message: 'this is uninitialized', + loc: place.loc, + }); + let mergedKind = null; + for (const value of values) { + const kind = __classPrivateFieldGet(this, _InferenceState_values, "f").get(value); + mergedKind = + mergedKind !== null ? mergeAbstractValues(mergedKind, kind) : kind; + } + CompilerError.invariant(mergedKind !== null, { + reason: `[InferMutationAliasingEffects] Expected at least one value`, + description: `No value found at \`${printPlace(place)}\``, + loc: place.loc, + }); + return mergedKind; + } + assign(place, value) { + const values = __classPrivateFieldGet(this, _InferenceState_variables, "f").get(value.identifier.id); + CompilerError.invariant(values != null, { + reason: `[InferMutationAliasingEffects] Expected value for identifier to be initialized`, + description: `${printIdentifier(value.identifier)}`, + message: 'Expected value for identifier to be initialized', + loc: value.loc, + }); + __classPrivateFieldGet(this, _InferenceState_variables, "f").set(place.identifier.id, new Set(values)); + } + appendAlias(place, value) { + const values = __classPrivateFieldGet(this, _InferenceState_variables, "f").get(value.identifier.id); + CompilerError.invariant(values != null, { + reason: `[InferMutationAliasingEffects] Expected value for identifier to be initialized`, + description: `${printIdentifier(value.identifier)}`, + message: 'Expected value for identifier to be initialized', + loc: value.loc, + }); + const prevValues = this.values(place); + __classPrivateFieldGet(this, _InferenceState_variables, "f").set(place.identifier.id, new Set([...prevValues, ...values])); + } + define(place, value) { + CompilerError.invariant(__classPrivateFieldGet(this, _InferenceState_values, "f").has(value), { + reason: `[InferMutationAliasingEffects] Expected value to be initialized`, + description: printInstructionValue(value), + loc: value.loc, + }); + __classPrivateFieldGet(this, _InferenceState_variables, "f").set(place.identifier.id, new Set([value])); + } + isDefined(place) { + return __classPrivateFieldGet(this, _InferenceState_variables, "f").has(place.identifier.id); + } + freeze(place, reason) { + const value = this.kind(place); + switch (value.kind) { + case ValueKind.Context: + case ValueKind.Mutable: + case ValueKind.MaybeFrozen: { + const values = this.values(place); + for (const instrValue of values) { + this.freezeValue(instrValue, reason); + } + return true; + } + case ValueKind.Frozen: + case ValueKind.Global: + case ValueKind.Primitive: { + return false; + } + default: { + assertExhaustive$1(value.kind, `Unexpected value kind '${value.kind}'`); + } + } + } + freezeValue(value, reason) { + __classPrivateFieldGet(this, _InferenceState_values, "f").set(value, { + kind: ValueKind.Frozen, + reason: new Set([reason]), + }); + if (value.kind === 'FunctionExpression' && + (this.env.config.enablePreserveExistingMemoizationGuarantees || + this.env.config.enableTransitivelyFreezeFunctionExpressions)) { + for (const place of value.loweredFunc.func.context) { + this.freeze(place, reason); + } + } + } + mutate(variant, place) { + if (isRefOrRefValue(place.identifier)) { + return 'mutate-ref'; + } + const kind = this.kind(place).kind; + switch (variant) { + case 'MutateConditionally': + case 'MutateTransitiveConditionally': { + switch (kind) { + case ValueKind.Mutable: + case ValueKind.Context: { + return 'mutate'; + } + default: { + return 'none'; + } + } + } + case 'Mutate': + case 'MutateTransitive': { + switch (kind) { + case ValueKind.Mutable: + case ValueKind.Context: { + return 'mutate'; + } + case ValueKind.Primitive: { + return 'none'; + } + case ValueKind.Frozen: { + return 'mutate-frozen'; + } + case ValueKind.Global: { + return 'mutate-global'; + } + case ValueKind.MaybeFrozen: { + return 'mutate-frozen'; + } + default: { + assertExhaustive$1(kind, `Unexpected kind ${kind}`); + } + } + } + default: { + assertExhaustive$1(variant, `Unexpected mutation variant ${variant}`); + } + } + } + merge(other) { + let nextValues = null; + let nextVariables = null; + for (const [id, thisValue] of __classPrivateFieldGet(this, _InferenceState_values, "f")) { + const otherValue = __classPrivateFieldGet(other, _InferenceState_values, "f").get(id); + if (otherValue !== undefined) { + const mergedValue = mergeAbstractValues(thisValue, otherValue); + if (mergedValue !== thisValue) { + nextValues = nextValues !== null && nextValues !== void 0 ? nextValues : new Map(__classPrivateFieldGet(this, _InferenceState_values, "f")); + nextValues.set(id, mergedValue); + } + } + } + for (const [id, otherValue] of __classPrivateFieldGet(other, _InferenceState_values, "f")) { + if (__classPrivateFieldGet(this, _InferenceState_values, "f").has(id)) { + continue; + } + nextValues = nextValues !== null && nextValues !== void 0 ? nextValues : new Map(__classPrivateFieldGet(this, _InferenceState_values, "f")); + nextValues.set(id, otherValue); + } + for (const [id, thisValues] of __classPrivateFieldGet(this, _InferenceState_variables, "f")) { + const otherValues = __classPrivateFieldGet(other, _InferenceState_variables, "f").get(id); + if (otherValues !== undefined) { + let mergedValues = null; + for (const otherValue of otherValues) { + if (!thisValues.has(otherValue)) { + mergedValues = mergedValues !== null && mergedValues !== void 0 ? mergedValues : new Set(thisValues); + mergedValues.add(otherValue); + } + } + if (mergedValues !== null) { + nextVariables = nextVariables !== null && nextVariables !== void 0 ? nextVariables : new Map(__classPrivateFieldGet(this, _InferenceState_variables, "f")); + nextVariables.set(id, mergedValues); + } + } + } + for (const [id, otherValues] of __classPrivateFieldGet(other, _InferenceState_variables, "f")) { + if (__classPrivateFieldGet(this, _InferenceState_variables, "f").has(id)) { + continue; + } + nextVariables = nextVariables !== null && nextVariables !== void 0 ? nextVariables : new Map(__classPrivateFieldGet(this, _InferenceState_variables, "f")); + nextVariables.set(id, new Set(otherValues)); + } + if (nextVariables === null && nextValues === null) { + return null; + } + else { + return new InferenceState(this.env, __classPrivateFieldGet(this, _InferenceState_isFunctionExpression, "f"), nextValues !== null && nextValues !== void 0 ? nextValues : new Map(__classPrivateFieldGet(this, _InferenceState_values, "f")), nextVariables !== null && nextVariables !== void 0 ? nextVariables : new Map(__classPrivateFieldGet(this, _InferenceState_variables, "f"))); + } + } + clone() { + return new InferenceState(this.env, __classPrivateFieldGet(this, _InferenceState_isFunctionExpression, "f"), new Map(__classPrivateFieldGet(this, _InferenceState_values, "f")), new Map(__classPrivateFieldGet(this, _InferenceState_variables, "f"))); + } + debug() { + const result = { values: {}, variables: {} }; + const objects = new Map(); + function identify(value) { + let id = objects.get(value); + if (id == null) { + id = objects.size; + objects.set(value, id); + } + return id; + } + for (const [value, kind] of __classPrivateFieldGet(this, _InferenceState_values, "f")) { + const id = identify(value); + result.values[id] = { + abstract: this.debugAbstractValue(kind), + value: printInstructionValue(value), + }; + } + for (const [variable, values] of __classPrivateFieldGet(this, _InferenceState_variables, "f")) { + result.variables[`$${variable}`] = [...values].map(identify); + } + return result; + } + debugAbstractValue(value) { + return { + kind: value.kind, + reason: [...value.reason], + }; + } + inferPhi(phi) { + const values = new Set(); + for (const [_, operand] of phi.operands) { + const operandValues = __classPrivateFieldGet(this, _InferenceState_variables, "f").get(operand.identifier.id); + if (operandValues === undefined) + continue; + for (const v of operandValues) { + values.add(v); + } + } + if (values.size > 0) { + __classPrivateFieldGet(this, _InferenceState_variables, "f").set(phi.place.identifier.id, values); + } + } +} +_InferenceState_isFunctionExpression = new WeakMap(), _InferenceState_values = new WeakMap(), _InferenceState_variables = new WeakMap(); +function mergeAbstractValues(a, b) { + const kind = mergeValueKinds(a.kind, b.kind); + if (kind === a.kind && + kind === b.kind && + Set_isSuperset(a.reason, b.reason)) { + return a; + } + const reason = new Set(a.reason); + for (const r of b.reason) { + reason.add(r); + } + return { kind, reason }; +} +function conditionallyMutateIterator(place) { + if (!(isArrayType(place.identifier) || + isSetType(place.identifier) || + isMapType(place.identifier))) { + return { + kind: 'MutateTransitiveConditionally', + value: place, + }; + } + return null; +} +function computeSignatureForInstruction(context, env, instr) { + const { lvalue, value } = instr; + const effects = []; + switch (value.kind) { + case 'ArrayExpression': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + for (const element of value.elements) { + if (element.kind === 'Identifier') { + effects.push({ + kind: 'Capture', + from: element, + into: lvalue, + }); + } + else if (element.kind === 'Spread') { + const mutateIterator = conditionallyMutateIterator(element.place); + if (mutateIterator != null) { + effects.push(mutateIterator); + } + effects.push({ + kind: 'Capture', + from: element.place, + into: lvalue, + }); + } + else { + continue; + } + } + break; + } + case 'ObjectExpression': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + for (const property of value.properties) { + if (property.kind === 'ObjectProperty') { + effects.push({ + kind: 'Capture', + from: property.place, + into: lvalue, + }); + } + else { + effects.push({ + kind: 'Capture', + from: property.place, + into: lvalue, + }); + } + } + break; + } + case 'Await': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + effects.push({ kind: 'MutateTransitiveConditionally', value: value.value }); + effects.push({ + kind: 'Capture', + from: value.value, + into: lvalue, + }); + break; + } + case 'NewExpression': + case 'CallExpression': + case 'MethodCall': { + let callee; + let receiver; + let mutatesCallee; + if (value.kind === 'NewExpression') { + callee = value.callee; + receiver = value.callee; + mutatesCallee = false; + } + else if (value.kind === 'CallExpression') { + callee = value.callee; + receiver = value.callee; + mutatesCallee = true; + } + else if (value.kind === 'MethodCall') { + callee = value.property; + receiver = value.receiver; + mutatesCallee = false; + } + else { + assertExhaustive$1(value, `Unexpected value kind '${value.kind}'`); + } + const signature = getFunctionCallSignature(env, callee.identifier.type); + effects.push({ + kind: 'Apply', + receiver, + function: callee, + mutatesFunction: mutatesCallee, + args: value.args, + into: lvalue, + signature, + loc: value.loc, + }); + break; + } + case 'PropertyDelete': + case 'ComputedDelete': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + effects.push({ kind: 'Mutate', value: value.object }); + break; + } + case 'PropertyLoad': + case 'ComputedLoad': { + if (isPrimitiveType(lvalue.identifier)) { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + } + else { + effects.push({ + kind: 'CreateFrom', + from: value.object, + into: lvalue, + }); + } + break; + } + case 'PropertyStore': + case 'ComputedStore': { + const mutationReason = value.kind === 'PropertyStore' && + value.property === 'current' && + value.object.identifier.type.kind === 'Type' + ? { kind: 'AssignCurrentProperty' } + : null; + effects.push({ + kind: 'Mutate', + value: value.object, + reason: mutationReason, + }); + effects.push({ + kind: 'Capture', + from: value.value, + into: value.object, + }); + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + effects.push({ + kind: 'CreateFunction', + into: lvalue, + function: value, + captures: value.loweredFunc.func.context.filter(operand => operand.effect === Effect.Capture), + }); + break; + } + case 'GetIterator': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + if (isArrayType(value.collection.identifier) || + isMapType(value.collection.identifier) || + isSetType(value.collection.identifier)) { + effects.push({ + kind: 'Capture', + from: value.collection, + into: lvalue, + }); + } + else { + effects.push({ kind: 'Alias', from: value.collection, into: lvalue }); + effects.push({ + kind: 'MutateTransitiveConditionally', + value: value.collection, + }); + } + break; + } + case 'IteratorNext': { + effects.push({ kind: 'MutateConditionally', value: value.iterator }); + effects.push({ + kind: 'CreateFrom', + from: value.collection, + into: lvalue, + }); + break; + } + case 'NextPropertyOf': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'JsxExpression': + case 'JsxFragment': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Frozen, + reason: ValueReason.JsxCaptured, + }); + for (const operand of eachInstructionValueOperand(value)) { + effects.push({ + kind: 'Freeze', + value: operand, + reason: ValueReason.JsxCaptured, + }); + effects.push({ + kind: 'Capture', + from: operand, + into: lvalue, + }); + } + if (value.kind === 'JsxExpression') { + if (value.tag.kind === 'Identifier') { + effects.push({ + kind: 'Render', + place: value.tag, + }); + } + if (value.children != null) { + for (const child of value.children) { + effects.push({ + kind: 'Render', + place: child, + }); + } + } + for (const prop of value.props) { + if (prop.kind === 'JsxAttribute' && + prop.place.identifier.type.kind === 'Function' && + (isJsxType(prop.place.identifier.type.return) || + (prop.place.identifier.type.return.kind === 'Phi' && + prop.place.identifier.type.return.operands.some(operand => isJsxType(operand))))) { + effects.push({ + kind: 'Render', + place: prop.place, + }); + } + } + } + break; + } + case 'DeclareLocal': { + effects.push({ + kind: 'Create', + into: value.lvalue.place, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'Destructure': { + for (const patternItem of eachPatternItem(value.lvalue.pattern)) { + const place = patternItem.kind === 'Identifier' ? patternItem : patternItem.place; + if (isPrimitiveType(place.identifier)) { + effects.push({ + kind: 'Create', + into: place, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + } + else if (patternItem.kind === 'Identifier') { + effects.push({ + kind: 'CreateFrom', + from: value.value, + into: place, + }); + } + else { + effects.push({ + kind: 'Create', + into: place, + reason: ValueReason.Other, + value: context.nonMutatingSpreads.has(place.identifier.id) + ? ValueKind.Frozen + : ValueKind.Mutable, + }); + effects.push({ + kind: 'Capture', + from: value.value, + into: place, + }); + } + } + effects.push({ kind: 'Assign', from: value.value, into: lvalue }); + break; + } + case 'LoadContext': { + effects.push({ kind: 'CreateFrom', from: value.place, into: lvalue }); + break; + } + case 'DeclareContext': { + const kind = value.lvalue.kind; + if (!context.hoistedContextDeclarations.has(value.lvalue.place.identifier.declarationId) || + kind === InstructionKind.HoistedConst || + kind === InstructionKind.HoistedFunction || + kind === InstructionKind.HoistedLet) { + effects.push({ + kind: 'Create', + into: value.lvalue.place, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + } + else { + effects.push({ kind: 'Mutate', value: value.lvalue.place }); + } + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'StoreContext': { + if (value.lvalue.kind === InstructionKind.Reassign || + context.hoistedContextDeclarations.has(value.lvalue.place.identifier.declarationId)) { + effects.push({ kind: 'Mutate', value: value.lvalue.place }); + } + else { + effects.push({ + kind: 'Create', + into: value.lvalue.place, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + } + effects.push({ + kind: 'Capture', + from: value.value, + into: value.lvalue.place, + }); + effects.push({ kind: 'Assign', from: value.value, into: lvalue }); + break; + } + case 'LoadLocal': { + effects.push({ kind: 'Assign', from: value.place, into: lvalue }); + break; + } + case 'StoreLocal': { + effects.push({ + kind: 'Assign', + from: value.value, + into: value.lvalue.place, + }); + effects.push({ kind: 'Assign', from: value.value, into: lvalue }); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + effects.push({ + kind: 'Create', + into: value.lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'StoreGlobal': { + const variable = `\`${value.name}\``; + effects.push({ + kind: 'MutateGlobal', + place: value.value, + error: CompilerDiagnostic.create({ + category: ErrorCategory.Globals, + reason: 'Cannot reassign variables declared outside of the component/hook', + description: `Variable ${variable} is declared outside of the component/hook. Reassigning this value during render is a form of side effect, which can cause unpredictable behavior depending on when the component happens to re-render. If this variable is used in rendering, use useState instead. Otherwise, consider updating it in an effect. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render)`, + }).withDetails({ + kind: 'error', + loc: instr.loc, + message: `${variable} cannot be reassigned`, + }), + }); + effects.push({ kind: 'Assign', from: value.value, into: lvalue }); + break; + } + case 'TypeCastExpression': { + effects.push({ kind: 'Assign', from: value.value, into: lvalue }); + break; + } + case 'LoadGlobal': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Global, + reason: ValueReason.Global, + }); + break; + } + case 'StartMemoize': + case 'FinishMemoize': { + if (env.config.enablePreserveExistingMemoizationGuarantees) { + for (const operand of eachInstructionValueOperand(value)) { + effects.push({ + kind: 'Freeze', + value: operand, + reason: ValueReason.HookCaptured, + }); + } + } + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'TaggedTemplateExpression': + case 'BinaryExpression': + case 'Debugger': + case 'JSXText': + case 'MetaProperty': + case 'Primitive': + case 'RegExpLiteral': + case 'TemplateLiteral': + case 'UnaryExpression': + case 'UnsupportedNode': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + } + return { + effects, + }; +} +function computeEffectsForLegacySignature(state, signature, lvalue, receiver, args, loc) { + var _a, _b; + const returnValueReason = (_a = signature.returnValueReason) !== null && _a !== void 0 ? _a : ValueReason.Other; + const effects = []; + effects.push({ + kind: 'Create', + into: lvalue, + value: signature.returnValueKind, + reason: returnValueReason, + }); + if (signature.impure && state.env.config.validateNoImpureFunctionsInRender) { + effects.push({ + kind: 'Impure', + place: receiver, + error: CompilerDiagnostic.create({ + category: ErrorCategory.Purity, + reason: 'Cannot call impure function during render', + description: (signature.canonicalName != null + ? `\`${signature.canonicalName}\` is an impure function. ` + : '') + + 'Calling an impure function can produce unstable results that update unpredictably when the component happens to re-render. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent)', + }).withDetails({ + kind: 'error', + loc, + message: 'Cannot call impure function', + }), + }); + } + if (signature.knownIncompatible != null && state.env.enableValidations) { + const errors = new CompilerError(); + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.IncompatibleLibrary, + reason: 'Use of incompatible library', + description: [ + 'This API returns functions which cannot be memoized without leading to stale UI. ' + + 'To prevent this, by default React Compiler will skip memoizing this component/hook. ' + + 'However, you may see issues if values from this API are passed to other components/hooks that are ' + + 'memoized', + ].join(''), + }).withDetails({ + kind: 'error', + loc: receiver.loc, + message: signature.knownIncompatible, + })); + throw errors; + } + const stores = []; + const captures = []; + function visit(place, effect) { + switch (effect) { + case Effect.Store: { + effects.push({ + kind: 'Mutate', + value: place, + }); + stores.push(place); + break; + } + case Effect.Capture: { + captures.push(place); + break; + } + case Effect.ConditionallyMutate: { + effects.push({ + kind: 'MutateTransitiveConditionally', + value: place, + }); + break; + } + case Effect.ConditionallyMutateIterator: { + const mutateIterator = conditionallyMutateIterator(place); + if (mutateIterator != null) { + effects.push(mutateIterator); + } + effects.push({ + kind: 'Capture', + from: place, + into: lvalue, + }); + break; + } + case Effect.Freeze: { + effects.push({ + kind: 'Freeze', + value: place, + reason: returnValueReason, + }); + break; + } + case Effect.Mutate: { + effects.push({ kind: 'MutateTransitive', value: place }); + break; + } + case Effect.Read: { + effects.push({ + kind: 'ImmutableCapture', + from: place, + into: lvalue, + }); + break; + } + } + } + if (signature.mutableOnlyIfOperandsAreMutable && + areArgumentsImmutableAndNonMutating(state, args)) { + effects.push({ + kind: 'Alias', + from: receiver, + into: lvalue, + }); + for (const arg of args) { + if (arg.kind === 'Hole') { + continue; + } + const place = arg.kind === 'Identifier' ? arg : arg.place; + effects.push({ + kind: 'ImmutableCapture', + from: place, + into: lvalue, + }); + } + return effects; + } + if (signature.calleeEffect !== Effect.Capture) { + effects.push({ + kind: 'Alias', + from: receiver, + into: lvalue, + }); + } + visit(receiver, signature.calleeEffect); + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg.kind === 'Hole') { + continue; + } + const place = arg.kind === 'Identifier' ? arg : arg.place; + const signatureEffect = arg.kind === 'Identifier' && i < signature.positionalParams.length + ? signature.positionalParams[i] + : ((_b = signature.restParam) !== null && _b !== void 0 ? _b : Effect.ConditionallyMutate); + const effect = getArgumentEffect(signatureEffect, arg); + visit(place, effect); + } + if (captures.length !== 0) { + if (stores.length === 0) { + for (const capture of captures) { + effects.push({ kind: 'Alias', from: capture, into: lvalue }); + } + } + else { + for (const capture of captures) { + for (const store of stores) { + effects.push({ kind: 'Capture', from: capture, into: store }); + } + } + } + } + return effects; +} +function areArgumentsImmutableAndNonMutating(state, args) { + for (const arg of args) { + if (arg.kind === 'Hole') { + continue; + } + if (arg.kind === 'Identifier' && arg.identifier.type.kind === 'Function') { + const fnShape = state.env.getFunctionSignature(arg.identifier.type); + if (fnShape != null) { + return (!fnShape.positionalParams.some(isKnownMutableEffect) && + (fnShape.restParam == null || + !isKnownMutableEffect(fnShape.restParam))); + } + } + const place = arg.kind === 'Identifier' ? arg : arg.place; + const kind = state.kind(place).kind; + switch (kind) { + case ValueKind.Primitive: + case ValueKind.Frozen: { + break; + } + default: { + return false; + } + } + const values = state.values(place); + for (const value of values) { + if (value.kind === 'FunctionExpression' && + value.loweredFunc.func.params.some(param => { + const place = param.kind === 'Identifier' ? param : param.place; + const range = place.identifier.mutableRange; + return range.end > range.start + 1; + })) { + return false; + } + } + } + return true; +} +function computeEffectsForSignature(env, signature, lvalue, receiver, args, context = [], loc) { + var _a, _b, _c, _d, _e, _f, _g; + if (signature.params.length > args.length || + (args.length > signature.params.length && signature.rest == null)) { + return null; + } + const mutableSpreads = new Set(); + const substitutions = new Map(); + substitutions.set(signature.receiver, [receiver]); + substitutions.set(signature.returns, [lvalue]); + const params = signature.params; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg.kind === 'Hole') { + continue; + } + else if (params == null || i >= params.length || arg.kind === 'Spread') { + if (signature.rest == null) { + return null; + } + const place = arg.kind === 'Identifier' ? arg : arg.place; + getOrInsertWith(substitutions, signature.rest, () => []).push(place); + if (arg.kind === 'Spread') { + const mutateIterator = conditionallyMutateIterator(arg.place); + if (mutateIterator != null) { + mutableSpreads.add(arg.place.identifier.id); + } + } + } + else { + const param = params[i]; + substitutions.set(param, [arg]); + } + } + for (const operand of context) { + substitutions.set(operand.identifier.id, [operand]); + } + const effects = []; + for (const signatureTemporary of signature.temporaries) { + const temp = createTemporaryPlace(env, receiver.loc); + substitutions.set(signatureTemporary.identifier.id, [temp]); + } + for (const effect of signature.effects) { + switch (effect.kind) { + case 'MaybeAlias': + case 'Assign': + case 'ImmutableCapture': + case 'Alias': + case 'CreateFrom': + case 'Capture': { + const from = (_a = substitutions.get(effect.from.identifier.id)) !== null && _a !== void 0 ? _a : []; + const to = (_b = substitutions.get(effect.into.identifier.id)) !== null && _b !== void 0 ? _b : []; + for (const fromId of from) { + for (const toId of to) { + effects.push({ + kind: effect.kind, + from: fromId, + into: toId, + }); + } + } + break; + } + case 'Impure': + case 'MutateFrozen': + case 'MutateGlobal': { + const values = (_c = substitutions.get(effect.place.identifier.id)) !== null && _c !== void 0 ? _c : []; + for (const value of values) { + effects.push({ kind: effect.kind, place: value, error: effect.error }); + } + break; + } + case 'Render': { + const values = (_d = substitutions.get(effect.place.identifier.id)) !== null && _d !== void 0 ? _d : []; + for (const value of values) { + effects.push({ kind: effect.kind, place: value }); + } + break; + } + case 'Mutate': + case 'MutateTransitive': + case 'MutateTransitiveConditionally': + case 'MutateConditionally': { + const values = (_e = substitutions.get(effect.value.identifier.id)) !== null && _e !== void 0 ? _e : []; + for (const id of values) { + effects.push({ kind: effect.kind, value: id }); + } + break; + } + case 'Freeze': { + const values = (_f = substitutions.get(effect.value.identifier.id)) !== null && _f !== void 0 ? _f : []; + for (const value of values) { + if (mutableSpreads.has(value.identifier.id)) { + CompilerError.throwTodo({ + reason: 'Support spread syntax for hook arguments', + loc: value.loc, + }); + } + effects.push({ kind: 'Freeze', value, reason: effect.reason }); + } + break; + } + case 'Create': { + const into = (_g = substitutions.get(effect.into.identifier.id)) !== null && _g !== void 0 ? _g : []; + for (const value of into) { + effects.push({ + kind: 'Create', + into: value, + value: effect.value, + reason: effect.reason, + }); + } + break; + } + case 'Apply': { + const applyReceiver = substitutions.get(effect.receiver.identifier.id); + if (applyReceiver == null || applyReceiver.length !== 1) { + return null; + } + const applyFunction = substitutions.get(effect.function.identifier.id); + if (applyFunction == null || applyFunction.length !== 1) { + return null; + } + const applyInto = substitutions.get(effect.into.identifier.id); + if (applyInto == null || applyInto.length !== 1) { + return null; + } + const applyArgs = []; + for (const arg of effect.args) { + if (arg.kind === 'Hole') { + applyArgs.push(arg); + } + else if (arg.kind === 'Identifier') { + const applyArg = substitutions.get(arg.identifier.id); + if (applyArg == null || applyArg.length !== 1) { + return null; + } + applyArgs.push(applyArg[0]); + } + else { + const applyArg = substitutions.get(arg.place.identifier.id); + if (applyArg == null || applyArg.length !== 1) { + return null; + } + applyArgs.push({ kind: 'Spread', place: applyArg[0] }); + } + } + effects.push({ + kind: 'Apply', + mutatesFunction: effect.mutatesFunction, + receiver: applyReceiver[0], + args: applyArgs, + function: applyFunction[0], + into: applyInto[0], + signature: effect.signature, + loc, + }); + break; + } + case 'CreateFunction': { + CompilerError.throwTodo({ + reason: `Support CreateFrom effects in signatures`, + loc: receiver.loc, + }); + } + default: { + assertExhaustive$1(effect, `Unexpected effect kind '${effect.kind}'`); + } + } + } + return effects; +} +function buildSignatureFromFunctionExpression(env, fn) { + var _a; + let rest = null; + const params = []; + for (const param of fn.loweredFunc.func.params) { + if (param.kind === 'Identifier') { + params.push(param.identifier.id); + } + else { + rest = param.place.identifier.id; + } + } + return { + receiver: makeIdentifierId(0), + params, + rest: rest !== null && rest !== void 0 ? rest : createTemporaryPlace(env, fn.loc).identifier.id, + returns: fn.loweredFunc.func.returns.identifier.id, + effects: (_a = fn.loweredFunc.func.aliasingEffects) !== null && _a !== void 0 ? _a : [], + temporaries: [], + }; +} +function getWriteErrorReason(abstractValue) { + if (abstractValue.reason.has(ValueReason.Global)) { + return 'Modifying a variable defined outside a component or hook is not allowed. Consider using an effect'; + } + else if (abstractValue.reason.has(ValueReason.JsxCaptured)) { + return 'Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX'; + } + else if (abstractValue.reason.has(ValueReason.Context)) { + return `Modifying a value returned from 'useContext()' is not allowed.`; + } + else if (abstractValue.reason.has(ValueReason.KnownReturnSignature)) { + return 'Modifying a value returned from a function whose return value should not be mutated'; + } + else if (abstractValue.reason.has(ValueReason.ReactiveFunctionArgument)) { + return 'Modifying component props or hook arguments is not allowed. Consider using a local variable instead'; + } + else if (abstractValue.reason.has(ValueReason.State)) { + return "Modifying a value returned from 'useState()', which should not be modified directly. Use the setter function to update instead"; + } + else if (abstractValue.reason.has(ValueReason.ReducerState)) { + return "Modifying a value returned from 'useReducer()', which should not be modified directly. Use the dispatch function to update instead"; + } + else if (abstractValue.reason.has(ValueReason.Effect)) { + return 'Modifying a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the modification before calling useEffect()'; + } + else if (abstractValue.reason.has(ValueReason.HookCaptured)) { + return 'Modifying a value previously passed as an argument to a hook is not allowed. Consider moving the modification before calling the hook'; + } + else if (abstractValue.reason.has(ValueReason.HookReturn)) { + return 'Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed'; + } + else { + return 'This modifies a variable that React considers immutable'; + } +} +function getArgumentEffect(signatureEffect, arg) { + if (signatureEffect != null) { + if (arg.kind === 'Identifier') { + return signatureEffect; + } + else if (signatureEffect === Effect.Mutate || + signatureEffect === Effect.ConditionallyMutate) { + return signatureEffect; + } + else { + if (signatureEffect === Effect.Freeze) { + CompilerError.throwTodo({ + reason: 'Support spread syntax for hook arguments', + loc: arg.place.loc, + }); + } + return Effect.ConditionallyMutateIterator; + } + } + else { + return Effect.ConditionallyMutate; + } +} +function getFunctionCallSignature(env, type) { + if (type.kind !== 'Function') { + return null; + } + return env.getFunctionSignature(type); +} +function isKnownMutableEffect(effect) { + switch (effect) { + case Effect.Store: + case Effect.ConditionallyMutate: + case Effect.ConditionallyMutateIterator: + case Effect.Mutate: { + return true; + } + case Effect.Unknown: { + CompilerError.invariant(false, { + reason: 'Unexpected unknown effect', + loc: GeneratedSource, + }); + } + case Effect.Read: + case Effect.Capture: + case Effect.Freeze: { + return false; + } + default: { + assertExhaustive$1(effect, `Unexpected effect \`${effect}\``); + } + } +} +function mergeValueKinds(a, b) { + if (a === b) { + return a; + } + else if (a === ValueKind.MaybeFrozen || b === ValueKind.MaybeFrozen) { + return ValueKind.MaybeFrozen; + } + else if (a === ValueKind.Mutable || b === ValueKind.Mutable) { + if (a === ValueKind.Frozen || b === ValueKind.Frozen) { + return ValueKind.MaybeFrozen; + } + else if (a === ValueKind.Context || b === ValueKind.Context) { + return ValueKind.Context; + } + else { + return ValueKind.Mutable; + } + } + else if (a === ValueKind.Context || b === ValueKind.Context) { + if (a === ValueKind.Frozen || b === ValueKind.Frozen) { + return ValueKind.MaybeFrozen; + } + else { + return ValueKind.Context; + } + } + else if (a === ValueKind.Frozen || b === ValueKind.Frozen) { + return ValueKind.Frozen; + } + else if (a === ValueKind.Global || b === ValueKind.Global) { + return ValueKind.Global; + } + else { + CompilerError.invariant(a === ValueKind.Primitive && b == ValueKind.Primitive, { + reason: `Unexpected value kind in mergeValues()`, + description: `Found kinds ${a} and ${b}`, + loc: GeneratedSource, + }); + return ValueKind.Primitive; + } +} + +function pruneNonEscapingScopes(fn) { + const state = new State(fn.env); + for (const param of fn.params) { + if (param.kind === 'Identifier') { + state.declare(param.identifier.declarationId); + } + else { + state.declare(param.place.identifier.declarationId); + } + } + visitReactiveFunction(fn, new CollectDependenciesVisitor(fn.env, state), []); + const memoized = computeMemoizedIdentifiers(state); + visitReactiveFunction(fn, new PruneScopesTransform(), memoized); +} +var MemoizationLevel; +(function (MemoizationLevel) { + MemoizationLevel["Memoized"] = "Memoized"; + MemoizationLevel["Conditional"] = "Conditional"; + MemoizationLevel["Unmemoized"] = "Unmemoized"; + MemoizationLevel["Never"] = "Never"; +})(MemoizationLevel || (MemoizationLevel = {})); +function joinAliases(kind1, kind2) { + if (kind1 === MemoizationLevel.Memoized || + kind2 === MemoizationLevel.Memoized) { + return MemoizationLevel.Memoized; + } + else if (kind1 === MemoizationLevel.Conditional || + kind2 === MemoizationLevel.Conditional) { + return MemoizationLevel.Conditional; + } + else if (kind1 === MemoizationLevel.Unmemoized || + kind2 === MemoizationLevel.Unmemoized) { + return MemoizationLevel.Unmemoized; + } + else { + return MemoizationLevel.Never; + } +} +class State { + constructor(env) { + this.definitions = new Map(); + this.identifiers = new Map(); + this.scopes = new Map(); + this.escapingValues = new Set(); + this.env = env; + } + declare(id) { + this.identifiers.set(id, { + level: MemoizationLevel.Never, + memoized: false, + dependencies: new Set(), + scopes: new Set(), + seen: false, + }); + } + visitOperand(id, place, identifier) { + const scope = getPlaceScope(id, place); + if (scope !== null) { + let node = this.scopes.get(scope.id); + if (node === undefined) { + node = { + dependencies: [...scope.dependencies].map(dep => dep.identifier.declarationId), + seen: false, + }; + this.scopes.set(scope.id, node); + } + const identifierNode = this.identifiers.get(identifier); + CompilerError.invariant(identifierNode !== undefined, { + reason: 'Expected identifier to be initialized', + description: `[${id}] operand=${printPlace(place)} for identifier declaration ${identifier}`, + loc: place.loc, + }); + identifierNode.scopes.add(scope.id); + } + } +} +function computeMemoizedIdentifiers(state) { + const memoized = new Set(); + function visit(id, forceMemoize = false) { + const node = state.identifiers.get(id); + CompilerError.invariant(node !== undefined, { + reason: `Expected a node for all identifiers, none found for \`${id}\``, + loc: GeneratedSource, + }); + if (node.seen) { + return node.memoized; + } + node.seen = true; + node.memoized = false; + let hasMemoizedDependency = false; + for (const dep of node.dependencies) { + const isDepMemoized = visit(dep); + hasMemoizedDependency || (hasMemoizedDependency = isDepMemoized); + } + if (node.level === MemoizationLevel.Memoized || + (node.level === MemoizationLevel.Conditional && + (hasMemoizedDependency || forceMemoize)) || + (node.level === MemoizationLevel.Unmemoized && forceMemoize)) { + node.memoized = true; + memoized.add(id); + for (const scope of node.scopes) { + forceMemoizeScopeDependencies(scope); + } + } + return node.memoized; + } + function forceMemoizeScopeDependencies(id) { + const node = state.scopes.get(id); + CompilerError.invariant(node !== undefined, { + reason: 'Expected a node for all scopes', + loc: GeneratedSource, + }); + if (node.seen) { + return; + } + node.seen = true; + for (const dep of node.dependencies) { + visit(dep, true); + } + return; + } + for (const value of state.escapingValues) { + visit(value); + } + return memoized; +} +function computePatternLValues(pattern) { + const lvalues = []; + switch (pattern.kind) { + case 'ArrayPattern': { + for (const item of pattern.items) { + if (item.kind === 'Identifier') { + lvalues.push({ place: item, level: MemoizationLevel.Conditional }); + } + else if (item.kind === 'Spread') { + lvalues.push({ place: item.place, level: MemoizationLevel.Memoized }); + } + } + break; + } + case 'ObjectPattern': { + for (const property of pattern.properties) { + if (property.kind === 'ObjectProperty') { + lvalues.push({ + place: property.place, + level: MemoizationLevel.Conditional, + }); + } + else { + lvalues.push({ + place: property.place, + level: MemoizationLevel.Memoized, + }); + } + } + break; + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } + return lvalues; +} +class CollectDependenciesVisitor extends ReactiveFunctionVisitor { + constructor(env, state) { + super(); + this.env = env; + this.state = state; + this.options = { + memoizeJsxElements: !this.env.config.enableForest, + forceMemoizePrimitives: this.env.config.enableForest || + this.env.config.enablePreserveExistingMemoizationGuarantees, + }; + } + computeMemoizationInputs(value, lvalue) { + const env = this.env; + const options = this.options; + switch (value.kind) { + case 'ConditionalExpression': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [ + ...this.computeMemoizationInputs(value.consequent, null).rvalues, + ...this.computeMemoizationInputs(value.alternate, null).rvalues, + ], + }; + } + case 'LogicalExpression': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [ + ...this.computeMemoizationInputs(value.left, null).rvalues, + ...this.computeMemoizationInputs(value.right, null).rvalues, + ], + }; + } + case 'SequenceExpression': { + for (const instr of value.instructions) { + this.visitValueForMemoization(instr.id, instr.value, instr.lvalue); + } + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: this.computeMemoizationInputs(value.value, null).rvalues, + }; + } + case 'JsxExpression': { + const operands = []; + if (value.tag.kind === 'Identifier') { + operands.push(value.tag); + } + for (const prop of value.props) { + if (prop.kind === 'JsxAttribute') { + operands.push(prop.place); + } + else { + operands.push(prop.argument); + } + } + if (value.children !== null) { + for (const child of value.children) { + operands.push(child); + } + } + const level = options.memoizeJsxElements + ? MemoizationLevel.Memoized + : MemoizationLevel.Unmemoized; + return { + lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], + rvalues: operands, + }; + } + case 'JsxFragment': { + const level = options.memoizeJsxElements + ? MemoizationLevel.Memoized + : MemoizationLevel.Unmemoized; + return { + lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], + rvalues: value.children, + }; + } + case 'NextPropertyOf': + case 'StartMemoize': + case 'FinishMemoize': + case 'Debugger': + case 'ComputedDelete': + case 'PropertyDelete': + case 'LoadGlobal': + case 'MetaProperty': + case 'TemplateLiteral': + case 'Primitive': + case 'JSXText': + case 'BinaryExpression': + case 'UnaryExpression': { + if (options.forceMemoizePrimitives) { + const level = MemoizationLevel.Conditional; + return { + lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], + rvalues: [...eachReactiveValueOperand(value)], + }; + } + const level = MemoizationLevel.Never; + return { + lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], + rvalues: [], + }; + } + case 'Await': + case 'TypeCastExpression': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.value], + }; + } + case 'IteratorNext': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.iterator, value.collection], + }; + } + case 'GetIterator': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.collection], + }; + } + case 'LoadLocal': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.place], + }; + } + case 'LoadContext': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.place], + }; + } + case 'DeclareContext': { + const lvalues = [ + { place: value.lvalue.place, level: MemoizationLevel.Memoized }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Unmemoized }); + } + return { + lvalues, + rvalues: [], + }; + } + case 'DeclareLocal': { + const lvalues = [ + { place: value.lvalue.place, level: MemoizationLevel.Unmemoized }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Unmemoized }); + } + return { + lvalues, + rvalues: [], + }; + } + case 'PrefixUpdate': + case 'PostfixUpdate': { + const lvalues = [ + { place: value.lvalue, level: MemoizationLevel.Conditional }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + return { + lvalues, + rvalues: [value.value], + }; + } + case 'StoreLocal': { + const lvalues = [ + { place: value.lvalue.place, level: MemoizationLevel.Conditional }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + return { + lvalues, + rvalues: [value.value], + }; + } + case 'StoreContext': { + const lvalues = [ + { place: value.lvalue.place, level: MemoizationLevel.Memoized }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + return { + lvalues, + rvalues: [value.value], + }; + } + case 'StoreGlobal': { + const lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Unmemoized }); + } + return { + lvalues, + rvalues: [value.value], + }; + } + case 'Destructure': { + const lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + lvalues.push(...computePatternLValues(value.lvalue.pattern)); + return { + lvalues: lvalues, + rvalues: [value.value], + }; + } + case 'ComputedLoad': + case 'PropertyLoad': { + const level = MemoizationLevel.Conditional; + return { + lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], + rvalues: [value.object], + }; + } + case 'ComputedStore': { + const lvalues = [ + { place: value.object, level: MemoizationLevel.Conditional }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + return { + lvalues, + rvalues: [value.value], + }; + } + case 'OptionalExpression': { + const lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + return { + lvalues: lvalues, + rvalues: [ + ...this.computeMemoizationInputs(value.value, null).rvalues, + ], + }; + } + case 'TaggedTemplateExpression': { + const signature = getFunctionCallSignature(env, value.tag.identifier.type); + let lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Memoized }); + } + if ((signature === null || signature === void 0 ? void 0 : signature.noAlias) === true) { + return { + lvalues, + rvalues: [], + }; + } + const operands = [...eachReactiveValueOperand(value)]; + lvalues.push(...operands + .filter(operand => isMutableEffect(operand.effect, operand.loc)) + .map(place => ({ place, level: MemoizationLevel.Memoized }))); + return { + lvalues, + rvalues: operands, + }; + } + case 'CallExpression': { + const signature = getFunctionCallSignature(env, value.callee.identifier.type); + let lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Memoized }); + } + if ((signature === null || signature === void 0 ? void 0 : signature.noAlias) === true) { + return { + lvalues, + rvalues: [], + }; + } + const operands = [...eachReactiveValueOperand(value)]; + lvalues.push(...operands + .filter(operand => isMutableEffect(operand.effect, operand.loc)) + .map(place => ({ place, level: MemoizationLevel.Memoized }))); + return { + lvalues, + rvalues: operands, + }; + } + case 'MethodCall': { + const signature = getFunctionCallSignature(env, value.property.identifier.type); + let lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Memoized }); + } + if ((signature === null || signature === void 0 ? void 0 : signature.noAlias) === true) { + return { + lvalues, + rvalues: [], + }; + } + const operands = [...eachReactiveValueOperand(value)]; + lvalues.push(...operands + .filter(operand => isMutableEffect(operand.effect, operand.loc)) + .map(place => ({ place, level: MemoizationLevel.Memoized }))); + return { + lvalues, + rvalues: operands, + }; + } + case 'RegExpLiteral': + case 'ObjectMethod': + case 'FunctionExpression': + case 'ArrayExpression': + case 'NewExpression': + case 'ObjectExpression': + case 'PropertyStore': { + const operands = [...eachReactiveValueOperand(value)]; + const lvalues = operands + .filter(operand => isMutableEffect(operand.effect, operand.loc)) + .map(place => ({ place, level: MemoizationLevel.Memoized })); + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Memoized }); + } + return { + lvalues, + rvalues: operands, + }; + } + case 'UnsupportedNode': { + const lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Never }); + } + return { + lvalues, + rvalues: [], + }; + } + default: { + assertExhaustive$1(value, `Unexpected value kind \`${value.kind}\``); + } + } + } + visitValueForMemoization(id, value, lvalue) { + var _a, _b, _c; + const state = this.state; + const aliasing = this.computeMemoizationInputs(value, lvalue); + for (const operand of aliasing.rvalues) { + const operandId = (_a = state.definitions.get(operand.identifier.declarationId)) !== null && _a !== void 0 ? _a : operand.identifier.declarationId; + state.visitOperand(id, operand, operandId); + } + for (const { place: lvalue, level } of aliasing.lvalues) { + const lvalueId = (_b = state.definitions.get(lvalue.identifier.declarationId)) !== null && _b !== void 0 ? _b : lvalue.identifier.declarationId; + let node = state.identifiers.get(lvalueId); + if (node === undefined) { + node = { + level: MemoizationLevel.Never, + memoized: false, + dependencies: new Set(), + scopes: new Set(), + seen: false, + }; + state.identifiers.set(lvalueId, node); + } + node.level = joinAliases(node.level, level); + for (const operand of aliasing.rvalues) { + const operandId = (_c = state.definitions.get(operand.identifier.declarationId)) !== null && _c !== void 0 ? _c : operand.identifier.declarationId; + if (operandId === lvalueId) { + continue; + } + node.dependencies.add(operandId); + } + state.visitOperand(id, lvalue, lvalueId); + } + if (value.kind === 'LoadLocal' && lvalue !== null) { + state.definitions.set(lvalue.identifier.declarationId, value.place.identifier.declarationId); + } + else if (value.kind === 'CallExpression' || value.kind === 'MethodCall') { + let callee = value.kind === 'CallExpression' ? value.callee : value.property; + if (getHookKind(state.env, callee.identifier) != null) { + const signature = getFunctionCallSignature(this.env, callee.identifier.type); + if (signature && signature.noAlias === true) { + return; + } + for (const operand of value.args) { + const place = operand.kind === 'Spread' ? operand.place : operand; + state.escapingValues.add(place.identifier.declarationId); + } + } + } + } + visitInstruction(instruction, _scopes) { + this.visitValueForMemoization(instruction.id, instruction.value, instruction.lvalue); + } + visitTerminal(stmt, scopes) { + this.traverseTerminal(stmt, scopes); + if (stmt.terminal.kind === 'return') { + this.state.escapingValues.add(stmt.terminal.value.identifier.declarationId); + const identifierNode = this.state.identifiers.get(stmt.terminal.value.identifier.declarationId); + CompilerError.invariant(identifierNode !== undefined, { + reason: 'Expected identifier to be initialized', + loc: stmt.terminal.loc, + }); + for (const scope of scopes) { + identifierNode.scopes.add(scope.id); + } + } + } + visitScope(scope, scopes) { + for (const reassignment of scope.scope.reassignments) { + const identifierNode = this.state.identifiers.get(reassignment.declarationId); + CompilerError.invariant(identifierNode !== undefined, { + reason: 'Expected identifier to be initialized', + loc: reassignment.loc, + }); + for (const scope of scopes) { + identifierNode.scopes.add(scope.id); + } + identifierNode.scopes.add(scope.scope.id); + } + this.traverseScope(scope, [...scopes, scope.scope]); + } +} +class PruneScopesTransform extends ReactiveFunctionTransform { + constructor() { + super(...arguments); + this.prunedScopes = new Set(); + this.reassignments = new Map(); + } + transformScope(scopeBlock, state) { + this.visitScope(scopeBlock, state); + if ((scopeBlock.scope.declarations.size === 0 && + scopeBlock.scope.reassignments.size === 0) || + scopeBlock.scope.earlyReturnValue !== null) { + return { kind: 'keep' }; + } + const hasMemoizedOutput = Array.from(scopeBlock.scope.declarations.values()).some(decl => state.has(decl.identifier.declarationId)) || + Array.from(scopeBlock.scope.reassignments).some(identifier => state.has(identifier.declarationId)); + if (hasMemoizedOutput) { + return { kind: 'keep' }; + } + else { + this.prunedScopes.add(scopeBlock.scope.id); + return { + kind: 'replace-many', + value: scopeBlock.instructions, + }; + } + } + transformInstruction(instruction, state) { + var _a; + this.traverseInstruction(instruction, state); + const value = instruction.value; + if (value.kind === 'StoreLocal' && value.lvalue.kind === 'Reassign') { + const ids = getOrInsertDefault(this.reassignments, value.lvalue.place.identifier.declarationId, new Set()); + ids.add(value.value.identifier); + } + else if (value.kind === 'LoadLocal' && + value.place.identifier.scope != null && + instruction.lvalue != null && + instruction.lvalue.identifier.scope == null) { + const ids = getOrInsertDefault(this.reassignments, instruction.lvalue.identifier.declarationId, new Set()); + ids.add(value.place.identifier); + } + else if (value.kind === 'FinishMemoize') { + let decls; + if (value.decl.identifier.scope == null) { + decls = (_a = this.reassignments.get(value.decl.identifier.declarationId)) !== null && _a !== void 0 ? _a : [ + value.decl.identifier, + ]; + } + else { + decls = [value.decl.identifier]; + } + if ([...decls].every(decl => decl.scope == null || this.prunedScopes.has(decl.scope.id))) { + value.pruned = true; + } + } + return { kind: 'keep' }; + } +} + +let Visitor$5 = class Visitor extends ReactiveFunctionVisitor { + visitLValue(id, lvalue, state) { + this.visitPlace(id, lvalue, state); + } + visitPlace(_id, place, state) { + if (place.reactive) { + state.add(place.identifier.id); + } + } + visitPrunedScope(scopeBlock, state) { + this.traversePrunedScope(scopeBlock, state); + for (const [id, decl] of scopeBlock.scope.declarations) { + if (!isPrimitiveType(decl.identifier) && + !isStableRefType(decl.identifier, state)) { + state.add(id); + } + } + } +}; +function isStableRefType(identifier, reactiveIdentifiers) { + return isUseRefType(identifier) && !reactiveIdentifiers.has(identifier.id); +} +function collectReactiveIdentifiers(fn) { + const visitor = new Visitor$5(); + const state = new Set(); + visitReactiveFunction(fn, visitor, state); + return state; +} + +function pruneNonReactiveDependencies(fn) { + const reactiveIdentifiers = collectReactiveIdentifiers(fn); + visitReactiveFunction(fn, new Visitor$4(), reactiveIdentifiers); +} +let Visitor$4 = class Visitor extends ReactiveFunctionVisitor { + visitInstruction(instruction, state) { + this.traverseInstruction(instruction, state); + const { lvalue, value } = instruction; + switch (value.kind) { + case 'LoadLocal': { + if (lvalue !== null && state.has(value.place.identifier.id)) { + state.add(lvalue.identifier.id); + } + break; + } + case 'StoreLocal': { + if (state.has(value.value.identifier.id)) { + state.add(value.lvalue.place.identifier.id); + if (lvalue !== null) { + state.add(lvalue.identifier.id); + } + } + break; + } + case 'Destructure': { + if (state.has(value.value.identifier.id)) { + for (const lvalue of eachPatternOperand(value.lvalue.pattern)) { + if (isStableType(lvalue.identifier)) { + continue; + } + state.add(lvalue.identifier.id); + } + if (lvalue !== null) { + state.add(lvalue.identifier.id); + } + } + break; + } + case 'PropertyLoad': { + if (lvalue !== null && + state.has(value.object.identifier.id) && + !isStableType(lvalue.identifier)) { + state.add(lvalue.identifier.id); + } + break; + } + case 'ComputedLoad': { + if (lvalue !== null && + (state.has(value.object.identifier.id) || + state.has(value.property.identifier.id))) { + state.add(lvalue.identifier.id); + } + break; + } + } + } + visitScope(scopeBlock, state) { + this.traverseScope(scopeBlock, state); + for (const dep of scopeBlock.scope.dependencies) { + const isReactive = state.has(dep.identifier.id); + if (!isReactive) { + scopeBlock.scope.dependencies.delete(dep); + } + } + if (scopeBlock.scope.dependencies.size !== 0) { + for (const [, declaration] of scopeBlock.scope.declarations) { + state.add(declaration.identifier.id); + } + for (const reassignment of scopeBlock.scope.reassignments) { + state.add(reassignment.id); + } + } + } +}; + +function pruneUnusedLValues(fn) { + const lvalues = new Map(); + visitReactiveFunction(fn, new Visitor$3(), lvalues); + for (const [, instr] of lvalues) { + instr.lvalue = null; + } +} +let Visitor$3 = class Visitor extends ReactiveFunctionVisitor { + visitPlace(id, place, state) { + state.delete(place.identifier.declarationId); + } + visitInstruction(instruction, state) { + this.traverseInstruction(instruction, state); + if (instruction.lvalue !== null && + instruction.lvalue.identifier.name === null) { + state.set(instruction.lvalue.identifier.declarationId, instruction); + } + } +}; + +function pruneUnusedLabels(fn) { + const labels = new Set(); + visitReactiveFunction(fn, new Transform$2(), labels); +} +let Transform$2 = class Transform extends ReactiveFunctionTransform { + transformTerminal(stmt, state) { + this.traverseTerminal(stmt, state); + const { terminal } = stmt; + if ((terminal.kind === 'break' || terminal.kind === 'continue') && + terminal.targetKind === 'labeled') { + state.add(terminal.target); + } + const isReachableLabel = stmt.label !== null && state.has(stmt.label.id); + if (stmt.terminal.kind === 'label' && !isReachableLabel) { + const block = [...stmt.terminal.block]; + const last = block.at(-1); + if (last !== undefined && + last.kind === 'terminal' && + last.terminal.kind === 'break' && + last.terminal.target === null) { + block.pop(); + } + return { kind: 'replace-many', value: block }; + } + else { + if (!isReachableLabel && stmt.label != null) { + stmt.label.implicit = true; + } + return { kind: 'keep' }; + } + } +}; + +function pruneUnusedScopes(fn) { + visitReactiveFunction(fn, new Transform$1(), { + hasReturnStatement: false, + }); +} +let Transform$1 = class Transform extends ReactiveFunctionTransform { + visitTerminal(stmt, state) { + this.traverseTerminal(stmt, state); + if (stmt.terminal.kind === 'return') { + state.hasReturnStatement = true; + } + } + transformScope(scopeBlock, _state) { + const scopeState = { hasReturnStatement: false }; + this.visitScope(scopeBlock, scopeState); + if (!scopeState.hasReturnStatement && + scopeBlock.scope.reassignments.size === 0 && + (scopeBlock.scope.declarations.size === 0 || + !hasOwnDeclaration(scopeBlock))) { + return { + kind: 'replace', + value: { + kind: 'pruned-scope', + scope: scopeBlock.scope, + instructions: scopeBlock.instructions, + }, + }; + } + else { + return { kind: 'keep' }; + } + } +}; +function hasOwnDeclaration(block) { + for (const declaration of block.scope.declarations.values()) { + if (declaration.scope.id === block.scope.id) { + return true; + } + } + return false; +} + +function collectReferencedGlobals(fn) { + const identifiers = new Set(); + visitReactiveFunction(fn, new Visitor$2(), identifiers); + return identifiers; +} +let Visitor$2 = class Visitor extends ReactiveFunctionVisitor { + visitValue(id, value, state) { + this.traverseValue(id, value, state); + if (value.kind === 'FunctionExpression' || value.kind === 'ObjectMethod') { + this.visitHirFunction(value.loweredFunc.func, state); + } + else if (value.kind === 'LoadGlobal') { + state.add(value.binding.name); + } + } + visitReactiveFunctionValue(_id, _dependencies, fn, state) { + visitReactiveFunction(fn, this, state); + } +}; + +var _Scopes_instances, _Scopes_seen, _Scopes_stack, _Scopes_globals, _Scopes_programContext, _Scopes_lookup; +function renameVariables(fn) { + const globals = collectReferencedGlobals(fn); + const scopes = new Scopes(globals, fn.env.programContext); + renameVariablesImpl(fn, new Visitor$1(), scopes); + return new Set([...scopes.names, ...globals]); +} +function renameVariablesImpl(fn, visitor, scopes) { + scopes.enter(() => { + for (const param of fn.params) { + if (param.kind === 'Identifier') { + scopes.visit(param.identifier); + } + else { + scopes.visit(param.place.identifier); + } + } + visitReactiveFunction(fn, visitor, scopes); + }); +} +let Visitor$1 = class Visitor extends ReactiveFunctionVisitor { + visitParam(place, state) { + state.visit(place.identifier); + } + visitLValue(_id, lvalue, state) { + state.visit(lvalue.identifier); + } + visitPlace(id, place, state) { + state.visit(place.identifier); + } + visitBlock(block, state) { + state.enter(() => { + this.traverseBlock(block, state); + }); + } + visitPrunedScope(scopeBlock, state) { + this.traverseBlock(scopeBlock.instructions, state); + } + visitScope(scope, state) { + for (const [_, declaration] of scope.scope.declarations) { + state.visit(declaration.identifier); + } + this.traverseScope(scope, state); + } + visitValue(id, value, state) { + this.traverseValue(id, value, state); + if (value.kind === 'FunctionExpression' || value.kind === 'ObjectMethod') { + this.visitHirFunction(value.loweredFunc.func, state); + } + } + visitReactiveFunctionValue(_id, _dependencies, _fn, _state) { + renameVariablesImpl(_fn, this, _state); + } +}; +class Scopes { + constructor(globals, programContext) { + _Scopes_instances.add(this); + _Scopes_seen.set(this, new Map()); + _Scopes_stack.set(this, [new Map()]); + _Scopes_globals.set(this, void 0); + _Scopes_programContext.set(this, void 0); + this.names = new Set(); + __classPrivateFieldSet(this, _Scopes_globals, globals, "f"); + __classPrivateFieldSet(this, _Scopes_programContext, programContext, "f"); + } + visit(identifier) { + const originalName = identifier.name; + if (originalName === null) { + return; + } + const mappedName = __classPrivateFieldGet(this, _Scopes_seen, "f").get(identifier.declarationId); + if (mappedName !== undefined) { + identifier.name = mappedName; + return; + } + let name = originalName.value; + let id = 0; + if (isPromotedTemporary(originalName.value)) { + name = `t${id++}`; + } + else if (isPromotedJsxTemporary(originalName.value)) { + name = `T${id++}`; + } + while (__classPrivateFieldGet(this, _Scopes_instances, "m", _Scopes_lookup).call(this, name) !== null || __classPrivateFieldGet(this, _Scopes_globals, "f").has(name)) { + if (isPromotedTemporary(originalName.value)) { + name = `t${id++}`; + } + else if (isPromotedJsxTemporary(originalName.value)) { + name = `T${id++}`; + } + else { + name = `${originalName.value}$${id++}`; + } + } + __classPrivateFieldGet(this, _Scopes_programContext, "f").addNewReference(name); + const identifierName = makeIdentifierName(name); + identifier.name = identifierName; + __classPrivateFieldGet(this, _Scopes_seen, "f").set(identifier.declarationId, identifierName); + __classPrivateFieldGet(this, _Scopes_stack, "f").at(-1).set(identifierName.value, identifier.declarationId); + this.names.add(identifierName.value); + } + enter(fn) { + const next = new Map(); + __classPrivateFieldGet(this, _Scopes_stack, "f").push(next); + fn(); + const last = __classPrivateFieldGet(this, _Scopes_stack, "f").pop(); + CompilerError.invariant(last === next, { + reason: 'Mismatch push/pop calls', + loc: GeneratedSource, + }); + } +} +_Scopes_seen = new WeakMap(), _Scopes_stack = new WeakMap(), _Scopes_globals = new WeakMap(), _Scopes_programContext = new WeakMap(), _Scopes_instances = new WeakSet(), _Scopes_lookup = function _Scopes_lookup(name) { + for (let i = __classPrivateFieldGet(this, _Scopes_stack, "f").length - 1; i >= 0; i--) { + const scope = __classPrivateFieldGet(this, _Scopes_stack, "f")[i]; + const entry = scope.get(name); + if (entry !== undefined) { + return entry; + } + } + return null; +}; + +function stabilizeBlockIds(fn) { + const referenced = new Set(); + visitReactiveFunction(fn, new CollectReferencedLabels(), referenced); + const mappings = new Map(); + for (const blockId of referenced) { + mappings.set(blockId, makeBlockId(mappings.size)); + } + visitReactiveFunction(fn, new RewriteBlockIds(), mappings); +} +class CollectReferencedLabels extends ReactiveFunctionVisitor { + visitScope(scope, state) { + const { earlyReturnValue } = scope.scope; + if (earlyReturnValue != null) { + state.add(earlyReturnValue.label); + } + this.traverseScope(scope, state); + } + visitTerminal(stmt, state) { + if (stmt.label != null) { + if (!stmt.label.implicit) { + state.add(stmt.label.id); + } + } + this.traverseTerminal(stmt, state); + } +} +class RewriteBlockIds extends ReactiveFunctionVisitor { + visitScope(scope, state) { + const { earlyReturnValue } = scope.scope; + if (earlyReturnValue != null) { + const rewrittenId = getOrInsertDefault(state, earlyReturnValue.label, state.size); + earlyReturnValue.label = makeBlockId(rewrittenId); + } + this.traverseScope(scope, state); + } + visitTerminal(stmt, state) { + if (stmt.label != null) { + const rewrittenId = getOrInsertDefault(state, stmt.label.id, state.size); + stmt.label.id = makeBlockId(rewrittenId); + } + const terminal = stmt.terminal; + if (terminal.kind === 'break' || terminal.kind === 'continue') { + const rewrittenId = getOrInsertDefault(state, terminal.target, state.size); + terminal.target = makeBlockId(rewrittenId); + } + this.traverseTerminal(stmt, state); + } +} + +function inferMutationAliasingRanges(fn, { isFunctionExpression }) { + var _a, _b, _c, _d, _e, _f, _g; + const functionEffects = []; + const state = new AliasingState(); + const pendingPhis = new Map(); + const mutations = []; + const renders = []; + let index = 0; + const shouldRecordErrors = !isFunctionExpression && fn.env.enableValidations; + for (const param of [...fn.params, ...fn.context, fn.returns]) { + const place = param.kind === 'Identifier' ? param : param.place; + state.create(place, { kind: 'Object' }); + } + const seenBlocks = new Set(); + for (const block of fn.body.blocks.values()) { + for (const phi of block.phis) { + state.create(phi.place, { kind: 'Phi' }); + for (const [pred, operand] of phi.operands) { + if (!seenBlocks.has(pred)) { + const blockPhis = getOrInsertWith(pendingPhis, pred, () => []); + blockPhis.push({ from: operand, into: phi.place, index: index++ }); + } + else { + state.assign(index++, operand, phi.place); + } + } + } + seenBlocks.add(block.id); + for (const instr of block.instructions) { + if (instr.effects == null) + continue; + for (const effect of instr.effects) { + if (effect.kind === 'Create') { + state.create(effect.into, { kind: 'Object' }); + } + else if (effect.kind === 'CreateFunction') { + state.create(effect.into, { + kind: 'Function', + function: effect.function.loweredFunc.func, + }); + } + else if (effect.kind === 'CreateFrom') { + state.createFrom(index++, effect.from, effect.into); + } + else if (effect.kind === 'Assign') { + if (!state.nodes.has(effect.into.identifier)) { + state.create(effect.into, { kind: 'Object' }); + } + state.assign(index++, effect.from, effect.into); + } + else if (effect.kind === 'Alias') { + state.assign(index++, effect.from, effect.into); + } + else if (effect.kind === 'MaybeAlias') { + state.maybeAlias(index++, effect.from, effect.into); + } + else if (effect.kind === 'Capture') { + state.capture(index++, effect.from, effect.into); + } + else if (effect.kind === 'MutateTransitive' || + effect.kind === 'MutateTransitiveConditionally') { + mutations.push({ + index: index++, + id: instr.id, + transitive: true, + kind: effect.kind === 'MutateTransitive' + ? MutationKind.Definite + : MutationKind.Conditional, + reason: null, + place: effect.value, + }); + } + else if (effect.kind === 'Mutate' || + effect.kind === 'MutateConditionally') { + mutations.push({ + index: index++, + id: instr.id, + transitive: false, + kind: effect.kind === 'Mutate' + ? MutationKind.Definite + : MutationKind.Conditional, + reason: effect.kind === 'Mutate' ? ((_a = effect.reason) !== null && _a !== void 0 ? _a : null) : null, + place: effect.value, + }); + } + else if (effect.kind === 'MutateFrozen' || + effect.kind === 'MutateGlobal' || + effect.kind === 'Impure') { + if (shouldRecordErrors) { + fn.env.recordError(effect.error); + } + functionEffects.push(effect); + } + else if (effect.kind === 'Render') { + renders.push({ index: index++, place: effect.place }); + functionEffects.push(effect); + } + } + } + const blockPhis = pendingPhis.get(block.id); + if (blockPhis != null) { + for (const { from, into, index } of blockPhis) { + state.assign(index, from, into); + } + } + if (block.terminal.kind === 'return') { + state.assign(index++, block.terminal.value, fn.returns); + } + if ((block.terminal.kind === 'maybe-throw' || + block.terminal.kind === 'return') && + block.terminal.effects != null) { + for (const effect of block.terminal.effects) { + if (effect.kind === 'Alias') { + state.assign(index++, effect.from, effect.into); + } + else { + CompilerError.invariant(effect.kind === 'Freeze', { + reason: `Unexpected '${effect.kind}' effect for MaybeThrow terminal`, + loc: block.terminal.loc, + }); + } + } + } + } + for (const mutation of mutations) { + state.mutate(mutation.index, mutation.place.identifier, makeInstructionId(mutation.id + 1), mutation.transitive, mutation.kind, mutation.place.loc, mutation.reason, shouldRecordErrors ? fn.env : null); + } + for (const render of renders) { + state.render(render.index, render.place.identifier, shouldRecordErrors ? fn.env : null); + } + for (const param of [...fn.context, ...fn.params]) { + const place = param.kind === 'Identifier' ? param : param.place; + const node = state.nodes.get(place.identifier); + if (node == null) { + continue; + } + let mutated = false; + if (node.local != null) { + if (node.local.kind === MutationKind.Conditional) { + mutated = true; + functionEffects.push({ + kind: 'MutateConditionally', + value: Object.assign(Object.assign({}, place), { loc: node.local.loc }), + }); + } + else if (node.local.kind === MutationKind.Definite) { + mutated = true; + functionEffects.push({ + kind: 'Mutate', + value: Object.assign(Object.assign({}, place), { loc: node.local.loc }), + reason: node.mutationReason, + }); + } + } + if (node.transitive != null) { + if (node.transitive.kind === MutationKind.Conditional) { + mutated = true; + functionEffects.push({ + kind: 'MutateTransitiveConditionally', + value: Object.assign(Object.assign({}, place), { loc: node.transitive.loc }), + }); + } + else if (node.transitive.kind === MutationKind.Definite) { + mutated = true; + functionEffects.push({ + kind: 'MutateTransitive', + value: Object.assign(Object.assign({}, place), { loc: node.transitive.loc }), + }); + } + } + if (mutated) { + place.effect = Effect.Capture; + } + } + for (const block of fn.body.blocks.values()) { + for (const phi of block.phis) { + phi.place.effect = Effect.Store; + const isPhiMutatedAfterCreation = phi.place.identifier.mutableRange.end > + ((_c = (_b = block.instructions.at(0)) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : block.terminal.id); + for (const operand of phi.operands.values()) { + operand.effect = isPhiMutatedAfterCreation + ? Effect.Capture + : Effect.Read; + } + if (isPhiMutatedAfterCreation && + phi.place.identifier.mutableRange.start === 0) { + const firstInstructionIdOfBlock = (_e = (_d = block.instructions.at(0)) === null || _d === void 0 ? void 0 : _d.id) !== null && _e !== void 0 ? _e : block.terminal.id; + phi.place.identifier.mutableRange.start = makeInstructionId(firstInstructionIdOfBlock - 1); + } + } + for (const instr of block.instructions) { + for (const lvalue of eachInstructionLValue(instr)) { + lvalue.effect = Effect.ConditionallyMutate; + if (lvalue.identifier.mutableRange.start === 0) { + lvalue.identifier.mutableRange.start = instr.id; + } + if (lvalue.identifier.mutableRange.end === 0) { + lvalue.identifier.mutableRange.end = makeInstructionId(Math.max(instr.id + 1, lvalue.identifier.mutableRange.end)); + } + } + for (const operand of eachInstructionValueOperand(instr.value)) { + operand.effect = Effect.Read; + } + if (instr.effects == null) { + continue; + } + const operandEffects = new Map(); + for (const effect of instr.effects) { + switch (effect.kind) { + case 'Assign': + case 'Alias': + case 'Capture': + case 'CreateFrom': + case 'MaybeAlias': { + const isMutatedOrReassigned = effect.into.identifier.mutableRange.end > instr.id; + if (isMutatedOrReassigned) { + operandEffects.set(effect.from.identifier.id, Effect.Capture); + operandEffects.set(effect.into.identifier.id, Effect.Store); + } + else { + operandEffects.set(effect.from.identifier.id, Effect.Read); + operandEffects.set(effect.into.identifier.id, Effect.Store); + } + break; + } + case 'CreateFunction': + case 'Create': { + break; + } + case 'Mutate': { + operandEffects.set(effect.value.identifier.id, Effect.Store); + break; + } + case 'Apply': { + CompilerError.invariant(false, { + reason: `[AnalyzeFunctions] Expected Apply effects to be replaced with more precise effects`, + loc: effect.function.loc, + }); + } + case 'MutateTransitive': + case 'MutateConditionally': + case 'MutateTransitiveConditionally': { + operandEffects.set(effect.value.identifier.id, Effect.ConditionallyMutate); + break; + } + case 'Freeze': { + operandEffects.set(effect.value.identifier.id, Effect.Freeze); + break; + } + case 'ImmutableCapture': { + break; + } + case 'Impure': + case 'Render': + case 'MutateFrozen': + case 'MutateGlobal': { + break; + } + default: { + assertExhaustive$1(effect, `Unexpected effect kind ${effect.kind}`); + } + } + } + for (const lvalue of eachInstructionLValue(instr)) { + const effect = (_f = operandEffects.get(lvalue.identifier.id)) !== null && _f !== void 0 ? _f : Effect.ConditionallyMutate; + lvalue.effect = effect; + } + for (const operand of eachInstructionValueOperand(instr.value)) { + if (operand.identifier.mutableRange.end > instr.id && + operand.identifier.mutableRange.start === 0) { + operand.identifier.mutableRange.start = instr.id; + } + const effect = (_g = operandEffects.get(operand.identifier.id)) !== null && _g !== void 0 ? _g : Effect.Read; + operand.effect = effect; + } + if (instr.value.kind === 'StoreContext' && + instr.value.value.identifier.mutableRange.end <= instr.id) { + instr.value.value.identifier.mutableRange.end = makeInstructionId(instr.id + 1); + } + } + if (block.terminal.kind === 'return') { + block.terminal.value.effect = isFunctionExpression + ? Effect.Read + : Effect.Freeze; + } + else { + for (const operand of eachTerminalOperand(block.terminal)) { + operand.effect = Effect.Read; + } + } + } + const returns = fn.returns.identifier; + functionEffects.push({ + kind: 'Create', + into: fn.returns, + value: isPrimitiveType(returns) + ? ValueKind.Primitive + : isJsxType(returns.type) + ? ValueKind.Frozen + : ValueKind.Mutable, + reason: ValueReason.KnownReturnSignature, + }); + const tracked = []; + for (const param of [...fn.params, ...fn.context, fn.returns]) { + const place = param.kind === 'Identifier' ? param : param.place; + tracked.push(place); + } + for (const into of tracked) { + const mutationIndex = index++; + state.mutate(mutationIndex, into.identifier, null, true, MutationKind.Conditional, into.loc, null, null); + for (const from of tracked) { + if (from.identifier.id === into.identifier.id || + from.identifier.id === fn.returns.identifier.id) { + continue; + } + const fromNode = state.nodes.get(from.identifier); + CompilerError.invariant(fromNode != null, { + reason: `Expected a node to exist for all parameters and context variables`, + loc: into.loc, + }); + if (fromNode.lastMutated === mutationIndex) { + if (into.identifier.id === fn.returns.identifier.id) { + functionEffects.push({ + kind: 'Alias', + from, + into, + }); + } + else { + functionEffects.push({ + kind: 'Capture', + from, + into, + }); + } + } + } + } + return functionEffects; +} +function appendFunctionErrors(env, fn) { + var _a; + if (env == null) + return; + for (const effect of (_a = fn.aliasingEffects) !== null && _a !== void 0 ? _a : []) { + switch (effect.kind) { + case 'Impure': + case 'MutateFrozen': + case 'MutateGlobal': { + env.recordError(effect.error); + break; + } + } + } +} +var MutationKind; +(function (MutationKind) { + MutationKind[MutationKind["None"] = 0] = "None"; + MutationKind[MutationKind["Conditional"] = 1] = "Conditional"; + MutationKind[MutationKind["Definite"] = 2] = "Definite"; +})(MutationKind || (MutationKind = {})); +class AliasingState { + constructor() { + this.nodes = new Map(); + } + create(place, value) { + this.nodes.set(place.identifier, { + id: place.identifier, + createdFrom: new Map(), + captures: new Map(), + aliases: new Map(), + maybeAliases: new Map(), + edges: [], + transitive: null, + local: null, + lastMutated: 0, + mutationReason: null, + value, + }); + } + createFrom(index, from, into) { + this.create(into, { kind: 'Object' }); + const fromNode = this.nodes.get(from.identifier); + const toNode = this.nodes.get(into.identifier); + if (fromNode == null || toNode == null) { + return; + } + fromNode.edges.push({ index, node: into.identifier, kind: 'alias' }); + if (!toNode.createdFrom.has(from.identifier)) { + toNode.createdFrom.set(from.identifier, index); + } + } + capture(index, from, into) { + const fromNode = this.nodes.get(from.identifier); + const toNode = this.nodes.get(into.identifier); + if (fromNode == null || toNode == null) { + return; + } + fromNode.edges.push({ index, node: into.identifier, kind: 'capture' }); + if (!toNode.captures.has(from.identifier)) { + toNode.captures.set(from.identifier, index); + } + } + assign(index, from, into) { + const fromNode = this.nodes.get(from.identifier); + const toNode = this.nodes.get(into.identifier); + if (fromNode == null || toNode == null) { + return; + } + fromNode.edges.push({ index, node: into.identifier, kind: 'alias' }); + if (!toNode.aliases.has(from.identifier)) { + toNode.aliases.set(from.identifier, index); + } + } + maybeAlias(index, from, into) { + const fromNode = this.nodes.get(from.identifier); + const toNode = this.nodes.get(into.identifier); + if (fromNode == null || toNode == null) { + return; + } + fromNode.edges.push({ index, node: into.identifier, kind: 'maybeAlias' }); + if (!toNode.maybeAliases.has(from.identifier)) { + toNode.maybeAliases.set(from.identifier, index); + } + } + render(index, start, env) { + const seen = new Set(); + const queue = [start]; + while (queue.length !== 0) { + const current = queue.pop(); + if (seen.has(current)) { + continue; + } + seen.add(current); + const node = this.nodes.get(current); + if (node == null || node.transitive != null || node.local != null) { + continue; + } + if (node.value.kind === 'Function') { + appendFunctionErrors(env, node.value.function); + } + for (const [alias, when] of node.createdFrom) { + if (when >= index) { + continue; + } + queue.push(alias); + } + for (const [alias, when] of node.aliases) { + if (when >= index) { + continue; + } + queue.push(alias); + } + for (const [capture, when] of node.captures) { + if (when >= index) { + continue; + } + queue.push(capture); + } + } + } + mutate(index, start, end, transitive, startKind, loc, reason, env) { + var _a; + const seen = new Map(); + const queue = [{ place: start, transitive, direction: 'backwards', kind: startKind }]; + while (queue.length !== 0) { + const { place: current, transitive, direction, kind } = queue.pop(); + const previousKind = seen.get(current); + if (previousKind != null && previousKind >= kind) { + continue; + } + seen.set(current, kind); + const node = this.nodes.get(current); + if (node == null) { + continue; + } + (_a = node.mutationReason) !== null && _a !== void 0 ? _a : (node.mutationReason = reason); + node.lastMutated = Math.max(node.lastMutated, index); + if (end != null) { + node.id.mutableRange.end = makeInstructionId(Math.max(node.id.mutableRange.end, end)); + } + if (node.value.kind === 'Function' && + node.transitive == null && + node.local == null) { + appendFunctionErrors(env, node.value.function); + } + if (transitive) { + if (node.transitive == null || node.transitive.kind < kind) { + node.transitive = { kind, loc }; + } + } + else { + if (node.local == null || node.local.kind < kind) { + node.local = { kind, loc }; + } + } + for (const edge of node.edges) { + if (edge.index >= index) { + break; + } + queue.push({ + place: edge.node, + transitive, + direction: 'forwards', + kind: edge.kind === 'maybeAlias' ? MutationKind.Conditional : kind, + }); + } + for (const [alias, when] of node.createdFrom) { + if (when >= index) { + continue; + } + queue.push({ + place: alias, + transitive: true, + direction: 'backwards', + kind, + }); + } + if (direction === 'backwards' || node.value.kind !== 'Phi') { + for (const [alias, when] of node.aliases) { + if (when >= index) { + continue; + } + queue.push({ + place: alias, + transitive, + direction: 'backwards', + kind, + }); + } + for (const [alias, when] of node.maybeAliases) { + if (when >= index) { + continue; + } + queue.push({ + place: alias, + transitive, + direction: 'backwards', + kind: MutationKind.Conditional, + }); + } + } + if (transitive) { + for (const [capture, when] of node.captures) { + if (when >= index) { + continue; + } + queue.push({ + place: capture, + transitive, + direction: 'backwards', + kind, + }); + } + } + } + } +} + +function analyseFunctions(func) { + for (const [_, block] of func.body.blocks) { + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'ObjectMethod': + case 'FunctionExpression': { + lowerWithMutationAliasing(instr.value.loweredFunc.func); + for (const operand of instr.value.loweredFunc.func.context) { + operand.identifier.mutableRange = { + start: makeInstructionId(0), + end: makeInstructionId(0), + }; + operand.identifier.scope = null; + } + break; + } + } + } + } +} +function lowerWithMutationAliasing(fn) { + var _a, _b; + analyseFunctions(fn); + inferMutationAliasingEffects(fn, { isFunctionExpression: true }); + deadCodeElimination(fn); + const functionEffects = inferMutationAliasingRanges(fn, { + isFunctionExpression: true, + }); + rewriteInstructionKindsBasedOnReassignment(fn); + inferReactiveScopeVariables(fn); + fn.aliasingEffects = functionEffects; + const capturedOrMutated = new Set(); + for (const effect of functionEffects) { + switch (effect.kind) { + case 'Assign': + case 'Alias': + case 'Capture': + case 'CreateFrom': + case 'MaybeAlias': { + capturedOrMutated.add(effect.from.identifier.id); + break; + } + case 'Apply': { + CompilerError.invariant(false, { + reason: `[AnalyzeFunctions] Expected Apply effects to be replaced with more precise effects`, + loc: effect.function.loc, + }); + } + case 'Mutate': + case 'MutateConditionally': + case 'MutateTransitive': + case 'MutateTransitiveConditionally': { + capturedOrMutated.add(effect.value.identifier.id); + break; + } + case 'Impure': + case 'Render': + case 'MutateFrozen': + case 'MutateGlobal': + case 'CreateFunction': + case 'Create': + case 'Freeze': + case 'ImmutableCapture': { + break; + } + default: { + assertExhaustive$1(effect, `Unexpected effect kind ${effect.kind}`); + } + } + } + for (const operand of fn.context) { + if (capturedOrMutated.has(operand.identifier.id) || + operand.effect === Effect.Capture) { + operand.effect = Effect.Capture; + } + else { + operand.effect = Effect.Read; + } + } + (_b = (_a = fn.env.logger) === null || _a === void 0 ? void 0 : _a.debugLogIRs) === null || _b === void 0 ? void 0 : _b.call(_a, { + kind: 'hir', + name: 'AnalyseFunction (inner)', + value: fn, + }); +} + +function collectMaybeMemoDependencies(value, maybeDeps, optional) { + var _a; + switch (value.kind) { + case 'LoadGlobal': { + return { + root: { + kind: 'Global', + identifierName: value.binding.name, + }, + path: [], + loc: value.loc, + }; + } + case 'PropertyLoad': { + const object = maybeDeps.get(value.object.identifier.id); + if (object != null) { + return { + root: object.root, + path: [ + ...object.path, + { property: value.property, optional, loc: value.loc }, + ], + loc: value.loc, + }; + } + break; + } + case 'LoadLocal': + case 'LoadContext': { + const source = maybeDeps.get(value.place.identifier.id); + if (source != null) { + return source; + } + else if (value.place.identifier.name != null && + value.place.identifier.name.kind === 'named') { + return { + root: { + kind: 'NamedLocal', + value: Object.assign({}, value.place), + constant: false, + }, + path: [], + loc: value.place.loc, + }; + } + break; + } + case 'StoreLocal': { + const lvalue = value.lvalue.place.identifier; + const rvalue = value.value.identifier.id; + const aliased = maybeDeps.get(rvalue); + if (aliased != null && ((_a = lvalue.name) === null || _a === void 0 ? void 0 : _a.kind) !== 'named') { + maybeDeps.set(lvalue.id, aliased); + return aliased; + } + break; + } + } + return null; +} +function collectTemporaries(instr, env, sidemap) { + const { value, lvalue } = instr; + switch (value.kind) { + case 'FunctionExpression': { + sidemap.functions.set(instr.lvalue.identifier.id, instr); + break; + } + case 'LoadGlobal': { + const global = env.getGlobalDeclaration(value.binding, value.loc); + const hookKind = global !== null ? getHookKindForType(env, global) : null; + const lvalId = instr.lvalue.identifier.id; + if (hookKind === 'useMemo' || hookKind === 'useCallback') { + sidemap.manualMemos.set(lvalId, { + kind: hookKind, + loadInstr: instr, + }); + } + else if (value.binding.name === 'React') { + sidemap.react.add(lvalId); + } + break; + } + case 'PropertyLoad': { + if (sidemap.react.has(value.object.identifier.id)) { + const property = value.property; + if (property === 'useMemo' || property === 'useCallback') { + sidemap.manualMemos.set(instr.lvalue.identifier.id, { + kind: property, + loadInstr: instr, + }); + } + } + break; + } + case 'ArrayExpression': { + if (value.elements.every(e => e.kind === 'Identifier')) { + sidemap.maybeDepsLists.set(instr.lvalue.identifier.id, { + loc: value.loc, + deps: value.elements, + }); + } + break; + } + } + const maybeDep = collectMaybeMemoDependencies(value, sidemap.maybeDeps, sidemap.optionals.has(lvalue.identifier.id)); + if (maybeDep != null) { + sidemap.maybeDeps.set(lvalue.identifier.id, maybeDep); + } +} +function makeManualMemoizationMarkers(fnExpr, env, depsList, depsLoc, memoDecl, manualMemoId) { + return [ + { + id: makeInstructionId(0), + lvalue: createTemporaryPlace(env, fnExpr.loc), + value: { + kind: 'StartMemoize', + manualMemoId, + deps: depsList, + depsLoc, + loc: fnExpr.loc, + }, + effects: null, + loc: fnExpr.loc, + }, + { + id: makeInstructionId(0), + lvalue: createTemporaryPlace(env, fnExpr.loc), + value: { + kind: 'FinishMemoize', + manualMemoId, + decl: Object.assign({}, memoDecl), + loc: fnExpr.loc, + }, + effects: null, + loc: fnExpr.loc, + }, + ]; +} +function getManualMemoizationReplacement(fn, loc, kind) { + if (kind === 'useMemo') { + return { + kind: 'CallExpression', + callee: fn, + args: [], + loc, + }; + } + else { + return { + kind: 'LoadLocal', + place: { + kind: 'Identifier', + identifier: fn.identifier, + effect: Effect.Unknown, + reactive: false, + loc, + }, + loc, + }; + } +} +function extractManualMemoizationArgs(instr, kind, sidemap, env) { + const [fnPlace, depsListPlace] = instr.value.args; + if (fnPlace == null || fnPlace.kind !== 'Identifier') { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: `Expected a callback function to be passed to ${kind}`, + description: kind === 'useCallback' + ? 'The first argument to useCallback() must be a function to cache' + : 'The first argument to useMemo() must be a function that calculates a result to cache', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: instr.value.loc, + message: kind === 'useCallback' + ? `Expected a callback function` + : `Expected a memoization function`, + })); + return null; + } + if (depsListPlace == null) { + return { + fnPlace, + depsList: null, + depsLoc: null, + }; + } + const maybeDepsList = depsListPlace.kind === 'Identifier' + ? sidemap.maybeDepsLists.get(depsListPlace.identifier.id) + : null; + if (maybeDepsList == null) { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: `Expected the dependency list for ${kind} to be an array literal`, + description: `Expected the dependency list for ${kind} to be an array literal`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc: (depsListPlace === null || depsListPlace === void 0 ? void 0 : depsListPlace.kind) === 'Identifier' ? depsListPlace.loc : instr.loc, + message: `Expected the dependency list for ${kind} to be an array literal`, + })); + return null; + } + const depsList = []; + for (const dep of maybeDepsList.deps) { + const maybeDep = sidemap.maybeDeps.get(dep.identifier.id); + if (maybeDep == null) { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: `Expected the dependency list to be an array of simple expressions (e.g. \`x\`, \`x.y.z\`, \`x?.y?.z\`)`, + description: `Expected the dependency list to be an array of simple expressions (e.g. \`x\`, \`x.y.z\`, \`x?.y?.z\`)`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc: dep.loc, + message: `Expected the dependency list to be an array of simple expressions (e.g. \`x\`, \`x.y.z\`, \`x?.y?.z\`)`, + })); + } + else { + depsList.push(maybeDep); + } + } + return { + fnPlace, + depsList, + depsLoc: maybeDepsList.loc, + }; +} +function dropManualMemoization(func) { + const isValidationEnabled = func.env.config.validatePreserveExistingMemoizationGuarantees || + func.env.config.validateNoSetStateInRender || + func.env.config.enablePreserveExistingMemoizationGuarantees; + const optionals = findOptionalPlaces$1(func); + const sidemap = { + functions: new Map(), + manualMemos: new Map(), + react: new Set(), + maybeDeps: new Map(), + maybeDepsLists: new Map(), + optionals, + }; + let nextManualMemoId = 0; + const queuedInserts = new Map(); + for (const [_, block] of func.body.blocks) { + for (let i = 0; i < block.instructions.length; i++) { + const instr = block.instructions[i]; + if (instr.value.kind === 'CallExpression' || + instr.value.kind === 'MethodCall') { + const id = instr.value.kind === 'CallExpression' + ? instr.value.callee.identifier.id + : instr.value.property.identifier.id; + const manualMemo = sidemap.manualMemos.get(id); + if (manualMemo != null) { + const memoDetails = extractManualMemoizationArgs(instr, manualMemo.kind, sidemap, func.env); + if (memoDetails == null) { + continue; + } + const { fnPlace, depsList, depsLoc } = memoDetails; + instr.value = getManualMemoizationReplacement(fnPlace, instr.value.loc, manualMemo.kind); + if (isValidationEnabled) { + if (!sidemap.functions.has(fnPlace.identifier.id)) { + func.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: `Expected the first argument to be an inline function expression`, + description: `Expected the first argument to be an inline function expression`, + suggestions: [], + }).withDetails({ + kind: 'error', + loc: fnPlace.loc, + message: `Expected the first argument to be an inline function expression`, + })); + continue; + } + const memoDecl = manualMemo.kind === 'useMemo' + ? instr.lvalue + : { + kind: 'Identifier', + identifier: fnPlace.identifier, + effect: Effect.Unknown, + reactive: false, + loc: fnPlace.loc, + }; + const [startMarker, finishMarker] = makeManualMemoizationMarkers(fnPlace, func.env, depsList, depsLoc, memoDecl, nextManualMemoId++); + queuedInserts.set(manualMemo.loadInstr.id, startMarker); + queuedInserts.set(instr.id, finishMarker); + } + } + } + else { + collectTemporaries(instr, func.env, sidemap); + } + } + } + if (queuedInserts.size > 0) { + let hasChanges = false; + for (const [_, block] of func.body.blocks) { + let nextInstructions = null; + for (let i = 0; i < block.instructions.length; i++) { + const instr = block.instructions[i]; + const insertInstr = queuedInserts.get(instr.id); + if (insertInstr != null) { + nextInstructions = nextInstructions !== null && nextInstructions !== void 0 ? nextInstructions : block.instructions.slice(0, i); + nextInstructions.push(instr); + nextInstructions.push(insertInstr); + } + else if (nextInstructions != null) { + nextInstructions.push(instr); + } + } + if (nextInstructions !== null) { + block.instructions = nextInstructions; + hasChanges = true; + } + } + if (hasChanges) { + markInstructionIds(func.body); + } + } +} +function findOptionalPlaces$1(fn) { + const optionals = new Set(); + for (const [, block] of fn.body.blocks) { + if (block.terminal.kind === 'optional' && block.terminal.optional) { + const optionalTerminal = block.terminal; + let testBlock = fn.body.blocks.get(block.terminal.test); + loop: while (true) { + const terminal = testBlock.terminal; + switch (terminal.kind) { + case 'branch': { + if (terminal.fallthrough === optionalTerminal.fallthrough) { + const consequent = fn.body.blocks.get(terminal.consequent); + const last = consequent.instructions.at(-1); + if (last !== undefined && last.value.kind === 'StoreLocal') { + optionals.add(last.value.value.identifier.id); + } + break loop; + } + else { + testBlock = fn.body.blocks.get(terminal.fallthrough); + } + break; + } + case 'optional': + case 'logical': + case 'sequence': + case 'ternary': { + testBlock = fn.body.blocks.get(terminal.fallthrough); + break; + } + case 'maybe-throw': { + testBlock = fn.body.blocks.get(terminal.continuation); + break; + } + default: { + CompilerError.invariant(false, { + reason: `Unexpected terminal in optional`, + message: `Unexpected ${terminal.kind} in optional`, + loc: terminal.loc, + }); + } + } + } + } + } + return optionals; +} + +function createControlDominators(fn, isControlVariable) { + const postDominators = computePostDominatorTree(fn, { + includeThrowsAsExitNode: false, + }); + const postDominatorFrontierCache = new Map(); + function isControlledBlock(id) { + let controlBlocks = postDominatorFrontierCache.get(id); + if (controlBlocks === undefined) { + controlBlocks = postDominatorFrontier(fn, postDominators, id); + postDominatorFrontierCache.set(id, controlBlocks); + } + for (const blockId of controlBlocks) { + const controlBlock = fn.body.blocks.get(blockId); + switch (controlBlock.terminal.kind) { + case 'if': + case 'branch': { + if (isControlVariable(controlBlock.terminal.test)) { + return true; + } + break; + } + case 'switch': { + if (isControlVariable(controlBlock.terminal.test)) { + return true; + } + for (const case_ of controlBlock.terminal.cases) { + if (case_.test !== null && isControlVariable(case_.test)) { + return true; + } + } + break; + } + } + } + return false; + } + return isControlledBlock; +} +function postDominatorFrontier(fn, postDominators, targetId) { + const visited = new Set(); + const frontier = new Set(); + const targetPostDominators = postDominatorsOf(fn, postDominators, targetId); + for (const blockId of [...targetPostDominators, targetId]) { + if (visited.has(blockId)) { + continue; + } + visited.add(blockId); + const block = fn.body.blocks.get(blockId); + for (const pred of block.preds) { + if (!targetPostDominators.has(pred)) { + frontier.add(pred); + } + } + } + return frontier; +} +function postDominatorsOf(fn, postDominators, targetId) { + var _a; + const result = new Set(); + const visited = new Set(); + const queue = [targetId]; + while (queue.length) { + const currentId = queue.shift(); + if (visited.has(currentId)) { + continue; + } + visited.add(currentId); + const current = fn.body.blocks.get(currentId); + for (const pred of current.preds) { + const predPostDominator = (_a = postDominators.get(pred)) !== null && _a !== void 0 ? _a : pred; + if (predPostDominator === targetId || result.has(predPostDominator)) { + result.add(pred); + } + queue.push(pred); + } + } + return result; +} + +class StableSidemap { + constructor(env) { + this.map = new Map(); + this.env = env; + } + handleInstruction(instr) { + const { value, lvalue } = instr; + switch (value.kind) { + case 'CallExpression': + case 'MethodCall': { + if (evaluatesToStableTypeOrContainer(this.env, instr)) { + if (isStableType(lvalue.identifier)) { + this.map.set(lvalue.identifier.id, { + isStable: true, + }); + } + else { + this.map.set(lvalue.identifier.id, { + isStable: false, + }); + } + } + break; + } + case 'Destructure': + case 'PropertyLoad': { + const source = value.kind === 'Destructure' + ? value.value.identifier.id + : value.object.identifier.id; + const entry = this.map.get(source); + if (entry) { + for (const lvalue of eachInstructionLValue(instr)) { + if (isStableTypeContainer(lvalue.identifier)) { + this.map.set(lvalue.identifier.id, { + isStable: false, + }); + } + else if (isStableType(lvalue.identifier)) { + this.map.set(lvalue.identifier.id, { + isStable: true, + }); + } + } + } + break; + } + case 'StoreLocal': { + const entry = this.map.get(value.value.identifier.id); + if (entry) { + this.map.set(lvalue.identifier.id, entry); + this.map.set(value.lvalue.place.identifier.id, entry); + } + break; + } + case 'LoadLocal': { + const entry = this.map.get(value.place.identifier.id); + if (entry) { + this.map.set(lvalue.identifier.id, entry); + } + break; + } + } + } + isStable(id) { + const entry = this.map.get(id); + return entry != null ? entry.isStable : false; + } +} +function inferReactivePlaces(fn) { + const reactiveIdentifiers = new ReactivityMap(findDisjointMutableValues(fn)); + const stableIdentifierSources = new StableSidemap(fn.env); + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + reactiveIdentifiers.markReactive(place); + } + const isReactiveControlledBlock = createControlDominators(fn, place => reactiveIdentifiers.isReactive(place)); + do { + for (const [, block] of fn.body.blocks) { + let hasReactiveControl = isReactiveControlledBlock(block.id); + for (const phi of block.phis) { + if (reactiveIdentifiers.isReactive(phi.place)) { + continue; + } + let isPhiReactive = false; + for (const [, operand] of phi.operands) { + if (reactiveIdentifiers.isReactive(operand)) { + isPhiReactive = true; + break; + } + } + if (isPhiReactive) { + reactiveIdentifiers.markReactive(phi.place); + } + else { + for (const [pred] of phi.operands) { + if (isReactiveControlledBlock(pred)) { + reactiveIdentifiers.markReactive(phi.place); + break; + } + } + } + } + for (const instruction of block.instructions) { + stableIdentifierSources.handleInstruction(instruction); + const { value } = instruction; + let hasReactiveInput = false; + for (const operand of eachInstructionValueOperand(value)) { + const reactive = reactiveIdentifiers.isReactive(operand); + hasReactiveInput || (hasReactiveInput = reactive); + } + if (value.kind === 'CallExpression' && + (getHookKind(fn.env, value.callee.identifier) != null || + isUseOperator(value.callee.identifier))) { + hasReactiveInput = true; + } + else if (value.kind === 'MethodCall' && + (getHookKind(fn.env, value.property.identifier) != null || + isUseOperator(value.property.identifier))) { + hasReactiveInput = true; + } + if (hasReactiveInput) { + for (const lvalue of eachInstructionLValue(instruction)) { + if (stableIdentifierSources.isStable(lvalue.identifier.id)) { + continue; + } + reactiveIdentifiers.markReactive(lvalue); + } + } + if (hasReactiveInput || hasReactiveControl) { + for (const operand of eachInstructionValueOperand(value)) { + switch (operand.effect) { + case Effect.Capture: + case Effect.Store: + case Effect.ConditionallyMutate: + case Effect.ConditionallyMutateIterator: + case Effect.Mutate: { + if (isMutable(instruction, operand)) { + reactiveIdentifiers.markReactive(operand); + } + break; + } + case Effect.Freeze: + case Effect.Read: { + break; + } + case Effect.Unknown: { + CompilerError.invariant(false, { + reason: 'Unexpected unknown effect', + loc: operand.loc, + }); + } + default: { + assertExhaustive$1(operand.effect, `Unexpected effect kind \`${operand.effect}\``); + } + } + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + reactiveIdentifiers.isReactive(operand); + } + } + } while (reactiveIdentifiers.snapshot()); + function propagateReactivityToInnerFunctions(fn, isOutermost) { + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + if (!isOutermost) { + for (const operand of eachInstructionOperand(instr)) { + reactiveIdentifiers.isReactive(operand); + } + } + if (instr.value.kind === 'ObjectMethod' || + instr.value.kind === 'FunctionExpression') { + propagateReactivityToInnerFunctions(instr.value.loweredFunc.func, false); + } + } + if (!isOutermost) { + for (const operand of eachTerminalOperand(block.terminal)) { + reactiveIdentifiers.isReactive(operand); + } + } + } + } + propagateReactivityToInnerFunctions(fn, true); +} +class ReactivityMap { + constructor(aliasedIdentifiers) { + this.hasChanges = false; + this.reactive = new Set(); + this.aliasedIdentifiers = aliasedIdentifiers; + } + isReactive(place) { + var _a; + const identifier = (_a = this.aliasedIdentifiers.find(place.identifier)) !== null && _a !== void 0 ? _a : place.identifier; + const reactive = this.reactive.has(identifier.id); + if (reactive) { + place.reactive = true; + } + return reactive; + } + markReactive(place) { + var _a; + place.reactive = true; + const identifier = (_a = this.aliasedIdentifiers.find(place.identifier)) !== null && _a !== void 0 ? _a : place.identifier; + if (!this.reactive.has(identifier.id)) { + this.hasChanges = true; + this.reactive.add(identifier.id); + } + } + snapshot() { + const hasChanges = this.hasChanges; + this.hasChanges = false; + return hasChanges; + } +} + +function inlineImmediatelyInvokedFunctionExpressions(fn) { + const functions = new Map(); + const inlinedFunctions = new Set(); + const queue = Array.from(fn.body.blocks.values()); + queue: for (const block of queue) { + if (isStatementBlockKind(block.kind)) { + for (let ii = 0; ii < block.instructions.length; ii++) { + const instr = block.instructions[ii]; + switch (instr.value.kind) { + case 'FunctionExpression': { + if (instr.lvalue.identifier.name === null) { + functions.set(instr.lvalue.identifier.id, instr.value); + } + break; + } + case 'CallExpression': { + if (instr.value.args.length !== 0) { + continue; + } + const body = functions.get(instr.value.callee.identifier.id); + if (body === undefined) { + continue; + } + if (body.loweredFunc.func.params.length > 0 || + body.loweredFunc.func.async || + body.loweredFunc.func.generator) { + continue; + } + inlinedFunctions.add(instr.value.callee.identifier.id); + const continuationBlockId = fn.env.nextBlockId; + const continuationBlock = { + id: continuationBlockId, + instructions: block.instructions.slice(ii + 1), + kind: block.kind, + phis: new Set(), + preds: new Set(), + terminal: block.terminal, + }; + fn.body.blocks.set(continuationBlockId, continuationBlock); + block.instructions.length = ii; + if (hasSingleExitReturnTerminal(body.loweredFunc.func)) { + block.terminal = { + kind: 'goto', + block: body.loweredFunc.func.body.entry, + id: block.terminal.id, + loc: block.terminal.loc, + variant: GotoVariant.Break, + }; + for (const block of body.loweredFunc.func.body.blocks.values()) { + if (block.terminal.kind === 'return') { + block.instructions.push({ + id: makeInstructionId(0), + loc: block.terminal.loc, + lvalue: instr.lvalue, + value: { + kind: 'LoadLocal', + loc: block.terminal.loc, + place: block.terminal.value, + }, + effects: null, + }); + block.terminal = { + kind: 'goto', + block: continuationBlockId, + id: block.terminal.id, + loc: block.terminal.loc, + variant: GotoVariant.Break, + }; + } + } + for (const [id, block] of body.loweredFunc.func.body.blocks) { + block.preds.clear(); + fn.body.blocks.set(id, block); + } + } + else { + const newTerminal = { + block: body.loweredFunc.func.body.entry, + id: makeInstructionId(0), + kind: 'label', + fallthrough: continuationBlockId, + loc: block.terminal.loc, + }; + block.terminal = newTerminal; + const result = instr.lvalue; + declareTemporary(fn.env, block, result); + if (result.identifier.name == null) { + promoteTemporary(result.identifier); + } + for (const [id, block] of body.loweredFunc.func.body.blocks) { + block.preds.clear(); + rewriteBlock(fn.env, block, continuationBlockId, result); + fn.body.blocks.set(id, block); + } + } + queue.push(continuationBlock); + continue queue; + } + default: { + for (const place of eachInstructionValueOperand(instr.value)) { + functions.delete(place.identifier.id); + } + } + } + } + } + } + if (inlinedFunctions.size !== 0) { + for (const block of fn.body.blocks.values()) { + retainWhere(block.instructions, instr => !inlinedFunctions.has(instr.lvalue.identifier.id)); + } + reversePostorderBlocks(fn.body); + markInstructionIds(fn.body); + markPredecessors(fn.body); + mergeConsecutiveBlocks(fn); + } +} +function hasSingleExitReturnTerminal(fn) { + let hasReturn = false; + let exitCount = 0; + for (const [, block] of fn.body.blocks) { + if (block.terminal.kind === 'return' || block.terminal.kind === 'throw') { + hasReturn || (hasReturn = block.terminal.kind === 'return'); + exitCount++; + } + } + return exitCount === 1 && hasReturn; +} +function rewriteBlock(env, block, returnTarget, returnValue) { + const { terminal } = block; + if (terminal.kind !== 'return') { + return; + } + block.instructions.push({ + id: makeInstructionId(0), + loc: terminal.loc, + lvalue: createTemporaryPlace(env, terminal.loc), + value: { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Reassign, place: Object.assign({}, returnValue) }, + value: terminal.value, + type: null, + loc: terminal.loc, + }, + effects: null, + }); + block.terminal = { + kind: 'goto', + block: returnTarget, + id: makeInstructionId(0), + variant: GotoVariant.Break, + loc: block.terminal.loc, + }; +} +function declareTemporary(env, block, result) { + block.instructions.push({ + id: makeInstructionId(0), + loc: GeneratedSource, + lvalue: createTemporaryPlace(env, result.loc), + value: { + kind: 'DeclareLocal', + lvalue: { + place: result, + kind: InstructionKind.Let, + }, + type: null, + loc: result.loc, + }, + effects: null, + }); +} + +function alignMethodCallScopes(fn) { + const scopeMapping = new Map(); + const mergedScopes = new DisjointSet(); + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + if (value.kind === 'MethodCall') { + const lvalueScope = lvalue.identifier.scope; + const propertyScope = value.property.identifier.scope; + if (lvalueScope !== null) { + if (propertyScope !== null) { + mergedScopes.union([lvalueScope, propertyScope]); + } + else { + scopeMapping.set(value.property.identifier.id, lvalueScope); + } + } + else if (propertyScope !== null) { + scopeMapping.set(value.property.identifier.id, null); + } + } + else if (value.kind === 'FunctionExpression' || + value.kind === 'ObjectMethod') { + alignMethodCallScopes(value.loweredFunc.func); + } + } + } + mergedScopes.forEach((scope, root) => { + if (scope === root) { + return; + } + root.range.start = makeInstructionId(Math.min(scope.range.start, root.range.start)); + root.range.end = makeInstructionId(Math.max(scope.range.end, root.range.end)); + }); + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const mappedScope = scopeMapping.get(instr.lvalue.identifier.id); + if (mappedScope !== undefined) { + instr.lvalue.identifier.scope = mappedScope; + } + else if (instr.lvalue.identifier.scope !== null) { + const mergedScope = mergedScopes.find(instr.lvalue.identifier.scope); + if (mergedScope != null) { + instr.lvalue.identifier.scope = mergedScope; + } + } + } + } +} + +function alignReactiveScopesToBlockScopesHIR(fn) { + var _a, _b, _c, _d, _e, _f, _g; + const activeBlockFallthroughRanges = []; + const activeScopes = new Set(); + const seen = new Set(); + const valueBlockNodes = new Map(); + const placeScopes = new Map(); + function recordPlace(id, place, node) { + if (place.identifier.scope !== null) { + placeScopes.set(place, place.identifier.scope); + } + const scope = getPlaceScope(id, place); + if (scope == null) { + return; + } + activeScopes.add(scope); + node === null || node === void 0 ? void 0 : node.children.push({ kind: 'scope', scope, id }); + if (seen.has(scope)) { + return; + } + seen.add(scope); + if (node != null && node.valueRange !== null) { + scope.range.start = makeInstructionId(Math.min(node.valueRange.start, scope.range.start)); + scope.range.end = makeInstructionId(Math.max(node.valueRange.end, scope.range.end)); + } + } + for (const [, block] of fn.body.blocks) { + const startingId = (_b = (_a = block.instructions[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : block.terminal.id; + retainWhere_Set(activeScopes, scope => scope.range.end > startingId); + const top = activeBlockFallthroughRanges.at(-1); + if ((top === null || top === void 0 ? void 0 : top.fallthrough) === block.id) { + activeBlockFallthroughRanges.pop(); + for (const scope of activeScopes) { + scope.range.start = makeInstructionId(Math.min(scope.range.start, top.range.start)); + } + } + const { instructions, terminal } = block; + const node = (_c = valueBlockNodes.get(block.id)) !== null && _c !== void 0 ? _c : null; + for (const instr of instructions) { + for (const lvalue of eachInstructionLValue(instr)) { + recordPlace(instr.id, lvalue, node); + } + for (const operand of eachInstructionValueOperand(instr.value)) { + recordPlace(instr.id, operand, node); + } + } + for (const operand of eachTerminalOperand(terminal)) { + recordPlace(terminal.id, operand, node); + } + const fallthrough = terminalFallthrough(terminal); + if (fallthrough !== null && terminal.kind !== 'branch') { + const fallthroughBlock = fn.body.blocks.get(fallthrough); + const nextId = (_e = (_d = fallthroughBlock.instructions[0]) === null || _d === void 0 ? void 0 : _d.id) !== null && _e !== void 0 ? _e : fallthroughBlock.terminal.id; + for (const scope of activeScopes) { + if (scope.range.end > terminal.id) { + scope.range.end = makeInstructionId(Math.max(scope.range.end, nextId)); + } + } + activeBlockFallthroughRanges.push({ + fallthrough, + range: { + start: terminal.id, + end: nextId, + }, + }); + CompilerError.invariant(!valueBlockNodes.has(fallthrough), { + reason: 'Expect hir blocks to have unique fallthroughs', + loc: terminal.loc, + }); + if (node != null) { + valueBlockNodes.set(fallthrough, node); + } + } + else if (terminal.kind === 'goto') { + const start = activeBlockFallthroughRanges.find(range => range.fallthrough === terminal.block); + if (start != null && start !== activeBlockFallthroughRanges.at(-1)) { + const fallthroughBlock = fn.body.blocks.get(start.fallthrough); + const firstId = (_g = (_f = fallthroughBlock.instructions[0]) === null || _f === void 0 ? void 0 : _f.id) !== null && _g !== void 0 ? _g : fallthroughBlock.terminal.id; + for (const scope of activeScopes) { + if (scope.range.end <= terminal.id) { + continue; + } + scope.range.start = makeInstructionId(Math.min(start.range.start, scope.range.start)); + scope.range.end = makeInstructionId(Math.max(firstId, scope.range.end)); + } + } + } + mapTerminalSuccessors(terminal, successor => { + var _a, _b; + if (valueBlockNodes.has(successor)) { + return successor; + } + const successorBlock = fn.body.blocks.get(successor); + if (successorBlock.kind === 'block' || successorBlock.kind === 'catch') ; + else if (node == null || + terminal.kind === 'ternary' || + terminal.kind === 'logical' || + terminal.kind === 'optional') { + let valueRange; + if (node == null) { + CompilerError.invariant(fallthrough !== null, { + reason: `Expected a fallthrough for value block`, + loc: terminal.loc, + }); + const fallthroughBlock = fn.body.blocks.get(fallthrough); + const nextId = (_b = (_a = fallthroughBlock.instructions[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : fallthroughBlock.terminal.id; + valueRange = { + start: terminal.id, + end: nextId, + }; + } + else { + valueRange = node.valueRange; + } + const childNode = { + kind: 'node', + id: terminal.id, + children: [], + valueRange, + }; + node === null || node === void 0 ? void 0 : node.children.push(childNode); + valueBlockNodes.set(successor, childNode); + } + else { + valueBlockNodes.set(successor, node); + } + return successor; + }); + } +} + +function flattenReactiveLoopsHIR(fn) { + const activeLoops = Array(); + for (const [, block] of fn.body.blocks) { + retainWhere(activeLoops, id => id !== block.id); + const { terminal } = block; + switch (terminal.kind) { + case 'do-while': + case 'for': + case 'for-in': + case 'for-of': + case 'while': { + activeLoops.push(terminal.fallthrough); + break; + } + case 'scope': { + if (activeLoops.length !== 0) { + block.terminal = { + kind: 'pruned-scope', + block: terminal.block, + fallthrough: terminal.fallthrough, + id: terminal.id, + loc: terminal.loc, + scope: terminal.scope, + }; + } + break; + } + case 'branch': + case 'goto': + case 'if': + case 'label': + case 'logical': + case 'maybe-throw': + case 'optional': + case 'pruned-scope': + case 'return': + case 'sequence': + case 'switch': + case 'ternary': + case 'throw': + case 'try': + case 'unreachable': + case 'unsupported': { + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } + } +} + +function flattenScopesWithHooksOrUseHIR(fn) { + const activeScopes = []; + const prune = []; + for (const [, block] of fn.body.blocks) { + retainWhere(activeScopes, current => current.fallthrough !== block.id); + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'MethodCall': + case 'CallExpression': { + const callee = value.kind === 'MethodCall' ? value.property : value.callee; + if (getHookKind(fn.env, callee.identifier) != null || + isUseOperator(callee.identifier)) { + prune.push(...activeScopes.map(entry => entry.block)); + activeScopes.length = 0; + } + } + } + } + if (block.terminal.kind === 'scope') { + activeScopes.push({ + block: block.id, + fallthrough: block.terminal.fallthrough, + }); + } + } + for (const id of prune) { + const block = fn.body.blocks.get(id); + const terminal = block.terminal; + CompilerError.invariant(terminal.kind === 'scope', { + reason: `Expected block to have a scope terminal`, + description: `Expected block bb${block.id} to end in a scope terminal`, + loc: terminal.loc, + }); + const body = fn.body.blocks.get(terminal.block); + if (body.instructions.length === 1 && + body.terminal.kind === 'goto' && + body.terminal.block === terminal.fallthrough) { + block.terminal = { + kind: 'label', + block: terminal.block, + fallthrough: terminal.fallthrough, + id: terminal.id, + loc: terminal.loc, + }; + continue; + } + block.terminal = { + kind: 'pruned-scope', + block: terminal.block, + fallthrough: terminal.fallthrough, + id: terminal.id, + loc: terminal.loc, + scope: terminal.scope, + }; + } +} + +function pruneAlwaysInvalidatingScopes(fn) { + visitReactiveFunction(fn, new Transform(), false); +} +class Transform extends ReactiveFunctionTransform { + constructor() { + super(...arguments); + this.alwaysInvalidatingValues = new Set(); + this.unmemoizedValues = new Set(); + } + transformInstruction(instruction, withinScope) { + this.visitInstruction(instruction, withinScope); + const { lvalue, value } = instruction; + switch (value.kind) { + case 'ArrayExpression': + case 'ObjectExpression': + case 'JsxExpression': + case 'JsxFragment': + case 'NewExpression': { + if (lvalue !== null) { + this.alwaysInvalidatingValues.add(lvalue.identifier); + if (!withinScope) { + this.unmemoizedValues.add(lvalue.identifier); + } + } + break; + } + case 'StoreLocal': { + if (this.alwaysInvalidatingValues.has(value.value.identifier)) { + this.alwaysInvalidatingValues.add(value.lvalue.place.identifier); + } + if (this.unmemoizedValues.has(value.value.identifier)) { + this.unmemoizedValues.add(value.lvalue.place.identifier); + } + break; + } + case 'LoadLocal': { + if (lvalue !== null && + this.alwaysInvalidatingValues.has(value.place.identifier)) { + this.alwaysInvalidatingValues.add(lvalue.identifier); + } + if (lvalue !== null && + this.unmemoizedValues.has(value.place.identifier)) { + this.unmemoizedValues.add(lvalue.identifier); + } + break; + } + } + return { kind: 'keep' }; + } + transformScope(scopeBlock, _withinScope) { + this.visitScope(scopeBlock, true); + for (const dep of scopeBlock.scope.dependencies) { + if (this.unmemoizedValues.has(dep.identifier)) { + for (const [_, decl] of scopeBlock.scope.declarations) { + if (this.alwaysInvalidatingValues.has(decl.identifier)) { + this.unmemoizedValues.add(decl.identifier); + } + } + for (const identifier of scopeBlock.scope.reassignments) { + if (this.alwaysInvalidatingValues.has(identifier)) { + this.unmemoizedValues.add(identifier); + } + } + return { + kind: 'replace', + value: { + kind: 'pruned-scope', + scope: scopeBlock.scope, + instructions: scopeBlock.instructions, + }, + }; + } + } + return { kind: 'keep' }; + } +} + +function isPrimitiveBinaryOp(op) { + switch (op) { + case '+': + case '-': + case '/': + case '%': + case '*': + case '**': + case '&': + case '|': + case '>>': + case '<<': + case '^': + case '>': + case '<': + case '>=': + case '<=': + case '|>': + return true; + default: + return false; + } +} +function inferTypes(func) { + const unifier = new Unifier(func.env); + for (const e of generate(func)) { + unifier.unify(e.left, e.right); + } + apply(func, unifier); +} +function apply(func, unifier) { + for (const [_, block] of func.body.blocks) { + for (const phi of block.phis) { + phi.place.identifier.type = unifier.get(phi.place.identifier.type); + } + for (const instr of block.instructions) { + for (const operand of eachInstructionLValue(instr)) { + operand.identifier.type = unifier.get(operand.identifier.type); + } + for (const place of eachInstructionOperand(instr)) { + place.identifier.type = unifier.get(place.identifier.type); + } + const { lvalue, value } = instr; + lvalue.identifier.type = unifier.get(lvalue.identifier.type); + if (value.kind === 'FunctionExpression' || + value.kind === 'ObjectMethod') { + apply(value.loweredFunc.func, unifier); + } + } + } + const returns = func.returns.identifier; + returns.type = unifier.get(returns.type); +} +function equation(left, right) { + return { + left, + right, + }; +} +function* generate(func) { + if (func.fnType === 'Component') { + const [props, ref] = func.params; + if (props && props.kind === 'Identifier') { + yield equation(props.identifier.type, { + kind: 'Object', + shapeId: BuiltInPropsId, + }); + } + if (ref && ref.kind === 'Identifier') { + yield equation(ref.identifier.type, { + kind: 'Object', + shapeId: BuiltInUseRefId, + }); + } + } + const names = new Map(); + const returnTypes = []; + for (const [_, block] of func.body.blocks) { + for (const phi of block.phis) { + yield equation(phi.place.identifier.type, { + kind: 'Phi', + operands: [...phi.operands.values()].map(id => id.identifier.type), + }); + } + for (const instr of block.instructions) { + yield* generateInstructionTypes(func.env, names, instr); + } + const terminal = block.terminal; + if (terminal.kind === 'return') { + returnTypes.push(terminal.value.identifier.type); + } + } + if (returnTypes.length > 1) { + yield equation(func.returns.identifier.type, { + kind: 'Phi', + operands: returnTypes, + }); + } + else if (returnTypes.length === 1) { + yield equation(func.returns.identifier.type, returnTypes[0]); + } +} +function setName(names, id, name) { + var _a; + if (((_a = name.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named') { + names.set(id, name.name.value); + } +} +function getName(names, id) { + var _a; + return (_a = names.get(id)) !== null && _a !== void 0 ? _a : ''; +} +function* generateInstructionTypes(env, names, instr) { + const { lvalue, value } = instr; + const left = lvalue.identifier.type; + switch (value.kind) { + case 'TemplateLiteral': + case 'JSXText': + case 'Primitive': { + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'UnaryExpression': { + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'LoadLocal': { + setName(names, lvalue.identifier.id, value.place.identifier); + yield equation(left, value.place.identifier.type); + break; + } + case 'DeclareContext': + case 'LoadContext': { + break; + } + case 'StoreContext': { + if (value.lvalue.kind === InstructionKind.Const) { + yield equation(value.lvalue.place.identifier.type, value.value.identifier.type); + } + break; + } + case 'StoreLocal': { + yield equation(left, value.value.identifier.type); + yield equation(value.lvalue.place.identifier.type, value.value.identifier.type); + break; + } + case 'StoreGlobal': { + yield equation(left, value.value.identifier.type); + break; + } + case 'BinaryExpression': { + if (isPrimitiveBinaryOp(value.operator)) { + yield equation(value.left.identifier.type, { kind: 'Primitive' }); + yield equation(value.right.identifier.type, { kind: 'Primitive' }); + } + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + yield equation(value.value.identifier.type, { kind: 'Primitive' }); + yield equation(value.lvalue.identifier.type, { kind: 'Primitive' }); + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'LoadGlobal': { + const globalType = env.getGlobalDeclaration(value.binding, value.loc); + if (globalType) { + yield equation(left, globalType); + } + break; + } + case 'CallExpression': { + const returnType = makeType(); + let shapeId = null; + if (env.config.enableTreatSetIdentifiersAsStateSetters) { + const name = getName(names, value.callee.identifier.id); + if (name.startsWith('set')) { + shapeId = BuiltInSetStateId; + } + } + yield equation(value.callee.identifier.type, { + kind: 'Function', + shapeId, + return: returnType, + isConstructor: false, + }); + yield equation(left, returnType); + break; + } + case 'TaggedTemplateExpression': { + const returnType = makeType(); + yield equation(value.tag.identifier.type, { + kind: 'Function', + shapeId: null, + return: returnType, + isConstructor: false, + }); + yield equation(left, returnType); + break; + } + case 'ObjectExpression': { + for (const property of value.properties) { + if (property.kind === 'ObjectProperty' && + property.key.kind === 'computed') { + yield equation(property.key.name.identifier.type, { + kind: 'Primitive', + }); + } + } + yield equation(left, { kind: 'Object', shapeId: BuiltInObjectId }); + break; + } + case 'ArrayExpression': { + yield equation(left, { kind: 'Object', shapeId: BuiltInArrayId }); + break; + } + case 'PropertyLoad': { + yield equation(left, { + kind: 'Property', + objectType: value.object.identifier.type, + objectName: getName(names, value.object.identifier.id), + propertyName: { + kind: 'literal', + value: value.property, + }, + }); + break; + } + case 'ComputedLoad': { + yield equation(left, { + kind: 'Property', + objectType: value.object.identifier.type, + objectName: getName(names, value.object.identifier.id), + propertyName: { + kind: 'computed', + value: value.property.identifier.type, + }, + }); + break; + } + case 'MethodCall': { + const returnType = makeType(); + yield equation(value.property.identifier.type, { + kind: 'Function', + return: returnType, + shapeId: null, + isConstructor: false, + }); + yield equation(left, returnType); + break; + } + case 'Destructure': { + const pattern = value.lvalue.pattern; + if (pattern.kind === 'ArrayPattern') { + for (let i = 0; i < pattern.items.length; i++) { + const item = pattern.items[i]; + if (item.kind === 'Identifier') { + const propertyName = String(i); + yield equation(item.identifier.type, { + kind: 'Property', + objectType: value.value.identifier.type, + objectName: getName(names, value.value.identifier.id), + propertyName: { + kind: 'literal', + value: makePropertyLiteral(propertyName), + }, + }); + } + else if (item.kind === 'Spread') { + yield equation(item.place.identifier.type, { + kind: 'Object', + shapeId: BuiltInArrayId, + }); + } + else { + continue; + } + } + } + else { + for (const property of pattern.properties) { + if (property.kind === 'ObjectProperty') { + if (property.key.kind === 'identifier' || + property.key.kind === 'string') { + yield equation(property.place.identifier.type, { + kind: 'Property', + objectType: value.value.identifier.type, + objectName: getName(names, value.value.identifier.id), + propertyName: { + kind: 'literal', + value: makePropertyLiteral(property.key.name), + }, + }); + } + } + } + } + break; + } + case 'TypeCastExpression': { + yield equation(left, value.value.identifier.type); + break; + } + case 'PropertyDelete': + case 'ComputedDelete': { + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'FunctionExpression': { + yield* generate(value.loweredFunc.func); + yield equation(left, { + kind: 'Function', + shapeId: BuiltInFunctionId, + return: value.loweredFunc.func.returns.identifier.type, + isConstructor: false, + }); + break; + } + case 'NextPropertyOf': { + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'ObjectMethod': { + yield* generate(value.loweredFunc.func); + yield equation(left, { kind: 'ObjectMethod' }); + break; + } + case 'JsxExpression': + case 'JsxFragment': { + if (env.config.enableTreatRefLikeIdentifiersAsRefs) { + if (value.kind === 'JsxExpression') { + for (const prop of value.props) { + if (prop.kind === 'JsxAttribute' && prop.name === 'ref') { + yield equation(prop.place.identifier.type, { + kind: 'Object', + shapeId: BuiltInUseRefId, + }); + } + } + } + } + yield equation(left, { kind: 'Object', shapeId: BuiltInJsxId }); + break; + } + case 'NewExpression': { + const returnType = makeType(); + yield equation(value.callee.identifier.type, { + kind: 'Function', + return: returnType, + shapeId: null, + isConstructor: true, + }); + yield equation(left, returnType); + break; + } + case 'PropertyStore': { + yield equation(makeType(), { + kind: 'Property', + objectType: value.object.identifier.type, + objectName: getName(names, value.object.identifier.id), + propertyName: { + kind: 'literal', + value: value.property, + }, + }); + break; + } + case 'DeclareLocal': + case 'RegExpLiteral': + case 'MetaProperty': + case 'ComputedStore': + case 'Await': + case 'GetIterator': + case 'IteratorNext': + case 'UnsupportedNode': + case 'Debugger': + case 'FinishMemoize': + case 'StartMemoize': { + break; + } + default: + assertExhaustive$1(value, `Unhandled instruction value kind: ${value.kind}`); + } +} +class Unifier { + constructor(env) { + this.substitutions = new Map(); + this.env = env; + } + unify(tA, tB) { + if (tB.kind === 'Property') { + if (this.env.config.enableTreatRefLikeIdentifiersAsRefs && + isRefLikeName(tB)) { + this.unify(tB.objectType, { + kind: 'Object', + shapeId: BuiltInUseRefId, + }); + this.unify(tA, { + kind: 'Object', + shapeId: BuiltInRefValueId, + }); + return; + } + const objectType = this.get(tB.objectType); + const propertyType = tB.propertyName.kind === 'literal' + ? this.env.getPropertyType(objectType, tB.propertyName.value) + : this.env.getFallthroughPropertyType(objectType, tB.propertyName.value); + if (propertyType !== null) { + this.unify(tA, propertyType); + } + return; + } + if (typeEquals(tA, tB)) { + return; + } + if (tA.kind === 'Type') { + this.bindVariableTo(tA, tB); + return; + } + if (tB.kind === 'Type') { + this.bindVariableTo(tB, tA); + return; + } + if (tB.kind === 'Function' && + tA.kind === 'Function' && + tA.isConstructor === tB.isConstructor) { + this.unify(tA.return, tB.return); + return; + } + } + bindVariableTo(v, type) { + if (type.kind === 'Poly') { + return; + } + if (this.substitutions.has(v.id)) { + this.unify(this.substitutions.get(v.id), type); + return; + } + if (type.kind === 'Type' && this.substitutions.has(type.id)) { + this.unify(v, this.substitutions.get(type.id)); + return; + } + if (type.kind === 'Phi') { + CompilerError.invariant(type.operands.length > 0, { + reason: 'there should be at least one operand', + loc: GeneratedSource, + }); + let candidateType = null; + for (const operand of type.operands) { + const resolved = this.get(operand); + if (candidateType === null) { + candidateType = resolved; + } + else if (!typeEquals(resolved, candidateType)) { + const unionType = tryUnionTypes(resolved, candidateType); + if (unionType === null) { + candidateType = null; + break; + } + else { + candidateType = unionType; + } + } + } + if (candidateType !== null) { + this.unify(v, candidateType); + return; + } + } + if (this.occursCheck(v, type)) { + const resolvedType = this.tryResolveType(v, type); + if (resolvedType !== null) { + this.substitutions.set(v.id, resolvedType); + return; + } + throw new Error('cycle detected'); + } + this.substitutions.set(v.id, type); + } + tryResolveType(v, type) { + switch (type.kind) { + case 'Phi': { + const operands = []; + for (const operand of type.operands) { + if (operand.kind === 'Type' && operand.id === v.id) { + continue; + } + const resolved = this.tryResolveType(v, operand); + if (resolved === null) { + return null; + } + operands.push(resolved); + } + return { kind: 'Phi', operands }; + } + case 'Type': { + const substitution = this.get(type); + if (substitution !== type) { + const resolved = this.tryResolveType(v, substitution); + if (resolved !== null) { + this.substitutions.set(type.id, resolved); + } + return resolved; + } + return type; + } + case 'Property': { + const objectType = this.tryResolveType(v, this.get(type.objectType)); + if (objectType === null) { + return null; + } + return { + kind: 'Property', + objectName: type.objectName, + objectType, + propertyName: type.propertyName, + }; + } + case 'Function': { + const returnType = this.tryResolveType(v, this.get(type.return)); + if (returnType === null) { + return null; + } + return { + kind: 'Function', + return: returnType, + shapeId: type.shapeId, + isConstructor: type.isConstructor, + }; + } + case 'ObjectMethod': + case 'Object': + case 'Primitive': + case 'Poly': { + return type; + } + default: { + assertExhaustive$1(type, `Unexpected type kind '${type.kind}'`); + } + } + } + occursCheck(v, type) { + if (typeEquals(v, type)) + return true; + if (type.kind === 'Type' && this.substitutions.has(type.id)) { + return this.occursCheck(v, this.substitutions.get(type.id)); + } + if (type.kind === 'Phi') { + return type.operands.some(o => this.occursCheck(v, o)); + } + if (type.kind === 'Function') { + return this.occursCheck(v, type.return); + } + return false; + } + get(type) { + if (type.kind === 'Type') { + if (this.substitutions.has(type.id)) { + return this.get(this.substitutions.get(type.id)); + } + } + if (type.kind === 'Phi') { + return { kind: 'Phi', operands: type.operands.map(o => this.get(o)) }; + } + if (type.kind === 'Function') { + return { + kind: 'Function', + isConstructor: type.isConstructor, + shapeId: type.shapeId, + return: this.get(type.return), + }; + } + return type; + } +} +const RefLikeNameRE = /^(?:[a-zA-Z$_][a-zA-Z$_0-9]*)Ref$|^ref$/; +function isRefLikeName(t) { + return (t.propertyName.kind === 'literal' && + RefLikeNameRE.test(t.objectName) && + t.propertyName.value === 'current'); +} +function tryUnionTypes(ty1, ty2) { + let readonlyType; + let otherType; + if (ty1.kind === 'Object' && ty1.shapeId === BuiltInMixedReadonlyId) { + readonlyType = ty1; + otherType = ty2; + } + else if (ty2.kind === 'Object' && ty2.shapeId === BuiltInMixedReadonlyId) { + readonlyType = ty2; + otherType = ty1; + } + else { + return null; + } + if (otherType.kind === 'Primitive') { + return readonlyType; + } + else if (otherType.kind === 'Object' && + otherType.shapeId === BuiltInArrayId) { + return otherType; + } + return null; +} + +function validateContextVariableLValues(fn) { + const identifierKinds = new Map(); + validateContextVariableLValuesImpl(fn, identifierKinds, fn.env); +} +function validateContextVariableLValuesImpl(fn, identifierKinds, env) { + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'DeclareContext': + case 'StoreContext': { + visit(identifierKinds, value.lvalue.place, 'context', env); + break; + } + case 'LoadContext': { + visit(identifierKinds, value.place, 'context', env); + break; + } + case 'StoreLocal': + case 'DeclareLocal': { + visit(identifierKinds, value.lvalue.place, 'local', env); + break; + } + case 'LoadLocal': { + visit(identifierKinds, value.place, 'local', env); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + visit(identifierKinds, value.lvalue, 'local', env); + break; + } + case 'Destructure': { + for (const lvalue of eachPatternOperand(value.lvalue.pattern)) { + visit(identifierKinds, lvalue, 'destructure', env); + } + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + validateContextVariableLValuesImpl(value.loweredFunc.func, identifierKinds, env); + break; + } + default: { + for (const _ of eachInstructionValueLValue(value)) { + fn.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Todo, + reason: 'ValidateContextVariableLValues: unhandled instruction variant', + description: `Handle '${value.kind} lvalues`, + }).withDetails({ + kind: 'error', + loc: value.loc, + message: null, + })); + } + } + } + } + } +} +function visit(identifiers, place, kind, env) { + const prev = identifiers.get(place.identifier.id); + if (prev !== undefined) { + const wasContext = prev.kind === 'context'; + const isContext = kind === 'context'; + if (wasContext !== isContext) { + if (prev.kind === 'destructure' || kind === 'destructure') { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Todo, + reason: `Support destructuring of context variables`, + description: null, + }).withDetails({ + kind: 'error', + loc: kind === 'destructure' ? place.loc : prev.place.loc, + message: null, + })); + return; + } + CompilerError.invariant(false, { + reason: 'Expected all references to a variable to be consistently local or context references', + description: `Identifier ${printPlace(place)} is referenced as a ${kind} variable, but was previously referenced as a ${prev.kind} variable`, + message: `this is ${prev.kind}`, + loc: place.loc, + }); + } + } + identifiers.set(place.identifier.id, { place, kind }); +} + +function computeUnconditionalBlocks(fn) { + const unconditionalBlocks = new Set(); + const dominators = computePostDominatorTree(fn, { + includeThrowsAsExitNode: false, + }); + const exit = dominators.exit; + let current = fn.body.entry; + while (current !== null && current !== exit) { + CompilerError.invariant(!unconditionalBlocks.has(current), { + reason: 'Internal error: non-terminating loop in ComputeUnconditionalBlocks', + loc: GeneratedSource, + }); + unconditionalBlocks.add(current); + current = dominators.get(current); + } + return unconditionalBlocks; +} + +var Kind; +(function (Kind) { + Kind["Error"] = "Error"; + Kind["KnownHook"] = "KnownHook"; + Kind["PotentialHook"] = "PotentialHook"; + Kind["Global"] = "Global"; + Kind["Local"] = "Local"; +})(Kind || (Kind = {})); +function joinKinds(a, b) { + if (a === Kind.Error || b === Kind.Error) { + return Kind.Error; + } + else if (a === Kind.KnownHook || b === Kind.KnownHook) { + return Kind.KnownHook; + } + else if (a === Kind.PotentialHook || b === Kind.PotentialHook) { + return Kind.PotentialHook; + } + else if (a === Kind.Global || b === Kind.Global) { + return Kind.Global; + } + else { + return Kind.Local; + } +} +function validateHooksUsage(fn) { + const unconditionalBlocks = computeUnconditionalBlocks(fn); + const errorsByPlace = new Map(); + function trackError(loc, errorDetail) { + if (typeof loc === 'symbol') { + fn.env.recordError(errorDetail); + } + else { + errorsByPlace.set(loc, errorDetail); + } + } + function recordConditionalHookError(place) { + setKind(place, Kind.Error); + const reason = 'Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)'; + const previousError = typeof place.loc !== 'symbol' ? errorsByPlace.get(place.loc) : undefined; + if (previousError === undefined || previousError.reason !== reason) { + trackError(place.loc, new CompilerErrorDetail({ + category: ErrorCategory.Hooks, + description: null, + reason, + loc: place.loc, + suggestions: null, + })); + } + } + function recordInvalidHookUsageError(place) { + const previousError = typeof place.loc !== 'symbol' ? errorsByPlace.get(place.loc) : undefined; + if (previousError === undefined) { + trackError(place.loc, new CompilerErrorDetail({ + category: ErrorCategory.Hooks, + description: null, + reason: 'Hooks may not be referenced as normal values, they must be called. See https://react.dev/reference/rules/react-calls-components-and-hooks#never-pass-around-hooks-as-regular-values', + loc: place.loc, + suggestions: null, + })); + } + } + function recordDynamicHookUsageError(place) { + const previousError = typeof place.loc !== 'symbol' ? errorsByPlace.get(place.loc) : undefined; + if (previousError === undefined) { + trackError(place.loc, new CompilerErrorDetail({ + category: ErrorCategory.Hooks, + description: null, + reason: 'Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks', + loc: place.loc, + suggestions: null, + })); + } + } + const valueKinds = new Map(); + function getKindForPlace(place) { + const knownKind = valueKinds.get(place.identifier.id); + if (place.identifier.name !== null && + isHookName$2(place.identifier.name.value)) { + return joinKinds(knownKind !== null && knownKind !== void 0 ? knownKind : Kind.Local, Kind.PotentialHook); + } + else { + return knownKind !== null && knownKind !== void 0 ? knownKind : Kind.Local; + } + } + function visitPlace(place) { + const kind = valueKinds.get(place.identifier.id); + if (kind === Kind.KnownHook) { + recordInvalidHookUsageError(place); + } + } + function setKind(place, kind) { + valueKinds.set(place.identifier.id, kind); + } + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + const kind = getKindForPlace(place); + setKind(place, kind); + } + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + let kind = phi.place.identifier.name !== null && + isHookName$2(phi.place.identifier.name.value) + ? Kind.PotentialHook + : Kind.Local; + for (const [, operand] of phi.operands) { + const operandKind = valueKinds.get(operand.identifier.id); + if (operandKind !== undefined) { + kind = joinKinds(kind, operandKind); + } + } + valueKinds.set(phi.place.identifier.id, kind); + } + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'LoadGlobal': { + if (getHookKind(fn.env, instr.lvalue.identifier) != null) { + setKind(instr.lvalue, Kind.KnownHook); + } + else { + setKind(instr.lvalue, Kind.Global); + } + break; + } + case 'LoadContext': + case 'LoadLocal': { + visitPlace(instr.value.place); + const kind = getKindForPlace(instr.value.place); + setKind(instr.lvalue, kind); + break; + } + case 'StoreLocal': + case 'StoreContext': { + visitPlace(instr.value.value); + const kind = joinKinds(getKindForPlace(instr.value.value), getKindForPlace(instr.value.lvalue.place)); + setKind(instr.value.lvalue.place, kind); + setKind(instr.lvalue, kind); + break; + } + case 'ComputedLoad': { + visitPlace(instr.value.object); + const kind = getKindForPlace(instr.value.object); + setKind(instr.lvalue, joinKinds(getKindForPlace(instr.lvalue), kind)); + break; + } + case 'PropertyLoad': { + const objectKind = getKindForPlace(instr.value.object); + const isHookProperty = typeof instr.value.property === 'string' && + isHookName$2(instr.value.property); + let kind; + switch (objectKind) { + case Kind.Error: { + kind = Kind.Error; + break; + } + case Kind.KnownHook: { + kind = isHookProperty ? Kind.KnownHook : Kind.Local; + break; + } + case Kind.PotentialHook: { + kind = Kind.PotentialHook; + break; + } + case Kind.Global: { + kind = isHookProperty ? Kind.KnownHook : Kind.Global; + break; + } + case Kind.Local: { + kind = isHookProperty ? Kind.PotentialHook : Kind.Local; + break; + } + default: { + assertExhaustive$1(objectKind, `Unexpected kind \`${objectKind}\``); + } + } + setKind(instr.lvalue, kind); + break; + } + case 'CallExpression': { + const calleeKind = getKindForPlace(instr.value.callee); + const isHookCallee = calleeKind === Kind.KnownHook || calleeKind === Kind.PotentialHook; + if (isHookCallee && !unconditionalBlocks.has(block.id)) { + recordConditionalHookError(instr.value.callee); + } + else if (calleeKind === Kind.PotentialHook) { + recordDynamicHookUsageError(instr.value.callee); + } + for (const operand of eachInstructionOperand(instr)) { + if (operand === instr.value.callee) { + continue; + } + visitPlace(operand); + } + break; + } + case 'MethodCall': { + const calleeKind = getKindForPlace(instr.value.property); + const isHookCallee = calleeKind === Kind.KnownHook || calleeKind === Kind.PotentialHook; + if (isHookCallee && !unconditionalBlocks.has(block.id)) { + recordConditionalHookError(instr.value.property); + } + else if (calleeKind === Kind.PotentialHook) { + recordDynamicHookUsageError(instr.value.property); + } + for (const operand of eachInstructionOperand(instr)) { + if (operand === instr.value.property) { + continue; + } + visitPlace(operand); + } + break; + } + case 'Destructure': { + visitPlace(instr.value.value); + const objectKind = getKindForPlace(instr.value.value); + for (const lvalue of eachInstructionLValue(instr)) { + const isHookProperty = lvalue.identifier.name !== null && + isHookName$2(lvalue.identifier.name.value); + let kind; + switch (objectKind) { + case Kind.Error: { + kind = Kind.Error; + break; + } + case Kind.KnownHook: { + kind = Kind.KnownHook; + break; + } + case Kind.PotentialHook: { + kind = Kind.PotentialHook; + break; + } + case Kind.Global: { + kind = isHookProperty ? Kind.KnownHook : Kind.Global; + break; + } + case Kind.Local: { + kind = isHookProperty ? Kind.PotentialHook : Kind.Local; + break; + } + default: { + assertExhaustive$1(objectKind, `Unexpected kind \`${objectKind}\``); + } + } + setKind(lvalue, kind); + } + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + visitFunctionExpression(fn.env, instr.value.loweredFunc.func); + break; + } + default: { + for (const operand of eachInstructionOperand(instr)) { + visitPlace(operand); + } + for (const lvalue of eachInstructionLValue(instr)) { + const kind = getKindForPlace(lvalue); + setKind(lvalue, kind); + } + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + visitPlace(operand); + } + } + for (const [, error] of errorsByPlace) { + fn.env.recordError(error); + } +} +function visitFunctionExpression(env, fn) { + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'ObjectMethod': + case 'FunctionExpression': { + visitFunctionExpression(env, instr.value.loweredFunc.func); + break; + } + case 'MethodCall': + case 'CallExpression': { + const callee = instr.value.kind === 'CallExpression' + ? instr.value.callee + : instr.value.property; + const hookKind = getHookKind(fn.env, callee.identifier); + if (hookKind != null) { + env.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Hooks, + reason: 'Hooks must be called at the top level in the body of a function component or custom hook, and may not be called within function expressions. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)', + loc: callee.loc, + description: `Cannot call ${hookKind === 'Custom' ? 'hook' : hookKind} within a function expression`, + suggestions: null, + })); + } + break; + } + } + } + } +} + +function validateNoCapitalizedCalls(fn) { + var _a; + const envConfig = fn.env.config; + const ALLOW_LIST = new Set([ + ...DEFAULT_GLOBALS.keys(), + ...((_a = envConfig.validateNoCapitalizedCalls) !== null && _a !== void 0 ? _a : []), + ]); + const isAllowed = (name) => { + return ALLOW_LIST.has(name); + }; + const capitalLoadGlobals = new Map(); + const capitalizedProperties = new Map(); + const reason = 'Capitalized functions are reserved for components, which must be invoked with JSX. If this is a component, render it with JSX. Otherwise, ensure that it has no hook calls and rename it to begin with a lowercase letter. Alternatively, if you know for a fact that this function is not a component, you can allowlist it via the compiler config'; + for (const [, block] of fn.body.blocks) { + for (const { lvalue, value } of block.instructions) { + switch (value.kind) { + case 'LoadGlobal': { + if (value.binding.name != '' && + /^[A-Z]/.test(value.binding.name) && + !(value.binding.name.toUpperCase() === value.binding.name) && + !isAllowed(value.binding.name)) { + capitalLoadGlobals.set(lvalue.identifier.id, value.binding.name); + } + break; + } + case 'CallExpression': { + const calleeIdentifier = value.callee.identifier.id; + const calleeName = capitalLoadGlobals.get(calleeIdentifier); + if (calleeName != null) { + fn.env.recordError(new CompilerErrorDetail({ + category: ErrorCategory.CapitalizedCalls, + reason, + description: `${calleeName} may be a component`, + loc: value.loc, + suggestions: null, + })); + continue; + } + break; + } + case 'PropertyLoad': { + if (typeof value.property === 'string' && + /^[A-Z]/.test(value.property)) { + capitalizedProperties.set(lvalue.identifier.id, value.property); + } + break; + } + case 'MethodCall': { + const propertyIdentifier = value.property.identifier.id; + const propertyName = capitalizedProperties.get(propertyIdentifier); + if (propertyName != null) { + fn.env.recordError(new CompilerErrorDetail({ + category: ErrorCategory.CapitalizedCalls, + reason, + description: `${propertyName} may be a component`, + loc: value.loc, + suggestions: null, + })); + } + break; + } + } + } + } +} + +var _Env_changed, _Env_data, _Env_temporaries; +function makeRefId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected identifier id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +let _refId = 0; +function nextRefId() { + return makeRefId(_refId++); +} +class Env { + constructor() { + _Env_changed.set(this, false); + _Env_data.set(this, new Map()); + _Env_temporaries.set(this, new Map()); + } + lookup(place) { + var _a; + return (_a = __classPrivateFieldGet(this, _Env_temporaries, "f").get(place.identifier.id)) !== null && _a !== void 0 ? _a : place; + } + define(place, value) { + __classPrivateFieldGet(this, _Env_temporaries, "f").set(place.identifier.id, value); + } + resetChanged() { + __classPrivateFieldSet(this, _Env_changed, false, "f"); + } + hasChanged() { + return __classPrivateFieldGet(this, _Env_changed, "f"); + } + get(key) { + var _a, _b; + const operandId = (_b = (_a = __classPrivateFieldGet(this, _Env_temporaries, "f").get(key)) === null || _a === void 0 ? void 0 : _a.identifier.id) !== null && _b !== void 0 ? _b : key; + return __classPrivateFieldGet(this, _Env_data, "f").get(operandId); + } + set(key, value) { + var _a, _b; + const operandId = (_b = (_a = __classPrivateFieldGet(this, _Env_temporaries, "f").get(key)) === null || _a === void 0 ? void 0 : _a.identifier.id) !== null && _b !== void 0 ? _b : key; + const cur = __classPrivateFieldGet(this, _Env_data, "f").get(operandId); + const widenedValue = joinRefAccessTypes(value, cur !== null && cur !== void 0 ? cur : { kind: 'None' }); + if (!(cur == null && widenedValue.kind === 'None') && + (cur == null || !tyEqual(cur, widenedValue))) { + __classPrivateFieldSet(this, _Env_changed, true, "f"); + } + __classPrivateFieldGet(this, _Env_data, "f").set(operandId, widenedValue); + return this; + } +} +_Env_changed = new WeakMap(), _Env_data = new WeakMap(), _Env_temporaries = new WeakMap(); +function validateNoRefAccessInRender(fn) { + const env = new Env(); + collectTemporariesSidemap$1(fn, env); + const errors = new CompilerError(); + validateNoRefAccessInRenderImpl(fn, env, errors); + for (const detail of errors.details) { + fn.env.recordError(detail); + } +} +function collectTemporariesSidemap$1(fn, env) { + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'LoadLocal': { + const temp = env.lookup(value.place); + if (temp != null) { + env.define(lvalue, temp); + } + break; + } + case 'StoreLocal': { + const temp = env.lookup(value.value); + if (temp != null) { + env.define(lvalue, temp); + env.define(value.lvalue.place, temp); + } + break; + } + case 'PropertyLoad': { + if (isUseRefType(value.object.identifier) && + value.property === 'current') { + continue; + } + const temp = env.lookup(value.object); + if (temp != null) { + env.define(lvalue, temp); + } + break; + } + } + } + } +} +function refTypeOfType(place) { + if (isRefValueType(place.identifier)) { + return { kind: 'RefValue' }; + } + else if (isUseRefType(place.identifier)) { + return { kind: 'Ref', refId: nextRefId() }; + } + else { + return { kind: 'None' }; + } +} +function tyEqual(a, b) { + if (a.kind !== b.kind) { + return false; + } + switch (a.kind) { + case 'None': + return true; + case 'Ref': + return true; + case 'Nullable': + return true; + case 'Guard': + CompilerError.invariant(b.kind === 'Guard', { + reason: 'Expected ref value', + loc: GeneratedSource, + }); + return a.refId === b.refId; + case 'RefValue': + CompilerError.invariant(b.kind === 'RefValue', { + reason: 'Expected ref value', + loc: GeneratedSource, + }); + return a.loc == b.loc; + case 'Structure': { + CompilerError.invariant(b.kind === 'Structure', { + reason: 'Expected structure', + loc: GeneratedSource, + }); + const fnTypesEqual = (a.fn === null && b.fn === null) || + (a.fn !== null && + b.fn !== null && + a.fn.readRefEffect === b.fn.readRefEffect && + tyEqual(a.fn.returnType, b.fn.returnType)); + return (fnTypesEqual && + (a.value === b.value || + (a.value !== null && b.value !== null && tyEqual(a.value, b.value)))); + } + } +} +function joinRefAccessTypes(...types) { + function joinRefAccessRefTypes(a, b) { + if (a.kind === 'RefValue') { + if (b.kind === 'RefValue' && a.refId === b.refId) { + return a; + } + return { kind: 'RefValue' }; + } + else if (b.kind === 'RefValue') { + return b; + } + else if (a.kind === 'Ref' || b.kind === 'Ref') { + if (a.kind === 'Ref' && b.kind === 'Ref' && a.refId === b.refId) { + return a; + } + return { kind: 'Ref', refId: nextRefId() }; + } + else { + CompilerError.invariant(a.kind === 'Structure' && b.kind === 'Structure', { + reason: 'Expected structure', + loc: GeneratedSource, + }); + const fn = a.fn === null + ? b.fn + : b.fn === null + ? a.fn + : { + readRefEffect: a.fn.readRefEffect || b.fn.readRefEffect, + returnType: joinRefAccessTypes(a.fn.returnType, b.fn.returnType), + }; + const value = a.value === null + ? b.value + : b.value === null + ? a.value + : joinRefAccessRefTypes(a.value, b.value); + return { + kind: 'Structure', + fn, + value, + }; + } + } + return types.reduce((a, b) => { + if (a.kind === 'None') { + return b; + } + else if (b.kind === 'None') { + return a; + } + else if (a.kind === 'Guard') { + if (b.kind === 'Guard' && a.refId === b.refId) { + return a; + } + else if (b.kind === 'Nullable' || b.kind === 'Guard') { + return { kind: 'None' }; + } + else { + return b; + } + } + else if (b.kind === 'Guard') { + if (a.kind === 'Nullable') { + return { kind: 'None' }; + } + else { + return b; + } + } + else if (a.kind === 'Nullable') { + return b; + } + else if (b.kind === 'Nullable') { + return a; + } + else { + return joinRefAccessRefTypes(a, b); + } + }, { kind: 'None' }); +} +function validateNoRefAccessInRenderImpl(fn, env, errors) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + let returnValues = []; + let place; + for (const param of fn.params) { + if (param.kind === 'Identifier') { + place = param; + } + else { + place = param.place; + } + const type = refTypeOfType(place); + env.set(place.identifier.id, type); + } + const interpolatedAsJsx = new Set(); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { value } = instr; + if (value.kind === 'JsxExpression' || value.kind === 'JsxFragment') { + if (value.children != null) { + for (const child of value.children) { + interpolatedAsJsx.add(child.identifier.id); + } + } + } + } + } + for (let i = 0; (i == 0 || env.hasChanged()) && i < 10; i++) { + env.resetChanged(); + returnValues = []; + const safeBlocks = []; + for (const [, block] of fn.body.blocks) { + retainWhere(safeBlocks, entry => entry.block !== block.id); + for (const phi of block.phis) { + env.set(phi.place.identifier.id, joinRefAccessTypes(...Array(...phi.operands.values()).map(operand => { var _a; return (_a = env.get(operand.identifier.id)) !== null && _a !== void 0 ? _a : { kind: 'None' }; }))); + } + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'JsxExpression': + case 'JsxFragment': { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoDirectRefValueAccess(errors, operand, env); + } + break; + } + case 'ComputedLoad': + case 'PropertyLoad': { + if (instr.value.kind === 'ComputedLoad') { + validateNoDirectRefValueAccess(errors, instr.value.property, env); + } + const objType = env.get(instr.value.object.identifier.id); + let lookupType = null; + if ((objType === null || objType === void 0 ? void 0 : objType.kind) === 'Structure') { + lookupType = objType.value; + } + else if ((objType === null || objType === void 0 ? void 0 : objType.kind) === 'Ref') { + lookupType = { + kind: 'RefValue', + loc: instr.loc, + refId: objType.refId, + }; + } + env.set(instr.lvalue.identifier.id, lookupType !== null && lookupType !== void 0 ? lookupType : refTypeOfType(instr.lvalue)); + break; + } + case 'TypeCastExpression': { + env.set(instr.lvalue.identifier.id, (_a = env.get(instr.value.value.identifier.id)) !== null && _a !== void 0 ? _a : refTypeOfType(instr.lvalue)); + break; + } + case 'LoadContext': + case 'LoadLocal': { + env.set(instr.lvalue.identifier.id, (_b = env.get(instr.value.place.identifier.id)) !== null && _b !== void 0 ? _b : refTypeOfType(instr.lvalue)); + break; + } + case 'StoreContext': + case 'StoreLocal': { + env.set(instr.value.lvalue.place.identifier.id, (_c = env.get(instr.value.value.identifier.id)) !== null && _c !== void 0 ? _c : refTypeOfType(instr.value.lvalue.place)); + env.set(instr.lvalue.identifier.id, (_d = env.get(instr.value.value.identifier.id)) !== null && _d !== void 0 ? _d : refTypeOfType(instr.lvalue)); + break; + } + case 'Destructure': { + const objType = env.get(instr.value.value.identifier.id); + let lookupType = null; + if ((objType === null || objType === void 0 ? void 0 : objType.kind) === 'Structure') { + lookupType = objType.value; + } + env.set(instr.lvalue.identifier.id, lookupType !== null && lookupType !== void 0 ? lookupType : refTypeOfType(instr.lvalue)); + for (const lval of eachPatternOperand(instr.value.lvalue.pattern)) { + env.set(lval.identifier.id, lookupType !== null && lookupType !== void 0 ? lookupType : refTypeOfType(lval)); + } + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + let returnType = { kind: 'None' }; + let readRefEffect = false; + const innerErrors = new CompilerError(); + const result = validateNoRefAccessInRenderImpl(instr.value.loweredFunc.func, env, innerErrors); + if (!innerErrors.hasAnyErrors()) { + returnType = result; + } + else { + readRefEffect = true; + } + env.set(instr.lvalue.identifier.id, { + kind: 'Structure', + fn: { + readRefEffect, + returnType, + }, + value: null, + }); + break; + } + case 'MethodCall': + case 'CallExpression': { + const callee = instr.value.kind === 'CallExpression' + ? instr.value.callee + : instr.value.property; + const hookKind = getHookKindForType(fn.env, callee.identifier.type); + let returnType = { kind: 'None' }; + const fnType = env.get(callee.identifier.id); + let didError = false; + if ((fnType === null || fnType === void 0 ? void 0 : fnType.kind) === 'Structure' && fnType.fn !== null) { + returnType = fnType.fn.returnType; + if (fnType.fn.readRefEffect) { + didError = true; + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: callee.loc, + message: `This function accesses a ref value`, + })); + } + } + if (!didError) { + const isRefLValue = isUseRefType(instr.lvalue.identifier); + if (isRefLValue || + (hookKind != null && + hookKind !== 'useState' && + hookKind !== 'useReducer')) { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoDirectRefValueAccess(errors, operand, env); + } + } + else if (interpolatedAsJsx.has(instr.lvalue.identifier.id)) { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoRefValueAccess(errors, env, operand); + } + } + else if (hookKind == null && instr.effects != null) { + const visitedEffects = new Set(); + for (const effect of instr.effects) { + let place = null; + let validation = 'none'; + switch (effect.kind) { + case 'Freeze': { + place = effect.value; + validation = 'direct-ref'; + break; + } + case 'Mutate': + case 'MutateTransitive': + case 'MutateConditionally': + case 'MutateTransitiveConditionally': { + place = effect.value; + validation = 'ref-passed'; + break; + } + case 'Render': { + place = effect.place; + validation = 'ref-passed'; + break; + } + case 'Capture': + case 'Alias': + case 'MaybeAlias': + case 'Assign': + case 'CreateFrom': { + place = effect.from; + validation = 'ref-passed'; + break; + } + case 'ImmutableCapture': { + place = effect.from; + const isFrozen = instr.effects.some(e => e.kind === 'Freeze' && + e.value.identifier.id === effect.from.identifier.id); + validation = isFrozen ? 'direct-ref' : 'ref-passed'; + break; + } + } + if (place !== null && validation !== 'none') { + const key = `${place.identifier.id}:${validation}`; + if (!visitedEffects.has(key)) { + visitedEffects.add(key); + if (validation === 'direct-ref') { + validateNoDirectRefValueAccess(errors, place, env); + } + else { + validateNoRefPassedToFunction(errors, env, place, place.loc); + } + } + } + } + } + else { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoRefPassedToFunction(errors, env, operand, operand.loc); + } + } + } + env.set(instr.lvalue.identifier.id, returnType); + break; + } + case 'ObjectExpression': + case 'ArrayExpression': { + const types = []; + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoDirectRefValueAccess(errors, operand, env); + types.push((_e = env.get(operand.identifier.id)) !== null && _e !== void 0 ? _e : { kind: 'None' }); + } + const value = joinRefAccessTypes(...types); + if (value.kind === 'None' || + value.kind === 'Guard' || + value.kind === 'Nullable') { + env.set(instr.lvalue.identifier.id, { kind: 'None' }); + } + else { + env.set(instr.lvalue.identifier.id, { + kind: 'Structure', + value, + fn: null, + }); + } + break; + } + case 'PropertyDelete': + case 'PropertyStore': + case 'ComputedDelete': + case 'ComputedStore': { + const target = env.get(instr.value.object.identifier.id); + let safe = null; + if (instr.value.kind === 'PropertyStore' && + target != null && + target.kind === 'Ref') { + safe = safeBlocks.find(entry => entry.ref === target.refId); + } + if (safe != null) { + retainWhere(safeBlocks, entry => entry !== safe); + } + else { + validateNoRefUpdate(errors, env, instr.value.object, instr.loc); + } + if (instr.value.kind === 'ComputedDelete' || + instr.value.kind === 'ComputedStore') { + validateNoRefValueAccess(errors, env, instr.value.property); + } + if (instr.value.kind === 'ComputedStore' || + instr.value.kind === 'PropertyStore') { + validateNoDirectRefValueAccess(errors, instr.value.value, env); + const type = env.get(instr.value.value.identifier.id); + if (type != null && type.kind === 'Structure') { + let objectType = type; + if (target != null) { + objectType = joinRefAccessTypes(objectType, target); + } + env.set(instr.value.object.identifier.id, objectType); + } + } + break; + } + case 'StartMemoize': + case 'FinishMemoize': + break; + case 'LoadGlobal': { + if (instr.value.binding.name === 'undefined') { + env.set(instr.lvalue.identifier.id, { kind: 'Nullable' }); + } + break; + } + case 'Primitive': { + if (instr.value.value == null) { + env.set(instr.lvalue.identifier.id, { kind: 'Nullable' }); + } + break; + } + case 'UnaryExpression': { + if (instr.value.operator === '!') { + const value = env.get(instr.value.value.identifier.id); + const refId = (value === null || value === void 0 ? void 0 : value.kind) === 'RefValue' && value.refId != null + ? value.refId + : null; + if (refId !== null) { + env.set(instr.lvalue.identifier.id, { kind: 'Guard', refId }); + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }) + .withDetails({ + kind: 'error', + loc: instr.value.value.loc, + message: `Cannot access ref value during render`, + }) + .withDetails({ + kind: 'hint', + message: 'To initialize a ref only once, check that the ref is null with the pattern `if (ref.current == null) { ref.current = ... }`', + })); + break; + } + } + validateNoRefValueAccess(errors, env, instr.value.value); + break; + } + case 'BinaryExpression': { + const left = env.get(instr.value.left.identifier.id); + const right = env.get(instr.value.right.identifier.id); + let nullish = false; + let refId = null; + if ((left === null || left === void 0 ? void 0 : left.kind) === 'RefValue' && left.refId != null) { + refId = left.refId; + } + else if ((right === null || right === void 0 ? void 0 : right.kind) === 'RefValue' && right.refId != null) { + refId = right.refId; + } + if ((left === null || left === void 0 ? void 0 : left.kind) === 'Nullable') { + nullish = true; + } + else if ((right === null || right === void 0 ? void 0 : right.kind) === 'Nullable') { + nullish = true; + } + if (refId !== null && nullish) { + env.set(instr.lvalue.identifier.id, { kind: 'Guard', refId }); + } + else { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoRefValueAccess(errors, env, operand); + } + } + break; + } + default: { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoRefValueAccess(errors, env, operand); + } + break; + } + } + for (const operand of eachInstructionOperand(instr)) { + guardCheck(errors, operand, env); + } + if (isUseRefType(instr.lvalue.identifier) && + ((_f = env.get(instr.lvalue.identifier.id)) === null || _f === void 0 ? void 0 : _f.kind) !== 'Ref') { + env.set(instr.lvalue.identifier.id, joinRefAccessTypes((_g = env.get(instr.lvalue.identifier.id)) !== null && _g !== void 0 ? _g : { kind: 'None' }, { kind: 'Ref', refId: nextRefId() })); + } + if (isRefValueType(instr.lvalue.identifier) && + ((_h = env.get(instr.lvalue.identifier.id)) === null || _h === void 0 ? void 0 : _h.kind) !== 'RefValue') { + env.set(instr.lvalue.identifier.id, joinRefAccessTypes((_j = env.get(instr.lvalue.identifier.id)) !== null && _j !== void 0 ? _j : { kind: 'None' }, { kind: 'RefValue', loc: instr.loc })); + } + } + if (block.terminal.kind === 'if') { + const test = env.get(block.terminal.test.identifier.id); + if ((test === null || test === void 0 ? void 0 : test.kind) === 'Guard' && + safeBlocks.find(entry => entry.ref === test.refId) == null) { + safeBlocks.push({ block: block.terminal.fallthrough, ref: test.refId }); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + if (block.terminal.kind !== 'return') { + validateNoRefValueAccess(errors, env, operand); + if (block.terminal.kind !== 'if') { + guardCheck(errors, operand, env); + } + } + else { + validateNoDirectRefValueAccess(errors, operand, env); + guardCheck(errors, operand, env); + returnValues.push(env.get(operand.identifier.id)); + } + } + } + if (errors.hasAnyErrors()) { + return { kind: 'None' }; + } + } + CompilerError.invariant(!env.hasChanged(), { + reason: 'Ref type environment did not converge', + loc: GeneratedSource, + }); + return joinRefAccessTypes(...returnValues.filter((env) => env !== undefined)); +} +function destructure(type) { + if ((type === null || type === void 0 ? void 0 : type.kind) === 'Structure' && type.value !== null) { + return destructure(type.value); + } + return type; +} +function guardCheck(errors, operand, env) { + var _a; + if (((_a = env.get(operand.identifier.id)) === null || _a === void 0 ? void 0 : _a.kind) === 'Guard') { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: operand.loc, + message: `Cannot access ref value during render`, + })); + } +} +function validateNoRefValueAccess(errors, env, operand) { + var _a; + const type = destructure(env.get(operand.identifier.id)); + if ((type === null || type === void 0 ? void 0 : type.kind) === 'RefValue' || + ((type === null || type === void 0 ? void 0 : type.kind) === 'Structure' && ((_a = type.fn) === null || _a === void 0 ? void 0 : _a.readRefEffect))) { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: (type.kind === 'RefValue' && type.loc) || operand.loc, + message: `Cannot access ref value during render`, + })); + } +} +function validateNoRefPassedToFunction(errors, env, operand, loc) { + var _a; + const type = destructure(env.get(operand.identifier.id)); + if ((type === null || type === void 0 ? void 0 : type.kind) === 'Ref' || + (type === null || type === void 0 ? void 0 : type.kind) === 'RefValue' || + ((type === null || type === void 0 ? void 0 : type.kind) === 'Structure' && ((_a = type.fn) === null || _a === void 0 ? void 0 : _a.readRefEffect))) { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: (type.kind === 'RefValue' && type.loc) || loc, + message: `Passing a ref to a function may read its value during render`, + })); + } +} +function validateNoRefUpdate(errors, env, operand, loc) { + const type = destructure(env.get(operand.identifier.id)); + if ((type === null || type === void 0 ? void 0 : type.kind) === 'Ref' || (type === null || type === void 0 ? void 0 : type.kind) === 'RefValue') { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: (type.kind === 'RefValue' && type.loc) || loc, + message: `Cannot update ref during render`, + })); + } +} +function validateNoDirectRefValueAccess(errors, operand, env) { + var _a; + const type = destructure(env.get(operand.identifier.id)); + if ((type === null || type === void 0 ? void 0 : type.kind) === 'RefValue') { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: (_a = type.loc) !== null && _a !== void 0 ? _a : operand.loc, + message: `Cannot access ref value during render`, + })); + } +} +const ERROR_DESCRIPTION = 'React refs are values that are not needed for rendering. Refs should only be accessed ' + + 'outside of render, such as in event handlers or effects. ' + + 'Accessing a ref value (the `current` property) during render can cause your component ' + + 'not to update as expected (https://react.dev/reference/react/useRef)'; + +function validateNoSetStateInRender(fn) { + const unconditionalSetStateFunctions = new Set(); + const errors = validateNoSetStateInRenderImpl(fn, unconditionalSetStateFunctions); + for (const detail of errors.details) { + fn.env.recordError(detail); + } +} +function validateNoSetStateInRenderImpl(fn, unconditionalSetStateFunctions) { + const unconditionalBlocks = computeUnconditionalBlocks(fn); + let activeManualMemoId = null; + const errors = new CompilerError(); + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'LoadLocal': { + if (unconditionalSetStateFunctions.has(instr.value.place.identifier.id)) { + unconditionalSetStateFunctions.add(instr.lvalue.identifier.id); + } + break; + } + case 'StoreLocal': { + if (unconditionalSetStateFunctions.has(instr.value.value.identifier.id)) { + unconditionalSetStateFunctions.add(instr.value.lvalue.place.identifier.id); + unconditionalSetStateFunctions.add(instr.lvalue.identifier.id); + } + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + if ([...eachInstructionValueOperand(instr.value)].some(operand => isSetStateType(operand.identifier) || + unconditionalSetStateFunctions.has(operand.identifier.id)) && + validateNoSetStateInRenderImpl(instr.value.loweredFunc.func, unconditionalSetStateFunctions).hasAnyErrors()) { + unconditionalSetStateFunctions.add(instr.lvalue.identifier.id); + } + break; + } + case 'StartMemoize': { + CompilerError.invariant(activeManualMemoId === null, { + reason: 'Unexpected nested StartMemoize instructions', + loc: instr.value.loc, + }); + activeManualMemoId = instr.value.manualMemoId; + break; + } + case 'FinishMemoize': { + CompilerError.invariant(activeManualMemoId === instr.value.manualMemoId, { + reason: 'Expected FinishMemoize to align with previous StartMemoize instruction', + loc: instr.value.loc, + }); + activeManualMemoId = null; + break; + } + case 'CallExpression': { + const callee = instr.value.callee; + if (isSetStateType(callee.identifier) || + unconditionalSetStateFunctions.has(callee.identifier.id)) { + if (activeManualMemoId !== null) { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.RenderSetState, + reason: 'Calling setState from useMemo may trigger an infinite loop', + description: 'Each time the memo callback is evaluated it will change state. This can cause a memoization dependency to change, running the memo function again and causing an infinite loop. Instead of setting state in useMemo(), prefer deriving the value during render. (https://react.dev/reference/react/useState)', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: callee.loc, + message: 'Found setState() within useMemo()', + })); + } + else if (unconditionalBlocks.has(block.id)) { + const enableUseKeyedState = fn.env.config.enableUseKeyedState; + if (enableUseKeyedState) { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.RenderSetState, + reason: 'Cannot call setState during render', + description: 'Calling setState during render may trigger an infinite loop.\n' + + '* To reset state when other state/props change, use `const [state, setState] = useKeyedState(initialState, key)` to reset `state` when `key` changes.\n' + + '* To derive data from other state/props, compute the derived data during render without using state', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: callee.loc, + message: 'Found setState() in render', + })); + } + else { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.RenderSetState, + reason: 'Cannot call setState during render', + description: 'Calling setState during render may trigger an infinite loop.\n' + + '* To reset state when other state/props change, store the previous value in state and update conditionally: https://react.dev/reference/react/useState#storing-information-from-previous-renders\n' + + '* To derive data from other state/props, compute the derived data during render without using state', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: callee.loc, + message: 'Found setState() in render', + })); + } + } + } + break; + } + } + } + } + return errors; +} + +function validatePreservedManualMemoization(fn) { + const state = { + env: fn.env, + manualMemoState: null, + }; + visitReactiveFunction(fn, new Visitor(), state); +} +function prettyPrintScopeDependency(val) { + var _a; + let rootStr; + if (((_a = val.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named') { + rootStr = val.identifier.name.value; + } + else { + rootStr = '[unnamed]'; + } + return `${rootStr}${val.path.map(v => `${v.optional ? '?.' : '.'}${v.property}`).join('')}`; +} +var CompareDependencyResult; +(function (CompareDependencyResult) { + CompareDependencyResult[CompareDependencyResult["Ok"] = 0] = "Ok"; + CompareDependencyResult[CompareDependencyResult["RootDifference"] = 1] = "RootDifference"; + CompareDependencyResult[CompareDependencyResult["PathDifference"] = 2] = "PathDifference"; + CompareDependencyResult[CompareDependencyResult["Subpath"] = 3] = "Subpath"; + CompareDependencyResult[CompareDependencyResult["RefAccessDifference"] = 4] = "RefAccessDifference"; +})(CompareDependencyResult || (CompareDependencyResult = {})); +function merge$1(a, b) { + return Math.max(a, b); +} +function getCompareDependencyResultDescription(result) { + switch (result) { + case CompareDependencyResult.Ok: + return 'Dependencies equal'; + case CompareDependencyResult.RootDifference: + case CompareDependencyResult.PathDifference: + return 'Inferred different dependency than source'; + case CompareDependencyResult.RefAccessDifference: + return 'Differences in ref.current access'; + case CompareDependencyResult.Subpath: + return 'Inferred less specific property than source'; + } +} +function compareDeps(inferred, source) { + const rootsEqual = (inferred.root.kind === 'Global' && + source.root.kind === 'Global' && + inferred.root.identifierName === source.root.identifierName) || + (inferred.root.kind === 'NamedLocal' && + source.root.kind === 'NamedLocal' && + inferred.root.value.identifier.id === source.root.value.identifier.id); + if (!rootsEqual) { + return CompareDependencyResult.RootDifference; + } + let isSubpath = true; + for (let i = 0; i < Math.min(inferred.path.length, source.path.length); i++) { + if (inferred.path[i].property !== source.path[i].property) { + isSubpath = false; + break; + } + else if (inferred.path[i].optional !== source.path[i].optional) { + return CompareDependencyResult.PathDifference; + } + } + if (isSubpath && + (source.path.length === inferred.path.length || + (inferred.path.length >= source.path.length && + !inferred.path.some(token => token.property === 'current')))) { + return CompareDependencyResult.Ok; + } + else { + if (isSubpath) { + if (source.path.some(token => token.property === 'current') || + inferred.path.some(token => token.property === 'current')) { + return CompareDependencyResult.RefAccessDifference; + } + else { + return CompareDependencyResult.Subpath; + } + } + else { + return CompareDependencyResult.PathDifference; + } + } +} +function validateInferredDep(dep, temporaries, declsWithinMemoBlock, validDepsInMemoBlock, env, memoLocation) { + var _a; + let normalizedDep; + const maybeNormalizedRoot = temporaries.get(dep.identifier.id); + if (maybeNormalizedRoot != null) { + normalizedDep = { + root: maybeNormalizedRoot.root, + path: [...maybeNormalizedRoot.path, ...dep.path], + loc: maybeNormalizedRoot.loc, + }; + } + else { + CompilerError.invariant(((_a = dep.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named', { + reason: 'ValidatePreservedManualMemoization: expected scope dependency to be named', + loc: GeneratedSource, + }); + normalizedDep = { + root: { + kind: 'NamedLocal', + value: { + kind: 'Identifier', + identifier: dep.identifier, + loc: GeneratedSource, + effect: Effect.Read, + reactive: false, + }, + constant: false, + }, + path: [...dep.path], + loc: GeneratedSource, + }; + } + for (const decl of declsWithinMemoBlock) { + if (normalizedDep.root.kind === 'NamedLocal' && + decl === normalizedDep.root.value.identifier.declarationId) { + return; + } + } + let errorDiagnostic = null; + for (const originalDep of validDepsInMemoBlock) { + const compareResult = compareDeps(normalizedDep, originalDep); + if (compareResult === CompareDependencyResult.Ok) { + return; + } + else { + errorDiagnostic = merge$1(errorDiagnostic !== null && errorDiagnostic !== void 0 ? errorDiagnostic : compareResult, compareResult); + } + } + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.PreserveManualMemo, + reason: 'Existing memoization could not be preserved', + description: [ + 'React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. ', + 'The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected. ', + (dep.identifier.name != null && dep.identifier.name.kind === 'named') + ? `The inferred dependency was \`${prettyPrintScopeDependency(dep)}\`, but the source dependencies were [${validDepsInMemoBlock + .map(dep => printManualMemoDependency$1(dep, true)) + .join(', ')}]. ${errorDiagnostic + ? getCompareDependencyResultDescription(errorDiagnostic) + : 'Inferred dependency not present in source'}` + : '', + ] + .join('') + .trim(), + suggestions: null, + }).withDetails({ + kind: 'error', + loc: memoLocation, + message: 'Could not preserve existing manual memoization', + })); +} +class Visitor extends ReactiveFunctionVisitor { + constructor() { + super(...arguments); + this.scopes = new Set(); + this.prunedScopes = new Set(); + this.temporaries = new Map(); + } + recordDepsInValue(value, state) { + var _a, _b; + switch (value.kind) { + case 'SequenceExpression': { + for (const instr of value.instructions) { + this.visitInstruction(instr, state); + } + this.recordDepsInValue(value.value, state); + break; + } + case 'OptionalExpression': { + this.recordDepsInValue(value.value, state); + break; + } + case 'ConditionalExpression': { + this.recordDepsInValue(value.test, state); + this.recordDepsInValue(value.consequent, state); + this.recordDepsInValue(value.alternate, state); + break; + } + case 'LogicalExpression': { + this.recordDepsInValue(value.left, state); + this.recordDepsInValue(value.right, state); + break; + } + default: { + collectMaybeMemoDependencies(value, this.temporaries, false); + if (value.kind === 'StoreLocal' || + value.kind === 'StoreContext' || + value.kind === 'Destructure') { + for (const storeTarget of eachInstructionValueLValue(value)) { + (_a = state.manualMemoState) === null || _a === void 0 ? void 0 : _a.decls.add(storeTarget.identifier.declarationId); + if (((_b = storeTarget.identifier.name) === null || _b === void 0 ? void 0 : _b.kind) === 'named') { + this.temporaries.set(storeTarget.identifier.id, { + root: { + kind: 'NamedLocal', + value: storeTarget, + constant: false, + }, + path: [], + loc: storeTarget.loc, + }); + } + } + } + break; + } + } + } + recordTemporaries(instr, state) { + var _a; + const temporaries = this.temporaries; + const { lvalue, value } = instr; + const lvalId = lvalue === null || lvalue === void 0 ? void 0 : lvalue.identifier.id; + if (lvalId != null && temporaries.has(lvalId)) { + return; + } + const isNamedLocal = ((_a = lvalue === null || lvalue === void 0 ? void 0 : lvalue.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named'; + if (lvalue !== null && isNamedLocal && state.manualMemoState != null) { + state.manualMemoState.decls.add(lvalue.identifier.declarationId); + } + this.recordDepsInValue(value, state); + if (lvalue != null) { + temporaries.set(lvalue.identifier.id, { + root: { + kind: 'NamedLocal', + value: Object.assign({}, lvalue), + constant: false, + }, + path: [], + loc: lvalue.loc, + }); + } + } + visitScope(scopeBlock, state) { + this.traverseScope(scopeBlock, state); + if (state.manualMemoState != null && + state.manualMemoState.depsFromSource != null) { + for (const dep of scopeBlock.scope.dependencies) { + validateInferredDep(dep, this.temporaries, state.manualMemoState.decls, state.manualMemoState.depsFromSource, state.env, state.manualMemoState.loc); + } + } + this.scopes.add(scopeBlock.scope.id); + for (const id of scopeBlock.scope.merged) { + this.scopes.add(id); + } + } + visitPrunedScope(scopeBlock, state) { + this.traversePrunedScope(scopeBlock, state); + this.prunedScopes.add(scopeBlock.scope.id); + } + visitInstruction(instruction, state) { + var _a, _b; + this.recordTemporaries(instruction, state); + const value = instruction.value; + if (value.kind === 'StoreLocal' && + value.lvalue.kind === 'Reassign' && + state.manualMemoState != null) { + const ids = getOrInsertDefault(state.manualMemoState.reassignments, value.lvalue.place.identifier.declarationId, new Set()); + ids.add(value.value.identifier); + } + if (value.kind === 'LoadLocal' && + value.place.identifier.scope != null && + instruction.lvalue != null && + instruction.lvalue.identifier.scope == null && + state.manualMemoState != null) { + const ids = getOrInsertDefault(state.manualMemoState.reassignments, instruction.lvalue.identifier.declarationId, new Set()); + ids.add(value.place.identifier); + } + if (value.kind === 'StartMemoize') { + CompilerError.invariant(state.manualMemoState == null, { + reason: 'Unexpected nested StartMemoize instructions', + description: `Bad manual memoization ids: ${(_a = state.manualMemoState) === null || _a === void 0 ? void 0 : _a.manualMemoId}, ${value.manualMemoId}`, + loc: value.loc, + }); + if (value.hasInvalidDeps === true) { + return; + } + let depsFromSource = null; + if (value.deps != null) { + depsFromSource = value.deps; + } + state.manualMemoState = { + loc: instruction.loc, + decls: new Set(), + depsFromSource, + manualMemoId: value.manualMemoId, + reassignments: new Map(), + }; + for (const { identifier, loc } of eachInstructionValueOperand(value)) { + if (identifier.scope != null && + !this.scopes.has(identifier.scope.id) && + !this.prunedScopes.has(identifier.scope.id)) { + state.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.PreserveManualMemo, + reason: 'Existing memoization could not be preserved', + description: [ + 'React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. ', + 'This dependency may be mutated later, which could cause the value to change unexpectedly', + ].join(''), + }).withDetails({ + kind: 'error', + loc, + message: 'This dependency may be modified later', + })); + } + } + } + if (value.kind === 'FinishMemoize') { + if (state.manualMemoState == null) { + return; + } + CompilerError.invariant(state.manualMemoState.manualMemoId === value.manualMemoId, { + reason: 'Unexpected mismatch between StartMemoize and FinishMemoize', + description: `Encountered StartMemoize id=${state.manualMemoState.manualMemoId} followed by FinishMemoize id=${value.manualMemoId}`, + loc: value.loc, + }); + const reassignments = state.manualMemoState.reassignments; + state.manualMemoState = null; + if (!value.pruned) { + for (const { identifier, loc } of eachInstructionValueOperand(value)) { + let decls; + if (identifier.scope == null) { + decls = (_b = reassignments.get(identifier.declarationId)) !== null && _b !== void 0 ? _b : [identifier]; + } + else { + decls = [identifier]; + } + for (const identifier of decls) { + if (isUnmemoized(identifier, this.scopes)) { + state.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.PreserveManualMemo, + reason: 'Existing memoization could not be preserved', + description: [ + 'React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. This value was memoized in source but not in compilation output', + '', + ] + .join('') + .trim(), + }).withDetails({ + kind: 'error', + loc, + message: 'Could not preserve existing memoization', + })); + } + } + } + } + } + } +} +function isUnmemoized(operand, scopes) { + return operand.scope != null && !scopes.has(operand.scope.id); +} + +const IMPORTANT_INSTRUMENTED_TYPES = new Set([ + 'ArrowFunctionExpression', + 'AssignmentPattern', + 'ObjectMethod', + 'ExpressionStatement', + 'BreakStatement', + 'ContinueStatement', + 'ReturnStatement', + 'ThrowStatement', + 'TryStatement', + 'VariableDeclarator', + 'IfStatement', + 'ForStatement', + 'ForInStatement', + 'ForOfStatement', + 'WhileStatement', + 'DoWhileStatement', + 'SwitchStatement', + 'SwitchCase', + 'WithStatement', + 'FunctionDeclaration', + 'FunctionExpression', + 'LabeledStatement', + 'ConditionalExpression', + 'LogicalExpression', + 'VariableDeclaration', + 'Identifier', +]); +function isManualMemoization(node) { + if (libExports$1.isCallExpression(node)) { + const callee = node.callee; + if (libExports$1.isIdentifier(callee)) { + return callee.name === 'useMemo' || callee.name === 'useCallback'; + } + if (libExports$1.isMemberExpression(callee) && + libExports$1.isIdentifier(callee.property) && + libExports$1.isIdentifier(callee.object)) { + return (callee.object.name === 'React' && + (callee.property.name === 'useMemo' || + callee.property.name === 'useCallback')); + } + } + return false; +} +function locationKey(loc) { + return `${loc.start.line}:${loc.start.column}-${loc.end.line}:${loc.end.column}`; +} +function validateSourceLocations(func, generatedAst, env) { + const importantOriginalLocations = new Map(); + func.traverse({ + enter(path) { + const node = path.node; + if (!IMPORTANT_INSTRUMENTED_TYPES.has(node.type)) { + return; + } + if (isManualMemoization(node)) { + return; + } + if (libExports$1.isReturnStatement(node) && node.argument != null) { + const parentBody = path.parentPath; + const parentFunc = parentBody === null || parentBody === void 0 ? void 0 : parentBody.parentPath; + if ((parentBody === null || parentBody === void 0 ? void 0 : parentBody.isBlockStatement()) && + (parentFunc === null || parentFunc === void 0 ? void 0 : parentFunc.isArrowFunctionExpression()) && + parentBody.node.body.length === 1 && + parentBody.node.directives.length === 0) { + return; + } + } + if (node.loc) { + const key = locationKey(node.loc); + const existing = importantOriginalLocations.get(key); + if (existing) { + existing.nodeTypes.add(node.type); + } + else { + importantOriginalLocations.set(key, { + loc: node.loc, + nodeTypes: new Set([node.type]), + }); + } + } + }, + }); + const generatedLocations = new Map(); + function collectGeneratedLocations(node) { + if (node.loc) { + const key = locationKey(node.loc); + const nodeTypes = generatedLocations.get(key); + if (nodeTypes) { + nodeTypes.add(node.type); + } + else { + generatedLocations.set(key, new Set([node.type])); + } + } + const keys = libExports$1.VISITOR_KEYS[node.type]; + if (!keys) { + return; + } + for (const key of keys) { + const value = node[key]; + if (Array.isArray(value)) { + for (const item of value) { + if (libExports$1.isNode(item)) { + collectGeneratedLocations(item); + } + } + } + else if (libExports$1.isNode(value)) { + collectGeneratedLocations(value); + } + } + } + collectGeneratedLocations(generatedAst.body); + for (const outlined of generatedAst.outlined) { + collectGeneratedLocations(outlined.fn.body); + } + const strictNodeTypes = new Set([ + 'VariableDeclaration', + 'VariableDeclarator', + 'Identifier', + ]); + const reportMissingLocation = (loc, nodeType) => { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Todo, + reason: 'Important source location missing in generated code', + description: `Source location for ${nodeType} is missing in the generated output. This can cause coverage instrumentation ` + + `to fail to track this code properly, resulting in inaccurate coverage reports.`, + }).withDetails({ + kind: 'error', + loc, + message: null, + })); + }; + const reportWrongNodeType = (loc, expectedType, actualTypes) => { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Todo, + reason: 'Important source location has wrong node type in generated code', + description: `Source location for ${expectedType} exists in the generated output but with wrong node type(s): ${Array.from(actualTypes).join(', ')}. ` + + `This can cause coverage instrumentation to fail to track this code properly, resulting in inaccurate coverage reports.`, + }).withDetails({ + kind: 'error', + loc, + message: null, + })); + }; + for (const [key, { loc, nodeTypes }] of importantOriginalLocations) { + const generatedNodeTypes = generatedLocations.get(key); + if (!generatedNodeTypes) { + reportMissingLocation(loc, Array.from(nodeTypes).join(', ')); + } + else { + for (const nodeType of nodeTypes) { + if (strictNodeTypes.has(nodeType) && + !generatedNodeTypes.has(nodeType)) { + const hasValidNodeType = Array.from(generatedNodeTypes).some(genType => nodeTypes.has(genType)); + if (hasValidNodeType) { + reportMissingLocation(loc, nodeType); + } + else { + reportWrongNodeType(loc, nodeType, generatedNodeTypes); + } + } + } + } + } +} + +function validateUseMemo(fn) { + const voidMemoErrors = new CompilerError(); + const useMemos = new Set(); + const react = new Set(); + const functions = new Map(); + const unusedUseMemos = new Map(); + for (const [, block] of fn.body.blocks) { + for (const { lvalue, value } of block.instructions) { + if (unusedUseMemos.size !== 0) { + for (const operand of eachInstructionValueOperand(value)) { + unusedUseMemos.delete(operand.identifier.id); + } + } + switch (value.kind) { + case 'LoadGlobal': { + if (value.binding.name === 'useMemo') { + useMemos.add(lvalue.identifier.id); + } + else if (value.binding.name === 'React') { + react.add(lvalue.identifier.id); + } + break; + } + case 'PropertyLoad': { + if (react.has(value.object.identifier.id)) { + if (value.property === 'useMemo') { + useMemos.add(lvalue.identifier.id); + } + } + break; + } + case 'FunctionExpression': { + functions.set(lvalue.identifier.id, value); + break; + } + case 'MethodCall': + case 'CallExpression': { + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + const isUseMemo = useMemos.has(callee.identifier.id); + if (!isUseMemo || value.args.length === 0) { + continue; + } + const [arg] = value.args; + if (arg.kind !== 'Identifier') { + continue; + } + const body = functions.get(arg.identifier.id); + if (body === undefined) { + continue; + } + if (body.loweredFunc.func.params.length > 0) { + const firstParam = body.loweredFunc.func.params[0]; + const loc = firstParam.kind === 'Identifier' + ? firstParam.loc + : firstParam.place.loc; + fn.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: 'useMemo() callbacks may not accept parameters', + description: 'useMemo() callbacks are called by React to cache calculations across re-renders. They should not take parameters. Instead, directly reference the props, state, or local variables needed for the computation', + suggestions: null, + }).withDetails({ + kind: 'error', + loc, + message: 'Callbacks with parameters are not supported', + })); + } + if (body.loweredFunc.func.async || body.loweredFunc.func.generator) { + fn.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: 'useMemo() callbacks may not be async or generator functions', + description: 'useMemo() callbacks are called once and must synchronously return a value', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: body.loc, + message: 'Async and generator functions are not supported', + })); + } + validateNoContextVariableAssignment(body.loweredFunc.func, fn.env); + if (fn.env.config.validateNoVoidUseMemo) { + if (!hasNonVoidReturn(body.loweredFunc.func)) { + voidMemoErrors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.VoidUseMemo, + reason: 'useMemo() callbacks must return a value', + description: `This useMemo() callback doesn't return a value. useMemo() is for computing and caching values, not for arbitrary side effects`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc: body.loc, + message: 'useMemo() callbacks must return a value', + })); + } + else { + unusedUseMemos.set(lvalue.identifier.id, callee.loc); + } + } + break; + } + } + } + if (unusedUseMemos.size !== 0) { + for (const operand of eachTerminalOperand(block.terminal)) { + unusedUseMemos.delete(operand.identifier.id); + } + } + } + if (unusedUseMemos.size !== 0) { + for (const loc of unusedUseMemos.values()) { + voidMemoErrors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.VoidUseMemo, + reason: 'useMemo() result is unused', + description: `This useMemo() value is unused. useMemo() is for computing and caching values, not for arbitrary side effects`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc, + message: 'useMemo() result is unused', + })); + } + } + fn.env.logErrors(voidMemoErrors.asResult()); +} +function validateNoContextVariableAssignment(fn, env) { + const context = new Set(fn.context.map(place => place.identifier.id)); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const value = instr.value; + switch (value.kind) { + case 'StoreContext': { + if (context.has(value.lvalue.place.identifier.id)) { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: 'useMemo() callbacks may not reassign variables declared outside of the callback', + description: 'useMemo() callbacks must be pure functions and cannot reassign variables defined outside of the callback function', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: value.lvalue.place.loc, + message: 'Cannot reassign variable', + })); + } + break; + } + } + } + } +} +function hasNonVoidReturn(func) { + for (const [, block] of func.body.blocks) { + if (block.terminal.kind === 'return') { + if (block.terminal.returnVariant === 'Explicit' || + block.terminal.returnVariant === 'Implicit') { + return true; + } + } + } + return false; +} + +function validateLocalsNotReassignedAfterRender(fn) { + const contextVariables = new Set(); + const reassignment = getContextReassignment(fn, contextVariables, false, false, fn.env); + if (reassignment !== null) { + const variable = reassignment.identifier.name != null && + reassignment.identifier.name.kind === 'named' + ? `\`${reassignment.identifier.name.value}\`` + : 'variable'; + fn.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'Cannot reassign variable after render completes', + description: `Reassigning ${variable} after render has completed can cause inconsistent behavior on subsequent renders. Consider using state instead`, + }).withDetails({ + kind: 'error', + loc: reassignment.loc, + message: `Cannot reassign ${variable} after render completes`, + })); + } +} +function getContextReassignment(fn, contextVariables, isFunctionExpression, isAsync, env) { + const reassigningFunctions = new Map(); + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'FunctionExpression': + case 'ObjectMethod': { + let reassignment = getContextReassignment(value.loweredFunc.func, contextVariables, true, isAsync || value.loweredFunc.func.async, env); + if (reassignment === null) { + for (const operand of eachInstructionValueOperand(value)) { + const reassignmentFromOperand = reassigningFunctions.get(operand.identifier.id); + if (reassignmentFromOperand !== undefined) { + reassignment = reassignmentFromOperand; + break; + } + } + } + if (reassignment !== null) { + if (isAsync || value.loweredFunc.func.async) { + const variable = reassignment.identifier.name !== null && + reassignment.identifier.name.kind === 'named' + ? `\`${reassignment.identifier.name.value}\`` + : 'variable'; + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'Cannot reassign variable in async function', + description: 'Reassigning a variable in an async function can cause inconsistent behavior on subsequent renders. Consider using state instead', + }).withDetails({ + kind: 'error', + loc: reassignment.loc, + message: `Cannot reassign ${variable}`, + })); + return null; + } + reassigningFunctions.set(lvalue.identifier.id, reassignment); + } + break; + } + case 'StoreLocal': { + const reassignment = reassigningFunctions.get(value.value.identifier.id); + if (reassignment !== undefined) { + reassigningFunctions.set(value.lvalue.place.identifier.id, reassignment); + reassigningFunctions.set(lvalue.identifier.id, reassignment); + } + break; + } + case 'LoadLocal': { + const reassignment = reassigningFunctions.get(value.place.identifier.id); + if (reassignment !== undefined) { + reassigningFunctions.set(lvalue.identifier.id, reassignment); + } + break; + } + case 'DeclareContext': { + if (!isFunctionExpression) { + contextVariables.add(value.lvalue.place.identifier.id); + } + break; + } + case 'StoreContext': { + if (isFunctionExpression) { + if (contextVariables.has(value.lvalue.place.identifier.id)) { + return value.lvalue.place; + } + } + else { + contextVariables.add(value.lvalue.place.identifier.id); + } + const reassignment = reassigningFunctions.get(value.value.identifier.id); + if (reassignment !== undefined) { + reassigningFunctions.set(value.lvalue.place.identifier.id, reassignment); + reassigningFunctions.set(lvalue.identifier.id, reassignment); + } + break; + } + default: { + let operands = eachInstructionValueOperand(value); + if (value.kind === 'CallExpression') { + const signature = getFunctionCallSignature(fn.env, value.callee.identifier.type); + if (signature === null || signature === void 0 ? void 0 : signature.noAlias) { + operands = [value.callee]; + } + } + else if (value.kind === 'MethodCall') { + const signature = getFunctionCallSignature(fn.env, value.property.identifier.type); + if (signature === null || signature === void 0 ? void 0 : signature.noAlias) { + operands = [value.receiver, value.property]; + } + } + else if (value.kind === 'TaggedTemplateExpression') { + const signature = getFunctionCallSignature(fn.env, value.tag.identifier.type); + if (signature === null || signature === void 0 ? void 0 : signature.noAlias) { + operands = [value.tag]; + } + } + for (const operand of operands) { + CompilerError.invariant(operand.effect !== Effect.Unknown, { + reason: `Expected effects to be inferred prior to ValidateLocalsNotReassignedAfterRender`, + loc: operand.loc, + }); + const reassignment = reassigningFunctions.get(operand.identifier.id); + if (reassignment !== undefined) { + if (operand.effect === Effect.Freeze) { + return reassignment; + } + else { + for (const lval of eachInstructionLValue(instr)) { + reassigningFunctions.set(lval.identifier.id, reassignment); + } + } + } + } + break; + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + const reassignment = reassigningFunctions.get(operand.identifier.id); + if (reassignment !== undefined) { + return reassignment; + } + } + } + return null; +} + +function outlineFunctions(fn, fbtOperands) { + var _a; + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const { value, lvalue } = instr; + if (value.kind === 'FunctionExpression' || + value.kind === 'ObjectMethod') { + outlineFunctions(value.loweredFunc.func, fbtOperands); + } + if (value.kind === 'FunctionExpression' && + value.loweredFunc.func.context.length === 0 && + value.loweredFunc.func.id === null && + !fbtOperands.has(lvalue.identifier.id)) { + const loweredFunc = value.loweredFunc.func; + const id = fn.env.generateGloballyUniqueIdentifierName((_a = loweredFunc.id) !== null && _a !== void 0 ? _a : loweredFunc.nameHint); + loweredFunc.id = id.value; + fn.env.outlineFunction(loweredFunc, null); + instr.value = { + kind: 'LoadGlobal', + binding: { + kind: 'Global', + name: id.value, + }, + loc: value.loc, + }; + } + } + } +} + +function validateNoSetStateInEffects(fn, env) { + const setStateFunctions = new Map(); + const errors = new CompilerError(); + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'LoadLocal': { + if (setStateFunctions.has(instr.value.place.identifier.id)) { + setStateFunctions.set(instr.lvalue.identifier.id, instr.value.place); + } + break; + } + case 'StoreLocal': { + if (setStateFunctions.has(instr.value.value.identifier.id)) { + setStateFunctions.set(instr.value.lvalue.place.identifier.id, instr.value.value); + setStateFunctions.set(instr.lvalue.identifier.id, instr.value.value); + } + break; + } + case 'FunctionExpression': { + if ([...eachInstructionValueOperand(instr.value)].some(operand => isSetStateType(operand.identifier) || + setStateFunctions.has(operand.identifier.id))) { + const callee = getSetStateCall(instr.value.loweredFunc.func, setStateFunctions, env); + if (callee !== null) { + setStateFunctions.set(instr.lvalue.identifier.id, callee); + } + } + break; + } + case 'MethodCall': + case 'CallExpression': { + const callee = instr.value.kind === 'MethodCall' + ? instr.value.property + : instr.value.callee; + if (isUseEffectEventType(callee.identifier)) { + const arg = instr.value.args[0]; + if (arg !== undefined && arg.kind === 'Identifier') { + const setState = setStateFunctions.get(arg.identifier.id); + if (setState !== undefined) { + setStateFunctions.set(instr.lvalue.identifier.id, setState); + } + } + } + else if (isUseEffectHookType(callee.identifier) || + isUseLayoutEffectHookType(callee.identifier) || + isUseInsertionEffectHookType(callee.identifier)) { + const arg = instr.value.args[0]; + if (arg !== undefined && arg.kind === 'Identifier') { + const setState = setStateFunctions.get(arg.identifier.id); + if (setState !== undefined) { + const enableVerbose = env.config.enableVerboseNoSetStateInEffect; + if (enableVerbose) { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.EffectSetState, + reason: 'Calling setState synchronously within an effect can trigger cascading renders', + description: 'Effects are intended to synchronize state between React and external systems. ' + + 'Calling setState synchronously causes cascading renders that hurt performance.\n\n' + + 'This pattern may indicate one of several issues:\n\n' + + '**1. Non-local derived data**: If the value being set could be computed from props/state ' + + 'but requires data from a parent component, consider restructuring state ownership so the ' + + 'derivation can happen during render in the component that owns the relevant state.\n\n' + + "**2. Derived event pattern**: If you're detecting when a prop changes (e.g., `isPlaying` " + + 'transitioning from false to true), this often indicates the parent should provide an event ' + + 'callback (like `onPlay`) instead of just the current state. Request access to the original event.\n\n' + + "**3. Force update / external sync**: If you're forcing a re-render to sync with an external " + + 'data source (mutable values outside React), use `useSyncExternalStore` to properly subscribe ' + + 'to external state changes.\n\n' + + 'See: https://react.dev/learn/you-might-not-need-an-effect', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: setState.loc, + message: 'Avoid calling setState() directly within an effect', + })); + } + else { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.EffectSetState, + reason: 'Calling setState synchronously within an effect can trigger cascading renders', + description: 'Effects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. ' + + 'In general, the body of an effect should do one or both of the following:\n' + + '* Update external systems with the latest state from React.\n' + + '* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\n' + + 'Calling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. ' + + '(https://react.dev/learn/you-might-not-need-an-effect)', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: setState.loc, + message: 'Avoid calling setState() directly within an effect', + })); + } + } + } + } + break; + } + } + } + } + return errors.asResult(); +} +function getSetStateCall(fn, setStateFunctions, env) { + const enableAllowSetStateFromRefsInEffects = env.config.enableAllowSetStateFromRefsInEffects; + const refDerivedValues = new Set(); + const isDerivedFromRef = (place) => { + return (refDerivedValues.has(place.identifier.id) || + isUseRefType(place.identifier) || + isRefValueType(place.identifier)); + }; + const isRefControlledBlock = enableAllowSetStateFromRefsInEffects + ? createControlDominators(fn, place => isDerivedFromRef(place)) + : () => false; + for (const [, block] of fn.body.blocks) { + if (enableAllowSetStateFromRefsInEffects) { + for (const phi of block.phis) { + if (isDerivedFromRef(phi.place)) { + continue; + } + let isPhiDerivedFromRef = false; + for (const [, operand] of phi.operands) { + if (isDerivedFromRef(operand)) { + isPhiDerivedFromRef = true; + break; + } + } + if (isPhiDerivedFromRef) { + refDerivedValues.add(phi.place.identifier.id); + } + else { + for (const [pred] of phi.operands) { + if (isRefControlledBlock(pred)) { + refDerivedValues.add(phi.place.identifier.id); + break; + } + } + } + } + } + for (const instr of block.instructions) { + if (enableAllowSetStateFromRefsInEffects) { + const hasRefOperand = Iterable_some(eachInstructionValueOperand(instr.value), isDerivedFromRef); + if (hasRefOperand) { + for (const lvalue of eachInstructionLValue(instr)) { + refDerivedValues.add(lvalue.identifier.id); + } + for (const operand of eachInstructionValueOperand(instr.value)) { + switch (operand.effect) { + case Effect.Capture: + case Effect.Store: + case Effect.ConditionallyMutate: + case Effect.ConditionallyMutateIterator: + case Effect.Mutate: { + if (isMutable(instr, operand)) { + refDerivedValues.add(operand.identifier.id); + } + break; + } + case Effect.Freeze: + case Effect.Read: { + break; + } + case Effect.Unknown: { + CompilerError.invariant(false, { + reason: 'Unexpected unknown effect', + loc: operand.loc, + }); + } + default: { + assertExhaustive$1(operand.effect, `Unexpected effect kind \`${operand.effect}\``); + } + } + } + } + if (instr.value.kind === 'PropertyLoad' && + instr.value.property === 'current' && + (isUseRefType(instr.value.object.identifier) || + isRefValueType(instr.value.object.identifier))) { + refDerivedValues.add(instr.lvalue.identifier.id); + } + } + switch (instr.value.kind) { + case 'LoadLocal': { + if (setStateFunctions.has(instr.value.place.identifier.id)) { + setStateFunctions.set(instr.lvalue.identifier.id, instr.value.place); + } + break; + } + case 'StoreLocal': { + if (setStateFunctions.has(instr.value.value.identifier.id)) { + setStateFunctions.set(instr.value.lvalue.place.identifier.id, instr.value.value); + setStateFunctions.set(instr.lvalue.identifier.id, instr.value.value); + } + break; + } + case 'CallExpression': { + const callee = instr.value.callee; + if (isSetStateType(callee.identifier) || + setStateFunctions.has(callee.identifier.id)) { + if (enableAllowSetStateFromRefsInEffects) { + const arg = instr.value.args.at(0); + if (arg !== undefined && + arg.kind === 'Identifier' && + refDerivedValues.has(arg.identifier.id)) { + return null; + } + else if (isRefControlledBlock(block.id)) { + continue; + } + } + return callee; + } + } + } + } + } + return null; +} + +function validateNoJSXInTryStatement(fn) { + const activeTryBlocks = []; + const errors = new CompilerError(); + for (const [, block] of fn.body.blocks) { + retainWhere(activeTryBlocks, id => id !== block.id); + if (activeTryBlocks.length !== 0) { + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'JsxExpression': + case 'JsxFragment': { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.ErrorBoundaries, + reason: 'Avoid constructing JSX within try/catch', + description: `React does not immediately render components when JSX is rendered, so any errors from this component will not be caught by the try/catch. To catch errors in rendering a given component, wrap that component in an error boundary. (https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)`, + }).withDetails({ + kind: 'error', + loc: value.loc, + message: 'Avoid constructing JSX within try/catch', + })); + break; + } + } + } + } + if (block.terminal.kind === 'try') { + activeTryBlocks.push(block.terminal.handler); + } + } + return errors.asResult(); +} + +function collectHoistablePropertyLoads(fn, temporaries, hoistableFromOptionals) { + const registry = new PropertyPathRegistry(); + const knownImmutableIdentifiers = new Set(); + if (fn.fnType === 'Component' || fn.fnType === 'Hook') { + for (const p of fn.params) { + if (p.kind === 'Identifier') { + knownImmutableIdentifiers.add(p.identifier.id); + } + } + } + return collectHoistablePropertyLoadsImpl(fn, { + temporaries, + knownImmutableIdentifiers, + hoistableFromOptionals, + registry, + nestedFnImmutableContext: null, + assumedInvokedFns: getAssumedInvokedFunctions(fn), + }); +} +function collectHoistablePropertyLoadsImpl(fn, context) { + const nodes = collectNonNullsInBlocks(fn, context); + propagateNonNull(fn, nodes, context.registry); + return nodes; +} +function keyByScopeId(fn, source) { + const keyedByScopeId = new Map(); + for (const [_, block] of fn.body.blocks) { + if (block.terminal.kind === 'scope') { + keyedByScopeId.set(block.terminal.scope.id, source.get(block.terminal.block)); + } + } + return keyedByScopeId; +} +class PropertyPathRegistry { + constructor() { + this.roots = new Map(); + } + getOrCreateIdentifier(identifier, reactive, loc) { + let rootNode = this.roots.get(identifier.id); + if (rootNode === undefined) { + rootNode = { + root: identifier.id, + properties: new Map(), + optionalProperties: new Map(), + fullPath: { + identifier, + reactive, + path: [], + loc, + }, + hasOptional: false, + parent: null, + }; + this.roots.set(identifier.id, rootNode); + } + else { + CompilerError.invariant(reactive === rootNode.fullPath.reactive, { + reason: '[HoistablePropertyLoads] Found inconsistencies in `reactive` flag when deduping identifier reads within the same scope', + loc: identifier.loc, + }); + } + return rootNode; + } + static getOrCreatePropertyEntry(parent, entry) { + const map = entry.optional ? parent.optionalProperties : parent.properties; + let child = map.get(entry.property); + if (child == null) { + child = { + properties: new Map(), + optionalProperties: new Map(), + parent: parent, + fullPath: { + identifier: parent.fullPath.identifier, + reactive: parent.fullPath.reactive, + path: parent.fullPath.path.concat(entry), + loc: entry.loc, + }, + hasOptional: parent.hasOptional || entry.optional, + }; + map.set(entry.property, child); + } + return child; + } + getOrCreateProperty(n) { + let currNode = this.getOrCreateIdentifier(n.identifier, n.reactive, n.loc); + if (n.path.length === 0) { + return currNode; + } + for (let i = 0; i < n.path.length - 1; i++) { + currNode = PropertyPathRegistry.getOrCreatePropertyEntry(currNode, n.path[i]); + } + return PropertyPathRegistry.getOrCreatePropertyEntry(currNode, n.path.at(-1)); + } +} +function getMaybeNonNullInInstruction(value, context) { + var _a, _b, _c; + let path = null; + if (value.kind === 'PropertyLoad') { + path = (_a = context.temporaries.get(value.object.identifier.id)) !== null && _a !== void 0 ? _a : { + identifier: value.object.identifier, + reactive: value.object.reactive, + path: [], + loc: value.loc, + }; + } + else if (value.kind === 'Destructure') { + path = (_b = context.temporaries.get(value.value.identifier.id)) !== null && _b !== void 0 ? _b : null; + } + else if (value.kind === 'ComputedLoad') { + path = (_c = context.temporaries.get(value.object.identifier.id)) !== null && _c !== void 0 ? _c : null; + } + return path != null ? context.registry.getOrCreateProperty(path) : null; +} +function isImmutableAtInstr(identifier, instr, context) { + if (context.nestedFnImmutableContext != null) { + return context.nestedFnImmutableContext.has(identifier.id); + } + else { + const mutableAtInstr = identifier.mutableRange.end > identifier.mutableRange.start + 1 && + identifier.scope != null && + inRange({ + id: instr, + }, identifier.scope.range); + return (!mutableAtInstr || context.knownImmutableIdentifiers.has(identifier.id)); + } +} +function collectNonNullsInBlocks(fn, context) { + var _a; + const knownNonNullIdentifiers = new Set(); + if (fn.fnType === 'Component' && + fn.params.length > 0 && + fn.params[0].kind === 'Identifier') { + const identifier = fn.params[0].identifier; + knownNonNullIdentifiers.add(context.registry.getOrCreateIdentifier(identifier, true, fn.params[0].loc)); + } + const nodes = new Map(); + for (const [_, block] of fn.body.blocks) { + const assumedNonNullObjects = new Set(knownNonNullIdentifiers); + const maybeOptionalChain = context.hoistableFromOptionals.get(block.id); + if (maybeOptionalChain != null) { + assumedNonNullObjects.add(context.registry.getOrCreateProperty(maybeOptionalChain)); + } + for (const instr of block.instructions) { + const maybeNonNull = getMaybeNonNullInInstruction(instr.value, context); + if (maybeNonNull != null && + isImmutableAtInstr(maybeNonNull.fullPath.identifier, instr.id, context)) { + assumedNonNullObjects.add(maybeNonNull); + } + if (instr.value.kind === 'FunctionExpression') { + const innerFn = instr.value.loweredFunc; + if (context.assumedInvokedFns.has(innerFn)) { + const innerHoistableMap = collectHoistablePropertyLoadsImpl(innerFn.func, Object.assign(Object.assign({}, context), { nestedFnImmutableContext: (_a = context.nestedFnImmutableContext) !== null && _a !== void 0 ? _a : new Set(innerFn.func.context + .filter(place => isImmutableAtInstr(place.identifier, instr.id, context)) + .map(place => place.identifier.id)) })); + const innerHoistables = assertNonNull(innerHoistableMap.get(innerFn.func.body.entry)); + for (const entry of innerHoistables.assumedNonNullObjects) { + assumedNonNullObjects.add(entry); + } + } + } + else if (fn.env.config.enablePreserveExistingMemoizationGuarantees && + instr.value.kind === 'StartMemoize' && + instr.value.deps != null) { + for (const dep of instr.value.deps) { + if (dep.root.kind === 'NamedLocal') { + if (!isImmutableAtInstr(dep.root.value.identifier, instr.id, context)) { + continue; + } + for (let i = 0; i < dep.path.length; i++) { + const pathEntry = dep.path[i]; + if (pathEntry.optional) { + break; + } + const depNode = context.registry.getOrCreateProperty({ + identifier: dep.root.value.identifier, + path: dep.path.slice(0, i), + reactive: dep.root.value.reactive, + loc: dep.loc, + }); + assumedNonNullObjects.add(depNode); + } + } + } + } + } + nodes.set(block.id, { + block, + assumedNonNullObjects, + }); + } + return nodes; +} +function propagateNonNull(fn, nodes, registry) { + const blockSuccessors = new Map(); + const terminalPreds = new Set(); + for (const [blockId, block] of fn.body.blocks) { + for (const pred of block.preds) { + getOrInsertDefault(blockSuccessors, pred, new Set()).add(blockId); + } + if (block.terminal.kind === 'throw' || block.terminal.kind === 'return') { + terminalPreds.add(blockId); + } + } + function recursivelyPropagateNonNull(nodeId, direction, traversalState) { + var _a; + if (traversalState.has(nodeId)) { + return false; + } + traversalState.set(nodeId, 'active'); + const node = nodes.get(nodeId); + if (node == null) { + CompilerError.invariant(false, { + reason: `Bad node ${nodeId}, kind: ${direction}`, + loc: GeneratedSource, + }); + } + const neighbors = Array.from(direction === 'backward' + ? ((_a = blockSuccessors.get(nodeId)) !== null && _a !== void 0 ? _a : []) + : node.block.preds); + let changed = false; + for (const pred of neighbors) { + if (!traversalState.has(pred)) { + const neighborChanged = recursivelyPropagateNonNull(pred, direction, traversalState); + changed || (changed = neighborChanged); + } + } + const neighborAccesses = Set_intersect(Array.from(neighbors) + .filter(n => traversalState.get(n) === 'done') + .map(n => assertNonNull(nodes.get(n)).assumedNonNullObjects)); + const prevObjects = assertNonNull(nodes.get(nodeId)).assumedNonNullObjects; + const mergedObjects = Set_union(prevObjects, neighborAccesses); + reduceMaybeOptionalChains(mergedObjects, registry); + assertNonNull(nodes.get(nodeId)).assumedNonNullObjects = mergedObjects; + traversalState.set(nodeId, 'done'); + changed || (changed = !Set_equal(prevObjects, mergedObjects)); + return changed; + } + const traversalState = new Map(); + const reversedBlocks = [...fn.body.blocks]; + reversedBlocks.reverse(); + let changed; + let i = 0; + do { + CompilerError.invariant(i++ < 100, { + reason: '[CollectHoistablePropertyLoads] fixed point iteration did not terminate after 100 loops', + loc: GeneratedSource, + }); + changed = false; + for (const [blockId] of fn.body.blocks) { + const forwardChanged = recursivelyPropagateNonNull(blockId, 'forward', traversalState); + changed || (changed = forwardChanged); + } + traversalState.clear(); + for (const [blockId] of reversedBlocks) { + const backwardChanged = recursivelyPropagateNonNull(blockId, 'backward', traversalState); + changed || (changed = backwardChanged); + } + traversalState.clear(); + } while (changed); +} +function assertNonNull(value, source) { + CompilerError.invariant(value != null, { + reason: 'Unexpected null', + description: source != null ? `(from ${source})` : null, + loc: GeneratedSource, + }); + return value; +} +function reduceMaybeOptionalChains(nodes, registry) { + let optionalChainNodes = Set_filter(nodes, n => n.hasOptional); + if (optionalChainNodes.size === 0) { + return; + } + let changed; + do { + changed = false; + for (const original of optionalChainNodes) { + let { identifier, path: origPath, reactive, loc: origLoc, } = original.fullPath; + let currNode = registry.getOrCreateIdentifier(identifier, reactive, origLoc); + for (let i = 0; i < origPath.length; i++) { + const entry = origPath[i]; + const nextEntry = entry.optional && nodes.has(currNode) + ? { property: entry.property, optional: false, loc: entry.loc } + : entry; + currNode = PropertyPathRegistry.getOrCreatePropertyEntry(currNode, nextEntry); + } + if (currNode !== original) { + changed = true; + optionalChainNodes.delete(original); + optionalChainNodes.add(currNode); + nodes.delete(original); + nodes.add(currNode); + } + } + } while (changed); +} +function getAssumedInvokedFunctions(fn, temporaries = new Map()) { + var _a; + const hoistableFunctions = new Set(); + for (const block of fn.body.blocks.values()) { + for (const { lvalue, value } of block.instructions) { + if (value.kind === 'FunctionExpression') { + temporaries.set(lvalue.identifier.id, { + fn: value.loweredFunc, + mayInvoke: new Set(), + }); + } + else if (value.kind === 'StoreLocal') { + const lvalue = value.lvalue.place.identifier; + const maybeLoweredFunc = temporaries.get(value.value.identifier.id); + if (maybeLoweredFunc != null) { + temporaries.set(lvalue.id, maybeLoweredFunc); + } + } + else if (value.kind === 'LoadLocal') { + const maybeLoweredFunc = temporaries.get(value.place.identifier.id); + if (maybeLoweredFunc != null) { + temporaries.set(lvalue.identifier.id, maybeLoweredFunc); + } + } + } + } + for (const block of fn.body.blocks.values()) { + for (const { lvalue, value } of block.instructions) { + if (value.kind === 'CallExpression') { + const callee = value.callee; + const maybeHook = getHookKind(fn.env, callee.identifier); + const maybeLoweredFunc = temporaries.get(callee.identifier.id); + if (maybeLoweredFunc != null) { + hoistableFunctions.add(maybeLoweredFunc.fn); + } + else if (maybeHook != null) { + for (const arg of value.args) { + if (arg.kind === 'Identifier') { + const maybeLoweredFunc = temporaries.get(arg.identifier.id); + if (maybeLoweredFunc != null) { + hoistableFunctions.add(maybeLoweredFunc.fn); + } + } + } + } + } + else if (value.kind === 'JsxExpression') { + for (const attr of value.props) { + if (attr.kind === 'JsxSpreadAttribute') { + continue; + } + const maybeLoweredFunc = temporaries.get(attr.place.identifier.id); + if (maybeLoweredFunc != null) { + hoistableFunctions.add(maybeLoweredFunc.fn); + } + } + for (const child of (_a = value.children) !== null && _a !== void 0 ? _a : []) { + const maybeLoweredFunc = temporaries.get(child.identifier.id); + if (maybeLoweredFunc != null) { + hoistableFunctions.add(maybeLoweredFunc.fn); + } + } + } + else if (value.kind === 'FunctionExpression') { + const loweredFunc = value.loweredFunc.func; + const lambdasCalled = getAssumedInvokedFunctions(loweredFunc, temporaries); + const maybeLoweredFunc = temporaries.get(lvalue.identifier.id); + if (maybeLoweredFunc != null) { + for (const called of lambdasCalled) { + maybeLoweredFunc.mayInvoke.add(called); + } + } + } + } + if (block.terminal.kind === 'return') { + const maybeLoweredFunc = temporaries.get(block.terminal.value.identifier.id); + if (maybeLoweredFunc != null) { + hoistableFunctions.add(maybeLoweredFunc.fn); + } + } + } + for (const [_, { fn, mayInvoke }] of temporaries) { + if (hoistableFunctions.has(fn)) { + for (const called of mayInvoke) { + hoistableFunctions.add(called); + } + } + } + return hoistableFunctions; +} + +var _a, _ReactiveScopeDependencyTreeHIR_hoistableObjects, _ReactiveScopeDependencyTreeHIR_deps, _ReactiveScopeDependencyTreeHIR_getOrCreateRoot, _ReactiveScopeDependencyTreeHIR_debugImpl; +class ReactiveScopeDependencyTreeHIR { + constructor(hoistableObjects) { + var _b; + _ReactiveScopeDependencyTreeHIR_hoistableObjects.set(this, new Map()); + _ReactiveScopeDependencyTreeHIR_deps.set(this, new Map()); + for (const { path, identifier, reactive, loc } of hoistableObjects) { + let currNode = __classPrivateFieldGet(_a, _a, "m", _ReactiveScopeDependencyTreeHIR_getOrCreateRoot).call(_a, identifier, reactive, __classPrivateFieldGet(this, _ReactiveScopeDependencyTreeHIR_hoistableObjects, "f"), path.length > 0 && path[0].optional ? 'Optional' : 'NonNull', loc); + for (let i = 0; i < path.length; i++) { + const prevAccessType = (_b = currNode.properties.get(path[i].property)) === null || _b === void 0 ? void 0 : _b.accessType; + const accessType = i + 1 < path.length && path[i + 1].optional ? 'Optional' : 'NonNull'; + CompilerError.invariant(prevAccessType == null || prevAccessType === accessType, { + reason: 'Conflicting access types', + loc: GeneratedSource, + }); + let nextNode = currNode.properties.get(path[i].property); + if (nextNode == null) { + nextNode = { + properties: new Map(), + accessType, + loc: path[i].loc, + }; + currNode.properties.set(path[i].property, nextNode); + } + currNode = nextNode; + } + } + } + addDependency(dep) { + const { identifier, reactive, path, loc } = dep; + let depCursor = __classPrivateFieldGet(_a, _a, "m", _ReactiveScopeDependencyTreeHIR_getOrCreateRoot).call(_a, identifier, reactive, __classPrivateFieldGet(this, _ReactiveScopeDependencyTreeHIR_deps, "f"), PropertyAccessType.UnconditionalAccess, loc); + let hoistableCursor = __classPrivateFieldGet(this, _ReactiveScopeDependencyTreeHIR_hoistableObjects, "f").get(identifier); + for (const entry of path) { + let nextHoistableCursor; + let nextDepCursor; + if (entry.optional) { + if (hoistableCursor != null) { + nextHoistableCursor = hoistableCursor === null || hoistableCursor === void 0 ? void 0 : hoistableCursor.properties.get(entry.property); + } + let accessType; + if (hoistableCursor != null && + hoistableCursor.accessType === 'NonNull') { + accessType = PropertyAccessType.UnconditionalAccess; + } + else { + accessType = PropertyAccessType.OptionalAccess; + } + nextDepCursor = makeOrMergeProperty(depCursor, entry.property, accessType, entry.loc); + } + else if (hoistableCursor != null && + hoistableCursor.accessType === 'NonNull') { + nextHoistableCursor = hoistableCursor.properties.get(entry.property); + nextDepCursor = makeOrMergeProperty(depCursor, entry.property, PropertyAccessType.UnconditionalAccess, entry.loc); + } + else { + break; + } + depCursor = nextDepCursor; + hoistableCursor = nextHoistableCursor; + } + depCursor.accessType = merge(depCursor.accessType, PropertyAccessType.OptionalDependency); + } + deriveMinimalDependencies() { + const results = new Set(); + for (const [rootId, rootNode] of __classPrivateFieldGet(this, _ReactiveScopeDependencyTreeHIR_deps, "f").entries()) { + collectMinimalDependenciesInSubtree(rootNode, rootNode.reactive, rootId, [], results); + } + return results; + } + printDeps(includeAccesses) { + let res = []; + for (const [rootId, rootNode] of __classPrivateFieldGet(this, _ReactiveScopeDependencyTreeHIR_deps, "f").entries()) { + const rootResults = printSubtree(rootNode, includeAccesses).map(result => `${printIdentifier(rootId)}.${result}`); + res.push(rootResults); + } + return res.flat().join('\n'); + } + static debug(roots) { + const buf = [`tree() [`]; + for (const [rootId, rootNode] of roots) { + buf.push(`${printIdentifier(rootId)} (${rootNode.accessType}):`); + __classPrivateFieldGet(this, _a, "m", _ReactiveScopeDependencyTreeHIR_debugImpl).call(this, buf, rootNode, 1); + } + buf.push(']'); + return buf.length > 2 ? buf.join('\n') : buf.join(''); + } +} +_a = ReactiveScopeDependencyTreeHIR, _ReactiveScopeDependencyTreeHIR_hoistableObjects = new WeakMap(), _ReactiveScopeDependencyTreeHIR_deps = new WeakMap(), _ReactiveScopeDependencyTreeHIR_getOrCreateRoot = function _ReactiveScopeDependencyTreeHIR_getOrCreateRoot(identifier, reactive, roots, defaultAccessType, loc) { + let rootNode = roots.get(identifier); + if (rootNode === undefined) { + rootNode = { + properties: new Map(), + reactive, + accessType: defaultAccessType, + loc, + }; + roots.set(identifier, rootNode); + } + else { + CompilerError.invariant(reactive === rootNode.reactive, { + reason: '[DeriveMinimalDependenciesHIR] Conflicting reactive root flag', + description: `Identifier ${printIdentifier(identifier)}`, + loc: GeneratedSource, + }); + } + return rootNode; +}, _ReactiveScopeDependencyTreeHIR_debugImpl = function _ReactiveScopeDependencyTreeHIR_debugImpl(buf, node, depth = 0) { + for (const [property, childNode] of node.properties) { + buf.push(`${' '.repeat(depth)}.${property} (${childNode.accessType}):`); + __classPrivateFieldGet(this, _a, "m", _ReactiveScopeDependencyTreeHIR_debugImpl).call(this, buf, childNode, depth + 1); + } +}; +var PropertyAccessType; +(function (PropertyAccessType) { + PropertyAccessType["OptionalAccess"] = "OptionalAccess"; + PropertyAccessType["UnconditionalAccess"] = "UnconditionalAccess"; + PropertyAccessType["OptionalDependency"] = "OptionalDependency"; + PropertyAccessType["UnconditionalDependency"] = "UnconditionalDependency"; +})(PropertyAccessType || (PropertyAccessType = {})); +function isOptional(access) { + return (access === PropertyAccessType.OptionalAccess || + access === PropertyAccessType.OptionalDependency); +} +function isDependency(access) { + return (access === PropertyAccessType.OptionalDependency || + access === PropertyAccessType.UnconditionalDependency); +} +function merge(access1, access2) { + const resultIsUnconditional = !(isOptional(access1) && isOptional(access2)); + const resultIsDependency = isDependency(access1) || isDependency(access2); + if (resultIsUnconditional) { + if (resultIsDependency) { + return PropertyAccessType.UnconditionalDependency; + } + else { + return PropertyAccessType.UnconditionalAccess; + } + } + else { + if (resultIsDependency) { + return PropertyAccessType.OptionalDependency; + } + else { + return PropertyAccessType.OptionalAccess; + } + } +} +function collectMinimalDependenciesInSubtree(node, reactive, rootIdentifier, path, results) { + if (isDependency(node.accessType)) { + results.add({ identifier: rootIdentifier, reactive, path, loc: node.loc }); + } + else { + for (const [childName, childNode] of node.properties) { + collectMinimalDependenciesInSubtree(childNode, reactive, rootIdentifier, [ + ...path, + { + property: childName, + optional: isOptional(childNode.accessType), + loc: childNode.loc, + }, + ], results); + } + } +} +function printSubtree(node, includeAccesses) { + const results = []; + for (const [propertyName, propertyNode] of node.properties) { + if (includeAccesses || isDependency(propertyNode.accessType)) { + results.push(`${propertyName} (${propertyNode.accessType})`); + } + const propertyResults = printSubtree(propertyNode, includeAccesses); + results.push(...propertyResults.map(result => `${propertyName}.${result}`)); + } + return results; +} +function makeOrMergeProperty(node, property, accessType, loc) { + let child = node.properties.get(property); + if (child == null) { + child = { + properties: new Map(), + accessType, + loc, + }; + node.properties.set(property, child); + } + else { + child.accessType = merge(child.accessType, accessType); + } + return child; +} + +function collectOptionalChainSidemap(fn) { + const context = { + currFn: fn, + blocks: fn.body.blocks, + seenOptionals: new Set(), + processedInstrsInOptional: new Set(), + temporariesReadInOptional: new Map(), + hoistableObjects: new Map(), + }; + traverseFunction(fn, context); + return { + temporariesReadInOptional: context.temporariesReadInOptional, + processedInstrsInOptional: context.processedInstrsInOptional, + hoistableObjects: context.hoistableObjects, + }; +} +function traverseFunction(fn, context) { + for (const [_, block] of fn.body.blocks) { + for (const instr of block.instructions) { + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + traverseFunction(instr.value.loweredFunc.func, Object.assign(Object.assign({}, context), { currFn: instr.value.loweredFunc.func, blocks: instr.value.loweredFunc.func.body.blocks })); + } + } + if (block.terminal.kind === 'optional' && + !context.seenOptionals.has(block.id)) { + traverseOptionalBlock(block, context, null); + } + } +} +function matchOptionalTestBlock(terminal, blocks) { + const consequentBlock = assertNonNull(blocks.get(terminal.consequent)); + if (consequentBlock.instructions.length === 2 && + consequentBlock.instructions[0].value.kind === 'PropertyLoad' && + consequentBlock.instructions[1].value.kind === 'StoreLocal') { + const propertyLoad = consequentBlock + .instructions[0]; + const storeLocal = consequentBlock.instructions[1].value; + const storeLocalInstr = consequentBlock.instructions[1]; + CompilerError.invariant(propertyLoad.value.object.identifier.id === terminal.test.identifier.id, { + reason: '[OptionalChainDeps] Inconsistent optional chaining property load', + description: `Test=${printIdentifier(terminal.test.identifier)} PropertyLoad base=${printIdentifier(propertyLoad.value.object.identifier)}`, + loc: propertyLoad.loc, + }); + CompilerError.invariant(storeLocal.value.identifier.id === propertyLoad.lvalue.identifier.id, { + reason: '[OptionalChainDeps] Unexpected storeLocal', + loc: propertyLoad.loc, + }); + if (consequentBlock.terminal.kind !== 'goto' || + consequentBlock.terminal.variant !== GotoVariant.Break) { + return null; + } + const alternate = assertNonNull(blocks.get(terminal.alternate)); + CompilerError.invariant(alternate.instructions.length === 2 && + alternate.instructions[0].value.kind === 'Primitive' && + alternate.instructions[1].value.kind === 'StoreLocal', { + reason: 'Unexpected alternate structure', + loc: terminal.loc, + }); + return { + consequentId: storeLocal.lvalue.place.identifier.id, + property: propertyLoad.value.property, + propertyId: propertyLoad.lvalue.identifier.id, + storeLocalInstr, + consequentGoto: consequentBlock.terminal.block, + propertyLoadLoc: propertyLoad.loc, + }; + } + return null; +} +function traverseOptionalBlock(optional, context, outerAlternate) { + context.seenOptionals.add(optional.id); + const maybeTest = context.blocks.get(optional.terminal.test); + let test; + let baseObject; + if (maybeTest.terminal.kind === 'branch') { + CompilerError.invariant(optional.terminal.optional, { + reason: '[OptionalChainDeps] Expect base case to be always optional', + loc: optional.terminal.loc, + }); + if (maybeTest.instructions.length === 0 || + maybeTest.instructions[0].value.kind !== 'LoadLocal') { + return null; + } + const path = []; + for (let i = 1; i < maybeTest.instructions.length; i++) { + const instrVal = maybeTest.instructions[i].value; + const prevInstr = maybeTest.instructions[i - 1]; + if (instrVal.kind === 'PropertyLoad' && + instrVal.object.identifier.id === prevInstr.lvalue.identifier.id) { + path.push({ + property: instrVal.property, + optional: false, + loc: instrVal.loc, + }); + } + else { + return null; + } + } + CompilerError.invariant(maybeTest.terminal.test.identifier.id === + maybeTest.instructions.at(-1).lvalue.identifier.id, { + reason: '[OptionalChainDeps] Unexpected test expression', + loc: maybeTest.terminal.loc, + }); + baseObject = { + identifier: maybeTest.instructions[0].value.place.identifier, + reactive: maybeTest.instructions[0].value.place.reactive, + path, + loc: maybeTest.instructions[0].value.place.loc, + }; + test = maybeTest.terminal; + } + else if (maybeTest.terminal.kind === 'optional') { + const testBlock = context.blocks.get(maybeTest.terminal.fallthrough); + if (testBlock.terminal.kind !== 'branch') { + return null; + } + const innerOptional = traverseOptionalBlock(maybeTest, context, testBlock.terminal.alternate); + if (innerOptional == null) { + return null; + } + if (testBlock.terminal.test.identifier.id !== innerOptional) { + return null; + } + if (!optional.terminal.optional) { + context.hoistableObjects.set(optional.id, assertNonNull(context.temporariesReadInOptional.get(innerOptional))); + } + baseObject = assertNonNull(context.temporariesReadInOptional.get(innerOptional)); + test = testBlock.terminal; + } + else { + return null; + } + if (test.alternate === outerAlternate) { + CompilerError.invariant(optional.instructions.length === 0, { + reason: '[OptionalChainDeps] Unexpected instructions an inner optional block. ' + + 'This indicates that the compiler may be incorrectly concatenating two unrelated optional chains', + loc: optional.terminal.loc, + }); + } + const matchConsequentResult = matchOptionalTestBlock(test, context.blocks); + if (!matchConsequentResult) { + return null; + } + CompilerError.invariant(matchConsequentResult.consequentGoto === optional.terminal.fallthrough, { + reason: '[OptionalChainDeps] Unexpected optional goto-fallthrough', + description: `${matchConsequentResult.consequentGoto} != ${optional.terminal.fallthrough}`, + loc: optional.terminal.loc, + }); + const load = { + identifier: baseObject.identifier, + reactive: baseObject.reactive, + path: [ + ...baseObject.path, + { + property: matchConsequentResult.property, + optional: optional.terminal.optional, + loc: matchConsequentResult.propertyLoadLoc, + }, + ], + loc: matchConsequentResult.propertyLoadLoc, + }; + context.processedInstrsInOptional.add(matchConsequentResult.storeLocalInstr); + context.processedInstrsInOptional.add(test); + context.temporariesReadInOptional.set(matchConsequentResult.consequentId, load); + context.temporariesReadInOptional.set(matchConsequentResult.propertyId, load); + return matchConsequentResult.consequentId; +} + +var _DependencyCollectionContext_instances, _DependencyCollectionContext_declarations, _DependencyCollectionContext_reassignments, _DependencyCollectionContext_scopes, _DependencyCollectionContext_dependencies, _DependencyCollectionContext_temporaries, _DependencyCollectionContext_temporariesUsedOutsideScope, _DependencyCollectionContext_processedInstrsInOptional, _DependencyCollectionContext_innerFnContext, _DependencyCollectionContext_checkValidDependency, _DependencyCollectionContext_isScopeActive; +function propagateScopeDependenciesHIR(fn) { + const usedOutsideDeclaringScope = findTemporariesUsedOutsideDeclaringScope(fn); + const temporaries = collectTemporariesSidemap(fn, usedOutsideDeclaringScope); + const { temporariesReadInOptional, processedInstrsInOptional, hoistableObjects, } = collectOptionalChainSidemap(fn); + const hoistablePropertyLoads = keyByScopeId(fn, collectHoistablePropertyLoads(fn, temporaries, hoistableObjects)); + const scopeDeps = collectDependencies$1(fn, usedOutsideDeclaringScope, new Map([...temporaries, ...temporariesReadInOptional]), processedInstrsInOptional); + for (const [scope, deps] of scopeDeps) { + if (deps.length === 0) { + continue; + } + const hoistables = hoistablePropertyLoads.get(scope.id); + CompilerError.invariant(hoistables != null, { + reason: '[PropagateScopeDependencies] Scope not found in tracked blocks', + loc: GeneratedSource, + }); + const tree = new ReactiveScopeDependencyTreeHIR([...hoistables.assumedNonNullObjects].map(o => o.fullPath)); + for (const dep of deps) { + tree.addDependency(Object.assign({}, dep)); + } + const candidates = tree.deriveMinimalDependencies(); + for (const candidateDep of candidates) { + if (!Iterable_some(scope.dependencies, existingDep => existingDep.identifier.declarationId === + candidateDep.identifier.declarationId && + areEqualPaths(existingDep.path, candidateDep.path))) + scope.dependencies.add(candidateDep); + } + } +} +function findTemporariesUsedOutsideDeclaringScope(fn) { + const declarations = new Map(); + const prunedScopes = new Set(); + const scopeTraversal = new ScopeBlockTraversal(); + const usedOutsideDeclaringScope = new Set(); + function handlePlace(place) { + const declaringScope = declarations.get(place.identifier.declarationId); + if (declaringScope != null && + !scopeTraversal.isScopeActive(declaringScope) && + !prunedScopes.has(declaringScope)) { + usedOutsideDeclaringScope.add(place.identifier.declarationId); + } + } + function handleInstruction(instr) { + const scope = scopeTraversal.currentScope; + if (scope == null || prunedScopes.has(scope)) { + return; + } + switch (instr.value.kind) { + case 'LoadLocal': + case 'LoadContext': + case 'PropertyLoad': { + declarations.set(instr.lvalue.identifier.declarationId, scope); + break; + } + } + } + for (const [blockId, block] of fn.body.blocks) { + scopeTraversal.recordScopes(block); + const scopeStartInfo = scopeTraversal.blockInfos.get(blockId); + if ((scopeStartInfo === null || scopeStartInfo === void 0 ? void 0 : scopeStartInfo.kind) === 'begin' && scopeStartInfo.pruned) { + prunedScopes.add(scopeStartInfo.scope.id); + } + for (const instr of block.instructions) { + for (const place of eachInstructionOperand(instr)) { + handlePlace(place); + } + handleInstruction(instr); + } + for (const place of eachTerminalOperand(block.terminal)) { + handlePlace(place); + } + } + return usedOutsideDeclaringScope; +} +function collectTemporariesSidemap(fn, usedOutsideDeclaringScope) { + const temporaries = new Map(); + collectTemporariesSidemapImpl(fn, usedOutsideDeclaringScope, temporaries, null); + return temporaries; +} +function isLoadContextMutable(instrValue, id) { + if (instrValue.kind === 'LoadContext') { + return (instrValue.place.identifier.scope != null && + id >= instrValue.place.identifier.scope.range.end); + } + return false; +} +function collectTemporariesSidemapImpl(fn, usedOutsideDeclaringScope, temporaries, innerFnContext) { + for (const [_, block] of fn.body.blocks) { + for (const { value, lvalue, id: origInstrId } of block.instructions) { + const instrId = innerFnContext != null ? innerFnContext.instrId : origInstrId; + const usedOutside = usedOutsideDeclaringScope.has(lvalue.identifier.declarationId); + if (value.kind === 'PropertyLoad' && !usedOutside) { + if (innerFnContext == null || + temporaries.has(value.object.identifier.id)) { + const property = getProperty(value.object, value.property, false, value.loc, temporaries); + temporaries.set(lvalue.identifier.id, property); + } + } + else if ((value.kind === 'LoadLocal' || isLoadContextMutable(value, instrId)) && + lvalue.identifier.name == null && + value.place.identifier.name !== null && + !usedOutside) { + if (innerFnContext == null || + fn.context.some(context => context.identifier.id === value.place.identifier.id)) { + temporaries.set(lvalue.identifier.id, { + identifier: value.place.identifier, + reactive: value.place.reactive, + path: [], + loc: value.loc, + }); + } + } + else if (value.kind === 'FunctionExpression' || + value.kind === 'ObjectMethod') { + collectTemporariesSidemapImpl(value.loweredFunc.func, usedOutsideDeclaringScope, temporaries, innerFnContext !== null && innerFnContext !== void 0 ? innerFnContext : { instrId }); + } + } + } +} +function getProperty(object, propertyName, optional, loc, temporaries) { + const resolvedDependency = temporaries.get(object.identifier.id); + let property; + if (resolvedDependency == null) { + property = { + identifier: object.identifier, + reactive: object.reactive, + path: [{ property: propertyName, optional, loc }], + loc, + }; + } + else { + property = { + identifier: resolvedDependency.identifier, + reactive: resolvedDependency.reactive, + path: [ + ...resolvedDependency.path, + { property: propertyName, optional, loc }, + ], + loc, + }; + } + return property; +} +class DependencyCollectionContext { + constructor(temporariesUsedOutsideScope, temporaries, processedInstrsInOptional) { + _DependencyCollectionContext_instances.add(this); + _DependencyCollectionContext_declarations.set(this, new Map()); + _DependencyCollectionContext_reassignments.set(this, new Map()); + _DependencyCollectionContext_scopes.set(this, empty()); + _DependencyCollectionContext_dependencies.set(this, empty()); + this.deps = new Map(); + _DependencyCollectionContext_temporaries.set(this, void 0); + _DependencyCollectionContext_temporariesUsedOutsideScope.set(this, void 0); + _DependencyCollectionContext_processedInstrsInOptional.set(this, void 0); + _DependencyCollectionContext_innerFnContext.set(this, null); + __classPrivateFieldSet(this, _DependencyCollectionContext_temporariesUsedOutsideScope, temporariesUsedOutsideScope, "f"); + __classPrivateFieldSet(this, _DependencyCollectionContext_temporaries, temporaries, "f"); + __classPrivateFieldSet(this, _DependencyCollectionContext_processedInstrsInOptional, processedInstrsInOptional, "f"); + } + enterScope(scope) { + __classPrivateFieldSet(this, _DependencyCollectionContext_dependencies, __classPrivateFieldGet(this, _DependencyCollectionContext_dependencies, "f").push([]), "f"); + __classPrivateFieldSet(this, _DependencyCollectionContext_scopes, __classPrivateFieldGet(this, _DependencyCollectionContext_scopes, "f").push(scope), "f"); + } + exitScope(scope, pruned) { + var _a; + const scopedDependencies = __classPrivateFieldGet(this, _DependencyCollectionContext_dependencies, "f").value; + CompilerError.invariant(scopedDependencies != null, { + reason: '[PropagateScopeDeps]: Unexpected scope mismatch', + loc: scope.loc, + }); + __classPrivateFieldSet(this, _DependencyCollectionContext_scopes, __classPrivateFieldGet(this, _DependencyCollectionContext_scopes, "f").pop(), "f"); + __classPrivateFieldSet(this, _DependencyCollectionContext_dependencies, __classPrivateFieldGet(this, _DependencyCollectionContext_dependencies, "f").pop(), "f"); + for (const dep of scopedDependencies) { + if (__classPrivateFieldGet(this, _DependencyCollectionContext_instances, "m", _DependencyCollectionContext_checkValidDependency).call(this, dep)) { + (_a = __classPrivateFieldGet(this, _DependencyCollectionContext_dependencies, "f").value) === null || _a === void 0 ? void 0 : _a.push(dep); + } + } + if (!pruned) { + this.deps.set(scope, scopedDependencies); + } + } + isUsedOutsideDeclaringScope(place) { + return __classPrivateFieldGet(this, _DependencyCollectionContext_temporariesUsedOutsideScope, "f").has(place.identifier.declarationId); + } + declare(identifier, decl) { + if (__classPrivateFieldGet(this, _DependencyCollectionContext_innerFnContext, "f") != null) + return; + if (!__classPrivateFieldGet(this, _DependencyCollectionContext_declarations, "f").has(identifier.declarationId)) { + __classPrivateFieldGet(this, _DependencyCollectionContext_declarations, "f").set(identifier.declarationId, decl); + } + __classPrivateFieldGet(this, _DependencyCollectionContext_reassignments, "f").set(identifier, decl); + } + hasDeclared(identifier) { + return __classPrivateFieldGet(this, _DependencyCollectionContext_declarations, "f").has(identifier.declarationId); + } + get currentScope() { + return __classPrivateFieldGet(this, _DependencyCollectionContext_scopes, "f"); + } + visitOperand(place) { + var _a; + this.visitDependency((_a = __classPrivateFieldGet(this, _DependencyCollectionContext_temporaries, "f").get(place.identifier.id)) !== null && _a !== void 0 ? _a : { + identifier: place.identifier, + reactive: place.reactive, + path: [], + loc: place.loc, + }); + } + visitProperty(object, property, optional, loc) { + const nextDependency = getProperty(object, property, optional, loc, __classPrivateFieldGet(this, _DependencyCollectionContext_temporaries, "f")); + this.visitDependency(nextDependency); + } + visitDependency(maybeDependency) { + var _a; + const originalDeclaration = __classPrivateFieldGet(this, _DependencyCollectionContext_declarations, "f").get(maybeDependency.identifier.declarationId); + if (originalDeclaration !== undefined && + originalDeclaration.scope.value !== null) { + originalDeclaration.scope.each(scope => { + if (!__classPrivateFieldGet(this, _DependencyCollectionContext_instances, "m", _DependencyCollectionContext_isScopeActive).call(this, scope) && + !Iterable_some(scope.declarations.values(), decl => decl.identifier.declarationId === + maybeDependency.identifier.declarationId)) { + scope.declarations.set(maybeDependency.identifier.id, { + identifier: maybeDependency.identifier, + scope: originalDeclaration.scope.value, + }); + } + }); + } + if (isUseRefType(maybeDependency.identifier) && + ((_a = maybeDependency.path.at(0)) === null || _a === void 0 ? void 0 : _a.property) === 'current') { + maybeDependency = { + identifier: maybeDependency.identifier, + reactive: maybeDependency.reactive, + path: [], + loc: maybeDependency.loc, + }; + } + if (__classPrivateFieldGet(this, _DependencyCollectionContext_instances, "m", _DependencyCollectionContext_checkValidDependency).call(this, maybeDependency)) { + __classPrivateFieldGet(this, _DependencyCollectionContext_dependencies, "f").value.push(maybeDependency); + } + } + visitReassignment(place) { + const currentScope = this.currentScope.value; + if (currentScope != null && + !Iterable_some(currentScope.reassignments, identifier => identifier.declarationId === place.identifier.declarationId) && + __classPrivateFieldGet(this, _DependencyCollectionContext_instances, "m", _DependencyCollectionContext_checkValidDependency).call(this, { + identifier: place.identifier, + reactive: place.reactive, + path: [], + loc: place.loc, + })) { + currentScope.reassignments.add(place.identifier); + } + } + enterInnerFn(innerFn, cb) { + var _a; + const prevContext = __classPrivateFieldGet(this, _DependencyCollectionContext_innerFnContext, "f"); + __classPrivateFieldSet(this, _DependencyCollectionContext_innerFnContext, (_a = __classPrivateFieldGet(this, _DependencyCollectionContext_innerFnContext, "f")) !== null && _a !== void 0 ? _a : { outerInstrId: innerFn.id }, "f"); + const result = cb(); + __classPrivateFieldSet(this, _DependencyCollectionContext_innerFnContext, prevContext, "f"); + return result; + } + isDeferredDependency(instr) { + return (__classPrivateFieldGet(this, _DependencyCollectionContext_processedInstrsInOptional, "f").has(instr.value) || + (instr.kind === HIRValue.Instruction && + __classPrivateFieldGet(this, _DependencyCollectionContext_temporaries, "f").has(instr.value.lvalue.identifier.id))); + } +} +_DependencyCollectionContext_declarations = new WeakMap(), _DependencyCollectionContext_reassignments = new WeakMap(), _DependencyCollectionContext_scopes = new WeakMap(), _DependencyCollectionContext_dependencies = new WeakMap(), _DependencyCollectionContext_temporaries = new WeakMap(), _DependencyCollectionContext_temporariesUsedOutsideScope = new WeakMap(), _DependencyCollectionContext_processedInstrsInOptional = new WeakMap(), _DependencyCollectionContext_innerFnContext = new WeakMap(), _DependencyCollectionContext_instances = new WeakSet(), _DependencyCollectionContext_checkValidDependency = function _DependencyCollectionContext_checkValidDependency(maybeDependency) { + var _a; + if (isRefValueType(maybeDependency.identifier)) { + return false; + } + if (isObjectMethodType(maybeDependency.identifier)) { + return false; + } + const identifier = maybeDependency.identifier; + const currentDeclaration = (_a = __classPrivateFieldGet(this, _DependencyCollectionContext_reassignments, "f").get(identifier)) !== null && _a !== void 0 ? _a : __classPrivateFieldGet(this, _DependencyCollectionContext_declarations, "f").get(identifier.declarationId); + const currentScope = this.currentScope.value; + return (currentScope != null && + currentDeclaration !== undefined && + currentDeclaration.id < currentScope.range.start); +}, _DependencyCollectionContext_isScopeActive = function _DependencyCollectionContext_isScopeActive(scope) { + if (__classPrivateFieldGet(this, _DependencyCollectionContext_scopes, "f") === null) { + return false; + } + return __classPrivateFieldGet(this, _DependencyCollectionContext_scopes, "f").find(state => state === scope); +}; +var HIRValue; +(function (HIRValue) { + HIRValue[HIRValue["Instruction"] = 1] = "Instruction"; + HIRValue[HIRValue["Terminal"] = 2] = "Terminal"; +})(HIRValue || (HIRValue = {})); +function handleInstruction(instr, context) { + const { id, value, lvalue } = instr; + context.declare(lvalue.identifier, { + id, + scope: context.currentScope, + }); + if (context.isDeferredDependency({ kind: HIRValue.Instruction, value: instr })) { + return; + } + if (value.kind === 'PropertyLoad') { + context.visitProperty(value.object, value.property, false, value.loc); + } + else if (value.kind === 'StoreLocal') { + context.visitOperand(value.value); + if (value.lvalue.kind === InstructionKind.Reassign) { + context.visitReassignment(value.lvalue.place); + } + context.declare(value.lvalue.place.identifier, { + id, + scope: context.currentScope, + }); + } + else if (value.kind === 'DeclareLocal' || value.kind === 'DeclareContext') { + if (convertHoistedLValueKind(value.lvalue.kind) === null) { + context.declare(value.lvalue.place.identifier, { + id, + scope: context.currentScope, + }); + } + } + else if (value.kind === 'Destructure') { + context.visitOperand(value.value); + for (const place of eachPatternOperand(value.lvalue.pattern)) { + if (value.lvalue.kind === InstructionKind.Reassign) { + context.visitReassignment(place); + } + context.declare(place.identifier, { + id, + scope: context.currentScope, + }); + } + } + else if (value.kind === 'StoreContext') { + if (!context.hasDeclared(value.lvalue.place.identifier) || + value.lvalue.kind !== InstructionKind.Reassign) { + context.declare(value.lvalue.place.identifier, { + id, + scope: context.currentScope, + }); + } + for (const operand of eachInstructionValueOperand(value)) { + context.visitOperand(operand); + } + } + else { + for (const operand of eachInstructionValueOperand(value)) { + context.visitOperand(operand); + } + } +} +function collectDependencies$1(fn, usedOutsideDeclaringScope, temporaries, processedInstrsInOptional) { + const context = new DependencyCollectionContext(usedOutsideDeclaringScope, temporaries, processedInstrsInOptional); + for (const param of fn.params) { + if (param.kind === 'Identifier') { + context.declare(param.identifier, { + id: makeInstructionId(0), + scope: empty(), + }); + } + else { + context.declare(param.place.identifier, { + id: makeInstructionId(0), + scope: empty(), + }); + } + } + const scopeTraversal = new ScopeBlockTraversal(); + const handleFunction = (fn) => { + for (const [blockId, block] of fn.body.blocks) { + scopeTraversal.recordScopes(block); + const scopeBlockInfo = scopeTraversal.blockInfos.get(blockId); + if ((scopeBlockInfo === null || scopeBlockInfo === void 0 ? void 0 : scopeBlockInfo.kind) === 'begin') { + context.enterScope(scopeBlockInfo.scope); + } + else if ((scopeBlockInfo === null || scopeBlockInfo === void 0 ? void 0 : scopeBlockInfo.kind) === 'end') { + context.exitScope(scopeBlockInfo.scope, scopeBlockInfo.pruned); + } + for (const phi of block.phis) { + for (const operand of phi.operands) { + const maybeOptionalChain = temporaries.get(operand[1].identifier.id); + if (maybeOptionalChain) { + context.visitDependency(maybeOptionalChain); + } + } + } + for (const instr of block.instructions) { + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + context.declare(instr.lvalue.identifier, { + id: instr.id, + scope: context.currentScope, + }); + const innerFn = instr.value.loweredFunc.func; + context.enterInnerFn(instr, () => { + handleFunction(innerFn); + }); + } + else { + handleInstruction(instr, context); + } + } + if (!context.isDeferredDependency({ + kind: HIRValue.Terminal, + value: block.terminal, + })) { + for (const place of eachTerminalOperand(block.terminal)) { + context.visitOperand(place); + } + } + } + }; + handleFunction(fn); + return context.deps; +} + +function outlineJSX(fn) { + const outlinedFns = []; + outlineJsxImpl(fn, outlinedFns); + for (const outlinedFn of outlinedFns) { + fn.env.outlineFunction(outlinedFn, 'Component'); + } +} +function outlineJsxImpl(fn, outlinedFns) { + const globals = new Map(); + function processAndOutlineJSX(state, rewriteInstr) { + if (state.jsx.length <= 1) { + return; + } + const result = process$1(fn, [...state.jsx].sort((a, b) => a.id - b.id), globals); + if (result) { + outlinedFns.push(result.fn); + rewriteInstr.set(state.jsx.at(0).id, result.instrs); + } + } + for (const [, block] of fn.body.blocks) { + const rewriteInstr = new Map(); + let state = { + jsx: [], + children: new Set(), + }; + for (let i = block.instructions.length - 1; i >= 0; i--) { + const instr = block.instructions[i]; + const { value, lvalue } = instr; + switch (value.kind) { + case 'LoadGlobal': { + globals.set(lvalue.identifier.id, instr); + break; + } + case 'FunctionExpression': { + outlineJsxImpl(value.loweredFunc.func, outlinedFns); + break; + } + case 'JsxExpression': { + if (!state.children.has(lvalue.identifier.id)) { + processAndOutlineJSX(state, rewriteInstr); + state = { + jsx: [], + children: new Set(), + }; + } + state.jsx.push(instr); + if (value.children) { + for (const child of value.children) { + state.children.add(child.identifier.id); + } + } + break; + } + case 'ArrayExpression': + case 'Await': + case 'BinaryExpression': + case 'CallExpression': + case 'ComputedDelete': + case 'ComputedLoad': + case 'ComputedStore': + case 'Debugger': + case 'DeclareContext': + case 'DeclareLocal': + case 'Destructure': + case 'FinishMemoize': + case 'GetIterator': + case 'IteratorNext': + case 'JSXText': + case 'JsxFragment': + case 'LoadContext': + case 'LoadLocal': + case 'MetaProperty': + case 'MethodCall': + case 'NewExpression': + case 'NextPropertyOf': + case 'ObjectExpression': + case 'ObjectMethod': + case 'PostfixUpdate': + case 'PrefixUpdate': + case 'Primitive': + case 'PropertyDelete': + case 'PropertyLoad': + case 'PropertyStore': + case 'RegExpLiteral': + case 'StartMemoize': + case 'StoreContext': + case 'StoreGlobal': + case 'StoreLocal': + case 'TaggedTemplateExpression': + case 'TemplateLiteral': + case 'TypeCastExpression': + case 'UnsupportedNode': + case 'UnaryExpression': { + break; + } + default: { + assertExhaustive$1(value, `Unexpected instruction: ${value}`); + } + } + } + processAndOutlineJSX(state, rewriteInstr); + if (rewriteInstr.size > 0) { + const newInstrs = []; + for (let i = 0; i < block.instructions.length; i++) { + const id = i + 1; + if (rewriteInstr.has(id)) { + const instrs = rewriteInstr.get(id); + newInstrs.push(...instrs); + } + else { + newInstrs.push(block.instructions[i]); + } + } + block.instructions = newInstrs; + } + deadCodeElimination(fn); + } +} +function process$1(fn, jsx, globals) { + if (fn.fnType === 'Component') { + return null; + } + const props = collectProps(fn.env, jsx); + if (!props) + return null; + const outlinedTag = fn.env.generateGloballyUniqueIdentifierName(null).value; + const newInstrs = emitOutlinedJsx(fn.env, jsx, props, outlinedTag); + if (!newInstrs) + return null; + const outlinedFn = emitOutlinedFn(fn.env, jsx, props, globals); + if (!outlinedFn) + return null; + outlinedFn.id = outlinedTag; + return { instrs: newInstrs, fn: outlinedFn }; +} +function collectProps(env, instructions) { + let id = 1; + function generateName(oldName) { + let newName = oldName; + while (seen.has(newName)) { + newName = `${oldName}${id++}`; + } + seen.add(newName); + env.programContext.addNewReference(newName); + return newName; + } + const attributes = []; + const jsxIds = new Set(instructions.map(i => i.lvalue.identifier.id)); + const seen = new Set(); + for (const instr of instructions) { + const { value } = instr; + for (const at of value.props) { + if (at.kind === 'JsxSpreadAttribute') { + return null; + } + if (at.kind === 'JsxAttribute') { + const newName = generateName(at.name); + attributes.push({ + originalName: at.name, + newName, + place: at.place, + }); + } + } + if (value.children) { + for (const child of value.children) { + if (jsxIds.has(child.identifier.id)) { + continue; + } + promoteTemporary(child.identifier); + const newName = generateName('t'); + attributes.push({ + originalName: child.identifier.name.value, + newName: newName, + place: child, + }); + } + } + } + return attributes; +} +function emitOutlinedJsx(env, instructions, outlinedProps, outlinedTag) { + const props = outlinedProps.map(p => ({ + kind: 'JsxAttribute', + name: p.newName, + place: p.place, + })); + const loadJsx = { + id: makeInstructionId(0), + loc: GeneratedSource, + lvalue: createTemporaryPlace(env, GeneratedSource), + value: { + kind: 'LoadGlobal', + binding: { + kind: 'ModuleLocal', + name: outlinedTag, + }, + loc: GeneratedSource, + }, + effects: null, + }; + promoteTemporaryJsxTag(loadJsx.lvalue.identifier); + const jsxExpr = { + id: makeInstructionId(0), + loc: GeneratedSource, + lvalue: instructions.at(-1).lvalue, + value: { + kind: 'JsxExpression', + tag: Object.assign({}, loadJsx.lvalue), + props, + children: null, + loc: GeneratedSource, + openingLoc: GeneratedSource, + closingLoc: GeneratedSource, + }, + effects: null, + }; + return [loadJsx, jsxExpr]; +} +function emitOutlinedFn(env, jsx, oldProps, globals) { + const instructions = []; + const oldToNewProps = createOldToNewPropsMapping(env, oldProps); + const propsObj = createTemporaryPlace(env, GeneratedSource); + promoteTemporary(propsObj.identifier); + const destructurePropsInstr = emitDestructureProps(env, propsObj, oldToNewProps); + instructions.push(destructurePropsInstr); + const updatedJsxInstructions = emitUpdatedJsx(jsx, oldToNewProps); + const loadGlobalInstrs = emitLoadGlobals(jsx, globals); + if (!loadGlobalInstrs) { + return null; + } + instructions.push(...loadGlobalInstrs); + instructions.push(...updatedJsxInstructions); + const block = { + kind: 'block', + id: makeBlockId(0), + instructions, + terminal: { + id: makeInstructionId(0), + kind: 'return', + returnVariant: 'Explicit', + loc: GeneratedSource, + value: instructions.at(-1).lvalue, + effects: null, + }, + preds: new Set(), + phis: new Set(), + }; + const fn = { + loc: GeneratedSource, + id: null, + nameHint: null, + fnType: 'Other', + env, + params: [propsObj], + returnTypeAnnotation: null, + returns: createTemporaryPlace(env, GeneratedSource), + context: [], + body: { + entry: block.id, + blocks: new Map([[block.id, block]]), + }, + generator: false, + async: false, + directives: [], + aliasingEffects: [], + }; + return fn; +} +function emitLoadGlobals(jsx, globals) { + const instructions = []; + for (const { value } of jsx) { + if (value.tag.kind === 'Identifier') { + const loadGlobalInstr = globals.get(value.tag.identifier.id); + if (!loadGlobalInstr) { + return null; + } + instructions.push(loadGlobalInstr); + } + } + return instructions; +} +function emitUpdatedJsx(jsx, oldToNewProps) { + const newInstrs = []; + const jsxIds = new Set(jsx.map(i => i.lvalue.identifier.id)); + for (const instr of jsx) { + const { value } = instr; + const newProps = []; + for (const prop of value.props) { + invariant(prop.kind === 'JsxAttribute', `Expected only attributes but found ${prop.kind}`); + if (prop.name === 'key') { + continue; + } + const newProp = oldToNewProps.get(prop.place.identifier.id); + invariant(newProp !== undefined, `Expected a new property for ${printIdentifier(prop.place.identifier)}`); + newProps.push({ + kind: 'JsxAttribute', + name: newProp.originalName, + place: newProp.place, + }); + } + let newChildren = null; + if (value.children) { + newChildren = []; + for (const child of value.children) { + if (jsxIds.has(child.identifier.id)) { + newChildren.push(Object.assign({}, child)); + continue; + } + const newChild = oldToNewProps.get(child.identifier.id); + invariant(newChild !== undefined, `Expected a new prop for ${printIdentifier(child.identifier)}`); + newChildren.push(Object.assign({}, newChild.place)); + } + } + newInstrs.push(Object.assign(Object.assign({}, instr), { value: Object.assign(Object.assign({}, value), { props: newProps, children: newChildren }) })); + } + return newInstrs; +} +function createOldToNewPropsMapping(env, oldProps) { + const oldToNewProps = new Map(); + for (const oldProp of oldProps) { + if (oldProp.originalName === 'key') { + continue; + } + const newProp = Object.assign(Object.assign({}, oldProp), { place: createTemporaryPlace(env, GeneratedSource) }); + newProp.place.identifier.name = makeIdentifierName(oldProp.newName); + oldToNewProps.set(oldProp.place.identifier.id, newProp); + } + return oldToNewProps; +} +function emitDestructureProps(env, propsObj, oldToNewProps) { + const properties = []; + for (const [_, prop] of oldToNewProps) { + properties.push({ + kind: 'ObjectProperty', + key: { + kind: 'string', + name: prop.newName, + }, + type: 'property', + place: prop.place, + }); + } + const destructurePropsInstr = { + id: makeInstructionId(0), + lvalue: createTemporaryPlace(env, GeneratedSource), + loc: GeneratedSource, + value: { + kind: 'Destructure', + lvalue: { + pattern: { + kind: 'ObjectPattern', + properties, + loc: GeneratedSource, + }, + kind: InstructionKind.Let, + }, + loc: GeneratedSource, + value: propsObj, + }, + effects: null, + }; + return destructurePropsInstr; +} + +function optimizePropsMethodCalls(fn) { + for (const [, block] of fn.body.blocks) { + for (let i = 0; i < block.instructions.length; i++) { + const instr = block.instructions[i]; + if (instr.value.kind === 'MethodCall' && + isPropsType(instr.value.receiver.identifier)) { + instr.value = { + kind: 'CallExpression', + callee: instr.value.property, + args: instr.value.args, + loc: instr.value.loc, + }; + } + } + } +} + +function validateStaticComponents(fn) { + const error = new CompilerError(); + const knownDynamicComponents = new Map(); + for (const block of fn.body.blocks.values()) { + phis: for (const phi of block.phis) { + for (const operand of phi.operands.values()) { + const loc = knownDynamicComponents.get(operand.identifier.id); + if (loc != null) { + knownDynamicComponents.set(phi.place.identifier.id, loc); + continue phis; + } + } + } + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'FunctionExpression': + case 'NewExpression': + case 'MethodCall': + case 'CallExpression': { + knownDynamicComponents.set(lvalue.identifier.id, value.loc); + break; + } + case 'LoadLocal': { + const loc = knownDynamicComponents.get(value.place.identifier.id); + if (loc != null) { + knownDynamicComponents.set(lvalue.identifier.id, loc); + } + break; + } + case 'StoreLocal': { + const loc = knownDynamicComponents.get(value.value.identifier.id); + if (loc != null) { + knownDynamicComponents.set(lvalue.identifier.id, loc); + knownDynamicComponents.set(value.lvalue.place.identifier.id, loc); + } + break; + } + case 'JsxExpression': { + if (value.tag.kind === 'Identifier') { + const location = knownDynamicComponents.get(value.tag.identifier.id); + if (location != null) { + error.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.StaticComponents, + reason: 'Cannot create components during render', + description: `Components created during render will reset their state each time they are created. Declare components outside of render`, + }) + .withDetails({ + kind: 'error', + loc: value.tag.loc, + message: 'This component is created during render', + }) + .withDetails({ + kind: 'error', + loc: location, + message: 'The component is created during render here', + })); + } + } + } + } + } + } + return error.asResult(); +} + +function validateNoFreezingKnownMutableFunctions(fn) { + const contextMutationEffects = new Map(); + function visitOperand(operand) { + if (operand.effect === Effect.Freeze) { + const effect = contextMutationEffects.get(operand.identifier.id); + if (effect != null) { + const place = effect.value; + const variable = place != null && + place.identifier.name != null && + place.identifier.name.kind === 'named' + ? `\`${place.identifier.name.value}\`` + : 'a local variable'; + fn.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'Cannot modify local variables after render completes', + description: `This argument is a function which may reassign or mutate ${variable} after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead`, + }) + .withDetails({ + kind: 'error', + loc: operand.loc, + message: `This function may (indirectly) reassign or modify ${variable} after render`, + }) + .withDetails({ + kind: 'error', + loc: effect.value.loc, + message: `This modifies ${variable}`, + })); + } + } + } + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'LoadLocal': { + const effect = contextMutationEffects.get(value.place.identifier.id); + if (effect != null) { + contextMutationEffects.set(lvalue.identifier.id, effect); + } + break; + } + case 'StoreLocal': { + const effect = contextMutationEffects.get(value.value.identifier.id); + if (effect != null) { + contextMutationEffects.set(lvalue.identifier.id, effect); + contextMutationEffects.set(value.lvalue.place.identifier.id, effect); + } + break; + } + case 'FunctionExpression': { + if (value.loweredFunc.func.aliasingEffects != null) { + const context = new Set(value.loweredFunc.func.context.map(p => p.identifier.id)); + effects: for (const effect of value.loweredFunc.func + .aliasingEffects) { + switch (effect.kind) { + case 'Mutate': + case 'MutateTransitive': { + const knownMutation = contextMutationEffects.get(effect.value.identifier.id); + if (knownMutation != null) { + contextMutationEffects.set(lvalue.identifier.id, knownMutation); + } + else if (context.has(effect.value.identifier.id) && + !isRefOrRefLikeMutableType(effect.value.identifier.type)) { + contextMutationEffects.set(lvalue.identifier.id, effect); + break effects; + } + break; + } + case 'MutateConditionally': + case 'MutateTransitiveConditionally': { + const knownMutation = contextMutationEffects.get(effect.value.identifier.id); + if (knownMutation != null) { + contextMutationEffects.set(lvalue.identifier.id, knownMutation); + } + break; + } + } + } + } + break; + } + default: { + for (const operand of eachInstructionValueOperand(value)) { + visitOperand(operand); + } + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + visitOperand(operand); + } + } +} + +function validateNoDerivedComputationsInEffects(fn) { + const candidateDependencies = new Map(); + const functions = new Map(); + const locals = new Map(); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + if (value.kind === 'LoadLocal') { + locals.set(lvalue.identifier.id, value.place.identifier.id); + } + else if (value.kind === 'ArrayExpression') { + candidateDependencies.set(lvalue.identifier.id, value); + } + else if (value.kind === 'FunctionExpression') { + functions.set(lvalue.identifier.id, value); + } + else if (value.kind === 'CallExpression' || + value.kind === 'MethodCall') { + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + if (isUseEffectHookType(callee.identifier) && + value.args.length === 2 && + value.args[0].kind === 'Identifier' && + value.args[1].kind === 'Identifier') { + const effectFunction = functions.get(value.args[0].identifier.id); + const deps = candidateDependencies.get(value.args[1].identifier.id); + if (effectFunction != null && + deps != null && + deps.elements.length !== 0 && + deps.elements.every(element => element.kind === 'Identifier')) { + const dependencies = deps.elements.map(dep => { + var _a; + CompilerError.invariant(dep.kind === 'Identifier', { + reason: `Dependency is checked as a place above`, + loc: value.loc, + }); + return (_a = locals.get(dep.identifier.id)) !== null && _a !== void 0 ? _a : dep.identifier.id; + }); + validateEffect$1(effectFunction.loweredFunc.func, dependencies, fn.env); + } + } + } + } + } +} +function validateEffect$1(effectFunction, effectDeps, env) { + for (const operand of effectFunction.context) { + if (isSetStateType(operand.identifier)) { + continue; + } + else if (effectDeps.find(dep => dep === operand.identifier.id) != null) { + continue; + } + else { + return; + } + } + for (const dep of effectDeps) { + if (effectFunction.context.find(operand => operand.identifier.id === dep) == + null) { + return; + } + } + const seenBlocks = new Set(); + const values = new Map(); + for (const dep of effectDeps) { + values.set(dep, [dep]); + } + const setStateLocations = []; + for (const block of effectFunction.body.blocks.values()) { + for (const pred of block.preds) { + if (!seenBlocks.has(pred)) { + return; + } + } + for (const phi of block.phis) { + const aggregateDeps = new Set(); + for (const operand of phi.operands.values()) { + const deps = values.get(operand.identifier.id); + if (deps != null) { + for (const dep of deps) { + aggregateDeps.add(dep); + } + } + } + if (aggregateDeps.size !== 0) { + values.set(phi.place.identifier.id, Array.from(aggregateDeps)); + } + } + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'Primitive': + case 'JSXText': + case 'LoadGlobal': { + break; + } + case 'LoadLocal': { + const deps = values.get(instr.value.place.identifier.id); + if (deps != null) { + values.set(instr.lvalue.identifier.id, deps); + } + break; + } + case 'ComputedLoad': + case 'PropertyLoad': + case 'BinaryExpression': + case 'TemplateLiteral': + case 'CallExpression': + case 'MethodCall': { + const aggregateDeps = new Set(); + for (const operand of eachInstructionValueOperand(instr.value)) { + const deps = values.get(operand.identifier.id); + if (deps != null) { + for (const dep of deps) { + aggregateDeps.add(dep); + } + } + } + if (aggregateDeps.size !== 0) { + values.set(instr.lvalue.identifier.id, Array.from(aggregateDeps)); + } + if (instr.value.kind === 'CallExpression' && + isSetStateType(instr.value.callee.identifier) && + instr.value.args.length === 1 && + instr.value.args[0].kind === 'Identifier') { + const deps = values.get(instr.value.args[0].identifier.id); + if (deps != null && new Set(deps).size === effectDeps.length) { + setStateLocations.push(instr.value.callee.loc); + } + else { + return; + } + } + break; + } + default: { + return; + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + if (values.has(operand.identifier.id)) { + return; + } + } + seenBlocks.add(block.id); + } + for (const loc of setStateLocations) { + env.recordError(new CompilerErrorDetail({ + category: ErrorCategory.EffectDerivationsOfState, + reason: 'Values derived from props and state should be calculated during render, not in an effect. (https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state)', + description: null, + loc, + suggestions: null, + })); + } +} + +const MAX_FIXPOINT_ITERATIONS = 100; +class DerivationCache { + constructor() { + this.hasChanges = false; + this.cache = new Map(); + this.previousCache = null; + } + takeSnapshot() { + this.previousCache = new Map(); + for (const [key, value] of this.cache.entries()) { + this.previousCache.set(key, { + place: value.place, + sourcesIds: new Set(value.sourcesIds), + typeOfValue: value.typeOfValue, + isStateSource: value.isStateSource, + }); + } + } + checkForChanges() { + if (this.previousCache === null) { + this.hasChanges = true; + return; + } + for (const [key, value] of this.cache.entries()) { + const previousValue = this.previousCache.get(key); + if (previousValue === undefined || + !this.isDerivationEqual(previousValue, value)) { + this.hasChanges = true; + return; + } + } + if (this.cache.size !== this.previousCache.size) { + this.hasChanges = true; + return; + } + this.hasChanges = false; + } + snapshot() { + const hasChanges = this.hasChanges; + this.hasChanges = false; + return hasChanges; + } + addDerivationEntry(derivedVar, sourcesIds, typeOfValue, isStateSource) { + var _a; + let finalIsSource = isStateSource; + if (!finalIsSource) { + for (const sourceId of sourcesIds) { + const sourceMetadata = this.cache.get(sourceId); + if ((sourceMetadata === null || sourceMetadata === void 0 ? void 0 : sourceMetadata.isStateSource) && + ((_a = sourceMetadata.place.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) !== 'named') { + finalIsSource = true; + break; + } + } + } + this.cache.set(derivedVar.identifier.id, { + place: derivedVar, + sourcesIds: sourcesIds, + typeOfValue: typeOfValue !== null && typeOfValue !== void 0 ? typeOfValue : 'ignored', + isStateSource: finalIsSource, + }); + } + isDerivationEqual(a, b) { + if (a.typeOfValue !== b.typeOfValue) { + return false; + } + if (a.sourcesIds.size !== b.sourcesIds.size) { + return false; + } + for (const id of a.sourcesIds) { + if (!b.sourcesIds.has(id)) { + return false; + } + } + return true; + } +} +function isNamedIdentifier(place) { + return (place.identifier.name !== null && place.identifier.name.kind === 'named'); +} +function validateNoDerivedComputationsInEffects_exp(fn) { + const functions = new Map(); + const candidateDependencies = new Map(); + const derivationCache = new DerivationCache(); + const errors = new CompilerError(); + const effectsCache = new Map(); + const setStateLoads = new Map(); + const setStateUsages = new Map(); + const context = { + functions, + candidateDependencies, + errors, + derivationCache, + effectsCache, + setStateLoads, + setStateUsages, + }; + if (fn.fnType === 'Hook') { + for (const param of fn.params) { + if (param.kind === 'Identifier') { + context.derivationCache.cache.set(param.identifier.id, { + place: param, + sourcesIds: new Set(), + typeOfValue: 'fromProps', + isStateSource: true, + }); + } + } + } + else if (fn.fnType === 'Component') { + const props = fn.params[0]; + if (props != null && props.kind === 'Identifier') { + context.derivationCache.cache.set(props.identifier.id, { + place: props, + sourcesIds: new Set(), + typeOfValue: 'fromProps', + isStateSource: true, + }); + } + } + let iterationCount = 0; + do { + context.derivationCache.takeSnapshot(); + for (const block of fn.body.blocks.values()) { + recordPhiDerivations(block, context); + for (const instr of block.instructions) { + recordInstructionDerivations(instr, context); + } + } + context.derivationCache.checkForChanges(); + iterationCount++; + CompilerError.invariant(iterationCount < MAX_FIXPOINT_ITERATIONS, { + reason: '[ValidateNoDerivedComputationsInEffects] Fixpoint iteration failed to converge.', + description: `Fixpoint iteration exceeded ${MAX_FIXPOINT_ITERATIONS} iterations while tracking derivations. This suggests a cyclic dependency in the derivation cache.`, + loc: fn.loc, + }); + } while (context.derivationCache.snapshot()); + for (const [, effect] of effectsCache) { + validateEffect(effect.effect, effect.dependencies, context); + } + return errors.asResult(); +} +function recordPhiDerivations(block, context) { + for (const phi of block.phis) { + let typeOfValue = 'ignored'; + let sourcesIds = new Set(); + for (const operand of phi.operands.values()) { + const operandMetadata = context.derivationCache.cache.get(operand.identifier.id); + if (operandMetadata === undefined) { + continue; + } + typeOfValue = joinValue(typeOfValue, operandMetadata.typeOfValue); + sourcesIds.add(operand.identifier.id); + } + if (typeOfValue !== 'ignored') { + context.derivationCache.addDerivationEntry(phi.place, sourcesIds, typeOfValue, false); + } + } +} +function joinValue(lvalueType, valueType) { + if (lvalueType === 'ignored') + return valueType; + if (valueType === 'ignored') + return lvalueType; + if (lvalueType === valueType) + return lvalueType; + return 'fromPropsAndState'; +} +function getRootSetState(key, loads, visited = new Set()) { + if (visited.has(key)) { + return null; + } + visited.add(key); + const parentId = loads.get(key); + if (parentId === undefined) { + return null; + } + if (parentId === null) { + return key; + } + return getRootSetState(parentId, loads, visited); +} +function maybeRecordSetState(instr, loads, usages) { + for (const operand of eachInstructionLValue(instr)) { + if (instr.value.kind === 'LoadLocal' && + loads.has(instr.value.place.identifier.id)) { + loads.set(operand.identifier.id, instr.value.place.identifier.id); + } + else { + if (isSetStateType(operand.identifier)) { + loads.set(operand.identifier.id, null); + } + } + const rootSetState = getRootSetState(operand.identifier.id, loads); + if (rootSetState !== null && usages.get(rootSetState) === undefined) { + usages.set(rootSetState, new Set([operand.loc])); + } + } +} +function recordInstructionDerivations(instr, context, isFirstPass) { + var _a; + maybeRecordSetState(instr, context.setStateLoads, context.setStateUsages); + let typeOfValue = 'ignored'; + let isSource = false; + const sources = new Set(); + const { lvalue, value } = instr; + if (value.kind === 'FunctionExpression') { + context.functions.set(lvalue.identifier.id, value); + for (const [, block] of value.loweredFunc.func.body.blocks) { + recordPhiDerivations(block, context); + for (const instr of block.instructions) { + recordInstructionDerivations(instr, context); + } + } + } + else if (value.kind === 'CallExpression' || value.kind === 'MethodCall') { + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + if (isUseEffectHookType(callee.identifier) && + value.args.length === 2 && + value.args[0].kind === 'Identifier' && + value.args[1].kind === 'Identifier') { + const effectFunction = context.functions.get(value.args[0].identifier.id); + const deps = context.candidateDependencies.get(value.args[1].identifier.id); + if (effectFunction != null && deps != null) { + context.effectsCache.set(value.args[0].identifier.id, { + effect: effectFunction.loweredFunc.func, + dependencies: deps, + }); + } + } + else if (isUseStateType(lvalue.identifier)) { + typeOfValue = 'fromState'; + context.derivationCache.addDerivationEntry(lvalue, new Set(), typeOfValue, true); + return; + } + } + else if (value.kind === 'ArrayExpression') { + context.candidateDependencies.set(lvalue.identifier.id, value); + } + for (const operand of eachInstructionOperand(instr)) { + if (context.setStateLoads.has(operand.identifier.id)) { + const rootSetStateId = getRootSetState(operand.identifier.id, context.setStateLoads); + if (rootSetStateId !== null) { + (_a = context.setStateUsages.get(rootSetStateId)) === null || _a === void 0 ? void 0 : _a.add(operand.loc); + } + } + const operandMetadata = context.derivationCache.cache.get(operand.identifier.id); + if (operandMetadata === undefined) { + continue; + } + typeOfValue = joinValue(typeOfValue, operandMetadata.typeOfValue); + sources.add(operand.identifier.id); + } + if (typeOfValue === 'ignored') { + return; + } + for (const lvalue of eachInstructionLValue(instr)) { + context.derivationCache.addDerivationEntry(lvalue, sources, typeOfValue, isSource); + } + if (value.kind === 'FunctionExpression') { + return; + } + for (const operand of eachInstructionOperand(instr)) { + switch (operand.effect) { + case Effect.Capture: + case Effect.Store: + case Effect.ConditionallyMutate: + case Effect.ConditionallyMutateIterator: + case Effect.Mutate: { + if (isMutable(instr, operand)) { + if (context.derivationCache.cache.has(operand.identifier.id)) { + const operandMetadata = context.derivationCache.cache.get(operand.identifier.id); + if (operandMetadata !== undefined) { + operandMetadata.typeOfValue = joinValue(typeOfValue, operandMetadata.typeOfValue); + } + } + else { + context.derivationCache.addDerivationEntry(operand, sources, typeOfValue, false); + } + } + break; + } + case Effect.Freeze: + case Effect.Read: { + break; + } + case Effect.Unknown: { + CompilerError.invariant(false, { + reason: 'Unexpected unknown effect', + loc: operand.loc, + }); + } + default: { + assertExhaustive$1(operand.effect, `Unexpected effect kind \`${operand.effect}\``); + } + } + } +} +function buildTreeNode(sourceId, context, visited = new Set()) { + const sourceMetadata = context.derivationCache.cache.get(sourceId); + if (!sourceMetadata) { + return []; + } + if (sourceMetadata.isStateSource && isNamedIdentifier(sourceMetadata.place)) { + return [ + { + name: sourceMetadata.place.identifier.name.value, + typeOfValue: sourceMetadata.typeOfValue, + isSource: sourceMetadata.isStateSource, + children: [], + }, + ]; + } + const children = []; + const namedSiblings = new Set(); + for (const childId of sourceMetadata.sourcesIds) { + CompilerError.invariant(childId !== sourceId, { + reason: 'Unexpected self-reference: a value should not have itself as a source', + loc: sourceMetadata.place.loc, + }); + const childNodes = buildTreeNode(childId, context, new Set([ + ...visited, + ...(isNamedIdentifier(sourceMetadata.place) + ? [sourceMetadata.place.identifier.name.value] + : []), + ])); + if (childNodes) { + for (const childNode of childNodes) { + if (!namedSiblings.has(childNode.name)) { + children.push(childNode); + namedSiblings.add(childNode.name); + } + } + } + } + if (isNamedIdentifier(sourceMetadata.place) && + !visited.has(sourceMetadata.place.identifier.name.value)) { + return [ + { + name: sourceMetadata.place.identifier.name.value, + typeOfValue: sourceMetadata.typeOfValue, + isSource: sourceMetadata.isStateSource, + children: children, + }, + ]; + } + return children; +} +function renderTree(node, indent = '', isLast = true, propsSet, stateSet) { + const prefix = indent + (isLast ? '└── ' : '├── '); + const childIndent = indent + (isLast ? ' ' : '│ '); + let result = `${prefix}${node.name}`; + if (node.isSource) { + let typeLabel; + if (node.typeOfValue === 'fromProps') { + propsSet.add(node.name); + typeLabel = 'Prop'; + } + else if (node.typeOfValue === 'fromState') { + stateSet.add(node.name); + typeLabel = 'State'; + } + else { + propsSet.add(node.name); + stateSet.add(node.name); + typeLabel = 'Prop and State'; + } + result += ` (${typeLabel})`; + } + if (node.children.length > 0) { + result += '\n'; + node.children.forEach((child, index) => { + const isLastChild = index === node.children.length - 1; + result += renderTree(child, childIndent, isLastChild, propsSet, stateSet); + if (index < node.children.length - 1) { + result += '\n'; + } + }); + } + return result; +} +function getFnLocalDeps(fn) { + if (!fn) { + return undefined; + } + const deps = new Set(); + for (const [, block] of fn.loweredFunc.func.body.blocks) { + for (const instr of block.instructions) { + if (instr.value.kind === 'LoadLocal') { + deps.add(instr.value.place.identifier.id); + } + } + } + return deps; +} +function validateEffect(effectFunction, dependencies, context) { + var _a; + const seenBlocks = new Set(); + const effectDerivedSetStateCalls = []; + const effectSetStateUsages = new Map(); + for (const dep of dependencies.elements) { + if (dep.kind === 'Identifier') { + const root = getRootSetState(dep.identifier.id, context.setStateLoads); + if (root !== null) { + effectSetStateUsages.set(root, new Set([dep.loc])); + } + } + } + let cleanUpFunctionDeps; + const globals = new Set(); + for (const block of effectFunction.body.blocks.values()) { + if (block.terminal.kind === 'return' && + block.terminal.returnVariant === 'Explicit') { + cleanUpFunctionDeps = getFnLocalDeps(context.functions.get(block.terminal.value.identifier.id)); + } + for (const pred of block.preds) { + if (!seenBlocks.has(pred)) { + return; + } + } + for (const instr of block.instructions) { + if (isUseRefType(instr.lvalue.identifier)) { + return; + } + maybeRecordSetState(instr, context.setStateLoads, effectSetStateUsages); + for (const operand of eachInstructionOperand(instr)) { + if (context.setStateLoads.has(operand.identifier.id)) { + const rootSetStateId = getRootSetState(operand.identifier.id, context.setStateLoads); + if (rootSetStateId !== null) { + (_a = effectSetStateUsages.get(rootSetStateId)) === null || _a === void 0 ? void 0 : _a.add(operand.loc); + } + } + } + if (instr.value.kind === 'CallExpression' && + isSetStateType(instr.value.callee.identifier) && + instr.value.args.length === 1 && + instr.value.args[0].kind === 'Identifier') { + const calleeMetadata = context.derivationCache.cache.get(instr.value.callee.identifier.id); + if ((calleeMetadata === null || calleeMetadata === void 0 ? void 0 : calleeMetadata.typeOfValue) != 'fromState') { + continue; + } + const argMetadata = context.derivationCache.cache.get(instr.value.args[0].identifier.id); + if (argMetadata !== undefined) { + effectDerivedSetStateCalls.push({ + value: instr.value, + id: instr.value.callee.identifier.id, + sourceIds: argMetadata.sourcesIds, + typeOfValue: argMetadata.typeOfValue, + }); + } + } + else if (instr.value.kind === 'CallExpression') { + const calleeMetadata = context.derivationCache.cache.get(instr.value.callee.identifier.id); + if (calleeMetadata !== undefined && + (calleeMetadata.typeOfValue === 'fromProps' || + calleeMetadata.typeOfValue === 'fromPropsAndState')) { + return; + } + if (globals.has(instr.value.callee.identifier.id)) { + return; + } + } + else if (instr.value.kind === 'LoadGlobal') { + globals.add(instr.lvalue.identifier.id); + for (const operand of eachInstructionOperand(instr)) { + globals.add(operand.identifier.id); + } + } + } + seenBlocks.add(block.id); + } + for (const derivedSetStateCall of effectDerivedSetStateCalls) { + const rootSetStateCall = getRootSetState(derivedSetStateCall.id, context.setStateLoads); + if (rootSetStateCall !== null && + effectSetStateUsages.has(rootSetStateCall) && + context.setStateUsages.has(rootSetStateCall) && + effectSetStateUsages.get(rootSetStateCall).size === + context.setStateUsages.get(rootSetStateCall).size - 1) { + const propsSet = new Set(); + const stateSet = new Set(); + const rootNodesMap = new Map(); + for (const id of derivedSetStateCall.sourceIds) { + const nodes = buildTreeNode(id, context); + for (const node of nodes) { + if (!rootNodesMap.has(node.name)) { + rootNodesMap.set(node.name, node); + } + } + } + const rootNodes = Array.from(rootNodesMap.values()); + const trees = rootNodes.map((node, index) => renderTree(node, '', index === rootNodes.length - 1, propsSet, stateSet)); + for (const dep of derivedSetStateCall.sourceIds) { + if (cleanUpFunctionDeps !== undefined && cleanUpFunctionDeps.has(dep)) { + return; + } + } + const propsArr = Array.from(propsSet); + const stateArr = Array.from(stateSet); + let rootSources = ''; + if (propsArr.length > 0) { + rootSources += `Props: [${propsArr.join(', ')}]`; + } + if (stateArr.length > 0) { + if (rootSources) + rootSources += '\n'; + rootSources += `State: [${stateArr.join(', ')}]`; + } + const description = `Using an effect triggers an additional render which can hurt performance and user experience, potentially briefly showing stale values to the user + +This setState call is setting a derived value that depends on the following reactive sources: + +${rootSources} + +Data Flow Tree: +${trees.join('\n')} + +See: https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state`; + context.errors.pushDiagnostic(CompilerDiagnostic.create({ + description: description, + category: ErrorCategory.EffectDerivationsOfState, + reason: 'You might not need an effect. Derive values in render, not effects.', + }).withDetails({ + kind: 'error', + loc: derivedSetStateCall.value.callee.loc, + message: 'This should be computed during render, not in an effect', + })); + } + } +} + +function nameAnonymousFunctions(fn) { + if (fn.id == null) { + return; + } + const parentName = fn.id; + const functions = nameAnonymousFunctionsImpl(fn); + function visit(node, prefix) { + var _a, _b; + if (node.generatedName != null && node.fn.nameHint == null) { + const name = `${prefix}${node.generatedName}]`; + node.fn.nameHint = name; + node.fn.loweredFunc.func.nameHint = name; + } + const nextPrefix = `${prefix}${(_b = (_a = node.generatedName) !== null && _a !== void 0 ? _a : node.fn.name) !== null && _b !== void 0 ? _b : ''} > `; + for (const inner of node.inner) { + visit(inner, nextPrefix); + } + } + for (const node of functions) { + visit(node, `${parentName}[`); + } +} +function nameAnonymousFunctionsImpl(fn) { + var _a, _b; + const functions = new Map(); + const names = new Map(); + const nodes = []; + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'LoadGlobal': { + names.set(lvalue.identifier.id, value.binding.name); + break; + } + case 'LoadContext': + case 'LoadLocal': { + const name = value.place.identifier.name; + if (name != null && name.kind === 'named') { + names.set(lvalue.identifier.id, name.value); + } + const func = functions.get(value.place.identifier.id); + if (func != null) { + functions.set(lvalue.identifier.id, func); + } + break; + } + case 'PropertyLoad': { + const objectName = names.get(value.object.identifier.id); + if (objectName != null) { + names.set(lvalue.identifier.id, `${objectName}.${String(value.property)}`); + } + break; + } + case 'FunctionExpression': { + const inner = nameAnonymousFunctionsImpl(value.loweredFunc.func); + const node = { + fn: value, + generatedName: null, + inner, + }; + nodes.push(node); + if (value.name == null) { + functions.set(lvalue.identifier.id, node); + } + break; + } + case 'StoreContext': + case 'StoreLocal': { + const node = functions.get(value.value.identifier.id); + const variableName = value.lvalue.place.identifier.name; + if (node != null && + node.generatedName == null && + variableName != null && + variableName.kind === 'named') { + node.generatedName = variableName.value; + functions.delete(value.value.identifier.id); + } + break; + } + case 'CallExpression': + case 'MethodCall': { + const callee = value.kind === 'MethodCall' ? value.property : value.callee; + const hookKind = getHookKind(fn.env, callee.identifier); + let calleeName = null; + if (hookKind != null && hookKind !== 'Custom') { + calleeName = hookKind; + } + else { + calleeName = (_a = names.get(callee.identifier.id)) !== null && _a !== void 0 ? _a : '(anonymous)'; + } + let fnArgCount = 0; + for (const arg of value.args) { + if (arg.kind === 'Identifier' && functions.has(arg.identifier.id)) { + fnArgCount++; + } + } + for (let i = 0; i < value.args.length; i++) { + const arg = value.args[i]; + if (arg.kind === 'Spread') { + continue; + } + const node = functions.get(arg.identifier.id); + if (node != null && node.generatedName == null) { + const generatedName = fnArgCount > 1 ? `${calleeName}(arg${i})` : `${calleeName}()`; + node.generatedName = generatedName; + functions.delete(arg.identifier.id); + } + } + break; + } + case 'JsxExpression': { + for (const attr of value.props) { + if (attr.kind === 'JsxSpreadAttribute') { + continue; + } + const node = functions.get(attr.place.identifier.id); + if (node != null && node.generatedName == null) { + const elementName = value.tag.kind === 'BuiltinTag' + ? value.tag.name + : ((_b = names.get(value.tag.identifier.id)) !== null && _b !== void 0 ? _b : null); + const propName = elementName == null + ? attr.name + : `<${elementName}>.${attr.name}`; + node.generatedName = `${propName}`; + functions.delete(attr.place.identifier.id); + } + } + break; + } + } + } + } + return nodes; +} + +function optimizeForSSR(fn) { + const inlinedState = new Map(); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'Destructure': { + if (inlinedState.has(value.value.identifier.id) && + value.lvalue.pattern.kind === 'ArrayPattern' && + value.lvalue.pattern.items.length >= 1 && + value.lvalue.pattern.items[0].kind === 'Identifier') { + continue; + } + break; + } + case 'MethodCall': + case 'CallExpression': { + const calleee = value.kind === 'CallExpression' ? value.callee : value.property; + const hookKind = getHookKind(fn.env, calleee.identifier); + switch (hookKind) { + case 'useReducer': { + if (value.args.length === 2 && + value.args[1].kind === 'Identifier') { + const arg = value.args[1]; + const replace = { + kind: 'LoadLocal', + place: arg, + loc: arg.loc, + }; + inlinedState.set(instr.lvalue.identifier.id, replace); + } + else if (value.args.length === 3 && + value.args[1].kind === 'Identifier' && + value.args[2].kind === 'Identifier') { + const arg = value.args[1]; + const initializer = value.args[2]; + const replace = { + kind: 'CallExpression', + callee: initializer, + args: [arg], + loc: value.loc, + }; + inlinedState.set(instr.lvalue.identifier.id, replace); + } + break; + } + case 'useState': { + if (value.args.length === 1 && + value.args[0].kind === 'Identifier') { + const arg = value.args[0]; + if (isPrimitiveType(arg.identifier) || + isPlainObjectType(arg.identifier) || + isArrayType(arg.identifier)) { + const replace = { + kind: 'LoadLocal', + place: arg, + loc: arg.loc, + }; + inlinedState.set(instr.lvalue.identifier.id, replace); + } + } + break; + } + } + } + } + if (inlinedState.size !== 0) { + for (const operand of eachInstructionValueOperand(value)) { + inlinedState.delete(operand.identifier.id); + } + } + } + if (inlinedState.size !== 0) { + for (const operand of eachTerminalOperand(block.terminal)) { + inlinedState.delete(operand.identifier.id); + } + } + } + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'FunctionExpression': { + if (hasKnownNonRenderCall(value.loweredFunc.func)) { + instr.value = { + kind: 'Primitive', + value: undefined, + loc: value.loc, + }; + } + break; + } + case 'JsxExpression': { + if (value.tag.kind === 'BuiltinTag' && + value.tag.name.indexOf('-') === -1) { + const tag = value.tag.name; + retainWhere(value.props, prop => { + return (prop.kind === 'JsxSpreadAttribute' || + (!isKnownEventHandler(tag, prop.name) && prop.name !== 'ref')); + }); + } + break; + } + case 'Destructure': { + if (inlinedState.has(value.value.identifier.id)) { + CompilerError.invariant(value.lvalue.pattern.kind === 'ArrayPattern' && + value.lvalue.pattern.items.length >= 1 && + value.lvalue.pattern.items[0].kind === 'Identifier', { + reason: 'Expected a valid destructuring pattern for inlined state', + message: 'Expected a valid destructuring pattern', + loc: value.loc, + }); + const store = { + kind: 'StoreLocal', + loc: value.loc, + type: null, + lvalue: { + kind: value.lvalue.kind, + place: value.lvalue.pattern.items[0], + }, + value: value.value, + }; + instr.value = store; + } + break; + } + case 'MethodCall': + case 'CallExpression': { + const calleee = value.kind === 'CallExpression' ? value.callee : value.property; + const hookKind = getHookKind(fn.env, calleee.identifier); + switch (hookKind) { + case 'useEffectEvent': { + if (value.args.length === 1 && + value.args[0].kind === 'Identifier') { + const load = { + kind: 'LoadLocal', + place: value.args[0], + loc: value.loc, + }; + instr.value = load; + } + break; + } + case 'useEffect': + case 'useLayoutEffect': + case 'useInsertionEffect': { + instr.value = { + kind: 'Primitive', + value: undefined, + loc: value.loc, + }; + break; + } + case 'useReducer': + case 'useState': { + const replace = inlinedState.get(instr.lvalue.identifier.id); + if (replace != null) { + instr.value = replace; + } + break; + } + } + } + } + } + } +} +function hasKnownNonRenderCall(fn) { + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + if (instr.value.kind === 'CallExpression' && + (isSetStateType(instr.value.callee.identifier) || + isStartTransitionType(instr.value.callee.identifier))) { + return true; + } + } + } + return false; +} +const EVENT_HANDLER_PATTERN = /^on[A-Z]/; +function isKnownEventHandler(_tag, prop) { + return EVENT_HANDLER_PATTERN.test(prop); +} + +function validateExhaustiveDependencies(fn) { + const env = fn.env; + const reactive = collectReactiveIdentifiersHIR(fn); + const temporaries = new Map(); + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + temporaries.set(place.identifier.id, { + kind: 'Local', + identifier: place.identifier, + path: [], + context: false, + loc: place.loc, + }); + } + let startMemo = null; + function onStartMemoize(value, dependencies, locals) { + CompilerError.invariant(startMemo == null, { + reason: 'Unexpected nested memo calls', + loc: value.loc, + }); + startMemo = value; + dependencies.clear(); + locals.clear(); + } + function onFinishMemoize(value, dependencies, locals) { + var _a; + CompilerError.invariant(startMemo != null && startMemo.manualMemoId === value.manualMemoId, { + reason: 'Found FinishMemoize without corresponding StartMemoize', + loc: value.loc, + }); + if (env.config.validateExhaustiveMemoizationDependencies) { + visitCandidateDependency(value.decl, temporaries, dependencies, locals); + const inferred = Array.from(dependencies); + const diagnostic = validateDependencies(inferred, (_a = startMemo.deps) !== null && _a !== void 0 ? _a : [], reactive, startMemo.depsLoc, ErrorCategory.MemoDependencies, 'all'); + if (diagnostic != null) { + fn.env.recordError(diagnostic); + startMemo.hasInvalidDeps = true; + } + } + dependencies.clear(); + locals.clear(); + startMemo = null; + } + collectDependencies(fn, temporaries, { + onStartMemoize, + onFinishMemoize, + onEffect: (inferred, manual, manualMemoLoc) => { + if (env.config.validateExhaustiveEffectDependencies === 'off') { + return; + } + const manualDeps = []; + for (const dep of manual) { + if (dep.kind === 'Local') { + manualDeps.push({ + root: { + kind: 'NamedLocal', + constant: false, + value: { + effect: Effect.Read, + identifier: dep.identifier, + kind: 'Identifier', + loc: dep.loc, + reactive: reactive.has(dep.identifier.id), + }, + }, + path: dep.path, + loc: dep.loc, + }); + } + else { + manualDeps.push({ + root: { + kind: 'Global', + identifierName: dep.binding.name, + }, + path: [], + loc: GeneratedSource, + }); + } + } + const effectReportMode = typeof env.config.validateExhaustiveEffectDependencies === 'string' + ? env.config.validateExhaustiveEffectDependencies + : 'all'; + const diagnostic = validateDependencies(Array.from(inferred), manualDeps, reactive, manualMemoLoc, ErrorCategory.EffectExhaustiveDependencies, effectReportMode); + if (diagnostic != null) { + fn.env.recordError(diagnostic); + } + }, + }, false); +} +function validateDependencies(inferred, manualDependencies, reactive, manualMemoLoc, category, exhaustiveDepsReportMode) { + var _a, _b, _c, _d; + inferred.sort((a, b) => { + var _a, _b; + if (a.kind === 'Global' && b.kind == 'Global') { + return a.binding.name.localeCompare(b.binding.name); + } + else if (a.kind == 'Local' && b.kind == 'Local') { + CompilerError.invariant(a.identifier.name != null && + a.identifier.name.kind === 'named' && + b.identifier.name != null && + b.identifier.name.kind === 'named', { + reason: 'Expected dependencies to be named variables', + loc: a.loc, + }); + if (a.identifier.id !== b.identifier.id) { + return a.identifier.name.value.localeCompare(b.identifier.name.value); + } + if (a.path.length !== b.path.length) { + return a.path.length - b.path.length; + } + for (let i = 0; i < a.path.length; i++) { + const aProperty = a.path[i]; + const bProperty = b.path[i]; + const aOptional = aProperty.optional ? 0 : 1; + const bOptional = bProperty.optional ? 0 : 1; + if (aOptional !== bOptional) { + return aOptional - bOptional; + } + else if (aProperty.property !== bProperty.property) { + return String(aProperty.property).localeCompare(String(bProperty.property)); + } + } + return 0; + } + else { + const aName = a.kind === 'Global' ? a.binding.name : (_a = a.identifier.name) === null || _a === void 0 ? void 0 : _a.value; + const bName = b.kind === 'Global' ? b.binding.name : (_b = b.identifier.name) === null || _b === void 0 ? void 0 : _b.value; + if (aName != null && bName != null) { + return aName.localeCompare(bName); + } + return 0; + } + }); + retainWhere(inferred, (dep, ix) => { + const match = inferred.findIndex(prevDep => { + return (isEqualTemporary(prevDep, dep) || + (prevDep.kind === 'Local' && + dep.kind === 'Local' && + prevDep.identifier.id === dep.identifier.id && + isSubPath(prevDep.path, dep.path))); + }); + return match === -1 || match >= ix; + }); + const matched = new Set(); + const missing = []; + const extra = []; + for (const inferredDependency of inferred) { + if (inferredDependency.kind === 'Global') { + for (const manualDependency of manualDependencies) { + if (manualDependency.root.kind === 'Global' && + manualDependency.root.identifierName === + inferredDependency.binding.name) { + matched.add(manualDependency); + extra.push(manualDependency); + } + } + continue; + } + CompilerError.invariant(inferredDependency.kind === 'Local', { + reason: 'Unexpected function dependency', + loc: inferredDependency.loc, + }); + if (isEffectEventFunctionType(inferredDependency.identifier)) { + continue; + } + let hasMatchingManualDependency = false; + for (const manualDependency of manualDependencies) { + if (manualDependency.root.kind === 'NamedLocal' && + manualDependency.root.value.identifier.id === + inferredDependency.identifier.id && + (areEqualPaths(manualDependency.path, inferredDependency.path) || + isSubPathIgnoringOptionals(manualDependency.path, inferredDependency.path))) { + hasMatchingManualDependency = true; + matched.add(manualDependency); + } + } + if (hasMatchingManualDependency || + isOptionalDependency(inferredDependency, reactive)) { + continue; + } + missing.push(inferredDependency); + } + for (const dep of manualDependencies) { + if (matched.has(dep)) { + continue; + } + if (dep.root.kind === 'NamedLocal' && dep.root.constant) { + CompilerError.invariant(!dep.root.value.reactive && isPrimitiveType(dep.root.value.identifier), { + reason: 'Expected constant-folded dependency to be non-reactive', + loc: dep.root.value.loc, + }); + continue; + } + extra.push(dep); + } + const filteredMissing = exhaustiveDepsReportMode === 'extra-only' ? [] : missing; + const filteredExtra = exhaustiveDepsReportMode === 'missing-only' ? [] : extra; + if (filteredMissing.length !== 0 || filteredExtra.length !== 0) { + let suggestion = null; + if (manualMemoLoc != null && + typeof manualMemoLoc !== 'symbol' && + manualMemoLoc.start.index != null && + manualMemoLoc.end.index != null) { + suggestion = { + description: 'Update dependencies', + range: [manualMemoLoc.start.index, manualMemoLoc.end.index], + op: CompilerSuggestionOperation.Replace, + text: `[${inferred + .filter(dep => dep.kind === 'Local' && + !isOptionalDependency(dep, reactive) && + !isEffectEventFunctionType(dep.identifier)) + .map(printInferredDependency) + .join(', ')}]`, + }; + } + const diagnostic = createDiagnostic(category, filteredMissing, filteredExtra, suggestion); + for (const dep of filteredMissing) { + let reactiveStableValueHint = ''; + if (isStableType(dep.identifier)) { + reactiveStableValueHint = + '. Refs, setState functions, and other "stable" values generally do not need to be added ' + + 'as dependencies, but this variable may change over time to point to different values'; + } + diagnostic.withDetails({ + kind: 'error', + message: `Missing dependency \`${printInferredDependency(dep)}\`${reactiveStableValueHint}`, + loc: dep.loc, + }); + } + for (const dep of filteredExtra) { + if (dep.root.kind === 'Global') { + diagnostic.withDetails({ + kind: 'error', + message: `Unnecessary dependency \`${printManualMemoDependency(dep)}\`. ` + + 'Values declared outside of a component/hook should not be listed as ' + + 'dependencies as the component will not re-render if they change', + loc: (_a = dep.loc) !== null && _a !== void 0 ? _a : manualMemoLoc, + }); + } + else { + const root = dep.root.value; + const matchingInferred = inferred.find((inferredDep) => { + return (inferredDep.kind === 'Local' && + inferredDep.identifier.id === root.identifier.id && + isSubPathIgnoringOptionals(inferredDep.path, dep.path)); + }); + if (matchingInferred != null && + isEffectEventFunctionType(matchingInferred.identifier)) { + diagnostic.withDetails({ + kind: 'error', + message: `Functions returned from \`useEffectEvent\` must not be included in the dependency array. ` + + `Remove \`${printManualMemoDependency(dep)}\` from the dependencies.`, + loc: (_b = dep.loc) !== null && _b !== void 0 ? _b : manualMemoLoc, + }); + } + else if (matchingInferred != null && + !isOptionalDependency(matchingInferred, reactive)) { + diagnostic.withDetails({ + kind: 'error', + message: `Overly precise dependency \`${printManualMemoDependency(dep)}\`, ` + + `use \`${printInferredDependency(matchingInferred)}\` instead`, + loc: (_c = dep.loc) !== null && _c !== void 0 ? _c : manualMemoLoc, + }); + } + else { + diagnostic.withDetails({ + kind: 'error', + message: `Unnecessary dependency \`${printManualMemoDependency(dep)}\``, + loc: (_d = dep.loc) !== null && _d !== void 0 ? _d : manualMemoLoc, + }); + } + } + } + if (suggestion != null) { + diagnostic.withDetails({ + kind: 'hint', + message: `Inferred dependencies: \`${suggestion.text}\``, + }); + } + return diagnostic; + } + return null; +} +function addDependency(dep, dependencies, locals) { + if (dep.kind === 'Aggregate') { + for (const x of dep.dependencies) { + addDependency(x, dependencies, locals); + } + } + else if (dep.kind === 'Global') { + dependencies.add(dep); + } + else if (!locals.has(dep.identifier.id)) { + dependencies.add(dep); + } +} +function visitCandidateDependency(place, temporaries, dependencies, locals) { + const dep = temporaries.get(place.identifier.id); + if (dep != null) { + addDependency(dep, dependencies, locals); + } +} +function collectDependencies(fn, temporaries, callbacks, isFunctionExpression) { + var _a, _b; + const optionals = findOptionalPlaces(fn); + const locals = new Set(); + if (isFunctionExpression) { + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + locals.add(place.identifier.id); + } + } + const dependencies = new Set(); + function visit(place) { + visitCandidateDependency(place, temporaries, dependencies, locals); + } + for (const block of fn.body.blocks.values()) { + for (const phi of block.phis) { + const deps = []; + for (const operand of phi.operands.values()) { + const dep = temporaries.get(operand.identifier.id); + if (dep == null) { + continue; + } + if (dep.kind === 'Aggregate') { + deps.push(...dep.dependencies); + } + else { + deps.push(dep); + } + } + if (deps.length === 0) { + continue; + } + else if (deps.length === 1) { + temporaries.set(phi.place.identifier.id, deps[0]); + } + else { + temporaries.set(phi.place.identifier.id, { + kind: 'Aggregate', + dependencies: new Set(deps), + }); + } + } + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'LoadGlobal': { + temporaries.set(lvalue.identifier.id, { + kind: 'Global', + binding: value.binding, + }); + break; + } + case 'LoadContext': + case 'LoadLocal': { + const temp = temporaries.get(value.place.identifier.id); + if (temp != null) { + if (temp.kind === 'Local') { + const local = Object.assign(Object.assign({}, temp), { loc: value.place.loc }); + temporaries.set(lvalue.identifier.id, local); + } + else { + temporaries.set(lvalue.identifier.id, temp); + } + if (locals.has(value.place.identifier.id)) { + locals.add(lvalue.identifier.id); + } + } + break; + } + case 'DeclareLocal': { + const local = { + kind: 'Local', + identifier: value.lvalue.place.identifier, + path: [], + context: false, + loc: value.lvalue.place.loc, + }; + temporaries.set(value.lvalue.place.identifier.id, local); + locals.add(value.lvalue.place.identifier.id); + break; + } + case 'StoreLocal': { + if (value.lvalue.place.identifier.name == null) { + const temp = temporaries.get(value.value.identifier.id); + if (temp != null) { + temporaries.set(value.lvalue.place.identifier.id, temp); + } + break; + } + visit(value.value); + if (value.lvalue.kind !== InstructionKind.Reassign) { + const local = { + kind: 'Local', + identifier: value.lvalue.place.identifier, + path: [], + context: false, + loc: value.lvalue.place.loc, + }; + temporaries.set(value.lvalue.place.identifier.id, local); + locals.add(value.lvalue.place.identifier.id); + } + break; + } + case 'DeclareContext': { + const local = { + kind: 'Local', + identifier: value.lvalue.place.identifier, + path: [], + context: true, + loc: value.lvalue.place.loc, + }; + temporaries.set(value.lvalue.place.identifier.id, local); + break; + } + case 'StoreContext': { + visit(value.value); + if (value.lvalue.kind !== InstructionKind.Reassign) { + const local = { + kind: 'Local', + identifier: value.lvalue.place.identifier, + path: [], + context: true, + loc: value.lvalue.place.loc, + }; + temporaries.set(value.lvalue.place.identifier.id, local); + locals.add(value.lvalue.place.identifier.id); + } + break; + } + case 'Destructure': { + visit(value.value); + if (value.lvalue.kind !== InstructionKind.Reassign) { + for (const lvalue of eachInstructionValueLValue(value)) { + const local = { + kind: 'Local', + identifier: lvalue.identifier, + path: [], + context: false, + loc: lvalue.loc, + }; + temporaries.set(lvalue.identifier.id, local); + locals.add(lvalue.identifier.id); + } + } + break; + } + case 'PropertyLoad': { + if (typeof value.property === 'number' || + (isUseRefType(value.object.identifier) && + value.property === 'current')) { + visit(value.object); + break; + } + const object = temporaries.get(value.object.identifier.id); + if (object != null && object.kind === 'Local') { + const optional = (_a = optionals.get(value.object.identifier.id)) !== null && _a !== void 0 ? _a : false; + const local = { + kind: 'Local', + identifier: object.identifier, + context: object.context, + path: [ + ...object.path, + { + optional, + property: value.property, + loc: value.loc, + }, + ], + loc: value.loc, + }; + temporaries.set(lvalue.identifier.id, local); + } + break; + } + case 'FunctionExpression': + case 'ObjectMethod': { + const functionDeps = collectDependencies(value.loweredFunc.func, temporaries, null, true); + temporaries.set(lvalue.identifier.id, functionDeps); + addDependency(functionDeps, dependencies, locals); + break; + } + case 'StartMemoize': { + const onStartMemoize = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onStartMemoize; + if (onStartMemoize != null) { + onStartMemoize(value, dependencies, locals); + } + break; + } + case 'FinishMemoize': { + const onFinishMemoize = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onFinishMemoize; + if (onFinishMemoize != null) { + onFinishMemoize(value, dependencies, locals); + } + break; + } + case 'ArrayExpression': { + const arrayDeps = new Set(); + for (const item of value.elements) { + if (item.kind === 'Hole') { + continue; + } + const place = item.kind === 'Identifier' ? item : item.place; + visitCandidateDependency(place, temporaries, arrayDeps, new Set()); + visit(place); + } + temporaries.set(lvalue.identifier.id, { + kind: 'Aggregate', + dependencies: arrayDeps, + loc: value.loc, + }); + break; + } + case 'CallExpression': + case 'MethodCall': { + const receiver = value.kind === 'CallExpression' ? value.callee : value.property; + const onEffect = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onEffect; + if (onEffect != null && isEffectHook(receiver.identifier)) { + const [fn, deps] = value.args; + if ((fn === null || fn === void 0 ? void 0 : fn.kind) === 'Identifier' && (deps === null || deps === void 0 ? void 0 : deps.kind) === 'Identifier') { + const fnDeps = temporaries.get(fn.identifier.id); + const manualDeps = temporaries.get(deps.identifier.id); + if ((fnDeps === null || fnDeps === void 0 ? void 0 : fnDeps.kind) === 'Aggregate' && + (manualDeps === null || manualDeps === void 0 ? void 0 : manualDeps.kind) === 'Aggregate') { + onEffect(fnDeps.dependencies, manualDeps.dependencies, (_b = manualDeps.loc) !== null && _b !== void 0 ? _b : null); + } + } + } + for (const operand of eachInstructionValueOperand(value)) { + if (value.kind === 'MethodCall' && + operand.identifier.id === value.property.identifier.id) { + continue; + } + visit(operand); + } + break; + } + default: { + for (const operand of eachInstructionValueOperand(value)) { + visit(operand); + } + for (const lvalue of eachInstructionLValue(instr)) { + locals.add(lvalue.identifier.id); + } + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + if (optionals.has(operand.identifier.id)) { + continue; + } + visit(operand); + } + } + return { kind: 'Aggregate', dependencies }; +} +function printInferredDependency(dep) { + switch (dep.kind) { + case 'Global': { + return dep.binding.name; + } + case 'Local': { + CompilerError.invariant(dep.identifier.name != null && dep.identifier.name.kind === 'named', { + reason: 'Expected dependencies to be named variables', + loc: dep.loc, + }); + return `${dep.identifier.name.value}${dep.path.map(p => (p.optional ? '?' : '') + '.' + p.property).join('')}`; + } + } +} +function printManualMemoDependency(dep) { + let identifierName; + if (dep.root.kind === 'Global') { + identifierName = dep.root.identifierName; + } + else { + const name = dep.root.value.identifier.name; + CompilerError.invariant(name != null && name.kind === 'named', { + reason: 'Expected manual dependencies to be named variables', + loc: dep.root.value.loc, + }); + identifierName = name.value; + } + return `${identifierName}${dep.path.map(p => (p.optional ? '?' : '') + '.' + p.property).join('')}`; +} +function isEqualTemporary(a, b) { + switch (a.kind) { + case 'Aggregate': { + return false; + } + case 'Global': { + return b.kind === 'Global' && a.binding.name === b.binding.name; + } + case 'Local': { + return (b.kind === 'Local' && + a.identifier.id === b.identifier.id && + areEqualPaths(a.path, b.path)); + } + } +} +function collectReactiveIdentifiersHIR(fn) { + const reactive = new Set(); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + for (const lvalue of eachInstructionLValue(instr)) { + if (lvalue.reactive) { + reactive.add(lvalue.identifier.id); + } + } + for (const operand of eachInstructionValueOperand(instr.value)) { + if (operand.reactive) { + reactive.add(operand.identifier.id); + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + if (operand.reactive) { + reactive.add(operand.identifier.id); + } + } + } + return reactive; +} +function findOptionalPlaces(fn) { + const optionals = new Map(); + const visited = new Set(); + for (const [, block] of fn.body.blocks) { + if (visited.has(block.id)) { + continue; + } + if (block.terminal.kind === 'optional') { + visited.add(block.id); + const optionalTerminal = block.terminal; + let testBlock = fn.body.blocks.get(block.terminal.test); + const queue = [block.terminal.optional]; + loop: while (true) { + visited.add(testBlock.id); + const terminal = testBlock.terminal; + switch (terminal.kind) { + case 'branch': { + const isOptional = queue.pop(); + CompilerError.invariant(isOptional !== undefined, { + reason: 'Expected an optional value for each optional test condition', + loc: terminal.test.loc, + }); + if (isOptional != null) { + optionals.set(terminal.test.identifier.id, isOptional); + } + if (terminal.fallthrough === optionalTerminal.fallthrough) { + const consequent = fn.body.blocks.get(terminal.consequent); + const last = consequent.instructions.at(-1); + if (last !== undefined && last.value.kind === 'StoreLocal') { + if (isOptional != null) { + optionals.set(last.value.value.identifier.id, isOptional); + } + } + break loop; + } + else { + testBlock = fn.body.blocks.get(terminal.fallthrough); + } + break; + } + case 'optional': { + queue.push(terminal.optional); + testBlock = fn.body.blocks.get(terminal.test); + break; + } + case 'logical': + case 'ternary': { + queue.push(null); + testBlock = fn.body.blocks.get(terminal.test); + break; + } + case 'sequence': { + testBlock = fn.body.blocks.get(terminal.block); + break; + } + case 'maybe-throw': { + testBlock = fn.body.blocks.get(terminal.continuation); + break; + } + default: { + CompilerError.invariant(false, { + reason: `Unexpected terminal in optional`, + message: `Unexpected ${terminal.kind} in optional`, + loc: terminal.loc, + }); + } + } + } + CompilerError.invariant(queue.length === 0, { + reason: 'Expected a matching number of conditional blocks and branch points', + loc: block.terminal.loc, + }); + } + } + return optionals; +} +function isOptionalDependency(inferredDependency, reactive) { + return (!reactive.has(inferredDependency.identifier.id) && + (isStableType(inferredDependency.identifier) || + isPrimitiveType(inferredDependency.identifier))); +} +function createDiagnostic(category, missing, extra, suggestion) { + let reason; + let description; + function joinMissingExtraDetail(missingString, extraString, joinStr) { + return [ + missing.length !== 0 ? missingString : null, + extra.length !== 0 ? extraString : null, + ] + .filter(Boolean) + .join(joinStr); + } + switch (category) { + case ErrorCategory.MemoDependencies: { + reason = `Found ${joinMissingExtraDetail('missing', 'extra', '/')} memoization dependencies`; + description = joinMissingExtraDetail('Missing dependencies can cause a value to update less often than it should, resulting in stale UI', 'Extra dependencies can cause a value to update more often than it should, resulting in performance' + + ' problems such as excessive renders or effects firing too often', '. '); + break; + } + case ErrorCategory.EffectExhaustiveDependencies: { + reason = `Found ${joinMissingExtraDetail('missing', 'extra', '/')} effect dependencies`; + description = joinMissingExtraDetail('Missing dependencies can cause an effect to fire less often than it should', 'Extra dependencies can cause an effect to fire more often than it should, resulting' + + ' in performance problems such as excessive renders and side effects', '. '); + break; + } + default: { + CompilerError.invariant(false, { + reason: `Unexpected error category: ${category}`, + loc: GeneratedSource, + }); + } + } + return CompilerDiagnostic.create({ + category, + reason, + description, + suggestions: suggestion != null ? [suggestion] : null, + }); +} +function isEffectHook(identifier) { + return (isUseEffectHookType(identifier) || + isUseLayoutEffectHookType(identifier) || + isUseInsertionEffectHookType(identifier)); +} + +function run(func, config, fnType, mode, programContext, logger, filename, code) { + var _a, _b; + const contextIdentifiers = findContextIdentifiers(func); + const env = new Environment(func.scope, fnType, mode, config, contextIdentifiers, func, logger, filename, code, programContext); + (_b = (_a = env.logger) === null || _a === void 0 ? void 0 : _a.debugLogIRs) === null || _b === void 0 ? void 0 : _b.call(_a, { + kind: 'debug', + name: 'EnvironmentConfig', + value: prettyFormat(env.config), + }); + return runWithEnvironment(func, env); +} +function runWithEnvironment(func, env) { + const log = (value) => { + var _a, _b; + (_b = (_a = env.logger) === null || _a === void 0 ? void 0 : _a.debugLogIRs) === null || _b === void 0 ? void 0 : _b.call(_a, value); + }; + const hir = lower(func, env); + log({ kind: 'hir', name: 'HIR', value: hir }); + pruneMaybeThrows(hir); + log({ kind: 'hir', name: 'PruneMaybeThrows', value: hir }); + validateContextVariableLValues(hir); + validateUseMemo(hir); + if (env.enableDropManualMemoization) { + dropManualMemoization(hir); + log({ kind: 'hir', name: 'DropManualMemoization', value: hir }); + } + inlineImmediatelyInvokedFunctionExpressions(hir); + log({ + kind: 'hir', + name: 'InlineImmediatelyInvokedFunctionExpressions', + value: hir, + }); + mergeConsecutiveBlocks(hir); + log({ kind: 'hir', name: 'MergeConsecutiveBlocks', value: hir }); + assertConsistentIdentifiers(hir); + assertTerminalSuccessorsExist(hir); + enterSSA(hir); + log({ kind: 'hir', name: 'SSA', value: hir }); + eliminateRedundantPhi(hir); + log({ kind: 'hir', name: 'EliminateRedundantPhi', value: hir }); + assertConsistentIdentifiers(hir); + constantPropagation(hir); + log({ kind: 'hir', name: 'ConstantPropagation', value: hir }); + inferTypes(hir); + log({ kind: 'hir', name: 'InferTypes', value: hir }); + if (env.enableValidations) { + if (env.config.validateHooksUsage) { + validateHooksUsage(hir); + } + if (env.config.validateNoCapitalizedCalls) { + validateNoCapitalizedCalls(hir); + } + } + optimizePropsMethodCalls(hir); + log({ kind: 'hir', name: 'OptimizePropsMethodCalls', value: hir }); + analyseFunctions(hir); + log({ kind: 'hir', name: 'AnalyseFunctions', value: hir }); + inferMutationAliasingEffects(hir); + log({ kind: 'hir', name: 'InferMutationAliasingEffects', value: hir }); + if (env.outputMode === 'ssr') { + optimizeForSSR(hir); + log({ kind: 'hir', name: 'OptimizeForSSR', value: hir }); + } + deadCodeElimination(hir); + log({ kind: 'hir', name: 'DeadCodeElimination', value: hir }); + pruneMaybeThrows(hir); + log({ kind: 'hir', name: 'PruneMaybeThrows', value: hir }); + inferMutationAliasingRanges(hir, { + isFunctionExpression: false, + }); + log({ kind: 'hir', name: 'InferMutationAliasingRanges', value: hir }); + if (env.enableValidations) { + validateLocalsNotReassignedAfterRender(hir); + if (env.config.assertValidMutableRanges) { + assertValidMutableRanges(hir); + } + if (env.config.validateRefAccessDuringRender) { + validateNoRefAccessInRender(hir); + } + if (env.config.validateNoSetStateInRender) { + validateNoSetStateInRender(hir); + } + if (env.config.validateNoDerivedComputationsInEffects_exp && + env.outputMode === 'lint') { + env.logErrors(validateNoDerivedComputationsInEffects_exp(hir)); + } + else if (env.config.validateNoDerivedComputationsInEffects) { + validateNoDerivedComputationsInEffects(hir); + } + if (env.config.validateNoSetStateInEffects && env.outputMode === 'lint') { + env.logErrors(validateNoSetStateInEffects(hir, env)); + } + if (env.config.validateNoJSXInTryStatements && env.outputMode === 'lint') { + env.logErrors(validateNoJSXInTryStatement(hir)); + } + validateNoFreezingKnownMutableFunctions(hir); + } + inferReactivePlaces(hir); + log({ kind: 'hir', name: 'InferReactivePlaces', value: hir }); + if (env.enableValidations) { + if (env.config.validateExhaustiveMemoizationDependencies || + env.config.validateExhaustiveEffectDependencies) { + validateExhaustiveDependencies(hir); + } + } + rewriteInstructionKindsBasedOnReassignment(hir); + log({ + kind: 'hir', + name: 'RewriteInstructionKindsBasedOnReassignment', + value: hir, + }); + if (env.enableValidations && + env.config.validateStaticComponents && + env.outputMode === 'lint') { + env.logErrors(validateStaticComponents(hir)); + } + if (env.enableMemoization) { + inferReactiveScopeVariables(hir); + log({ kind: 'hir', name: 'InferReactiveScopeVariables', value: hir }); + } + const fbtOperands = memoizeFbtAndMacroOperandsInSameScope(hir); + log({ + kind: 'hir', + name: 'MemoizeFbtAndMacroOperandsInSameScope', + value: hir, + }); + if (env.config.enableJsxOutlining) { + outlineJSX(hir); + } + if (env.config.enableNameAnonymousFunctions) { + nameAnonymousFunctions(hir); + log({ + kind: 'hir', + name: 'NameAnonymousFunctions', + value: hir, + }); + } + if (env.config.enableFunctionOutlining) { + outlineFunctions(hir, fbtOperands); + log({ kind: 'hir', name: 'OutlineFunctions', value: hir }); + } + alignMethodCallScopes(hir); + log({ + kind: 'hir', + name: 'AlignMethodCallScopes', + value: hir, + }); + alignObjectMethodScopes(hir); + log({ + kind: 'hir', + name: 'AlignObjectMethodScopes', + value: hir, + }); + pruneUnusedLabelsHIR(hir); + log({ + kind: 'hir', + name: 'PruneUnusedLabelsHIR', + value: hir, + }); + alignReactiveScopesToBlockScopesHIR(hir); + log({ + kind: 'hir', + name: 'AlignReactiveScopesToBlockScopesHIR', + value: hir, + }); + mergeOverlappingReactiveScopesHIR(hir); + log({ + kind: 'hir', + name: 'MergeOverlappingReactiveScopesHIR', + value: hir, + }); + assertValidBlockNesting(hir); + buildReactiveScopeTerminalsHIR(hir); + log({ + kind: 'hir', + name: 'BuildReactiveScopeTerminalsHIR', + value: hir, + }); + assertValidBlockNesting(hir); + flattenReactiveLoopsHIR(hir); + log({ + kind: 'hir', + name: 'FlattenReactiveLoopsHIR', + value: hir, + }); + flattenScopesWithHooksOrUseHIR(hir); + log({ + kind: 'hir', + name: 'FlattenScopesWithHooksOrUseHIR', + value: hir, + }); + assertTerminalSuccessorsExist(hir); + assertTerminalPredsExist(hir); + propagateScopeDependenciesHIR(hir); + log({ + kind: 'hir', + name: 'PropagateScopeDependenciesHIR', + value: hir, + }); + const reactiveFunction = buildReactiveFunction(hir); + log({ + kind: 'reactive', + name: 'BuildReactiveFunction', + value: reactiveFunction, + }); + assertWellFormedBreakTargets(reactiveFunction); + pruneUnusedLabels(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneUnusedLabels', + value: reactiveFunction, + }); + assertScopeInstructionsWithinScopes(reactiveFunction); + pruneNonEscapingScopes(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneNonEscapingScopes', + value: reactiveFunction, + }); + pruneNonReactiveDependencies(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneNonReactiveDependencies', + value: reactiveFunction, + }); + pruneUnusedScopes(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneUnusedScopes', + value: reactiveFunction, + }); + mergeReactiveScopesThatInvalidateTogether(reactiveFunction); + log({ + kind: 'reactive', + name: 'MergeReactiveScopesThatInvalidateTogether', + value: reactiveFunction, + }); + pruneAlwaysInvalidatingScopes(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneAlwaysInvalidatingScopes', + value: reactiveFunction, + }); + propagateEarlyReturns(reactiveFunction); + log({ + kind: 'reactive', + name: 'PropagateEarlyReturns', + value: reactiveFunction, + }); + pruneUnusedLValues(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneUnusedLValues', + value: reactiveFunction, + }); + promoteUsedTemporaries(reactiveFunction); + log({ + kind: 'reactive', + name: 'PromoteUsedTemporaries', + value: reactiveFunction, + }); + extractScopeDeclarationsFromDestructuring(reactiveFunction); + log({ + kind: 'reactive', + name: 'ExtractScopeDeclarationsFromDestructuring', + value: reactiveFunction, + }); + stabilizeBlockIds(reactiveFunction); + log({ + kind: 'reactive', + name: 'StabilizeBlockIds', + value: reactiveFunction, + }); + const uniqueIdentifiers = renameVariables(reactiveFunction); + log({ + kind: 'reactive', + name: 'RenameVariables', + value: reactiveFunction, + }); + pruneHoistedContexts(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneHoistedContexts', + value: reactiveFunction, + }); + if (env.config.enablePreserveExistingMemoizationGuarantees || + env.config.validatePreserveExistingMemoizationGuarantees) { + validatePreservedManualMemoization(reactiveFunction); + } + const ast = codegenFunction(reactiveFunction, { + uniqueIdentifiers, + fbtOperands, + }); + log({ kind: 'ast', name: 'Codegen', value: ast }); + for (const outlined of ast.outlined) { + log({ kind: 'ast', name: 'Codegen (outlined)', value: outlined.fn }); + } + if (env.config.validateSourceLocations) { + validateSourceLocations(func, ast, env); + } + if (env.config.throwUnknownException__testonly) { + throw new Error('unexpected error'); + } + if (env.hasErrors()) { + return Err(env.aggregateErrors()); + } + return Ok(ast); +} +function compileFn(func, config, fnType, mode, programContext, logger, filename, code) { + return run(func, config, fnType, mode, programContext, logger, filename, code); +} + +function filterSuppressionsThatAffectFunction(suppressionRanges, fn) { + const suppressionsInScope = []; + const fnNode = fn.node; + for (const suppressionRange of suppressionRanges) { + if (suppressionRange.disableComment.start == null || + fnNode.start == null || + fnNode.end == null) { + continue; + } + if (suppressionRange.disableComment.start > fnNode.start && + (suppressionRange.enableComment === null || + (suppressionRange.enableComment.end != null && + suppressionRange.enableComment.end < fnNode.end))) { + suppressionsInScope.push(suppressionRange); + } + if (suppressionRange.disableComment.start < fnNode.start && + (suppressionRange.enableComment === null || + (suppressionRange.enableComment.end != null && + suppressionRange.enableComment.end > fnNode.end))) { + suppressionsInScope.push(suppressionRange); + } + } + return suppressionsInScope; +} +function findProgramSuppressions(programComments, ruleNames, flowSuppressions) { + const suppressionRanges = []; + let disableComment = null; + let enableComment = null; + let source = null; + let disableNextLinePattern = null; + let disablePattern = null; + let enablePattern = null; + if (ruleNames != null && ruleNames.length !== 0) { + const rulePattern = `(${ruleNames.join('|')})`; + disableNextLinePattern = new RegExp(`eslint-disable-next-line ${rulePattern}`); + disablePattern = new RegExp(`eslint-disable ${rulePattern}`); + enablePattern = new RegExp(`eslint-enable ${rulePattern}`); + } + const flowSuppressionPattern = new RegExp('\\$(FlowFixMe\\w*|FlowExpectedError|FlowIssue)\\[react\\-rule'); + for (const comment of programComments) { + if (comment.start == null || comment.end == null) { + continue; + } + if (disableComment == null && + disableNextLinePattern != null && + disableNextLinePattern.test(comment.value)) { + disableComment = comment; + enableComment = comment; + source = 'Eslint'; + } + if (flowSuppressions && + disableComment == null && + flowSuppressionPattern.test(comment.value)) { + disableComment = comment; + enableComment = comment; + source = 'Flow'; + } + if (disablePattern != null && disablePattern.test(comment.value)) { + disableComment = comment; + source = 'Eslint'; + } + if (enablePattern != null && + enablePattern.test(comment.value) && + source === 'Eslint') { + enableComment = comment; + } + if (disableComment != null && source != null) { + suppressionRanges.push({ + disableComment: disableComment, + enableComment: enableComment, + source, + }); + disableComment = null; + enableComment = null; + source = null; + } + } + return suppressionRanges; +} +function suppressionsToCompilerError(suppressionRanges) { + var _a; + CompilerError.invariant(suppressionRanges.length !== 0, { + reason: `Expected at least suppression comment source range`, + loc: GeneratedSource, + }); + const error = new CompilerError(); + for (const suppressionRange of suppressionRanges) { + if (suppressionRange.disableComment.start == null || + suppressionRange.disableComment.end == null) { + continue; + } + let reason, suggestion; + switch (suppressionRange.source) { + case 'Eslint': + reason = + 'React Compiler has skipped optimizing this component because one or more React ESLint rules were disabled'; + suggestion = + 'Remove the ESLint suppression and address the React error'; + break; + case 'Flow': + reason = + 'React Compiler has skipped optimizing this component because one or more React rule violations were reported by Flow'; + suggestion = 'Remove the Flow suppression and address the React error'; + break; + default: + assertExhaustive$1(suppressionRange.source, 'Unhandled suppression source'); + } + error.pushDiagnostic(CompilerDiagnostic.create({ + reason: reason, + description: `React Compiler only works when your components follow all the rules of React, disabling them may result in unexpected or incorrect behavior. Found suppression \`${suppressionRange.disableComment.value.trim()}\``, + category: ErrorCategory.Suppression, + suggestions: [ + { + description: suggestion, + range: [ + suppressionRange.disableComment.start, + suppressionRange.disableComment.end, + ], + op: CompilerSuggestionOperation.Remove, + }, + ], + }).withDetails({ + kind: 'error', + loc: (_a = suppressionRange.disableComment.loc) !== null && _a !== void 0 ? _a : null, + message: 'Found React rule suppression', + })); + } + return error; +} + +const OPT_IN_DIRECTIVES = new Set(['use forget', 'use memo']); +const OPT_OUT_DIRECTIVES = new Set(['use no forget', 'use no memo']); +const DYNAMIC_GATING_DIRECTIVE = new RegExp('^use memo if\\(([^\\)]*)\\)$'); +function tryFindDirectiveEnablingMemoization(directives, opts) { + var _a, _b; + const optIn = directives.find(directive => OPT_IN_DIRECTIVES.has(directive.value.value)); + if (optIn != null) { + return Ok(optIn); + } + const dynamicGating = findDirectivesDynamicGating(directives, opts); + if (dynamicGating.isOk()) { + return Ok((_b = (_a = dynamicGating.unwrap()) === null || _a === void 0 ? void 0 : _a.directive) !== null && _b !== void 0 ? _b : null); + } + else { + return Err(dynamicGating.unwrapErr()); + } +} +function findDirectiveDisablingMemoization(directives, { customOptOutDirectives }) { + var _a, _b; + if (customOptOutDirectives != null) { + return ((_a = directives.find(directive => customOptOutDirectives.indexOf(directive.value.value) !== -1)) !== null && _a !== void 0 ? _a : null); + } + return ((_b = directives.find(directive => OPT_OUT_DIRECTIVES.has(directive.value.value))) !== null && _b !== void 0 ? _b : null); +} +function findDirectivesDynamicGating(directives, opts) { + var _a, _b; + if (opts.dynamicGating === null) { + return Ok(null); + } + const errors = new CompilerError(); + const result = []; + for (const directive of directives) { + const maybeMatch = DYNAMIC_GATING_DIRECTIVE.exec(directive.value.value); + if (maybeMatch != null && maybeMatch[1] != null) { + if (libExports$1.isValidIdentifier(maybeMatch[1])) { + result.push({ directive, match: maybeMatch[1] }); + } + else { + errors.push({ + reason: `Dynamic gating directive is not a valid JavaScript identifier`, + description: `Found '${directive.value.value}'`, + category: ErrorCategory.Gating, + loc: (_a = directive.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + }); + } + } + } + if (errors.hasAnyErrors()) { + return Err(errors); + } + else if (result.length > 1) { + const error = new CompilerError(); + error.push({ + reason: `Multiple dynamic gating directives found`, + description: `Expected a single directive but found [${result + .map(r => r.directive.value.value) + .join(', ')}]`, + category: ErrorCategory.Gating, + loc: (_b = result[0].directive.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + }); + return Err(error); + } + else if (result.length === 1) { + return Ok({ + gating: { + source: opts.dynamicGating.source, + importSpecifierName: result[0].match, + }, + directive: result[0].directive, + }); + } + else { + return Ok(null); + } +} +function isError(err) { + return !(err instanceof CompilerError) || err.hasErrors(); +} +function isConfigError(err) { + if (err instanceof CompilerError) { + return err.details.some(detail => detail.category === ErrorCategory.Config); + } + return false; +} +function logError(err, context, fnLoc) { + var _a, _b; + if (context.opts.logger) { + if (err instanceof CompilerError) { + for (const detail of err.details) { + context.opts.logger.logEvent(context.filename, { + kind: 'CompileError', + fnLoc, + detail, + }); + } + } + else { + let stringifiedError; + if (err instanceof Error) { + stringifiedError = (_a = err.stack) !== null && _a !== void 0 ? _a : err.message; + } + else { + stringifiedError = (_b = err === null || err === void 0 ? void 0 : err.toString()) !== null && _b !== void 0 ? _b : '[ null ]'; + } + context.opts.logger.logEvent(context.filename, { + kind: 'PipelineError', + fnLoc, + data: stringifiedError, + }); + } + } +} +function handleError(err, context, fnLoc) { + logError(err, context, fnLoc); + if (context.opts.panicThreshold === 'all_errors' || + (context.opts.panicThreshold === 'critical_errors' && isError(err)) || + isConfigError(err)) { + throw err; + } +} +function createNewFunctionNode(originalFn, compiledFn) { + var _a, _b, _c; + let transformedFn; + switch (originalFn.node.type) { + case 'FunctionDeclaration': { + const fn = { + type: 'FunctionDeclaration', + id: compiledFn.id, + loc: (_a = originalFn.node.loc) !== null && _a !== void 0 ? _a : null, + async: compiledFn.async, + generator: compiledFn.generator, + params: compiledFn.params, + body: compiledFn.body, + }; + transformedFn = fn; + break; + } + case 'ArrowFunctionExpression': { + const fn = { + type: 'ArrowFunctionExpression', + loc: (_b = originalFn.node.loc) !== null && _b !== void 0 ? _b : null, + async: compiledFn.async, + generator: compiledFn.generator, + params: compiledFn.params, + expression: originalFn.node.expression, + body: compiledFn.body, + }; + transformedFn = fn; + break; + } + case 'FunctionExpression': { + const fn = { + type: 'FunctionExpression', + id: compiledFn.id, + loc: (_c = originalFn.node.loc) !== null && _c !== void 0 ? _c : null, + async: compiledFn.async, + generator: compiledFn.generator, + params: compiledFn.params, + body: compiledFn.body, + }; + transformedFn = fn; + break; + } + default: { + assertExhaustive$1(originalFn.node, `Creating unhandled function: ${originalFn.node}`); + } + } + return transformedFn; +} +function insertNewOutlinedFunctionNode(program, originalFn, compiledFn) { + var _a, _b, _c; + switch (originalFn.type) { + case 'FunctionDeclaration': { + return originalFn.insertAfter(createNewFunctionNode(originalFn, compiledFn))[0]; + } + case 'ArrowFunctionExpression': + case 'FunctionExpression': { + const fn = { + type: 'FunctionDeclaration', + id: compiledFn.id, + loc: (_a = originalFn.node.loc) !== null && _a !== void 0 ? _a : null, + async: compiledFn.async, + generator: compiledFn.generator, + params: compiledFn.params, + body: compiledFn.body, + }; + const insertedFuncDecl = program.pushContainer('body', [fn])[0]; + CompilerError.invariant(insertedFuncDecl.isFunctionDeclaration(), { + reason: 'Expected inserted function declaration', + description: `Got: ${insertedFuncDecl}`, + loc: (_c = (_b = insertedFuncDecl.node) === null || _b === void 0 ? void 0 : _b.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + }); + return insertedFuncDecl; + } + default: { + assertExhaustive$1(originalFn, `Inserting unhandled function: ${originalFn}`); + } + } +} +const DEFAULT_ESLINT_SUPPRESSIONS = [ + 'react-hooks/exhaustive-deps', + 'react-hooks/rules-of-hooks', +]; +function isFilePartOfSources(sources, filename) { + if (typeof sources === 'function') { + return sources(filename); + } + for (const prefix of sources) { + if (filename.indexOf(prefix) !== -1) { + return true; + } + } + return false; +} +function compileProgram(program, pass) { + var _a, _b; + if (shouldSkipCompilation(program, pass)) { + return; + } + const restrictedImportsErr = validateRestrictedImports(program, pass.opts.environment); + if (restrictedImportsErr) { + handleError(restrictedImportsErr, pass, null); + return; + } + const suppressions = findProgramSuppressions(pass.comments, pass.opts.environment.validateExhaustiveMemoizationDependencies && + pass.opts.environment.validateHooksUsage + ? null + : ((_a = pass.opts.eslintSuppressionRules) !== null && _a !== void 0 ? _a : DEFAULT_ESLINT_SUPPRESSIONS), pass.opts.flowSuppressions); + const programContext = new ProgramContext({ + program: program, + opts: pass.opts, + filename: pass.filename, + code: pass.code, + suppressions, + hasModuleScopeOptOut: findDirectiveDisablingMemoization(program.node.directives, pass.opts) != + null, + }); + const queue = findFunctionsToCompile(program, pass, programContext); + const compiledFns = []; + const outputMode = (_b = pass.opts.outputMode) !== null && _b !== void 0 ? _b : (pass.opts.noEmit ? 'lint' : 'client'); + while (queue.length !== 0) { + const current = queue.shift(); + const compiled = processFn(current.fn, current.fnType, programContext, outputMode); + if (compiled != null) { + for (const outlined of compiled.outlined) { + CompilerError.invariant(outlined.fn.outlined.length === 0, { + reason: 'Unexpected nested outlined functions', + loc: outlined.fn.loc, + }); + const fn = insertNewOutlinedFunctionNode(program, current.fn, outlined.fn); + fn.skip(); + programContext.alreadyCompiled.add(fn.node); + if (outlined.type !== null) { + queue.push({ + kind: 'outlined', + fn, + fnType: outlined.type, + }); + } + } + compiledFns.push({ + kind: current.kind, + originalFn: current.fn, + compiledFn: compiled, + }); + } + } + if (programContext.hasModuleScopeOptOut) { + if (compiledFns.length > 0) { + const error = new CompilerError(); + error.pushErrorDetail(new CompilerErrorDetail({ + reason: 'Unexpected compiled functions when module scope opt-out is present', + category: ErrorCategory.Invariant, + loc: null, + })); + handleError(error, programContext, null); + } + return; + } + applyCompiledFunctions(program, compiledFns, pass, programContext); +} +function findFunctionsToCompile(program, pass, programContext) { + var _a; + const queue = []; + const traverseFunction = (fn, pass) => { + if (pass.opts.compilationMode === 'all' && + fn.scope.getProgramParent() !== fn.scope.parent) { + return; + } + const fnType = getReactFunctionType(fn, pass); + if (fnType === null || programContext.alreadyCompiled.has(fn.node)) { + return; + } + programContext.alreadyCompiled.add(fn.node); + fn.skip(); + queue.push({ kind: 'original', fn, fnType }); + }; + program.traverse({ + ClassDeclaration(node) { + node.skip(); + }, + ClassExpression(node) { + node.skip(); + }, + FunctionDeclaration: traverseFunction, + FunctionExpression: traverseFunction, + ArrowFunctionExpression: traverseFunction, + }, Object.assign(Object.assign({}, pass), { opts: Object.assign(Object.assign({}, pass.opts), pass.opts), filename: (_a = pass.filename) !== null && _a !== void 0 ? _a : null })); + return queue; +} +function processFn(fn, fnType, programContext, outputMode) { + var _a, _b, _c, _d, _e, _f, _g, _h; + let directives; + if (fn.node.body.type !== 'BlockStatement') { + directives = { + optIn: null, + optOut: null, + }; + } + else { + const optIn = tryFindDirectiveEnablingMemoization(fn.node.body.directives, programContext.opts); + if (optIn.isErr()) { + handleError(optIn.unwrapErr(), programContext, (_a = fn.node.loc) !== null && _a !== void 0 ? _a : null); + return null; + } + directives = { + optIn: optIn.unwrapOr(null), + optOut: findDirectiveDisablingMemoization(fn.node.body.directives, programContext.opts), + }; + } + let compiledFn; + const compileResult = tryCompileFunction(fn, fnType, programContext, outputMode); + if (compileResult.kind === 'error') { + if (directives.optOut != null) { + logError(compileResult.error, programContext, (_b = fn.node.loc) !== null && _b !== void 0 ? _b : null); + } + else { + handleError(compileResult.error, programContext, (_c = fn.node.loc) !== null && _c !== void 0 ? _c : null); + } + return null; + } + else { + compiledFn = compileResult.compiledFn; + } + if (programContext.opts.ignoreUseNoForget === false && + directives.optOut != null) { + programContext.logEvent({ + kind: 'CompileSkip', + fnLoc: (_d = fn.node.body.loc) !== null && _d !== void 0 ? _d : null, + reason: `Skipped due to '${directives.optOut.value}' directive.`, + loc: (_e = directives.optOut.loc) !== null && _e !== void 0 ? _e : null, + }); + return null; + } + programContext.logEvent({ + kind: 'CompileSuccess', + fnLoc: (_f = fn.node.loc) !== null && _f !== void 0 ? _f : null, + fnName: (_h = (_g = compiledFn.id) === null || _g === void 0 ? void 0 : _g.name) !== null && _h !== void 0 ? _h : null, + memoSlots: compiledFn.memoSlotsUsed, + memoBlocks: compiledFn.memoBlocks, + memoValues: compiledFn.memoValues, + prunedMemoBlocks: compiledFn.prunedMemoBlocks, + prunedMemoValues: compiledFn.prunedMemoValues, + }); + if (programContext.hasModuleScopeOptOut) { + return null; + } + else if (programContext.opts.outputMode === 'lint') { + return null; + } + else if (programContext.opts.compilationMode === 'annotation' && + directives.optIn == null) { + return null; + } + else { + return compiledFn; + } +} +function tryCompileFunction(fn, fnType, programContext, outputMode) { + var _a; + const suppressionsInFunction = filterSuppressionsThatAffectFunction(programContext.suppressions, fn); + if (suppressionsInFunction.length > 0) { + return { + kind: 'error', + error: suppressionsToCompilerError(suppressionsInFunction), + }; + } + try { + const result = compileFn(fn, programContext.opts.environment, fnType, outputMode, programContext, programContext.opts.logger, programContext.filename, programContext.code); + if (result.isOk()) { + return { kind: 'compile', compiledFn: result.unwrap() }; + } + else { + return { kind: 'error', error: result.unwrapErr() }; + } + } + catch (err) { + if (err instanceof CompilerError && + err.details.every(detail => detail.category !== ErrorCategory.Invariant)) { + programContext.logEvent({ + kind: 'CompileUnexpectedThrow', + fnLoc: (_a = fn.node.loc) !== null && _a !== void 0 ? _a : null, + data: err.toString(), + }); + } + return { kind: 'error', error: err }; + } +} +function applyCompiledFunctions(program, compiledFns, pass, programContext) { + var _a, _b; + let referencedBeforeDeclared = null; + for (const result of compiledFns) { + const { kind, originalFn, compiledFn } = result; + const transformedFn = createNewFunctionNode(originalFn, compiledFn); + programContext.alreadyCompiled.add(transformedFn); + let dynamicGating = null; + if (originalFn.node.body.type === 'BlockStatement') { + const result = findDirectivesDynamicGating(originalFn.node.body.directives, pass.opts); + if (result.isOk()) { + dynamicGating = (_b = (_a = result.unwrap()) === null || _a === void 0 ? void 0 : _a.gating) !== null && _b !== void 0 ? _b : null; + } + } + const functionGating = dynamicGating !== null && dynamicGating !== void 0 ? dynamicGating : pass.opts.gating; + if (kind === 'original' && functionGating != null) { + referencedBeforeDeclared !== null && referencedBeforeDeclared !== void 0 ? referencedBeforeDeclared : (referencedBeforeDeclared = getFunctionReferencedBeforeDeclarationAtTopLevel(program, compiledFns)); + insertGatedFunctionDeclaration(originalFn, transformedFn, programContext, functionGating, referencedBeforeDeclared.has(result)); + } + else { + originalFn.replaceWith(transformedFn); + } + } + if (compiledFns.length > 0) { + addImportsToProgram(program, programContext); + } +} +function shouldSkipCompilation(program, pass) { + if (pass.opts.sources) { + if (pass.filename === null) { + const error = new CompilerError(); + error.pushErrorDetail(new CompilerErrorDetail({ + reason: `Expected a filename but found none.`, + description: "When the 'sources' config options is specified, the React compiler will only compile files with a name", + category: ErrorCategory.Config, + loc: null, + })); + handleError(error, pass, null); + return true; + } + if (!isFilePartOfSources(pass.opts.sources, pass.filename)) { + return true; + } + } + if (hasMemoCacheFunctionImport(program, getReactCompilerRuntimeModule(pass.opts.target))) { + return true; + } + return false; +} +function getReactFunctionType(fn, pass) { + var _a, _b; + if (fn.node.body.type === 'BlockStatement') { + const optInDirectives = tryFindDirectiveEnablingMemoization(fn.node.body.directives, pass.opts); + if (optInDirectives.unwrapOr(null) != null) { + return (_a = getComponentOrHookLike(fn)) !== null && _a !== void 0 ? _a : 'Other'; + } + } + let componentSyntaxType = null; + if (fn.isFunctionDeclaration()) { + if (isComponentDeclaration(fn.node)) { + componentSyntaxType = 'Component'; + } + else if (isHookDeclaration(fn.node)) { + componentSyntaxType = 'Hook'; + } + } + switch (pass.opts.compilationMode) { + case 'annotation': { + return null; + } + case 'infer': { + return componentSyntaxType !== null && componentSyntaxType !== void 0 ? componentSyntaxType : getComponentOrHookLike(fn); + } + case 'syntax': { + return componentSyntaxType; + } + case 'all': { + return (_b = getComponentOrHookLike(fn)) !== null && _b !== void 0 ? _b : 'Other'; + } + default: { + assertExhaustive$1(pass.opts.compilationMode, `Unexpected compilationMode \`${pass.opts.compilationMode}\``); + } + } +} +function hasMemoCacheFunctionImport(program, moduleName) { + let hasUseMemoCache = false; + program.traverse({ + ImportSpecifier(path) { + const imported = path.get('imported'); + let importedName = null; + if (imported.isIdentifier()) { + importedName = imported.node.name; + } + else if (imported.isStringLiteral()) { + importedName = imported.node.value; + } + if (importedName === 'c' && + path.parentPath.isImportDeclaration() && + path.parentPath.get('source').node.value === moduleName) { + hasUseMemoCache = true; + } + }, + }); + return hasUseMemoCache; +} +function isHookName$1(s) { + return /^use[A-Z0-9]/.test(s); +} +function isHook$1(path) { + if (path.isIdentifier()) { + return isHookName$1(path.node.name); + } + else if (path.isMemberExpression() && + !path.node.computed && + isHook$1(path.get('property'))) { + const obj = path.get('object').node; + const isPascalCaseNameSpace = /^[A-Z].*/; + return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name); + } + else { + return false; + } +} +function isComponentName$1(path) { + return path.isIdentifier() && /^[A-Z]/.test(path.node.name); +} +function isReactAPI(path, functionName) { + const node = path.node; + return ((node.type === 'Identifier' && node.name === functionName) || + (node.type === 'MemberExpression' && + node.object.type === 'Identifier' && + node.object.name === 'React' && + node.property.type === 'Identifier' && + node.property.name === functionName)); +} +function isForwardRefCallback$1(path) { + return !!(path.parentPath.isCallExpression() && + path.parentPath.get('callee').isExpression() && + isReactAPI(path.parentPath.get('callee'), 'forwardRef')); +} +function isMemoCallback$1(path) { + return (path.parentPath.isCallExpression() && + path.parentPath.get('callee').isExpression() && + isReactAPI(path.parentPath.get('callee'), 'memo')); +} +function isValidPropsAnnotation(annot) { + if (annot == null) { + return true; + } + else if (annot.type === 'TSTypeAnnotation') { + switch (annot.typeAnnotation.type) { + case 'TSArrayType': + case 'TSBigIntKeyword': + case 'TSBooleanKeyword': + case 'TSConstructorType': + case 'TSFunctionType': + case 'TSLiteralType': + case 'TSNeverKeyword': + case 'TSNumberKeyword': + case 'TSStringKeyword': + case 'TSSymbolKeyword': + case 'TSTupleType': + return false; + } + return true; + } + else if (annot.type === 'TypeAnnotation') { + switch (annot.typeAnnotation.type) { + case 'ArrayTypeAnnotation': + case 'BooleanLiteralTypeAnnotation': + case 'BooleanTypeAnnotation': + case 'EmptyTypeAnnotation': + case 'FunctionTypeAnnotation': + case 'NumberLiteralTypeAnnotation': + case 'NumberTypeAnnotation': + case 'StringLiteralTypeAnnotation': + case 'StringTypeAnnotation': + case 'SymbolTypeAnnotation': + case 'ThisTypeAnnotation': + case 'TupleTypeAnnotation': + return false; + } + return true; + } + else if (annot.type === 'Noop') { + return true; + } + else { + assertExhaustive$1(annot, `Unexpected annotation node \`${annot}\``); + } +} +function isValidComponentParams(params) { + if (params.length === 0) { + return true; + } + else if (params.length > 0 && params.length <= 2) { + if (!isValidPropsAnnotation(params[0].node.typeAnnotation)) { + return false; + } + if (params.length === 1) { + return !params[0].isRestElement(); + } + else if (params[1].isIdentifier()) { + const { name } = params[1].node; + return name.includes('ref') || name.includes('Ref'); + } + else { + return false; + } + } + return false; +} +function getComponentOrHookLike(node) { + const functionName = getFunctionName$1(node); + if (functionName !== null && isComponentName$1(functionName)) { + let isComponent = callsHooksOrCreatesJsx(node) && + isValidComponentParams(node.get('params')) && + !returnsNonNode(node); + return isComponent ? 'Component' : null; + } + else if (functionName !== null && isHook$1(functionName)) { + return callsHooksOrCreatesJsx(node) ? 'Hook' : null; + } + if (node.isFunctionExpression() || node.isArrowFunctionExpression()) { + if (isForwardRefCallback$1(node) || isMemoCallback$1(node)) { + return callsHooksOrCreatesJsx(node) ? 'Component' : null; + } + } + return null; +} +function skipNestedFunctions(node) { + return (fn) => { + if (fn.node !== node.node) { + fn.skip(); + } + }; +} +function callsHooksOrCreatesJsx(node) { + let invokesHooks = false; + let createsJsx = false; + node.traverse({ + JSX() { + createsJsx = true; + }, + CallExpression(call) { + const callee = call.get('callee'); + if (callee.isExpression() && isHook$1(callee)) { + invokesHooks = true; + } + }, + ArrowFunctionExpression: skipNestedFunctions(node), + FunctionExpression: skipNestedFunctions(node), + FunctionDeclaration: skipNestedFunctions(node), + }); + return invokesHooks || createsJsx; +} +function isNonNode(node) { + if (!node) { + return true; + } + switch (node.type) { + case 'ObjectExpression': + case 'ArrowFunctionExpression': + case 'FunctionExpression': + case 'BigIntLiteral': + case 'ClassExpression': + case 'NewExpression': + return true; + } + return false; +} +function returnsNonNode(node) { + let returnsNonNode = false; + if (node.type === 'ArrowFunctionExpression' && + node.node.body.type !== 'BlockStatement') { + returnsNonNode = isNonNode(node.node.body); + } + node.traverse({ + ReturnStatement(ret) { + returnsNonNode = isNonNode(ret.node.argument); + }, + ArrowFunctionExpression: skipNestedFunctions(node), + FunctionExpression: skipNestedFunctions(node), + FunctionDeclaration: skipNestedFunctions(node), + ObjectMethod: node => node.skip(), + }); + return returnsNonNode; +} +function getFunctionName$1(path) { + if (path.isFunctionDeclaration()) { + const id = path.get('id'); + if (id.isIdentifier()) { + return id; + } + return null; + } + let id = null; + const parent = path.parentPath; + if (parent.isVariableDeclarator() && parent.get('init').node === path.node) { + id = parent.get('id'); + } + else if (parent.isAssignmentExpression() && + parent.get('right').node === path.node && + parent.get('operator') === '=') { + id = parent.get('left'); + } + else if (parent.isProperty() && + parent.get('value').node === path.node && + !parent.get('computed') && + parent.get('key').isLVal()) { + id = parent.get('key'); + } + else if (parent.isAssignmentPattern() && + parent.get('right').node === path.node && + !parent.get('computed')) { + id = parent.get('left'); + } + if (id !== null && (id.isIdentifier() || id.isMemberExpression())) { + return id; + } + else { + return null; + } +} +function getFunctionReferencedBeforeDeclarationAtTopLevel(program, fns) { + const fnNames = new Map(fns + .map(fn => [ + getFunctionName$1(fn.originalFn), + fn, + ]) + .filter((entry) => !!entry[0] && entry[0].isIdentifier()) + .map(entry => [entry[0].node.name, { id: entry[0].node, fn: entry[1] }])); + const referencedBeforeDeclaration = new Set(); + program.traverse({ + TypeAnnotation(path) { + path.skip(); + }, + TSTypeAnnotation(path) { + path.skip(); + }, + TypeAlias(path) { + path.skip(); + }, + TSTypeAliasDeclaration(path) { + path.skip(); + }, + Identifier(id) { + const fn = fnNames.get(id.node.name); + if (!fn) { + return; + } + if (id.node === fn.id) { + fnNames.delete(id.node.name); + return; + } + const scope = id.scope.getFunctionParent(); + if (scope === null && id.isReferencedIdentifier()) { + referencedBeforeDeclaration.add(fn.fn); + } + }, + }); + return referencedBeforeDeclaration; +} +function getReactCompilerRuntimeModule(target) { + if (target === '19') { + return 'react/compiler-runtime'; + } + else if (target === '17' || target === '18') { + return 'react-compiler-runtime'; + } + else { + CompilerError.invariant(target != null && + target.kind === 'donotuse_meta_internal' && + typeof target.runtimeModule === 'string', { + reason: 'Expected target to already be validated', + loc: GeneratedSource, + }); + return target.runtimeModule; + } +} + +function validateRestrictedImports(path, { validateBlocklistedImports }) { + if (validateBlocklistedImports == null || + validateBlocklistedImports.length === 0) { + return null; + } + const error = new CompilerError(); + const restrictedImports = new Set(validateBlocklistedImports); + path.traverse({ + ImportDeclaration(importDeclPath) { + var _a; + if (restrictedImports.has(importDeclPath.node.source.value)) { + error.push({ + category: ErrorCategory.Todo, + reason: 'Bailing out due to blocklisted import', + description: `Import from module ${importDeclPath.node.source.value}`, + loc: (_a = importDeclPath.node.loc) !== null && _a !== void 0 ? _a : null, + }); + } + }, + }); + if (error.hasAnyErrors()) { + return error; + } + else { + return null; + } +} +class ProgramContext { + constructor({ program, suppressions, opts, filename, code, hasModuleScopeOptOut, }) { + this.alreadyCompiled = new (WeakSet !== null && WeakSet !== void 0 ? WeakSet : Set)(); + this.knownReferencedNames = new Set(); + this.imports = new Map(); + this.scope = program.scope; + this.opts = opts; + this.filename = filename; + this.code = code; + this.reactRuntimeModule = getReactCompilerRuntimeModule(opts.target); + this.suppressions = suppressions; + this.hasModuleScopeOptOut = hasModuleScopeOptOut; + } + isHookName(name) { + return isHookName$2(name); + } + hasReference(name) { + return (this.knownReferencedNames.has(name) || + this.scope.hasBinding(name) || + this.scope.hasGlobal(name) || + this.scope.hasReference(name)); + } + newUid(name) { + let uid; + if (this.isHookName(name)) { + uid = name; + let i = 0; + while (this.hasReference(uid)) { + this.knownReferencedNames.add(uid); + uid = `${name}_${i++}`; + } + } + else if (!this.hasReference(name)) { + uid = name; + } + else { + uid = this.scope.generateUid(name); + } + this.knownReferencedNames.add(uid); + return uid; + } + addMemoCacheImport() { + return this.addImportSpecifier({ + source: this.reactRuntimeModule, + importSpecifierName: 'c', + }, '_c'); + } + addImportSpecifier({ source: module, importSpecifierName: specifier }, nameHint) { + var _a; + const maybeBinding = (_a = this.imports.get(module)) === null || _a === void 0 ? void 0 : _a.get(specifier); + if (maybeBinding != null) { + return Object.assign({}, maybeBinding); + } + const binding = { + kind: 'ImportSpecifier', + name: this.newUid(nameHint !== null && nameHint !== void 0 ? nameHint : specifier), + module, + imported: specifier, + }; + getOrInsertWith(this.imports, module, () => new Map()).set(specifier, Object.assign({}, binding)); + return binding; + } + addNewReference(name) { + this.knownReferencedNames.add(name); + } + assertGlobalBinding(name, localScope) { + var _a, _b; + const scope = localScope !== null && localScope !== void 0 ? localScope : this.scope; + if (!scope.hasReference(name) && !scope.hasBinding(name)) { + return Ok(undefined); + } + const error = new CompilerError(); + error.push({ + category: ErrorCategory.Todo, + reason: 'Encountered conflicting global in generated program', + description: `Conflict from local binding ${name}`, + loc: (_b = (_a = scope.getBinding(name)) === null || _a === void 0 ? void 0 : _a.path.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + }); + return Err(error); + } + logEvent(event) { + if (this.opts.logger != null) { + this.opts.logger.logEvent(this.filename, event); + } + } +} +function getExistingImports(program) { + const existingImports = new Map(); + program.traverse({ + ImportDeclaration(path) { + if (isNonNamespacedImport(path)) { + existingImports.set(path.node.source.value, path); + } + }, + }); + return existingImports; +} +function addImportsToProgram(path, programContext) { + const existingImports = getExistingImports(path); + const stmts = []; + const sortedModules = [...programContext.imports.entries()].sort(([a], [b]) => a.localeCompare(b)); + for (const [moduleName, importsMap] of sortedModules) { + for (const [specifierName, loweredImport] of importsMap) { + CompilerError.invariant(path.scope.getBinding(loweredImport.name) == null, { + reason: 'Encountered conflicting import specifiers in generated program', + description: `Conflict from import ${loweredImport.module}:(${loweredImport.imported} as ${loweredImport.name})`, + loc: GeneratedSource, + }); + CompilerError.invariant(loweredImport.module === moduleName && + loweredImport.imported === specifierName, { + reason: 'Found inconsistent import specifier. This is an internal bug.', + description: `Expected import ${moduleName}:${specifierName} but found ${loweredImport.module}:${loweredImport.imported}`, + loc: GeneratedSource, + }); + } + const sortedImport = [ + ...importsMap.values(), + ].sort(({ imported: a }, { imported: b }) => a.localeCompare(b)); + const importSpecifiers = sortedImport.map(specifier => { + return libExports$1.importSpecifier(libExports$1.identifier(specifier.name), libExports$1.identifier(specifier.imported)); + }); + const maybeExistingImports = existingImports.get(moduleName); + if (maybeExistingImports != null) { + maybeExistingImports.pushContainer('specifiers', importSpecifiers); + } + else { + if (path.node.sourceType === 'module') { + stmts.push(libExports$1.importDeclaration(importSpecifiers, libExports$1.stringLiteral(moduleName))); + } + else { + stmts.push(libExports$1.variableDeclaration('const', [ + libExports$1.variableDeclarator(libExports$1.objectPattern(sortedImport.map(specifier => { + return libExports$1.objectProperty(libExports$1.identifier(specifier.imported), libExports$1.identifier(specifier.name)); + })), libExports$1.callExpression(libExports$1.identifier('require'), [ + libExports$1.stringLiteral(moduleName), + ])), + ])); + } + } + } + path.unshiftContainer('body', stmts); +} +function isNonNamespacedImport(importDeclPath) { + return (importDeclPath + .get('specifiers') + .every(specifier => specifier.isImportSpecifier()) && + importDeclPath.node.importKind !== 'type' && + importDeclPath.node.importKind !== 'typeof'); +} + +v4.z.enum([ + 'all_errors', + 'critical_errors', + 'none', +]); +const DynamicGatingOptionsSchema = v4.z.object({ + source: v4.z.string(), +}); +const CustomOptOutDirectiveSchema = v4.z + .nullable(v4.z.array(v4.z.string())) + .default(null); +const CompilerReactTargetSchema = v4.z.union([ + v4.z.literal('17'), + v4.z.literal('18'), + v4.z.literal('19'), + v4.z.object({ + kind: v4.z.literal('donotuse_meta_internal'), + runtimeModule: v4.z.string().default('react'), + }), +]); +v4.z.enum([ + 'infer', + 'syntax', + 'annotation', + 'all', +]); +v4.z.enum([ + 'ssr', + 'client', + 'lint', +]); +const defaultOptions = { + compilationMode: 'infer', + panicThreshold: 'none', + environment: parseEnvironmentConfig({}).unwrap(), + logger: null, + gating: null, + noEmit: false, + outputMode: null, + dynamicGating: null, + eslintSuppressionRules: null, + flowSuppressions: true, + ignoreUseNoForget: false, + sources: filename => { + return filename.indexOf('node_modules') === -1; + }, + enableReanimatedCheck: true, + customOptOutDirectives: null, + target: '19', +}; +function parsePluginOptions(obj) { + if (obj == null || typeof obj !== 'object') { + return defaultOptions; + } + const parsedOptions = Object.create(null); + for (let [key, value] of Object.entries(obj)) { + if (typeof value === 'string') { + value = value.toLowerCase(); + } + if (isCompilerFlag(key)) { + switch (key) { + case 'environment': { + const environmentResult = parseEnvironmentConfig(value); + if (environmentResult.isErr()) { + CompilerError.throwInvalidConfig({ + reason: 'Error in validating environment config. This is an advanced setting and not meant to be used directly', + description: environmentResult.unwrapErr().toString(), + suggestions: null, + loc: null, + }); + } + parsedOptions[key] = environmentResult.unwrap(); + break; + } + case 'target': { + parsedOptions[key] = parseTargetConfig(value); + break; + } + case 'gating': { + if (value == null) { + parsedOptions[key] = null; + } + else { + parsedOptions[key] = tryParseExternalFunction(value); + } + break; + } + case 'dynamicGating': { + if (value == null) { + parsedOptions[key] = null; + } + else { + const result = DynamicGatingOptionsSchema.safeParse(value); + if (result.success) { + parsedOptions[key] = result.data; + } + else { + CompilerError.throwInvalidConfig({ + reason: 'Could not parse dynamic gating. Update React Compiler config to fix the error', + description: `${v4$1.fromZodError(result.error)}`, + loc: null, + suggestions: null, + }); + } + } + break; + } + case 'customOptOutDirectives': { + const result = CustomOptOutDirectiveSchema.safeParse(value); + if (result.success) { + parsedOptions[key] = result.data; + } + else { + CompilerError.throwInvalidConfig({ + reason: 'Could not parse custom opt out directives. Update React Compiler config to fix the error', + description: `${v4$1.fromZodError(result.error)}`, + loc: null, + suggestions: null, + }); + } + break; + } + default: { + parsedOptions[key] = value; + } + } + } + } + return Object.assign(Object.assign({}, defaultOptions), parsedOptions); +} +function parseTargetConfig(value) { + const parsed = CompilerReactTargetSchema.safeParse(value); + if (parsed.success) { + return parsed.data; + } + else { + CompilerError.throwInvalidConfig({ + reason: 'Not a valid target', + description: `${v4$1.fromZodError(parsed.error)}`, + suggestions: null, + loc: null, + }); + } +} +function isCompilerFlag(s) { + return hasOwnProperty$1(defaultOptions, s); +} + +function hasModule(name) { + if (typeof require === 'undefined') { + return false; + } + try { + return !!require.resolve(name); + } + catch (error) { + if (error.code === 'MODULE_NOT_FOUND' && + error.message.indexOf(name) !== -1) { + return false; + } + throw error; + } +} +function pipelineUsesReanimatedPlugin(plugins) { + if (Array.isArray(plugins)) { + for (const plugin of plugins) { + if (hasOwnProperty$1(plugin, 'key')) { + const key = plugin.key; + if (typeof key === 'string' && + key.indexOf('react-native-reanimated') !== -1) { + return true; + } + } + } + } + return hasModule('react-native-reanimated'); +} +function injectReanimatedFlag(options) { + return Object.assign(Object.assign({}, options), { environment: Object.assign(Object.assign({}, options.environment), { enableCustomTypeDefinitionForReanimated: true }) }); +} + +const ENABLE_REACT_COMPILER_TIMINGS = process.env['ENABLE_REACT_COMPILER_TIMINGS'] === '1'; +function BabelPluginReactCompiler(_babel) { + return { + name: 'react-forget', + visitor: { + Program: { + enter(prog, pass) { + var _a, _b, _c; + try { + const filename = (_a = pass.filename) !== null && _a !== void 0 ? _a : 'unknown'; + if (ENABLE_REACT_COMPILER_TIMINGS === true) { + performance.mark(`${filename}:start`, { + detail: 'BabelPlugin:Program:start', + }); + } + let opts = parsePluginOptions(pass.opts); + const isDev = (typeof true !== 'undefined' && true === true) || + process.env['NODE_ENV'] === 'development'; + if (opts.enableReanimatedCheck === true && + pipelineUsesReanimatedPlugin(pass.file.opts.plugins)) { + opts = injectReanimatedFlag(opts); + } + if (opts.environment.enableResetCacheOnSourceFileChanges !== false && + isDev) { + opts = Object.assign(Object.assign({}, opts), { environment: Object.assign(Object.assign({}, opts.environment), { enableResetCacheOnSourceFileChanges: true }) }); + } + compileProgram(prog, { + opts, + filename: (_b = pass.filename) !== null && _b !== void 0 ? _b : null, + comments: (_c = pass.file.ast.comments) !== null && _c !== void 0 ? _c : [], + code: pass.file.code, + }); + if (ENABLE_REACT_COMPILER_TIMINGS === true) { + performance.mark(`${filename}:end`, { + detail: 'BabelPlugin:Program:end', + }); + } + } + catch (e) { + if (e instanceof CompilerError) { + throw e.withPrintedMessage(pass.file.code, { eslint: false }); + } + throw e; + } + }, + exit(_, pass) { + var _a; + if (ENABLE_REACT_COMPILER_TIMINGS === true) { + const filename = (_a = pass.filename) !== null && _a !== void 0 ? _a : 'unknown'; + const measurement = performance.measure(filename, { + start: `${filename}:start`, + end: `${filename}:end`, + detail: 'BabelPlugin:Program', + }); + if ('logger' in pass.opts && pass.opts.logger != null) { + const logger = pass.opts.logger; + logger.logEvent(filename, { + kind: 'Timing', + measurement, + }); + } + } + }, + }, + }, + }; +} + +// ----------------------------------------------------------------------------- +// Land or remove (zero effort) +// +// Flags that can likely be deleted or landed without consequences +// ----------------------------------------------------------------------------- + + +// ----------------------------------------------------------------------------- +// eslint-plugin-react-hooks +// ----------------------------------------------------------------------------- +var eprh_enableUseKeyedStateCompilerLint = false; +var eprh_enableVerboseNoSetStateInEffectCompilerLint = false; +var eprh_enableExhaustiveEffectDependenciesCompilerLint = 'off'; + +var _LRUCache_values, _LRUCache_headIdx; +const COMPONENT_NAME_PATTERN = /^[A-Z]/; +const HOOK_NAME_PATTERN = /^use[A-Z0-9]/; +function mayContainReactCode(sourceCode) { + const ast = sourceCode.ast; + for (const node of ast.body) { + if (checkTopLevelNode(node)) { + return true; + } + } + return false; +} +function checkTopLevelNode(node) { + if (node.type === 'ComponentDeclaration' || node.type === 'HookDeclaration') { + return true; + } + if (node.type === 'ExportNamedDeclaration') { + const decl = node.declaration; + if (decl != null) { + return checkTopLevelNode(decl); + } + return false; + } + if (node.type === 'ExportDefaultDeclaration') { + const decl = node.declaration; + if (decl.type === 'FunctionExpression' || + decl.type === 'ArrowFunctionExpression' || + (decl.type === 'FunctionDeclaration' && + decl.id == null)) { + return true; + } + return checkTopLevelNode(decl); + } + if (node.type === 'FunctionDeclaration') { + if ('__componentDeclaration' in node || '__hookDeclaration' in node) { + return true; + } + const id = node.id; + if (id != null) { + const name = id.name; + if (COMPONENT_NAME_PATTERN.test(name) || HOOK_NAME_PATTERN.test(name)) { + return true; + } + } + } + if (node.type === 'VariableDeclaration') { + for (const decl of node.declarations) { + if (decl.id.type === 'Identifier') { + const init = decl.init; + if (init != null && + (init.type === 'ArrowFunctionExpression' || + init.type === 'FunctionExpression')) { + const name = decl.id.name; + if (COMPONENT_NAME_PATTERN.test(name) || + HOOK_NAME_PATTERN.test(name)) { + return true; + } + } + } + } + } + return false; +} +const COMPILER_OPTIONS = { + outputMode: 'lint', + panicThreshold: 'none', + flowSuppressions: false, + environment: { + validateRefAccessDuringRender: true, + validateNoSetStateInRender: true, + validateNoSetStateInEffects: true, + validateNoJSXInTryStatements: true, + validateNoImpureFunctionsInRender: true, + validateStaticComponents: true, + validateNoFreezingKnownMutableFunctions: true, + validateNoVoidUseMemo: true, + validateNoCapitalizedCalls: [], + validateHooksUsage: true, + validateNoDerivedComputationsInEffects: true, + enableUseKeyedState: eprh_enableUseKeyedStateCompilerLint, + enableVerboseNoSetStateInEffect: eprh_enableVerboseNoSetStateInEffectCompilerLint, + validateExhaustiveEffectDependencies: eprh_enableExhaustiveEffectDependenciesCompilerLint, + }, +}; +const FLOW_SUPPRESSION_REGEX = /\$FlowFixMe\[([^\]]*)\]/g; +function getFlowSuppressions(sourceCode) { + const comments = sourceCode.getAllComments(); + const results = []; + for (const commentNode of comments) { + const matches = commentNode.value.matchAll(FLOW_SUPPRESSION_REGEX); + for (const match of matches) { + if (match.index != null && commentNode.loc != null) { + const code = match[1]; + results.push({ + line: commentNode.loc.end.line, + code, + }); + } + } + } + return results; +} +function runReactCompilerImpl({ sourceCode, filename, userOpts, }) { + var _a, _b; + const options = parsePluginOptions(Object.assign(Object.assign(Object.assign({}, COMPILER_OPTIONS), userOpts), { environment: Object.assign(Object.assign({}, COMPILER_OPTIONS.environment), userOpts.environment) })); + const results = { + sourceCode: sourceCode.text, + filename, + userOpts, + flowSuppressions: [], + events: [], + }; + const userLogger = options.logger; + options.logger = { + logEvent: (eventFilename, event) => { + userLogger === null || userLogger === void 0 ? void 0 : userLogger.logEvent(eventFilename, event); + results.events.push(event); + }, + }; + try { + options.environment = validateEnvironmentConfig((_a = options.environment) !== null && _a !== void 0 ? _a : {}); + } + catch (err) { + (_b = options.logger) === null || _b === void 0 ? void 0 : _b.logEvent(filename, err); + } + let babelAST = null; + if (filename.endsWith('.tsx') || filename.endsWith('.ts')) { + try { + babelAST = BabelParser.parse(sourceCode.text, { + sourceFilename: filename, + sourceType: 'unambiguous', + plugins: ['typescript', 'jsx'], + }); + } + catch (_c) { + } + } + else { + try { + babelAST = HermesParser.parse(sourceCode.text, { + babel: true, + enableExperimentalComponentSyntax: true, + sourceFilename: filename, + sourceType: 'module', + }); + } + catch (_d) { + } + } + if (babelAST != null) { + results.flowSuppressions = getFlowSuppressions(sourceCode); + try { + core$1.transformFromAstSync(babelAST, sourceCode.text, { + filename, + highlightCode: false, + retainLines: true, + plugins: [[BabelPluginReactCompiler, options]], + sourceType: 'module', + configFile: false, + babelrc: false, + }); + } + catch (err) { + } + } + return results; +} +const SENTINEL = Symbol(); +class LRUCache { + constructor(size) { + _LRUCache_values.set(this, void 0); + _LRUCache_headIdx.set(this, 0); + __classPrivateFieldSet(this, _LRUCache_values, new Array(size).fill(SENTINEL), "f"); + } + get(key) { + const idx = __classPrivateFieldGet(this, _LRUCache_values, "f").findIndex(entry => entry[0] === key); + if (idx === __classPrivateFieldGet(this, _LRUCache_headIdx, "f")) { + return __classPrivateFieldGet(this, _LRUCache_values, "f")[__classPrivateFieldGet(this, _LRUCache_headIdx, "f")][1]; + } + else if (idx < 0) { + return null; + } + const entry = __classPrivateFieldGet(this, _LRUCache_values, "f")[idx]; + const len = __classPrivateFieldGet(this, _LRUCache_values, "f").length; + for (let i = 0; i < Math.min(idx, len - 1); i++) { + __classPrivateFieldGet(this, _LRUCache_values, "f")[(__classPrivateFieldGet(this, _LRUCache_headIdx, "f") + i + 1) % len] = + __classPrivateFieldGet(this, _LRUCache_values, "f")[(__classPrivateFieldGet(this, _LRUCache_headIdx, "f") + i) % len]; + } + __classPrivateFieldGet(this, _LRUCache_values, "f")[__classPrivateFieldGet(this, _LRUCache_headIdx, "f")] = entry; + return entry[1]; + } + push(key, value) { + __classPrivateFieldSet(this, _LRUCache_headIdx, (__classPrivateFieldGet(this, _LRUCache_headIdx, "f") - 1 + __classPrivateFieldGet(this, _LRUCache_values, "f").length) % __classPrivateFieldGet(this, _LRUCache_values, "f").length, "f"); + __classPrivateFieldGet(this, _LRUCache_values, "f")[__classPrivateFieldGet(this, _LRUCache_headIdx, "f")] = [key, value]; + } +} +_LRUCache_values = new WeakMap(), _LRUCache_headIdx = new WeakMap(); +const cache = new LRUCache(10); +function runReactCompiler({ sourceCode, filename, userOpts, }) { + const entry = cache.get(filename); + if (entry != null && + entry.sourceCode === sourceCode.text && + util.isDeepStrictEqual(entry.userOpts, userOpts)) { + return entry; + } + if (!mayContainReactCode(sourceCode)) { + const emptyResult = { + sourceCode: sourceCode.text, + filename, + userOpts, + flowSuppressions: [], + events: [], + }; + if (entry != null) { + Object.assign(entry, emptyResult); + } + else { + cache.push(filename, emptyResult); + } + return Object.assign({}, emptyResult); + } + const runEntry = runReactCompilerImpl({ + sourceCode, + filename, + userOpts, + }); + if (entry != null) { + Object.assign(entry, runEntry); + } + else { + cache.push(filename, runEntry); + } + return Object.assign({}, runEntry); +} + +function assertExhaustive(_, errorMsg) { + throw new Error(errorMsg); +} +function makeSuggestions(detail) { + const suggest = []; + if (Array.isArray(detail.suggestions)) { + for (const suggestion of detail.suggestions) { + switch (suggestion.op) { + case CompilerSuggestionOperation.InsertBefore: + suggest.push({ + desc: suggestion.description, + fix(fixer) { + return fixer.insertTextBeforeRange(suggestion.range, suggestion.text); + }, + }); + break; + case CompilerSuggestionOperation.InsertAfter: + suggest.push({ + desc: suggestion.description, + fix(fixer) { + return fixer.insertTextAfterRange(suggestion.range, suggestion.text); + }, + }); + break; + case CompilerSuggestionOperation.Replace: + suggest.push({ + desc: suggestion.description, + fix(fixer) { + return fixer.replaceTextRange(suggestion.range, suggestion.text); + }, + }); + break; + case CompilerSuggestionOperation.Remove: + suggest.push({ + desc: suggestion.description, + fix(fixer) { + return fixer.removeRange(suggestion.range); + }, + }); + break; + default: + assertExhaustive(suggestion, 'Unhandled suggestion operation'); + } + } + } + return suggest; +} +function getReactCompilerResult(context) { + var _a, _b, _c; + const sourceCode = (_a = context.sourceCode) !== null && _a !== void 0 ? _a : context.getSourceCode(); + const filename = (_b = context.filename) !== null && _b !== void 0 ? _b : context.getFilename(); + const userOpts = (_c = context.options[0]) !== null && _c !== void 0 ? _c : {}; + const results = runReactCompiler({ + sourceCode, + filename, + userOpts, + }); + return results; +} +function hasFlowSuppression(program, nodeLoc, suppressions) { + for (const commentNode of program.flowSuppressions) { + if (suppressions.includes(commentNode.code) && + commentNode.line === nodeLoc.start.line - 1) { + return true; + } + } + return false; +} +function makeRule(rule) { + const create = (context) => { + const result = getReactCompilerResult(context); + for (const event of result.events) { + if (event.kind === 'CompileError') { + const detail = event.detail; + if (detail.category === rule.category) { + const loc = detail.primaryLocation(); + if (loc == null || typeof loc === 'symbol') { + continue; + } + if (hasFlowSuppression(result, loc, [ + 'react-rule-hook', + 'react-rule-unsafe-ref', + ])) { + continue; + } + context.report({ + message: detail.printErrorMessage(result.sourceCode, { + eslint: true, + }), + loc, + suggest: makeSuggestions(detail.options), + }); + } + } + } + return {}; + }; + return { + meta: { + type: 'problem', + docs: { + description: rule.description, + recommended: rule.preset === LintRulePreset.Recommended, + url: `https://react.dev/reference/eslint-plugin-react-hooks/lints/${rule.name}`, + }, + fixable: 'code', + hasSuggestions: true, + schema: [{ type: 'object', additionalProperties: true }], + }, + create, + }; +} +const allRules = LintRules.reduce((acc, rule) => { + acc[rule.name] = { rule: makeRule(rule), severity: rule.severity }; + return acc; +}, {}); +const recommendedRules = LintRules.filter(rule => rule.preset === LintRulePreset.Recommended).reduce((acc, rule) => { + acc[rule.name] = { rule: makeRule(rule), severity: rule.severity }; + return acc; +}, {}); +const recommendedLatestRules = LintRules.filter(rule => rule.preset === LintRulePreset.Recommended || + rule.preset === LintRulePreset.RecommendedLatest).reduce((acc, rule) => { + acc[rule.name] = { rule: makeRule(rule), severity: rule.severity }; + return acc; +}, {}); +function mapErrorSeverityToESlint(severity) { + switch (severity) { + case ErrorSeverity.Error: { + return 'error'; + } + case ErrorSeverity.Warning: { + return 'warn'; + } + case ErrorSeverity.Hint: + case ErrorSeverity.Off: { + return 'off'; + } + default: { + assertExhaustive(severity, `Unhandled severity: ${severity}`); + } + } +} + +var assert_1; +var hasRequiredAssert; +function requireAssert() { + if (hasRequiredAssert) return assert_1; + hasRequiredAssert = 1; + function assert(cond) { + if (!cond) { + throw new Error('Assertion violated.'); + } + } + assert_1 = assert; + return assert_1; +} + +var codePathSegment; +var hasRequiredCodePathSegment; +function requireCodePathSegment() { + if (hasRequiredCodePathSegment) return codePathSegment; + hasRequiredCodePathSegment = 1; + + //------------------------------------------------------------------------------ + // Requirements + //------------------------------------------------------------------------------ + + //------------------------------------------------------------------------------ + // Helpers + //------------------------------------------------------------------------------ + + /** + * Checks whether or not a given segment is reachable. + * @param {CodePathSegment} segment A segment to check. + * @returns {boolean} `true` if the segment is reachable. + */ + function isReachable(segment) { + return segment.reachable; + } + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * A code path segment. + */ + class CodePathSegment { + /** + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * This array includes unreachable segments. + * @param {boolean} reachable A flag which shows this is reachable. + */ + constructor(id, allPrevSegments, reachable) { + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * An array of the next segments. + * @type {CodePathSegment[]} + */ + this.nextSegments = []; + + /** + * An array of the previous segments. + * @type {CodePathSegment[]} + */ + this.prevSegments = allPrevSegments.filter(isReachable); + + /** + * An array of the next segments. + * This array includes unreachable segments. + * @type {CodePathSegment[]} + */ + this.allNextSegments = []; + + /** + * An array of the previous segments. + * This array includes unreachable segments. + * @type {CodePathSegment[]} + */ + this.allPrevSegments = allPrevSegments; + + /** + * A flag which shows this is reachable. + * @type {boolean} + */ + this.reachable = reachable; + + // Internal data. + Object.defineProperty(this, 'internal', { + value: { + used: false, + loopedPrevSegments: [] + } + }); + } + + /** + * Checks a given previous segment is coming from the end of a loop. + * @param {CodePathSegment} segment A previous segment to check. + * @returns {boolean} `true` if the segment is coming from the end of a loop. + */ + isLoopedPrevSegment(segment) { + return this.internal.loopedPrevSegments.includes(segment); + } + + /** + * Creates the root segment. + * @param {string} id An identifier. + * @returns {CodePathSegment} The created segment. + */ + static newRoot(id) { + return new CodePathSegment(id, [], true); + } + + /** + * Creates a segment that follows given segments. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newNext(id, allPrevSegments) { + return new CodePathSegment(id, CodePathSegment.flattenUnusedSegments(allPrevSegments), allPrevSegments.some(isReachable)); + } + + /** + * Creates an unreachable segment that follows given segments. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newUnreachable(id, allPrevSegments) { + var segment = new CodePathSegment(id, CodePathSegment.flattenUnusedSegments(allPrevSegments), false); + + /* + * In `if (a) return a; foo();` case, the unreachable segment preceded by + * the return statement is not used but must not be remove. + */ + CodePathSegment.markUsed(segment); + return segment; + } + + /** + * Creates a segment that follows given segments. + * This factory method does not connect with `allPrevSegments`. + * But this inherits `reachable` flag. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newDisconnected(id, allPrevSegments) { + return new CodePathSegment(id, [], allPrevSegments.some(isReachable)); + } + + /** + * Makes a given segment being used. + * + * And this function registers the segment into the previous segments as a next. + * @param {CodePathSegment} segment A segment to mark. + * @returns {void} + */ + static markUsed(segment) { + if (segment.internal.used) { + return; + } + segment.internal.used = true; + var i; + if (segment.reachable) { + for (i = 0; i < segment.allPrevSegments.length; ++i) { + var prevSegment = segment.allPrevSegments[i]; + prevSegment.allNextSegments.push(segment); + prevSegment.nextSegments.push(segment); + } + } else { + for (i = 0; i < segment.allPrevSegments.length; ++i) { + segment.allPrevSegments[i].allNextSegments.push(segment); + } + } + } + + /** + * Marks a previous segment as looped. + * @param {CodePathSegment} segment A segment. + * @param {CodePathSegment} prevSegment A previous segment to mark. + * @returns {void} + */ + static markPrevSegmentAsLooped(segment, prevSegment) { + segment.internal.loopedPrevSegments.push(prevSegment); + } + + /** + * Replaces unused segments with the previous segments of each unused segment. + * @param {CodePathSegment[]} segments An array of segments to replace. + * @returns {CodePathSegment[]} The replaced array. + */ + static flattenUnusedSegments(segments) { + var done = Object.create(null); + var retv = []; + for (var i = 0; i < segments.length; ++i) { + var segment = segments[i]; + + // Ignores duplicated. + if (done[segment.id]) { + continue; + } + + // Use previous segments if unused. + if (!segment.internal.used) { + for (var j = 0; j < segment.allPrevSegments.length; ++j) { + var prevSegment = segment.allPrevSegments[j]; + if (!done[prevSegment.id]) { + done[prevSegment.id] = true; + retv.push(prevSegment); + } + } + } else { + done[segment.id] = true; + retv.push(segment); + } + } + return retv; + } + } + codePathSegment = CodePathSegment; + return codePathSegment; +} + +var forkContext; +var hasRequiredForkContext; +function requireForkContext() { + if (hasRequiredForkContext) return forkContext; + hasRequiredForkContext = 1; + + //------------------------------------------------------------------------------ + // Requirements + //------------------------------------------------------------------------------ + + // eslint-disable-next-line + var assert = requireAssert(); + // eslint-disable-next-line + var CodePathSegment = requireCodePathSegment(); + + //------------------------------------------------------------------------------ + // Helpers + //------------------------------------------------------------------------------ + + /** + * Gets whether or not a given segment is reachable. + * @param {CodePathSegment} segment A segment to get. + * @returns {boolean} `true` if the segment is reachable. + */ + function isReachable(segment) { + return segment.reachable; + } + + /** + * Creates new segments from the specific range of `context.segmentsList`. + * + * When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and + * `end` is `-1`, this creates `[g, h]`. This `g` is from `a`, `c`, and `e`. + * This `h` is from `b`, `d`, and `f`. + * @param {ForkContext} context An instance. + * @param {number} begin The first index of the previous segments. + * @param {number} end The last index of the previous segments. + * @param {Function} create A factory function of new segments. + * @returns {CodePathSegment[]} New segments. + */ + function makeSegments(context, begin, end, create) { + var list = context.segmentsList; + var normalizedBegin = begin >= 0 ? begin : list.length + begin; + var normalizedEnd = end >= 0 ? end : list.length + end; + var segments = []; + for (var i = 0; i < context.count; ++i) { + var allPrevSegments = []; + for (var j = normalizedBegin; j <= normalizedEnd; ++j) { + allPrevSegments.push(list[j][i]); + } + segments.push(create(context.idGenerator.next(), allPrevSegments)); + } + return segments; + } + + /** + * `segments` becomes doubly in a `finally` block. Then if a code path exits by a + * control statement (such as `break`, `continue`) from the `finally` block, the + * destination's segments may be half of the source segments. In that case, this + * merges segments. + * @param {ForkContext} context An instance. + * @param {CodePathSegment[]} segments Segments to merge. + * @returns {CodePathSegment[]} The merged segments. + */ + function mergeExtraSegments(context, segments) { + var currentSegments = segments; + while (currentSegments.length > context.count) { + var merged = []; + for (var i = 0, length = currentSegments.length / 2 | 0; i < length; ++i) { + merged.push(CodePathSegment.newNext(context.idGenerator.next(), [currentSegments[i], currentSegments[i + length]])); + } + currentSegments = merged; + } + return currentSegments; + } + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * A class to manage forking. + */ + class ForkContext { + /** + * @param {IdGenerator} idGenerator An identifier generator for segments. + * @param {ForkContext|null} upper An upper fork context. + * @param {number} count A number of parallel segments. + */ + constructor(idGenerator, upper, count) { + this.idGenerator = idGenerator; + this.upper = upper; + this.count = count; + this.segmentsList = []; + } + + /** + * The head segments. + * @type {CodePathSegment[]} + */ + get head() { + var list = this.segmentsList; + return list.length === 0 ? [] : list[list.length - 1]; + } + + /** + * A flag which shows empty. + * @type {boolean} + */ + get empty() { + return this.segmentsList.length === 0; + } + + /** + * A flag which shows reachable. + * @type {boolean} + */ + get reachable() { + var segments = this.head; + return segments.length > 0 && segments.some(isReachable); + } + + /** + * Creates new segments from this context. + * @param {number} begin The first index of previous segments. + * @param {number} end The last index of previous segments. + * @returns {CodePathSegment[]} New segments. + */ + makeNext(begin, end) { + return makeSegments(this, begin, end, CodePathSegment.newNext); + } + + /** + * Creates new segments from this context. + * The new segments is always unreachable. + * @param {number} begin The first index of previous segments. + * @param {number} end The last index of previous segments. + * @returns {CodePathSegment[]} New segments. + */ + makeUnreachable(begin, end) { + return makeSegments(this, begin, end, CodePathSegment.newUnreachable); + } + + /** + * Creates new segments from this context. + * The new segments don't have connections for previous segments. + * But these inherit the reachable flag from this context. + * @param {number} begin The first index of previous segments. + * @param {number} end The last index of previous segments. + * @returns {CodePathSegment[]} New segments. + */ + makeDisconnected(begin, end) { + return makeSegments(this, begin, end, CodePathSegment.newDisconnected); + } + + /** + * Adds segments into this context. + * The added segments become the head. + * @param {CodePathSegment[]} segments Segments to add. + * @returns {void} + */ + add(segments) { + assert(segments.length >= this.count, segments.length + " >= " + this.count); + this.segmentsList.push(mergeExtraSegments(this, segments)); + } + + /** + * Replaces the head segments with given segments. + * The current head segments are removed. + * @param {CodePathSegment[]} segments Segments to add. + * @returns {void} + */ + replaceHead(segments) { + assert(segments.length >= this.count, segments.length + " >= " + this.count); + this.segmentsList.splice(-1, 1, mergeExtraSegments(this, segments)); + } + + /** + * Adds all segments of a given fork context into this context. + * @param {ForkContext} context A fork context to add. + * @returns {void} + */ + addAll(context) { + assert(context.count === this.count); + var source = context.segmentsList; + for (var i = 0; i < source.length; ++i) { + this.segmentsList.push(source[i]); + } + } + + /** + * Clears all segments in this context. + * @returns {void} + */ + clear() { + this.segmentsList = []; + } + + /** + * Creates the root fork context. + * @param {IdGenerator} idGenerator An identifier generator for segments. + * @returns {ForkContext} New fork context. + */ + static newRoot(idGenerator) { + var context = new ForkContext(idGenerator, null, 1); + context.add([CodePathSegment.newRoot(idGenerator.next())]); + return context; + } + + /** + * Creates an empty fork context preceded by a given context. + * @param {ForkContext} parentContext The parent fork context. + * @param {boolean} forkLeavingPath A flag which shows inside of `finally` block. + * @returns {ForkContext} New fork context. + */ + static newEmpty(parentContext, forkLeavingPath) { + return new ForkContext(parentContext.idGenerator, parentContext, (forkLeavingPath ? 2 : 1) * parentContext.count); + } + } + forkContext = ForkContext; + return forkContext; +} + +var codePathState; +var hasRequiredCodePathState; +function requireCodePathState() { + if (hasRequiredCodePathState) return codePathState; + hasRequiredCodePathState = 1; + + //------------------------------------------------------------------------------ + // Requirements + //------------------------------------------------------------------------------ + + // eslint-disable-next-line + var CodePathSegment = requireCodePathSegment(); + // eslint-disable-next-line + var ForkContext = requireForkContext(); + + //------------------------------------------------------------------------------ + // Helpers + //------------------------------------------------------------------------------ + + /** + * Adds given segments into the `dest` array. + * If the `others` array does not includes the given segments, adds to the `all` + * array as well. + * + * This adds only reachable and used segments. + * @param {CodePathSegment[]} dest A destination array (`returnedSegments` or `thrownSegments`). + * @param {CodePathSegment[]} others Another destination array (`returnedSegments` or `thrownSegments`). + * @param {CodePathSegment[]} all The unified destination array (`finalSegments`). + * @param {CodePathSegment[]} segments Segments to add. + * @returns {void} + */ + function addToReturnedOrThrown(dest, others, all, segments) { + for (var i = 0; i < segments.length; ++i) { + var segment = segments[i]; + dest.push(segment); + if (!others.includes(segment)) { + all.push(segment); + } + } + } + + /** + * Gets a loop-context for a `continue` statement. + * @param {CodePathState} state A state to get. + * @param {string} label The label of a `continue` statement. + * @returns {LoopContext} A loop-context for a `continue` statement. + */ + function getContinueContext(state, label) { + if (!label) { + return state.loopContext; + } + var context = state.loopContext; + while (context) { + if (context.label === label) { + return context; + } + context = context.upper; + } + + /* c8 ignore next */ + return null; + } + + /** + * Gets a context for a `break` statement. + * @param {CodePathState} state A state to get. + * @param {string} label The label of a `break` statement. + * @returns {LoopContext|SwitchContext} A context for a `break` statement. + */ + function getBreakContext(state, label) { + var context = state.breakContext; + while (context) { + if (label ? context.label === label : context.breakable) { + return context; + } + context = context.upper; + } + + /* c8 ignore next */ + return null; + } + + /** + * Gets a context for a `return` statement. + * @param {CodePathState} state A state to get. + * @returns {TryContext|CodePathState} A context for a `return` statement. + */ + function getReturnContext(state) { + var context = state.tryContext; + while (context) { + if (context.hasFinalizer && context.position !== 'finally') { + return context; + } + context = context.upper; + } + return state; + } + + /** + * Gets a context for a `throw` statement. + * @param {CodePathState} state A state to get. + * @returns {TryContext|CodePathState} A context for a `throw` statement. + */ + function getThrowContext(state) { + var context = state.tryContext; + while (context) { + if (context.position === 'try' || context.hasFinalizer && context.position === 'catch') { + return context; + } + context = context.upper; + } + return state; + } + + /** + * Removes a given element from a given array. + * @param {any[]} xs An array to remove the specific element. + * @param {any} x An element to be removed. + * @returns {void} + */ + function remove(xs, x) { + xs.splice(xs.indexOf(x), 1); + } + + /** + * Disconnect given segments. + * + * This is used in a process for switch statements. + * If there is the "default" chunk before other cases, the order is different + * between node's and running's. + * @param {CodePathSegment[]} prevSegments Forward segments to disconnect. + * @param {CodePathSegment[]} nextSegments Backward segments to disconnect. + * @returns {void} + */ + function removeConnection(prevSegments, nextSegments) { + for (var i = 0; i < prevSegments.length; ++i) { + var prevSegment = prevSegments[i]; + var nextSegment = nextSegments[i]; + remove(prevSegment.nextSegments, nextSegment); + remove(prevSegment.allNextSegments, nextSegment); + remove(nextSegment.prevSegments, prevSegment); + remove(nextSegment.allPrevSegments, prevSegment); + } + } + + /** + * Creates looping path. + * @param {CodePathState} state The instance. + * @param {CodePathSegment[]} unflattenedFromSegments Segments which are source. + * @param {CodePathSegment[]} unflattenedToSegments Segments which are destination. + * @returns {void} + */ + function makeLooped(state, unflattenedFromSegments, unflattenedToSegments) { + var fromSegments = CodePathSegment.flattenUnusedSegments(unflattenedFromSegments); + var toSegments = CodePathSegment.flattenUnusedSegments(unflattenedToSegments); + var end = Math.min(fromSegments.length, toSegments.length); + for (var i = 0; i < end; ++i) { + var fromSegment = fromSegments[i]; + var toSegment = toSegments[i]; + if (toSegment.reachable) { + fromSegment.nextSegments.push(toSegment); + } + if (fromSegment.reachable) { + toSegment.prevSegments.push(fromSegment); + } + fromSegment.allNextSegments.push(toSegment); + toSegment.allPrevSegments.push(fromSegment); + if (toSegment.allPrevSegments.length >= 2) { + CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment); + } + state.notifyLooped(fromSegment, toSegment); + } + } + + /** + * Finalizes segments of `test` chunk of a ForStatement. + * + * - Adds `false` paths to paths which are leaving from the loop. + * - Sets `true` paths to paths which go to the body. + * @param {LoopContext} context A loop context to modify. + * @param {ChoiceContext} choiceContext A choice context of this loop. + * @param {CodePathSegment[]} head The current head paths. + * @returns {void} + */ + function finalizeTestSegmentsOfFor(context, choiceContext, head) { + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(head); + choiceContext.falseForkContext.add(head); + choiceContext.qqForkContext.add(head); + } + if (context.test !== true) { + context.brokenForkContext.addAll(choiceContext.falseForkContext); + } + context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1); + } + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * A class which manages state to analyze code paths. + */ + class CodePathState { + /** + * @param {IdGenerator} idGenerator An id generator to generate id for code + * path segments. + * @param {Function} onLooped A callback function to notify looping. + */ + constructor(idGenerator, onLooped) { + this.idGenerator = idGenerator; + this.notifyLooped = onLooped; + this.forkContext = ForkContext.newRoot(idGenerator); + this.choiceContext = null; + this.switchContext = null; + this.tryContext = null; + this.loopContext = null; + this.breakContext = null; + this.chainContext = null; + this.currentSegments = []; + this.initialSegment = this.forkContext.head[0]; + + // returnedSegments and thrownSegments push elements into finalSegments also. + var final = this.finalSegments = []; + var returned = this.returnedForkContext = []; + var thrown = this.thrownForkContext = []; + returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final); + thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final); + } + + /** + * The head segments. + * @type {CodePathSegment[]} + */ + get headSegments() { + return this.forkContext.head; + } + + /** + * The parent forking context. + * This is used for the root of new forks. + * @type {ForkContext} + */ + get parentForkContext() { + var current = this.forkContext; + return current && current.upper; + } + + /** + * Creates and stacks new forking context. + * @param {boolean} forkLeavingPath A flag which shows being in a + * "finally" block. + * @returns {ForkContext} The created context. + */ + pushForkContext(forkLeavingPath) { + this.forkContext = ForkContext.newEmpty(this.forkContext, forkLeavingPath); + return this.forkContext; + } + + /** + * Pops and merges the last forking context. + * @returns {ForkContext} The last context. + */ + popForkContext() { + var lastContext = this.forkContext; + this.forkContext = lastContext.upper; + this.forkContext.replaceHead(lastContext.makeNext(0, -1)); + return lastContext; + } + + /** + * Creates a new path. + * @returns {void} + */ + forkPath() { + this.forkContext.add(this.parentForkContext.makeNext(-1, -1)); + } + + /** + * Creates a bypass path. + * This is used for such as IfStatement which does not have "else" chunk. + * @returns {void} + */ + forkBypassPath() { + this.forkContext.add(this.parentForkContext.head); + } + + //-------------------------------------------------------------------------- + // ConditionalExpression, LogicalExpression, IfStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context for ConditionalExpression, LogicalExpression, AssignmentExpression (logical assignments only), + * IfStatement, WhileStatement, DoWhileStatement, or ForStatement. + * + * LogicalExpressions have cases that it goes different paths between the + * `true` case and the `false` case. + * + * For Example: + * + * if (a || b) { + * foo(); + * } else { + * bar(); + * } + * + * In this case, `b` is evaluated always in the code path of the `else` + * block, but it's not so in the code path of the `if` block. + * So there are 3 paths. + * + * a -> foo(); + * a -> b -> foo(); + * a -> b -> bar(); + * @param {string} kind A kind string. + * If the new context is LogicalExpression's or AssignmentExpression's, this is `"&&"` or `"||"` or `"??"`. + * If it's IfStatement's or ConditionalExpression's, this is `"test"`. + * Otherwise, this is `"loop"`. + * @param {boolean} isForkingAsResult A flag that shows that goes different + * paths between `true` and `false`. + * @returns {void} + */ + pushChoiceContext(kind, isForkingAsResult) { + this.choiceContext = { + upper: this.choiceContext, + kind: kind, + isForkingAsResult: isForkingAsResult, + trueForkContext: ForkContext.newEmpty(this.forkContext), + falseForkContext: ForkContext.newEmpty(this.forkContext), + qqForkContext: ForkContext.newEmpty(this.forkContext), + processed: false + }; + } + + /** + * Pops the last choice context and finalizes it. + * @throws {Error} (Unreachable.) + * @returns {ChoiceContext} The popped context. + */ + popChoiceContext() { + var context = this.choiceContext; + this.choiceContext = context.upper; + var forkContext = this.forkContext; + var headSegments = forkContext.head; + switch (context.kind) { + case '&&': + case '||': + case '??': + /* + * If any result were not transferred from child contexts, + * this sets the head segments to both cases. + * The head segments are the path of the right-hand operand. + */ + if (!context.processed) { + context.trueForkContext.add(headSegments); + context.falseForkContext.add(headSegments); + context.qqForkContext.add(headSegments); + } + + /* + * Transfers results to upper context if this context is in + * test chunk. + */ + if (context.isForkingAsResult) { + var parentContext = this.choiceContext; + parentContext.trueForkContext.addAll(context.trueForkContext); + parentContext.falseForkContext.addAll(context.falseForkContext); + parentContext.qqForkContext.addAll(context.qqForkContext); + parentContext.processed = true; + return context; + } + break; + case 'test': + if (!context.processed) { + /* + * The head segments are the path of the `if` block here. + * Updates the `true` path with the end of the `if` block. + */ + context.trueForkContext.clear(); + context.trueForkContext.add(headSegments); + } else { + /* + * The head segments are the path of the `else` block here. + * Updates the `false` path with the end of the `else` + * block. + */ + context.falseForkContext.clear(); + context.falseForkContext.add(headSegments); + } + break; + case 'loop': + /* + * Loops are addressed in popLoopContext(). + * This is called from popLoopContext(). + */ + return context; + + /* c8 ignore next */ + default: + throw new Error('unreachable'); + } + + // Merges all paths. + var prevForkContext = context.trueForkContext; + prevForkContext.addAll(context.falseForkContext); + forkContext.replaceHead(prevForkContext.makeNext(0, -1)); + return context; + } + + /** + * Makes a code path segment of the right-hand operand of a logical + * expression. + * @throws {Error} (Unreachable.) + * @returns {void} + */ + makeLogicalRight() { + var context = this.choiceContext; + var forkContext = this.forkContext; + if (context.processed) { + /* + * This got segments already from the child choice context. + * Creates the next path from own true/false fork context. + */ + var prevForkContext; + switch (context.kind) { + case '&&': + // if true then go to the right-hand side. + prevForkContext = context.trueForkContext; + break; + case '||': + // if false then go to the right-hand side. + prevForkContext = context.falseForkContext; + break; + case '??': + // Both true/false can short-circuit, so needs the third path to go to the right-hand side. That's qqForkContext. + prevForkContext = context.qqForkContext; + break; + default: + throw new Error('unreachable'); + } + forkContext.replaceHead(prevForkContext.makeNext(0, -1)); + prevForkContext.clear(); + context.processed = false; + } else { + /* + * This did not get segments from the child choice context. + * So addresses the head segments. + * The head segments are the path of the left-hand operand. + */ + switch (context.kind) { + case '&&': + // the false path can short-circuit. + context.falseForkContext.add(forkContext.head); + break; + case '||': + // the true path can short-circuit. + context.trueForkContext.add(forkContext.head); + break; + case '??': + // both can short-circuit. + context.trueForkContext.add(forkContext.head); + context.falseForkContext.add(forkContext.head); + break; + default: + throw new Error('unreachable'); + } + forkContext.replaceHead(forkContext.makeNext(-1, -1)); + } + } + + /** + * Makes a code path segment of the `if` block. + * @returns {void} + */ + makeIfConsequent() { + var context = this.choiceContext; + var forkContext = this.forkContext; + + /* + * If any result were not transferred from child contexts, + * this sets the head segments to both cases. + * The head segments are the path of the test expression. + */ + if (!context.processed) { + context.trueForkContext.add(forkContext.head); + context.falseForkContext.add(forkContext.head); + context.qqForkContext.add(forkContext.head); + } + context.processed = false; + + // Creates new path from the `true` case. + forkContext.replaceHead(context.trueForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment of the `else` block. + * @returns {void} + */ + makeIfAlternate() { + var context = this.choiceContext; + var forkContext = this.forkContext; + + /* + * The head segments are the path of the `if` block. + * Updates the `true` path with the end of the `if` block. + */ + context.trueForkContext.clear(); + context.trueForkContext.add(forkContext.head); + context.processed = true; + + // Creates new path from the `false` case. + forkContext.replaceHead(context.falseForkContext.makeNext(0, -1)); + } + + //-------------------------------------------------------------------------- + // ChainExpression + //-------------------------------------------------------------------------- + + /** + * Push a new `ChainExpression` context to the stack. + * This method is called on entering to each `ChainExpression` node. + * This context is used to count forking in the optional chain then merge them on the exiting from the `ChainExpression` node. + * @returns {void} + */ + pushChainContext() { + this.chainContext = { + upper: this.chainContext, + countChoiceContexts: 0 + }; + } + + /** + * Pop a `ChainExpression` context from the stack. + * This method is called on exiting from each `ChainExpression` node. + * This merges all forks of the last optional chaining. + * @returns {void} + */ + popChainContext() { + var context = this.chainContext; + this.chainContext = context.upper; + + // pop all choice contexts of this. + for (var i = context.countChoiceContexts; i > 0; --i) { + this.popChoiceContext(); + } + } + + /** + * Create a choice context for optional access. + * This method is called on entering to each `(Call|Member)Expression[optional=true]` node. + * This creates a choice context as similar to `LogicalExpression[operator="??"]` node. + * @returns {void} + */ + makeOptionalNode() { + if (this.chainContext) { + this.chainContext.countChoiceContexts += 1; + this.pushChoiceContext('??', false); + } + } + + /** + * Create a fork. + * This method is called on entering to the `arguments|property` property of each `(Call|Member)Expression` node. + * @returns {void} + */ + makeOptionalRight() { + if (this.chainContext) { + this.makeLogicalRight(); + } + } + + //-------------------------------------------------------------------------- + // SwitchStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context object of SwitchStatement and stacks it. + * @param {boolean} hasCase `true` if the switch statement has one or more + * case parts. + * @param {string|null} label The label text. + * @returns {void} + */ + pushSwitchContext(hasCase, label) { + this.switchContext = { + upper: this.switchContext, + hasCase: hasCase, + defaultSegments: null, + defaultBodySegments: null, + foundDefault: false, + lastIsDefault: false, + countForks: 0 + }; + this.pushBreakContext(true, label); + } + + /** + * Pops the last context of SwitchStatement and finalizes it. + * + * - Disposes all forking stack for `case` and `default`. + * - Creates the next code path segment from `context.brokenForkContext`. + * - If the last `SwitchCase` node is not a `default` part, creates a path + * to the `default` body. + * @returns {void} + */ + popSwitchContext() { + var context = this.switchContext; + this.switchContext = context.upper; + var forkContext = this.forkContext; + var brokenForkContext = this.popBreakContext().brokenForkContext; + if (context.countForks === 0) { + /* + * When there is only one `default` chunk and there is one or more + * `break` statements, even if forks are nothing, it needs to merge + * those. + */ + if (!brokenForkContext.empty) { + brokenForkContext.add(forkContext.makeNext(-1, -1)); + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + return; + } + var lastSegments = forkContext.head; + this.forkBypassPath(); + var lastCaseSegments = forkContext.head; + + /* + * `brokenForkContext` is used to make the next segment. + * It must add the last segment into `brokenForkContext`. + */ + brokenForkContext.add(lastSegments); + + /* + * A path which is failed in all case test should be connected to path + * of `default` chunk. + */ + if (!context.lastIsDefault) { + if (context.defaultBodySegments) { + /* + * Remove a link from `default` label to its chunk. + * It's false route. + */ + removeConnection(context.defaultSegments, context.defaultBodySegments); + makeLooped(this, lastCaseSegments, context.defaultBodySegments); + } else { + /* + * It handles the last case body as broken if `default` chunk + * does not exist. + */ + brokenForkContext.add(lastCaseSegments); + } + } + + // Pops the segment context stack until the entry segment. + for (var i = 0; i < context.countForks; ++i) { + this.forkContext = this.forkContext.upper; + } + + /* + * Creates a path from all brokenForkContext paths. + * This is a path after switch statement. + */ + this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment for a `SwitchCase` node. + * @param {boolean} isEmpty `true` if the body is empty. + * @param {boolean} isDefault `true` if the body is the default case. + * @returns {void} + */ + makeSwitchCaseBody(isEmpty, isDefault) { + var context = this.switchContext; + if (!context.hasCase) { + return; + } + + /* + * Merge forks. + * The parent fork context has two segments. + * Those are from the current case and the body of the previous case. + */ + var parentForkContext = this.forkContext; + var forkContext = this.pushForkContext(); + forkContext.add(parentForkContext.makeNext(0, -1)); + + /* + * Save `default` chunk info. + * If the `default` label is not at the last, we must make a path from + * the last `case` to the `default` chunk. + */ + if (isDefault) { + context.defaultSegments = parentForkContext.head; + if (isEmpty) { + context.foundDefault = true; + } else { + context.defaultBodySegments = forkContext.head; + } + } else { + if (!isEmpty && context.foundDefault) { + context.foundDefault = false; + context.defaultBodySegments = forkContext.head; + } + } + context.lastIsDefault = isDefault; + context.countForks += 1; + } + + //-------------------------------------------------------------------------- + // TryStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context object of TryStatement and stacks it. + * @param {boolean} hasFinalizer `true` if the try statement has a + * `finally` block. + * @returns {void} + */ + pushTryContext(hasFinalizer) { + this.tryContext = { + upper: this.tryContext, + position: 'try', + hasFinalizer: hasFinalizer, + returnedForkContext: hasFinalizer ? ForkContext.newEmpty(this.forkContext) : null, + thrownForkContext: ForkContext.newEmpty(this.forkContext), + lastOfTryIsReachable: false, + lastOfCatchIsReachable: false + }; + } + + /** + * Pops the last context of TryStatement and finalizes it. + * @returns {void} + */ + popTryContext() { + var context = this.tryContext; + this.tryContext = context.upper; + if (context.position === 'catch') { + // Merges two paths from the `try` block and `catch` block merely. + this.popForkContext(); + return; + } + + /* + * The following process is executed only when there is the `finally` + * block. + */ + + var returned = context.returnedForkContext; + var thrown = context.thrownForkContext; + if (returned.empty && thrown.empty) { + return; + } + + // Separate head to normal paths and leaving paths. + var headSegments = this.forkContext.head; + this.forkContext = this.forkContext.upper; + var normalSegments = headSegments.slice(0, headSegments.length / 2 | 0); + var leavingSegments = headSegments.slice(headSegments.length / 2 | 0); + + // Forwards the leaving path to upper contexts. + if (!returned.empty) { + getReturnContext(this).returnedForkContext.add(leavingSegments); + } + if (!thrown.empty) { + getThrowContext(this).thrownForkContext.add(leavingSegments); + } + + // Sets the normal path as the next. + this.forkContext.replaceHead(normalSegments); + + /* + * If both paths of the `try` block and the `catch` block are + * unreachable, the next path becomes unreachable as well. + */ + if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) { + this.forkContext.makeUnreachable(); + } + } + + /** + * Makes a code path segment for a `catch` block. + * @returns {void} + */ + makeCatchBlock() { + var context = this.tryContext; + var forkContext = this.forkContext; + var thrown = context.thrownForkContext; + + // Update state. + context.position = 'catch'; + context.thrownForkContext = ForkContext.newEmpty(forkContext); + context.lastOfTryIsReachable = forkContext.reachable; + + // Merge thrown paths. + thrown.add(forkContext.head); + var thrownSegments = thrown.makeNext(0, -1); + + // Fork to a bypass and the merged thrown path. + this.pushForkContext(); + this.forkBypassPath(); + this.forkContext.add(thrownSegments); + } + + /** + * Makes a code path segment for a `finally` block. + * + * In the `finally` block, parallel paths are created. The parallel paths + * are used as leaving-paths. The leaving-paths are paths from `return` + * statements and `throw` statements in a `try` block or a `catch` block. + * @returns {void} + */ + makeFinallyBlock() { + var context = this.tryContext; + var forkContext = this.forkContext; + var returned = context.returnedForkContext; + var thrown = context.thrownForkContext; + var headOfLeavingSegments = forkContext.head; + + // Update state. + if (context.position === 'catch') { + // Merges two paths from the `try` block and `catch` block. + this.popForkContext(); + forkContext = this.forkContext; + context.lastOfCatchIsReachable = forkContext.reachable; + } else { + context.lastOfTryIsReachable = forkContext.reachable; + } + context.position = 'finally'; + if (returned.empty && thrown.empty) { + // This path does not leave. + return; + } + + /* + * Create a parallel segment from merging returned and thrown. + * This segment will leave at the end of this finally block. + */ + var segments = forkContext.makeNext(-1, -1); + for (var i = 0; i < forkContext.count; ++i) { + var prevSegsOfLeavingSegment = [headOfLeavingSegments[i]]; + for (var j = 0; j < returned.segmentsList.length; ++j) { + prevSegsOfLeavingSegment.push(returned.segmentsList[j][i]); + } + for (var _j = 0; _j < thrown.segmentsList.length; ++_j) { + prevSegsOfLeavingSegment.push(thrown.segmentsList[_j][i]); + } + segments.push(CodePathSegment.newNext(this.idGenerator.next(), prevSegsOfLeavingSegment)); + } + this.pushForkContext(true); + this.forkContext.add(segments); + } + + /** + * Makes a code path segment from the first throwable node to the `catch` + * block or the `finally` block. + * @returns {void} + */ + makeFirstThrowablePathInTryBlock() { + var forkContext = this.forkContext; + if (!forkContext.reachable) { + return; + } + var context = getThrowContext(this); + if (context === this || context.position !== 'try' || !context.thrownForkContext.empty) { + return; + } + context.thrownForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeNext(-1, -1)); + } + + //-------------------------------------------------------------------------- + // Loop Statements + //-------------------------------------------------------------------------- + + /** + * Creates a context object of a loop statement and stacks it. + * @param {string} type The type of the node which was triggered. One of + * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`, + * and `ForStatement`. + * @param {string|null} label A label of the node which was triggered. + * @throws {Error} (Unreachable - unknown type.) + * @returns {void} + */ + pushLoopContext(type, label) { + var forkContext = this.forkContext; + var breakContext = this.pushBreakContext(true, label); + switch (type) { + case 'WhileStatement': + this.pushChoiceContext('loop', false); + this.loopContext = { + upper: this.loopContext, + type: type, + label: label, + test: void 0, + continueDestSegments: null, + brokenForkContext: breakContext.brokenForkContext + }; + break; + case 'DoWhileStatement': + this.pushChoiceContext('loop', false); + this.loopContext = { + upper: this.loopContext, + type: type, + label: label, + test: void 0, + entrySegments: null, + continueForkContext: ForkContext.newEmpty(forkContext), + brokenForkContext: breakContext.brokenForkContext + }; + break; + case 'ForStatement': + this.pushChoiceContext('loop', false); + this.loopContext = { + upper: this.loopContext, + type: type, + label: label, + test: void 0, + endOfInitSegments: null, + testSegments: null, + endOfTestSegments: null, + updateSegments: null, + endOfUpdateSegments: null, + continueDestSegments: null, + brokenForkContext: breakContext.brokenForkContext + }; + break; + case 'ForInStatement': + case 'ForOfStatement': + this.loopContext = { + upper: this.loopContext, + type: type, + label: label, + prevSegments: null, + leftSegments: null, + endOfLeftSegments: null, + continueDestSegments: null, + brokenForkContext: breakContext.brokenForkContext + }; + break; + + /* c8 ignore next */ + default: + throw new Error("unknown type: \"" + type + "\""); + } + } + + /** + * Pops the last context of a loop statement and finalizes it. + * @throws {Error} (Unreachable - unknown type.) + * @returns {void} + */ + popLoopContext() { + var context = this.loopContext; + this.loopContext = context.upper; + var forkContext = this.forkContext; + var brokenForkContext = this.popBreakContext().brokenForkContext; + + // Creates a looped path. + switch (context.type) { + case 'WhileStatement': + case 'ForStatement': + this.popChoiceContext(); + makeLooped(this, forkContext.head, context.continueDestSegments); + break; + case 'DoWhileStatement': + { + var choiceContext = this.popChoiceContext(); + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(forkContext.head); + choiceContext.falseForkContext.add(forkContext.head); + } + if (context.test !== true) { + brokenForkContext.addAll(choiceContext.falseForkContext); + } + + // `true` paths go to looping. + var segmentsList = choiceContext.trueForkContext.segmentsList; + for (var i = 0; i < segmentsList.length; ++i) { + makeLooped(this, segmentsList[i], context.entrySegments); + } + break; + } + case 'ForInStatement': + case 'ForOfStatement': + brokenForkContext.add(forkContext.head); + makeLooped(this, forkContext.head, context.leftSegments); + break; + + /* c8 ignore next */ + default: + throw new Error('unreachable'); + } + + // Go next. + if (brokenForkContext.empty) { + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } else { + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + } + + /** + * Makes a code path segment for the test part of a WhileStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeWhileTest(test) { + var context = this.loopContext; + var forkContext = this.forkContext; + var testSegments = forkContext.makeNext(0, -1); + + // Update state. + context.test = test; + context.continueDestSegments = testSegments; + forkContext.replaceHead(testSegments); + } + + /** + * Makes a code path segment for the body part of a WhileStatement. + * @returns {void} + */ + makeWhileBody() { + var context = this.loopContext; + var choiceContext = this.choiceContext; + var forkContext = this.forkContext; + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(forkContext.head); + choiceContext.falseForkContext.add(forkContext.head); + } + + // Update state. + if (context.test !== true) { + context.brokenForkContext.addAll(choiceContext.falseForkContext); + } + forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment for the body part of a DoWhileStatement. + * @returns {void} + */ + makeDoWhileBody() { + var context = this.loopContext; + var forkContext = this.forkContext; + var bodySegments = forkContext.makeNext(-1, -1); + + // Update state. + context.entrySegments = bodySegments; + forkContext.replaceHead(bodySegments); + } + + /** + * Makes a code path segment for the test part of a DoWhileStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeDoWhileTest(test) { + var context = this.loopContext; + var forkContext = this.forkContext; + context.test = test; + + // Creates paths of `continue` statements. + if (!context.continueForkContext.empty) { + context.continueForkContext.add(forkContext.head); + var testSegments = context.continueForkContext.makeNext(0, -1); + forkContext.replaceHead(testSegments); + } + } + + /** + * Makes a code path segment for the test part of a ForStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeForTest(test) { + var context = this.loopContext; + var forkContext = this.forkContext; + var endOfInitSegments = forkContext.head; + var testSegments = forkContext.makeNext(-1, -1); + + // Update state. + context.test = test; + context.endOfInitSegments = endOfInitSegments; + context.continueDestSegments = context.testSegments = testSegments; + forkContext.replaceHead(testSegments); + } + + /** + * Makes a code path segment for the update part of a ForStatement. + * @returns {void} + */ + makeForUpdate() { + var context = this.loopContext; + var choiceContext = this.choiceContext; + var forkContext = this.forkContext; + + // Make the next paths of the test. + if (context.testSegments) { + finalizeTestSegmentsOfFor(context, choiceContext, forkContext.head); + } else { + context.endOfInitSegments = forkContext.head; + } + + // Update state. + var updateSegments = forkContext.makeDisconnected(-1, -1); + context.continueDestSegments = context.updateSegments = updateSegments; + forkContext.replaceHead(updateSegments); + } + + /** + * Makes a code path segment for the body part of a ForStatement. + * @returns {void} + */ + makeForBody() { + var context = this.loopContext; + var choiceContext = this.choiceContext; + var forkContext = this.forkContext; + + // Update state. + if (context.updateSegments) { + context.endOfUpdateSegments = forkContext.head; + + // `update` -> `test` + if (context.testSegments) { + makeLooped(this, context.endOfUpdateSegments, context.testSegments); + } + } else if (context.testSegments) { + finalizeTestSegmentsOfFor(context, choiceContext, forkContext.head); + } else { + context.endOfInitSegments = forkContext.head; + } + var bodySegments = context.endOfTestSegments; + if (!bodySegments) { + /* + * If there is not the `test` part, the `body` path comes from the + * `init` part and the `update` part. + */ + var prevForkContext = ForkContext.newEmpty(forkContext); + prevForkContext.add(context.endOfInitSegments); + if (context.endOfUpdateSegments) { + prevForkContext.add(context.endOfUpdateSegments); + } + bodySegments = prevForkContext.makeNext(0, -1); + } + context.continueDestSegments = context.continueDestSegments || bodySegments; + forkContext.replaceHead(bodySegments); + } + + /** + * Makes a code path segment for the left part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfLeft() { + var context = this.loopContext; + var forkContext = this.forkContext; + var leftSegments = forkContext.makeDisconnected(-1, -1); + + // Update state. + context.prevSegments = forkContext.head; + context.leftSegments = context.continueDestSegments = leftSegments; + forkContext.replaceHead(leftSegments); + } + + /** + * Makes a code path segment for the right part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfRight() { + var context = this.loopContext; + var forkContext = this.forkContext; + var temp = ForkContext.newEmpty(forkContext); + temp.add(context.prevSegments); + var rightSegments = temp.makeNext(-1, -1); + + // Update state. + context.endOfLeftSegments = forkContext.head; + forkContext.replaceHead(rightSegments); + } + + /** + * Makes a code path segment for the body part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfBody() { + var context = this.loopContext; + var forkContext = this.forkContext; + var temp = ForkContext.newEmpty(forkContext); + temp.add(context.endOfLeftSegments); + var bodySegments = temp.makeNext(-1, -1); + + // Make a path: `right` -> `left`. + makeLooped(this, forkContext.head, context.leftSegments); + + // Update state. + context.brokenForkContext.add(forkContext.head); + forkContext.replaceHead(bodySegments); + } + + //-------------------------------------------------------------------------- + // Control Statements + //-------------------------------------------------------------------------- + + /** + * Creates new context for BreakStatement. + * @param {boolean} breakable The flag to indicate it can break by + * an unlabeled BreakStatement. + * @param {string|null} label The label of this context. + * @returns {Object} The new context. + */ + pushBreakContext(breakable, label) { + this.breakContext = { + upper: this.breakContext, + breakable: breakable, + label: label, + brokenForkContext: ForkContext.newEmpty(this.forkContext) + }; + return this.breakContext; + } + + /** + * Removes the top item of the break context stack. + * @returns {Object} The removed context. + */ + popBreakContext() { + var context = this.breakContext; + var forkContext = this.forkContext; + this.breakContext = context.upper; + + // Process this context here for other than switches and loops. + if (!context.breakable) { + var brokenForkContext = context.brokenForkContext; + if (!brokenForkContext.empty) { + brokenForkContext.add(forkContext.head); + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + } + return context; + } + + /** + * Makes a path for a `break` statement. + * + * It registers the head segment to a context of `break`. + * It makes new unreachable segment, then it set the head with the segment. + * @param {string} label A label of the break statement. + * @returns {void} + */ + makeBreak(label) { + var forkContext = this.forkContext; + if (!forkContext.reachable) { + return; + } + var context = getBreakContext(this, label); + if (context) { + context.brokenForkContext.add(forkContext.head); + } + + /* c8 ignore next */ + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + + /** + * Makes a path for a `continue` statement. + * + * It makes a looping path. + * It makes new unreachable segment, then it set the head with the segment. + * @param {string} label A label of the continue statement. + * @returns {void} + */ + makeContinue(label) { + var forkContext = this.forkContext; + if (!forkContext.reachable) { + return; + } + var context = getContinueContext(this, label); + if (context) { + if (context.continueDestSegments) { + makeLooped(this, forkContext.head, context.continueDestSegments); + + // If the context is a for-in/of loop, this effects a break also. + if (context.type === 'ForInStatement' || context.type === 'ForOfStatement') { + context.brokenForkContext.add(forkContext.head); + } + } else { + context.continueForkContext.add(forkContext.head); + } + } + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + + /** + * Makes a path for a `return` statement. + * + * It registers the head segment to a context of `return`. + * It makes new unreachable segment, then it set the head with the segment. + * @returns {void} + */ + makeReturn() { + var forkContext = this.forkContext; + if (forkContext.reachable) { + getReturnContext(this).returnedForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + } + + /** + * Makes a path for a `throw` statement. + * + * It registers the head segment to a context of `throw`. + * It makes new unreachable segment, then it set the head with the segment. + * @returns {void} + */ + makeThrow() { + var forkContext = this.forkContext; + if (forkContext.reachable) { + getThrowContext(this).thrownForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + } + + /** + * Makes the final path. + * @returns {void} + */ + makeFinal() { + var segments = this.currentSegments; + if (segments.length > 0 && segments[0].reachable) { + this.returnedForkContext.add(segments); + } + } + } + codePathState = CodePathState; + return codePathState; +} + +var idGenerator; +var hasRequiredIdGenerator; +function requireIdGenerator() { + if (hasRequiredIdGenerator) return idGenerator; + hasRequiredIdGenerator = 1; + + /* eslint-disable react-internal/safe-string-coercion */ + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * A generator for unique ids. + */ + class IdGenerator { + /** + * @param {string} prefix Optional. A prefix of generated ids. + */ + constructor(prefix) { + this.prefix = String(prefix); + this.n = 0; + } + + /** + * Generates id. + * @returns {string} A generated id. + */ + next() { + this.n = 1 + this.n | 0; + + /* c8 ignore start */ + if (this.n < 0) { + this.n = 1; + } /* c8 ignore stop */ + + return this.prefix + this.n; + } + } + idGenerator = IdGenerator; + return idGenerator; +} + +var codePath; +var hasRequiredCodePath; +function requireCodePath() { + if (hasRequiredCodePath) return codePath; + hasRequiredCodePath = 1; + + //------------------------------------------------------------------------------ + // Requirements + //------------------------------------------------------------------------------ + + // eslint-disable-next-line + var CodePathState = requireCodePathState(); + // eslint-disable-next-line + var IdGenerator = requireIdGenerator(); + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * A code path. + */ + class CodePath { + /** + * Creates a new instance. + * @param {Object} options Options for the function (see below). + * @param {string} options.id An identifier. + * @param {string} options.origin The type of code path origin. + * @param {CodePath|null} options.upper The code path of the upper function scope. + * @param {Function} options.onLooped A callback function to notify looping. + */ + constructor(_ref) { + var id = _ref.id, + origin = _ref.origin, + upper = _ref.upper, + onLooped = _ref.onLooped; + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * The reason that this code path was started. May be "program", + * "function", "class-field-initializer", or "class-static-block". + * @type {string} + */ + this.origin = origin; + + /** + * The code path of the upper function scope. + * @type {CodePath|null} + */ + this.upper = upper; + + /** + * The code paths of nested function scopes. + * @type {CodePath[]} + */ + this.childCodePaths = []; + + // Initializes internal state. + Object.defineProperty(this, 'internal', { + value: new CodePathState(new IdGenerator(id + "_"), onLooped) + }); + + // Adds this into `childCodePaths` of `upper`. + if (upper) { + upper.childCodePaths.push(this); + } + } + + /** + * Gets the state of a given code path. + * @param {CodePath} codePath A code path to get. + * @returns {CodePathState} The state of the code path. + */ + static getState(codePath) { + return codePath.internal; + } + + /** + * The initial code path segment. + * @type {CodePathSegment} + */ + get initialSegment() { + return this.internal.initialSegment; + } + + /** + * Final code path segments. + * This array is a mix of `returnedSegments` and `thrownSegments`. + * @type {CodePathSegment[]} + */ + get finalSegments() { + return this.internal.finalSegments; + } + + /** + * Final code path segments which is with `return` statements. + * This array contains the last path segment if it's reachable. + * Since the reachable last path returns `undefined`. + * @type {CodePathSegment[]} + */ + get returnedSegments() { + return this.internal.returnedForkContext; + } + + /** + * Final code path segments which is with `throw` statements. + * @type {CodePathSegment[]} + */ + get thrownSegments() { + return this.internal.thrownForkContext; + } + + /** + * Current code path segments. + * @type {CodePathSegment[]} + */ + get currentSegments() { + return this.internal.currentSegments; + } + + /** + * Traverses all segments in this code path. + * + * codePath.traverseSegments(function(segment, controller) { + * // do something. + * }); + * + * This method enumerates segments in order from the head. + * + * The `controller` object has two methods. + * + * - `controller.skip()` - Skip the following segments in this branch. + * - `controller.break()` - Skip all following segments. + * @param {Object} [options] Omittable. + * @param {CodePathSegment} [options.first] The first segment to traverse. + * @param {CodePathSegment} [options.last] The last segment to traverse. + * @param {Function} callback A callback function. + * @returns {void} + */ + traverseSegments(options, callback) { + var resolvedOptions; + var resolvedCallback; + if (typeof options === 'function') { + resolvedCallback = options; + resolvedOptions = {}; + } else { + resolvedOptions = options || {}; + resolvedCallback = callback; + } + var startSegment = resolvedOptions.first || this.internal.initialSegment; + var lastSegment = resolvedOptions.last; + var item = null; + var index = 0; + var end = 0; + var segment = null; + var visited = Object.create(null); + var stack = [[startSegment, 0]]; + var skippedSegment = null; + var broken = false; + var controller = { + skip: function () { + if (stack.length <= 1) { + broken = true; + } else { + skippedSegment = stack[stack.length - 2][0]; + } + }, + break: function () { + broken = true; + } + }; + + /** + * Checks a given previous segment has been visited. + * @param {CodePathSegment} prevSegment A previous segment to check. + * @returns {boolean} `true` if the segment has been visited. + */ + function isVisited(prevSegment) { + return visited[prevSegment.id] || segment.isLoopedPrevSegment(prevSegment); + } + while (stack.length > 0) { + item = stack[stack.length - 1]; + segment = item[0]; + index = item[1]; + if (index === 0) { + // Skip if this segment has been visited already. + if (visited[segment.id]) { + stack.pop(); + continue; + } + + // Skip if all previous segments have not been visited. + if (segment !== startSegment && segment.prevSegments.length > 0 && !segment.prevSegments.every(isVisited)) { + stack.pop(); + continue; + } + + // Reset the flag of skipping if all branches have been skipped. + if (skippedSegment && segment.prevSegments.includes(skippedSegment)) { + skippedSegment = null; + } + visited[segment.id] = true; + + // Call the callback when the first time. + if (!skippedSegment) { + resolvedCallback.call(this, segment, controller); + if (segment === lastSegment) { + controller.skip(); + } + if (broken) { + break; + } + } + } + + // Update the stack. + end = segment.nextSegments.length - 1; + if (index < end) { + item[1] += 1; + stack.push([segment.nextSegments[index], 0]); + } else if (index === end) { + item[0] = segment.nextSegments[index]; + item[1] = 0; + } else { + stack.pop(); + } + } + } + } + codePath = CodePath; + return codePath; +} + +var codePathAnalyzer; +var hasRequiredCodePathAnalyzer; +function requireCodePathAnalyzer() { + if (hasRequiredCodePathAnalyzer) return codePathAnalyzer; + hasRequiredCodePathAnalyzer = 1; + + /* eslint-disable react-internal/no-primitive-constructors */ + + //------------------------------------------------------------------------------ + // Requirements + //------------------------------------------------------------------------------ + + // eslint-disable-next-line + var assert = requireAssert(); + // eslint-disable-next-line + var CodePath = requireCodePath(); + // eslint-disable-next-line + var CodePathSegment = requireCodePathSegment(); + // eslint-disable-next-line + var IdGenerator = requireIdGenerator(); + var breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u; + + //------------------------------------------------------------------------------ + // Helpers + //------------------------------------------------------------------------------ + + /** + * Checks whether or not a given node is a `case` node (not `default` node). + * @param {ASTNode} node A `SwitchCase` node to check. + * @returns {boolean} `true` if the node is a `case` node (not `default` node). + */ + function isCaseNode(node) { + return Boolean(node.test); + } + + /** + * Checks if a given node appears as the value of a PropertyDefinition node. + * @param {ASTNode} node THe node to check. + * @returns {boolean} `true` if the node is a PropertyDefinition value, + * false if not. + */ + function isPropertyDefinitionValue(node) { + var parent = node.parent; + return parent && parent.type === 'PropertyDefinition' && parent.value === node; + } + + /** + * Checks whether the given logical operator is taken into account for the code + * path analysis. + * @param {string} operator The operator found in the LogicalExpression node + * @returns {boolean} `true` if the operator is "&&" or "||" or "??" + */ + function isHandledLogicalOperator(operator) { + return operator === '&&' || operator === '||' || operator === '??'; + } + + /** + * Checks whether the given assignment operator is a logical assignment operator. + * Logical assignments are taken into account for the code path analysis + * because of their short-circuiting semantics. + * @param {string} operator The operator found in the AssignmentExpression node + * @returns {boolean} `true` if the operator is "&&=" or "||=" or "??=" + */ + function isLogicalAssignmentOperator(operator) { + return operator === '&&=' || operator === '||=' || operator === '??='; + } + + /** + * Gets the label if the parent node of a given node is a LabeledStatement. + * @param {ASTNode} node A node to get. + * @returns {string|null} The label or `null`. + */ + function getLabel(node) { + if (node.parent.type === 'LabeledStatement') { + return node.parent.label.name; + } + return null; + } + + /** + * Checks whether or not a given logical expression node goes different path + * between the `true` case and the `false` case. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a test of a choice statement. + */ + function isForkingByTrueOrFalse(node) { + var parent = node.parent; + switch (parent.type) { + case 'ConditionalExpression': + case 'IfStatement': + case 'WhileStatement': + case 'DoWhileStatement': + case 'ForStatement': + return parent.test === node; + case 'LogicalExpression': + return isHandledLogicalOperator(parent.operator); + case 'AssignmentExpression': + return isLogicalAssignmentOperator(parent.operator); + default: + return false; + } + } + + /** + * Gets the boolean value of a given literal node. + * + * This is used to detect infinity loops (e.g. `while (true) {}`). + * Statements preceded by an infinity loop are unreachable if the loop didn't + * have any `break` statement. + * @param {ASTNode} node A node to get. + * @returns {boolean|undefined} a boolean value if the node is a Literal node, + * otherwise `undefined`. + */ + function getBooleanValueIfSimpleConstant(node) { + if (node.type === 'Literal') { + return Boolean(node.value); + } + return void 0; + } + + /** + * Checks that a given identifier node is a reference or not. + * + * This is used to detect the first throwable node in a `try` block. + * @param {ASTNode} node An Identifier node to check. + * @returns {boolean} `true` if the node is a reference. + */ + function isIdentifierReference(node) { + var parent = node.parent; + switch (parent.type) { + case 'LabeledStatement': + case 'BreakStatement': + case 'ContinueStatement': + case 'ArrayPattern': + case 'RestElement': + case 'ImportSpecifier': + case 'ImportDefaultSpecifier': + case 'ImportNamespaceSpecifier': + case 'CatchClause': + return false; + case 'FunctionDeclaration': + case 'ComponentDeclaration': + case 'HookDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + case 'ClassDeclaration': + case 'ClassExpression': + case 'VariableDeclarator': + return parent.id !== node; + case 'Property': + case 'PropertyDefinition': + case 'MethodDefinition': + return parent.key !== node || parent.computed || parent.shorthand; + case 'AssignmentPattern': + return parent.key !== node; + default: + return true; + } + } + + /** + * Updates the current segment with the head segment. + * This is similar to local branches and tracking branches of git. + * + * To separate the current and the head is in order to not make useless segments. + * + * In this process, both "onCodePathSegmentStart" and "onCodePathSegmentEnd" + * events are fired. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function forwardCurrentToHead(analyzer, node) { + var codePath = analyzer.codePath; + var state = CodePath.getState(codePath); + var currentSegments = state.currentSegments; + var headSegments = state.headSegments; + var end = Math.max(currentSegments.length, headSegments.length); + var i, currentSegment, headSegment; + + // Fires leaving events. + for (i = 0; i < end; ++i) { + currentSegment = currentSegments[i]; + headSegment = headSegments[i]; + if (currentSegment !== headSegment && currentSegment) { + if (currentSegment.reachable) { + analyzer.emitter.emit('onCodePathSegmentEnd', currentSegment, node); + } + } + } + + // Update state. + state.currentSegments = headSegments; + + // Fires entering events. + for (i = 0; i < end; ++i) { + currentSegment = currentSegments[i]; + headSegment = headSegments[i]; + if (currentSegment !== headSegment && headSegment) { + CodePathSegment.markUsed(headSegment); + if (headSegment.reachable) { + analyzer.emitter.emit('onCodePathSegmentStart', headSegment, node); + } + } + } + } + + /** + * Updates the current segment with empty. + * This is called at the last of functions or the program. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function leaveFromCurrentSegment(analyzer, node) { + var state = CodePath.getState(analyzer.codePath); + var currentSegments = state.currentSegments; + for (var i = 0; i < currentSegments.length; ++i) { + var currentSegment = currentSegments[i]; + if (currentSegment.reachable) { + analyzer.emitter.emit('onCodePathSegmentEnd', currentSegment, node); + } + } + state.currentSegments = []; + } + + /** + * Updates the code path due to the position of a given node in the parent node + * thereof. + * + * For example, if the node is `parent.consequent`, this creates a fork from the + * current path. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function preprocess(analyzer, node) { + var codePath = analyzer.codePath; + var state = CodePath.getState(codePath); + var parent = node.parent; + switch (parent.type) { + // The `arguments.length == 0` case is in `postprocess` function. + case 'CallExpression': + if (parent.optional === true && parent.arguments.length >= 1 && parent.arguments[0] === node) { + state.makeOptionalRight(); + } + break; + case 'MemberExpression': + if (parent.optional === true && parent.property === node) { + state.makeOptionalRight(); + } + break; + case 'LogicalExpression': + if (parent.right === node && isHandledLogicalOperator(parent.operator)) { + state.makeLogicalRight(); + } + break; + case 'AssignmentExpression': + if (parent.right === node && isLogicalAssignmentOperator(parent.operator)) { + state.makeLogicalRight(); + } + break; + case 'ConditionalExpression': + case 'IfStatement': + /* + * Fork if this node is at `consequent`/`alternate`. + * `popForkContext()` exists at `IfStatement:exit` and + * `ConditionalExpression:exit`. + */ + if (parent.consequent === node) { + state.makeIfConsequent(); + } else if (parent.alternate === node) { + state.makeIfAlternate(); + } + break; + case 'SwitchCase': + if (parent.consequent[0] === node) { + state.makeSwitchCaseBody(false, !parent.test); + } + break; + case 'TryStatement': + if (parent.handler === node) { + state.makeCatchBlock(); + } else if (parent.finalizer === node) { + state.makeFinallyBlock(); + } + break; + case 'WhileStatement': + if (parent.test === node) { + state.makeWhileTest(getBooleanValueIfSimpleConstant(node)); + } else { + assert(parent.body === node); + state.makeWhileBody(); + } + break; + case 'DoWhileStatement': + if (parent.body === node) { + state.makeDoWhileBody(); + } else { + assert(parent.test === node); + state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node)); + } + break; + case 'ForStatement': + if (parent.test === node) { + state.makeForTest(getBooleanValueIfSimpleConstant(node)); + } else if (parent.update === node) { + state.makeForUpdate(); + } else if (parent.body === node) { + state.makeForBody(); + } + break; + case 'ForInStatement': + case 'ForOfStatement': + if (parent.left === node) { + state.makeForInOfLeft(); + } else if (parent.right === node) { + state.makeForInOfRight(); + } else { + assert(parent.body === node); + state.makeForInOfBody(); + } + break; + case 'AssignmentPattern': + /* + * Fork if this node is at `right`. + * `left` is executed always, so it uses the current path. + * `popForkContext()` exists at `AssignmentPattern:exit`. + */ + if (parent.right === node) { + state.pushForkContext(); + state.forkBypassPath(); + state.forkPath(); + } + break; + } + } + + /** + * Updates the code path due to the type of a given node in entering. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function processCodePathToEnter(analyzer, node) { + var codePath = analyzer.codePath; + var state = codePath && CodePath.getState(codePath); + var parent = node.parent; + + /** + * Creates a new code path and trigger the onCodePathStart event + * based on the currently selected node. + * @param {string} origin The reason the code path was started. + * @returns {void} + */ + function startCodePath(origin) { + if (codePath) { + // Emits onCodePathSegmentStart events if updated. + forwardCurrentToHead(analyzer, node); + } + + // Create the code path of this scope. + codePath = analyzer.codePath = new CodePath({ + id: analyzer.idGenerator.next(), + origin: origin, + upper: codePath, + onLooped: analyzer.onLooped + }); + state = CodePath.getState(codePath); + + // Emits onCodePathStart events. + analyzer.emitter.emit('onCodePathStart', codePath, node); + } + + /* + * Special case: The right side of class field initializer is considered + * to be its own function, so we need to start a new code path in this + * case. + */ + if (isPropertyDefinitionValue(node)) { + startCodePath('class-field-initializer'); + + /* + * Intentional fall through because `node` needs to also be + * processed by the code below. For example, if we have: + * + * class Foo { + * a = () => {} + * } + * + * In this case, we also need start a second code path. + */ + } + switch (node.type) { + case 'Program': + startCodePath('program'); + break; + case 'FunctionDeclaration': + case 'ComponentDeclaration': + case 'HookDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + startCodePath('function'); + break; + case 'StaticBlock': + startCodePath('class-static-block'); + break; + case 'ChainExpression': + state.pushChainContext(); + break; + case 'CallExpression': + if (node.optional === true) { + state.makeOptionalNode(); + } + break; + case 'MemberExpression': + if (node.optional === true) { + state.makeOptionalNode(); + } + break; + case 'LogicalExpression': + if (isHandledLogicalOperator(node.operator)) { + state.pushChoiceContext(node.operator, isForkingByTrueOrFalse(node)); + } + break; + case 'AssignmentExpression': + if (isLogicalAssignmentOperator(node.operator)) { + state.pushChoiceContext(node.operator.slice(0, -1), + // removes `=` from the end + isForkingByTrueOrFalse(node)); + } + break; + case 'ConditionalExpression': + case 'IfStatement': + state.pushChoiceContext('test', false); + break; + case 'SwitchStatement': + state.pushSwitchContext(node.cases.some(isCaseNode), getLabel(node)); + break; + case 'TryStatement': + state.pushTryContext(Boolean(node.finalizer)); + break; + case 'SwitchCase': + /* + * Fork if this node is after the 2st node in `cases`. + * It's similar to `else` blocks. + * The next `test` node is processed in this path. + */ + if (parent.discriminant !== node && parent.cases[0] !== node) { + state.forkPath(); + } + break; + case 'WhileStatement': + case 'DoWhileStatement': + case 'ForStatement': + case 'ForInStatement': + case 'ForOfStatement': + state.pushLoopContext(node.type, getLabel(node)); + break; + case 'LabeledStatement': + if (!breakableTypePattern.test(node.body.type)) { + state.pushBreakContext(false, node.label.name); + } + break; + } + + // Emits onCodePathSegmentStart events if updated. + forwardCurrentToHead(analyzer, node); + } + + /** + * Updates the code path due to the type of a given node in leaving. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function processCodePathToExit(analyzer, node) { + var codePath = analyzer.codePath; + var state = CodePath.getState(codePath); + var dontForward = false; + switch (node.type) { + case 'ChainExpression': + state.popChainContext(); + break; + case 'IfStatement': + case 'ConditionalExpression': + state.popChoiceContext(); + break; + case 'LogicalExpression': + if (isHandledLogicalOperator(node.operator)) { + state.popChoiceContext(); + } + break; + case 'AssignmentExpression': + if (isLogicalAssignmentOperator(node.operator)) { + state.popChoiceContext(); + } + break; + case 'SwitchStatement': + state.popSwitchContext(); + break; + case 'SwitchCase': + /* + * This is the same as the process at the 1st `consequent` node in + * `preprocess` function. + * Must do if this `consequent` is empty. + */ + if (node.consequent.length === 0) { + state.makeSwitchCaseBody(true, !node.test); + } + if (state.forkContext.reachable) { + dontForward = true; + } + break; + case 'TryStatement': + state.popTryContext(); + break; + case 'BreakStatement': + forwardCurrentToHead(analyzer, node); + state.makeBreak(node.label && node.label.name); + dontForward = true; + break; + case 'ContinueStatement': + forwardCurrentToHead(analyzer, node); + state.makeContinue(node.label && node.label.name); + dontForward = true; + break; + case 'ReturnStatement': + forwardCurrentToHead(analyzer, node); + state.makeReturn(); + dontForward = true; + break; + case 'ThrowStatement': + forwardCurrentToHead(analyzer, node); + state.makeThrow(); + dontForward = true; + break; + case 'Identifier': + if (isIdentifierReference(node)) { + state.makeFirstThrowablePathInTryBlock(); + dontForward = true; + } + break; + case 'CallExpression': + case 'ImportExpression': + case 'MemberExpression': + case 'NewExpression': + case 'YieldExpression': + state.makeFirstThrowablePathInTryBlock(); + break; + case 'WhileStatement': + case 'DoWhileStatement': + case 'ForStatement': + case 'ForInStatement': + case 'ForOfStatement': + state.popLoopContext(); + break; + case 'AssignmentPattern': + state.popForkContext(); + break; + case 'LabeledStatement': + if (!breakableTypePattern.test(node.body.type)) { + state.popBreakContext(); + } + break; + } + + // Emits onCodePathSegmentStart events if updated. + if (!dontForward) { + forwardCurrentToHead(analyzer, node); + } + } + + /** + * Updates the code path to finalize the current code path. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function postprocess(analyzer, node) { + /** + * Ends the code path for the current node. + * @returns {void} + */ + function endCodePath() { + var codePath = analyzer.codePath; + + // Mark the current path as the final node. + CodePath.getState(codePath).makeFinal(); + + // Emits onCodePathSegmentEnd event of the current segments. + leaveFromCurrentSegment(analyzer, node); + + // Emits onCodePathEnd event of this code path. + analyzer.emitter.emit('onCodePathEnd', codePath, node); + codePath = analyzer.codePath = analyzer.codePath.upper; + } + switch (node.type) { + case 'Program': + case 'FunctionDeclaration': + case 'ComponentDeclaration': + case 'HookDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + case 'StaticBlock': + { + endCodePath(); + break; + } + + // The `arguments.length >= 1` case is in `preprocess` function. + case 'CallExpression': + if (node.optional === true && node.arguments.length === 0) { + CodePath.getState(analyzer.codePath).makeOptionalRight(); + } + break; + } + + /* + * Special case: The right side of class field initializer is considered + * to be its own function, so we need to end a code path in this + * case. + * + * We need to check after the other checks in order to close the + * code paths in the correct order for code like this: + * + * + * class Foo { + * a = () => {} + * } + * + * In this case, The ArrowFunctionExpression code path is closed first + * and then we need to close the code path for the PropertyDefinition + * value. + */ + if (isPropertyDefinitionValue(node)) { + endCodePath(); + } + } + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * The class to analyze code paths. + * This class implements the EventGenerator interface. + */ + class CodePathAnalyzer { + /** + * @param {EventGenerator} eventGenerator An event generator to wrap. + */ + constructor(emitters) { + this.emitter = { + emit: function (event) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + emitters[event]?.(...args); + } + }; + this.codePath = null; + this.idGenerator = new IdGenerator('s'); + this.currentNode = null; + this.onLooped = this.onLooped.bind(this); + } + + /** + * Does the process to enter a given AST node. + * This updates state of analysis and calls `enterNode` of the wrapped. + * @param {ASTNode} node A node which is entering. + * @returns {void} + */ + enterNode(node) { + this.currentNode = node; + + // Updates the code path due to node's position in its parent node. + if (node.parent) { + preprocess(this, node); + } + + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ + processCodePathToEnter(this, node); + this.currentNode = null; + } + + /** + * Does the process to leave a given AST node. + * This updates state of analysis and calls `leaveNode` of the wrapped. + * @param {ASTNode} node A node which is leaving. + * @returns {void} + */ + leaveNode(node) { + this.currentNode = node; + + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ + processCodePathToExit(this, node); + + // Emits the last onCodePathStart/onCodePathSegmentStart events. + postprocess(this, node); + this.currentNode = null; + } + + /** + * This is called on a code path looped. + * Then this raises a looped event. + * @param {CodePathSegment} fromSegment A segment of prev. + * @param {CodePathSegment} toSegment A segment of next. + * @returns {void} + */ + onLooped(fromSegment, toSegment) { + if (fromSegment.reachable && toSegment.reachable) { + this.emitter.emit('onCodePathSegmentLoop', fromSegment, toSegment, this.currentNode); + } + } + } + codePathAnalyzer = CodePathAnalyzer; + return codePathAnalyzer; +} + +var codePathAnalyzerExports = requireCodePathAnalyzer(); +var CodePathAnalyzer = /*@__PURE__*/getDefaultExportFromCjs(codePathAnalyzerExports); + +function isHookName(s) { + return s === 'use' || /^use[A-Z0-9]/.test(s); +} +function isHook(node) { + if (node.type === 'Identifier') { + return isHookName(node.name); + } + else if (node.type === 'MemberExpression' && + !node.computed && + isHook(node.property)) { + const obj = node.object; + const isPascalCaseNameSpace = /^[A-Z].*/; + return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name); + } + else { + return false; + } +} +function isComponentName(node) { + return node.type === 'Identifier' && /^[A-Z]/.test(node.name); +} +function isReactFunction(node, functionName) { + return (('name' in node && node.name === functionName) || + (node.type === 'MemberExpression' && + 'name' in node.object && + node.object.name === 'React' && + 'name' in node.property && + node.property.name === functionName)); +} +function isForwardRefCallback(node) { + return !!(node.parent && + 'callee' in node.parent && + node.parent.callee && + isReactFunction(node.parent.callee, 'forwardRef')); +} +function isMemoCallback(node) { + return !!(node.parent && + 'callee' in node.parent && + node.parent.callee && + isReactFunction(node.parent.callee, 'memo')); +} +function isInsideComponentOrHook(node) { + while (node) { + const functionName = getFunctionName(node); + if (functionName) { + if (isComponentName(functionName) || isHook(functionName)) { + return true; + } + } + if (isForwardRefCallback(node) || isMemoCallback(node)) { + return true; + } + node = node.parent; + } + return false; +} +function isInsideDoWhileLoop(node) { + while (node) { + if (node.type === 'DoWhileStatement') { + return true; + } + node = node.parent; + } + return false; +} +function isInsideTryCatch(node) { + while (node) { + if (node.type === 'TryStatement' || node.type === 'CatchClause') { + return true; + } + node = node.parent; + } + return false; +} +function getNodeWithoutReactNamespace(node) { + if (node.type === 'MemberExpression' && + node.object.type === 'Identifier' && + node.object.name === 'React' && + node.property.type === 'Identifier' && + !node.computed) { + return node.property; + } + return node; +} +function isEffectIdentifier(node, additionalHooks) { + const isBuiltInEffect = node.type === 'Identifier' && + (node.name === 'useEffect' || + node.name === 'useLayoutEffect' || + node.name === 'useInsertionEffect'); + if (isBuiltInEffect) { + return true; + } + if (additionalHooks && node.type === 'Identifier') { + return additionalHooks.test(node.name); + } + return false; +} +function isUseEffectEventIdentifier(node) { + return node.type === 'Identifier' && node.name === 'useEffectEvent'; +} +function useEffectEventError(fn, called) { + if (fn === null) { + return (`React Hook "useEffectEvent" can only be called at the top level of your component.` + + ` It cannot be passed down.`); + } + return (`\`${fn}\` is a function created with React Hook "useEffectEvent", and can only be called from ` + + 'Effects and Effect Events in the same component.' + + (called ? '' : ' It cannot be assigned to a variable or passed down.')); +} +function isUseIdentifier(node) { + return isReactFunction(node, 'use'); +} +const rule = { + meta: { + type: 'problem', + docs: { + description: 'enforces the Rules of Hooks', + recommended: true, + url: 'https://react.dev/reference/rules/rules-of-hooks', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + additionalHooks: { + type: 'string', + }, + }, + }, + ], + }, + create(context) { + const settings = context.settings || {}; + const additionalEffectHooks = getAdditionalEffectHooksFromSettings(settings); + let lastEffect = null; + const codePathReactHooksMapStack = []; + const codePathSegmentStack = []; + const useEffectEventFunctions = new WeakSet(); + function recordAllUseEffectEventFunctions(scope) { + for (const reference of scope.references) { + const parent = reference.identifier.parent; + if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'VariableDeclarator' && + parent.init && + parent.init.type === 'CallExpression' && + parent.init.callee && + isUseEffectEventIdentifier(parent.init.callee)) { + if (reference.resolved === null) { + throw new Error('Unexpected null reference.resolved'); + } + for (const ref of reference.resolved.references) { + if (ref !== reference) { + useEffectEventFunctions.add(ref.identifier); + } + } + } + } + } + const getSourceCode = typeof context.getSourceCode === 'function' + ? () => { + return context.getSourceCode(); + } + : () => { + return context.sourceCode; + }; + const getScope = typeof context.getScope === 'function' + ? () => { + return context.getScope(); + } + : (node) => { + return getSourceCode().getScope(node); + }; + function hasFlowSuppression(node, suppression) { + const sourceCode = getSourceCode(); + const comments = sourceCode.getAllComments(); + const flowSuppressionRegex = new RegExp('\\$FlowFixMe\\[' + suppression + '\\]'); + return comments.some(commentNode => flowSuppressionRegex.test(commentNode.value) && + commentNode.loc != null && + node.loc != null && + commentNode.loc.end.line === node.loc.start.line - 1); + } + const analyzer = new CodePathAnalyzer({ + onCodePathSegmentStart: (segment) => codePathSegmentStack.push(segment), + onCodePathSegmentEnd: () => codePathSegmentStack.pop(), + onCodePathStart: () => codePathReactHooksMapStack.push(new Map()), + onCodePathEnd(codePath, codePathNode) { + const reactHooksMap = codePathReactHooksMapStack.pop(); + if ((reactHooksMap === null || reactHooksMap === void 0 ? void 0 : reactHooksMap.size) === 0) { + return; + } + else if (typeof reactHooksMap === 'undefined') { + throw new Error('Unexpected undefined reactHooksMap'); + } + const cyclic = new Set(); + function countPathsFromStart(segment, pathHistory) { + const { cache } = countPathsFromStart; + let paths = cache.get(segment.id); + const pathList = new Set(pathHistory); + if (pathList.has(segment.id)) { + const pathArray = [...pathList]; + const cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1); + for (const cyclicSegment of cyclicSegments) { + cyclic.add(cyclicSegment); + } + return BigInt('0'); + } + pathList.add(segment.id); + if (paths !== undefined) { + return paths; + } + if (codePath.thrownSegments.includes(segment)) { + paths = BigInt('0'); + } + else if (segment.prevSegments.length === 0) { + paths = BigInt('1'); + } + else { + paths = BigInt('0'); + for (const prevSegment of segment.prevSegments) { + paths += countPathsFromStart(prevSegment, pathList); + } + } + if (segment.reachable && paths === BigInt('0')) { + cache.delete(segment.id); + } + else { + cache.set(segment.id, paths); + } + return paths; + } + function countPathsToEnd(segment, pathHistory) { + const { cache } = countPathsToEnd; + let paths = cache.get(segment.id); + const pathList = new Set(pathHistory); + if (pathList.has(segment.id)) { + const pathArray = Array.from(pathList); + const cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1); + for (const cyclicSegment of cyclicSegments) { + cyclic.add(cyclicSegment); + } + return BigInt('0'); + } + pathList.add(segment.id); + if (paths !== undefined) { + return paths; + } + if (codePath.thrownSegments.includes(segment)) { + paths = BigInt('0'); + } + else if (segment.nextSegments.length === 0) { + paths = BigInt('1'); + } + else { + paths = BigInt('0'); + for (const nextSegment of segment.nextSegments) { + paths += countPathsToEnd(nextSegment, pathList); + } + } + cache.set(segment.id, paths); + return paths; + } + function shortestPathLengthToStart(segment) { + const { cache } = shortestPathLengthToStart; + let length = cache.get(segment.id); + if (length === null) { + return Infinity; + } + if (length !== undefined) { + return length; + } + cache.set(segment.id, null); + if (segment.prevSegments.length === 0) { + length = 1; + } + else { + length = Infinity; + for (const prevSegment of segment.prevSegments) { + const prevLength = shortestPathLengthToStart(prevSegment); + if (prevLength < length) { + length = prevLength; + } + } + length += 1; + } + cache.set(segment.id, length); + return length; + } + countPathsFromStart.cache = new Map(); + countPathsToEnd.cache = new Map(); + shortestPathLengthToStart.cache = new Map(); + const allPathsFromStartToEnd = countPathsToEnd(codePath.initialSegment); + const codePathFunctionName = getFunctionName(codePathNode); + const isSomewhereInsideComponentOrHook = isInsideComponentOrHook(codePathNode); + const isDirectlyInsideComponentOrHook = codePathFunctionName + ? isComponentName(codePathFunctionName) || + isHook(codePathFunctionName) + : isForwardRefCallback(codePathNode) || isMemoCallback(codePathNode); + let shortestFinalPathLength = Infinity; + for (const finalSegment of codePath.finalSegments) { + if (!finalSegment.reachable) { + continue; + } + const length = shortestPathLengthToStart(finalSegment); + if (length < shortestFinalPathLength) { + shortestFinalPathLength = length; + } + } + for (const [segment, reactHooks] of reactHooksMap) { + if (!segment.reachable) { + continue; + } + const possiblyHasEarlyReturn = segment.nextSegments.length === 0 + ? shortestFinalPathLength <= shortestPathLengthToStart(segment) + : shortestFinalPathLength < shortestPathLengthToStart(segment); + const pathsFromStartToEnd = countPathsFromStart(segment) * countPathsToEnd(segment); + const cycled = cyclic.has(segment.id); + for (const hook of reactHooks) { + if (hasFlowSuppression(hook, 'react-rule-hook')) { + continue; + } + if (isUseIdentifier(hook) && isInsideTryCatch(hook)) { + context.report({ + node: hook, + message: `React Hook "${getSourceCode().getText(hook)}" cannot be called in a try/catch block.`, + }); + } + if ((cycled || isInsideDoWhileLoop(hook)) && + !isUseIdentifier(hook)) { + context.report({ + node: hook, + message: `React Hook "${getSourceCode().getText(hook)}" may be executed ` + + 'more than once. Possibly because it is called in a loop. ' + + 'React Hooks must be called in the exact same order in ' + + 'every component render.', + }); + } + if (isDirectlyInsideComponentOrHook) { + const isAsyncFunction = codePathNode.async; + if (isAsyncFunction) { + context.report({ + node: hook, + message: `React Hook "${getSourceCode().getText(hook)}" cannot be ` + + 'called in an async function.', + }); + } + if (!cycled && + pathsFromStartToEnd !== allPathsFromStartToEnd && + !isUseIdentifier(hook) && + !isInsideDoWhileLoop(hook)) { + const message = `React Hook "${getSourceCode().getText(hook)}" is called ` + + 'conditionally. React Hooks must be called in the exact ' + + 'same order in every component render.' + + (possiblyHasEarlyReturn + ? ' Did you accidentally call a React Hook after an' + + ' early return?' + : ''); + context.report({ node: hook, message }); + } + } + else if (codePathNode.parent != null && + (codePathNode.parent.type === 'MethodDefinition' || + codePathNode.parent.type === 'ClassProperty' || + codePathNode.parent.type === 'PropertyDefinition') && + codePathNode.parent.value === codePathNode) { + const message = `React Hook "${getSourceCode().getText(hook)}" cannot be called ` + + 'in a class component. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message }); + } + else if (codePathFunctionName) { + const message = `React Hook "${getSourceCode().getText(hook)}" is called in ` + + `function "${getSourceCode().getText(codePathFunctionName)}" ` + + 'that is neither a React function component nor a custom ' + + 'React Hook function.' + + ' React component names must start with an uppercase letter.' + + ' React Hook names must start with the word "use".'; + context.report({ node: hook, message }); + } + else if (codePathNode.type === 'Program') { + const message = `React Hook "${getSourceCode().getText(hook)}" cannot be called ` + + 'at the top level. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message }); + } + else { + if (isSomewhereInsideComponentOrHook && !isUseIdentifier(hook)) { + const message = `React Hook "${getSourceCode().getText(hook)}" cannot be called ` + + 'inside a callback. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message }); + } + } + } + } + }, + }); + return { + '*'(node) { + analyzer.enterNode(node); + }, + '*:exit'(node) { + analyzer.leaveNode(node); + }, + CallExpression(node) { + var _a, _b; + if (isHook(node.callee)) { + const reactHooksMap = last(codePathReactHooksMapStack); + const codePathSegment = last(codePathSegmentStack); + let reactHooks = reactHooksMap.get(codePathSegment); + if (!reactHooks) { + reactHooks = []; + reactHooksMap.set(codePathSegment, reactHooks); + } + reactHooks.push(node.callee); + } + const nodeWithoutNamespace = getNodeWithoutReactNamespace(node.callee); + if ((isEffectIdentifier(nodeWithoutNamespace, additionalEffectHooks) || + isUseEffectEventIdentifier(nodeWithoutNamespace)) && + node.arguments.length > 0) { + lastEffect = node; + } + if (isUseEffectEventIdentifier(nodeWithoutNamespace) && + ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.type) !== 'VariableDeclarator' && + ((_b = node.parent) === null || _b === void 0 ? void 0 : _b.type) !== 'ExpressionStatement') { + const message = useEffectEventError(null, false); + context.report({ + node, + message, + }); + } + }, + Identifier(node) { + if (lastEffect == null && useEffectEventFunctions.has(node)) { + const message = useEffectEventError(getSourceCode().getText(node), node.parent.type === 'CallExpression'); + context.report({ + node, + message, + }); + } + }, + 'CallExpression:exit'(node) { + if (node === lastEffect) { + lastEffect = null; + } + }, + FunctionDeclaration(node) { + if (isInsideComponentOrHook(node)) { + recordAllUseEffectEventFunctions(getScope(node)); + } + }, + ArrowFunctionExpression(node) { + if (isInsideComponentOrHook(node)) { + recordAllUseEffectEventFunctions(getScope(node)); + } + }, + ComponentDeclaration(node) { + recordAllUseEffectEventFunctions(getScope(node)); + }, + HookDeclaration(node) { + recordAllUseEffectEventFunctions(getScope(node)); + }, + }; + }, +}; +function getFunctionName(node) { + var _a, _b, _c, _d; + if (node.type === 'ComponentDeclaration' || + node.type === 'HookDeclaration' || + node.type === 'FunctionDeclaration' || + (node.type === 'FunctionExpression' && node.id)) { + return node.id; + } + else if (node.type === 'FunctionExpression' || + node.type === 'ArrowFunctionExpression') { + if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.type) === 'VariableDeclarator' && + node.parent.init === node) { + return node.parent.id; + } + else if (((_b = node.parent) === null || _b === void 0 ? void 0 : _b.type) === 'AssignmentExpression' && + node.parent.right === node && + node.parent.operator === '=') { + return node.parent.left; + } + else if (((_c = node.parent) === null || _c === void 0 ? void 0 : _c.type) === 'Property' && + node.parent.value === node && + !node.parent.computed) { + return node.parent.key; + } + else if (((_d = node.parent) === null || _d === void 0 ? void 0 : _d.type) === 'AssignmentPattern' && + node.parent.right === node && + !node.parent.computed) { + return node.parent.left; + } + else { + return undefined; + } + } + else { + return undefined; + } +} +function last(array) { + return array[array.length - 1]; +} + +function makeDeprecatedRule(version) { + return { + meta: { + type: 'suggestion', + docs: { + description: `Deprecated: this rule has been removed in ${version}.`, + }, + schema: [], + deprecated: true, + }, + create() { + return {}; + }, + }; +} +const rules = Object.assign(Object.assign({ 'exhaustive-deps': rule$1, 'rules-of-hooks': rule }, Object.fromEntries(Object.entries(allRules).map(([name, config]) => [name, config.rule]))), { 'component-hook-factories': makeDeprecatedRule('7.1.0') }); +const basicRuleConfigs = { + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'warn', +}; +const recommendedCompilerRuleConfigs = Object.fromEntries(Object.entries(recommendedRules).map(([name, ruleConfig]) => { + return [ + `react-hooks/${name}`, + mapErrorSeverityToESlint(ruleConfig.severity), + ]; +})); +const recommendedLatestCompilerRuleConfigs = Object.fromEntries(Object.entries(recommendedLatestRules).map(([name, ruleConfig]) => { + return [ + `react-hooks/${name}`, + mapErrorSeverityToESlint(ruleConfig.severity), + ]; +})); +const recommendedRuleConfigs = Object.assign(Object.assign({}, basicRuleConfigs), recommendedCompilerRuleConfigs); +const recommendedLatestRuleConfigs = Object.assign(Object.assign({}, basicRuleConfigs), recommendedLatestCompilerRuleConfigs); +const plugins = ['react-hooks']; +const configs = { + recommended: { + plugins, + rules: recommendedRuleConfigs, + }, + 'recommended-latest': { + plugins, + rules: recommendedLatestRuleConfigs, + }, + flat: {}, +}; +const plugin = { + meta: { + name: 'eslint-plugin-react-hooks', + version: '7.0.0', + }, + rules, + configs, +}; +Object.assign(configs.flat, { + 'recommended-latest': { + plugins: { 'react-hooks': plugin }, + rules: configs['recommended-latest'].rules, + }, + recommended: { + plugins: { 'react-hooks': plugin }, + rules: configs.recommended.rules, + }, +}); + +module.exports = plugin; + })(); +} diff --git a/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.production.js b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.production.js new file mode 100644 index 0000000000000000000000000000000000000000..3c95a916f6556aabaac34d57087ace63ed7caa6a --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.production.js @@ -0,0 +1,55291 @@ +/** + * @license React + * eslint-plugin-react-hooks.production.js + * + * 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. + */ + +'use strict'; + +var core$1 = require('@babel/core'); +var BabelParser = require('@babel/parser'); +var v4 = require('zod/v4'); +var v4$1 = require('zod-validation-error/v4'); +var crypto = require('crypto'); +var HermesParser = require('hermes-parser'); +var util = require('util'); + +const SETTINGS_KEY = 'react-hooks'; +const SETTINGS_ADDITIONAL_EFFECT_HOOKS_KEY = 'additionalEffectHooks'; +function getAdditionalEffectHooksFromSettings(settings) { + var _a; + const additionalHooks = (_a = settings[SETTINGS_KEY]) === null || _a === void 0 ? void 0 : _a[SETTINGS_ADDITIONAL_EFFECT_HOOKS_KEY]; + if (additionalHooks != null && typeof additionalHooks === 'string') { + return new RegExp(additionalHooks); + } + return undefined; +} + +const rule$1 = { + meta: { + type: 'suggestion', + docs: { + description: 'verifies the list of dependencies for Hooks like useEffect and similar', + recommended: true, + url: 'https://github.com/facebook/react/issues/14920', + }, + fixable: 'code', + hasSuggestions: true, + schema: [ + { + type: 'object', + additionalProperties: false, + enableDangerousAutofixThisMayCauseInfiniteLoops: false, + properties: { + additionalHooks: { + type: 'string', + }, + enableDangerousAutofixThisMayCauseInfiniteLoops: { + type: 'boolean', + }, + experimental_autoDependenciesHooks: { + type: 'array', + items: { + type: 'string', + }, + }, + requireExplicitEffectDeps: { + type: 'boolean', + }, + }, + }, + ], + }, + create(context) { + const rawOptions = context.options && context.options[0]; + const settings = context.settings || {}; + const additionalHooks = rawOptions && rawOptions.additionalHooks + ? new RegExp(rawOptions.additionalHooks) + : getAdditionalEffectHooksFromSettings(settings); + const enableDangerousAutofixThisMayCauseInfiniteLoops = (rawOptions && + rawOptions.enableDangerousAutofixThisMayCauseInfiniteLoops) || + false; + const experimental_autoDependenciesHooks = rawOptions && Array.isArray(rawOptions.experimental_autoDependenciesHooks) + ? rawOptions.experimental_autoDependenciesHooks + : []; + const requireExplicitEffectDeps = (rawOptions && rawOptions.requireExplicitEffectDeps) || false; + const options = { + additionalHooks, + experimental_autoDependenciesHooks, + enableDangerousAutofixThisMayCauseInfiniteLoops, + requireExplicitEffectDeps, + }; + function reportProblem(problem) { + if (enableDangerousAutofixThisMayCauseInfiniteLoops) { + if (Array.isArray(problem.suggest) && + problem.suggest.length > 0 && + problem.suggest[0]) { + problem.fix = problem.suggest[0].fix; + } + } + context.report(problem); + } + const getSourceCode = typeof context.getSourceCode === 'function' + ? () => { + return context.getSourceCode(); + } + : () => { + return context.sourceCode; + }; + const getScope = typeof context.getScope === 'function' + ? () => { + return context.getScope(); + } + : (node) => { + return context.sourceCode.getScope(node); + }; + const scopeManager = getSourceCode().scopeManager; + const setStateCallSites = new WeakMap(); + const stateVariables = new WeakSet(); + const stableKnownValueCache = new WeakMap(); + const functionWithoutCapturedValueCache = new WeakMap(); + const useEffectEventVariables = new WeakSet(); + function memoizeWithWeakMap(fn, map) { + return function (arg) { + if (map.has(arg)) { + return map.get(arg); + } + const result = fn(arg); + map.set(arg, result); + return result; + }; + } + function visitFunctionWithDependencies(node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook) { + if (isEffect && node.async) { + reportProblem({ + node: node, + message: `Effect callbacks are synchronous to prevent race conditions. ` + + `Put the async function inside:\n\n` + + 'useEffect(() => {\n' + + ' async function fetchData() {\n' + + ' // You can await here\n' + + ' const response = await MyAPI.getData(someId);\n' + + ' // ...\n' + + ' }\n' + + ' fetchData();\n' + + `}, [someId]); // Or [] if effect doesn't need props or state\n\n` + + 'Learn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching', + }); + } + const scope = scopeManager.acquire(node); + if (!scope) { + throw new Error('Unable to acquire scope for the current node. This is a bug in eslint-plugin-react-hooks, please file an issue.'); + } + const pureScopes = new Set(); + let componentScope = null; + { + let currentScope = scope.upper; + while (currentScope) { + pureScopes.add(currentScope); + if (currentScope.type === 'function' || + currentScope.type === 'hook' || + currentScope.type === 'component') { + break; + } + currentScope = currentScope.upper; + } + if (!currentScope) { + return; + } + componentScope = currentScope; + } + const isArray = Array.isArray; + function isStableKnownHookValue(resolved) { + if (!isArray(resolved.defs)) { + return false; + } + const def = resolved.defs[0]; + if (def == null) { + return false; + } + const defNode = def.node; + if (defNode.type !== 'VariableDeclarator') { + return false; + } + let init = defNode.init; + if (init == null) { + return false; + } + while (init.type === 'TSAsExpression' || init.type === 'AsExpression') { + init = init.expression; + } + let declaration = defNode.parent; + if (declaration == null && componentScope != null) { + fastFindReferenceWithParent(componentScope.block, def.node.id); + declaration = def.node.parent; + if (declaration == null) { + return false; + } + } + if (declaration != null && + 'kind' in declaration && + declaration.kind === 'const' && + init.type === 'Literal' && + (typeof init.value === 'string' || + typeof init.value === 'number' || + init.value === null)) { + return true; + } + if (init.type !== 'CallExpression') { + return false; + } + let callee = init.callee; + if (callee.type === 'MemberExpression' && + 'name' in callee.object && + callee.object.name === 'React' && + callee.property != null && + !callee.computed) { + callee = callee.property; + } + if (callee.type !== 'Identifier') { + return false; + } + const definitionNode = def.node; + const id = definitionNode.id; + const { name } = callee; + if (name === 'useRef' && id.type === 'Identifier') { + return true; + } + else if (isUseEffectEventIdentifier$1(callee) && + id.type === 'Identifier') { + for (const ref of resolved.references) { + if (ref !== id) { + useEffectEventVariables.add(ref.identifier); + } + } + return true; + } + else if (name === 'useState' || + name === 'useReducer' || + name === 'useActionState') { + if (id.type === 'ArrayPattern' && + id.elements.length === 2 && + isArray(resolved.identifiers)) { + if (id.elements[1] === resolved.identifiers[0]) { + if (name === 'useState') { + const references = resolved.references; + let writeCount = 0; + for (const reference of references) { + if (reference.isWrite()) { + writeCount++; + } + if (writeCount > 1) { + return false; + } + setStateCallSites.set(reference.identifier, id.elements[0]); + } + } + return true; + } + else if (id.elements[0] === resolved.identifiers[0]) { + if (name === 'useState') { + const references = resolved.references; + for (const reference of references) { + stateVariables.add(reference.identifier); + } + } + return false; + } + } + } + else if (name === 'useTransition') { + if (id.type === 'ArrayPattern' && + id.elements.length === 2 && + Array.isArray(resolved.identifiers)) { + if (id.elements[1] === resolved.identifiers[0]) { + return true; + } + } + } + return false; + } + function isFunctionWithoutCapturedValues(resolved) { + if (!isArray(resolved.defs)) { + return false; + } + const def = resolved.defs[0]; + if (def == null) { + return false; + } + if (def.node == null || def.node.id == null) { + return false; + } + const fnNode = def.node; + const childScopes = (componentScope === null || componentScope === void 0 ? void 0 : componentScope.childScopes) || []; + let fnScope = null; + for (const childScope of childScopes) { + const childScopeBlock = childScope.block; + if ((fnNode.type === 'FunctionDeclaration' && + childScopeBlock === fnNode) || + (fnNode.type === 'VariableDeclarator' && + childScopeBlock.parent === fnNode)) { + fnScope = childScope; + break; + } + } + if (fnScope == null) { + return false; + } + for (const ref of fnScope.through) { + if (ref.resolved == null) { + continue; + } + if (pureScopes.has(ref.resolved.scope) && + !memoizedIsStableKnownHookValue(ref.resolved)) { + return false; + } + } + return true; + } + const memoizedIsStableKnownHookValue = memoizeWithWeakMap(isStableKnownHookValue, stableKnownValueCache); + const memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache); + const currentRefsInEffectCleanup = new Map(); + function isInsideEffectCleanup(reference) { + let curScope = reference.from; + let isInReturnedFunction = false; + while (curScope != null && curScope.block !== node) { + if (curScope.type === 'function') { + isInReturnedFunction = + curScope.block.parent != null && + curScope.block.parent.type === 'ReturnStatement'; + } + curScope = curScope.upper; + } + return isInReturnedFunction; + } + const dependencies = new Map(); + const optionalChains = new Map(); + gatherDependenciesRecursively(scope); + function gatherDependenciesRecursively(currentScope) { + var _a, _b, _c, _d, _e, _f; + for (const reference of currentScope.references) { + if (!reference.resolved) { + continue; + } + if (!pureScopes.has(reference.resolved.scope)) { + continue; + } + const referenceNode = fastFindReferenceWithParent(node, reference.identifier); + if (referenceNode == null) { + continue; + } + const dependencyNode = getDependency(referenceNode); + const dependency = analyzePropertyChain(dependencyNode, optionalChains); + if (isEffect && + dependencyNode.type === 'Identifier' && + (((_a = dependencyNode.parent) === null || _a === void 0 ? void 0 : _a.type) === 'MemberExpression' || + ((_b = dependencyNode.parent) === null || _b === void 0 ? void 0 : _b.type) === 'OptionalMemberExpression') && + !dependencyNode.parent.computed && + dependencyNode.parent.property.type === 'Identifier' && + dependencyNode.parent.property.name === 'current' && + isInsideEffectCleanup(reference)) { + currentRefsInEffectCleanup.set(dependency, { + reference, + dependencyNode, + }); + } + if (((_c = dependencyNode.parent) === null || _c === void 0 ? void 0 : _c.type) === 'TSTypeQuery' || + ((_d = dependencyNode.parent) === null || _d === void 0 ? void 0 : _d.type) === 'TSTypeReference') { + continue; + } + const def = reference.resolved.defs[0]; + if (def == null) { + continue; + } + if (def.node != null && def.node.init === node.parent) { + continue; + } + if (def.type === 'TypeParameter' || + ((_e = dependencyNode.parent) === null || _e === void 0 ? void 0 : _e.type) === 'GenericTypeAnnotation') { + continue; + } + if (!dependencies.has(dependency)) { + const resolved = reference.resolved; + const isStable = memoizedIsStableKnownHookValue(resolved) || + memoizedIsFunctionWithoutCapturedValues(resolved); + dependencies.set(dependency, { + isStable, + references: [reference], + }); + } + else { + (_f = dependencies.get(dependency)) === null || _f === void 0 ? void 0 : _f.references.push(reference); + } + } + for (const childScope of currentScope.childScopes) { + gatherDependenciesRecursively(childScope); + } + } + currentRefsInEffectCleanup.forEach(({ reference, dependencyNode }, dependency) => { + var _a, _b; + const references = ((_a = reference.resolved) === null || _a === void 0 ? void 0 : _a.references) || []; + let foundCurrentAssignment = false; + for (const ref of references) { + const { identifier } = ref; + const { parent } = identifier; + if (parent != null && + parent.type === 'MemberExpression' && + !parent.computed && + parent.property.type === 'Identifier' && + parent.property.name === 'current' && + ((_b = parent.parent) === null || _b === void 0 ? void 0 : _b.type) === 'AssignmentExpression' && + parent.parent.left === parent) { + foundCurrentAssignment = true; + break; + } + } + if (foundCurrentAssignment) { + return; + } + reportProblem({ + node: dependencyNode.parent.property, + message: `The ref value '${dependency}.current' will likely have ` + + `changed by the time this effect cleanup function runs. If ` + + `this ref points to a node rendered by React, copy ` + + `'${dependency}.current' to a variable inside the effect, and ` + + `use that variable in the cleanup function.`, + }); + }); + const staleAssignments = new Set(); + function reportStaleAssignment(writeExpr, key) { + if (staleAssignments.has(key)) { + return; + } + staleAssignments.add(key); + reportProblem({ + node: writeExpr, + message: `Assignments to the '${key}' variable from inside React Hook ` + + `${getSourceCode().getText(reactiveHook)} will be lost after each ` + + `render. To preserve the value over time, store it in a useRef ` + + `Hook and keep the mutable value in the '.current' property. ` + + `Otherwise, you can move this variable directly inside ` + + `${getSourceCode().getText(reactiveHook)}.`, + }); + } + const stableDependencies = new Set(); + dependencies.forEach(({ isStable, references }, key) => { + if (isStable) { + stableDependencies.add(key); + } + references.forEach(reference => { + if (reference.writeExpr) { + reportStaleAssignment(reference.writeExpr, key); + } + }); + }); + if (staleAssignments.size > 0) { + return; + } + if (!declaredDependenciesNode) { + if (isAutoDepsHook) { + return; + } + let setStateInsideEffectWithoutDeps = null; + dependencies.forEach(({ references }, key) => { + if (setStateInsideEffectWithoutDeps) { + return; + } + references.forEach(reference => { + if (setStateInsideEffectWithoutDeps) { + return; + } + const id = reference.identifier; + const isSetState = setStateCallSites.has(id); + if (!isSetState) { + return; + } + let fnScope = reference.from; + while (fnScope != null && fnScope.type !== 'function') { + fnScope = fnScope.upper; + } + const isDirectlyInsideEffect = (fnScope === null || fnScope === void 0 ? void 0 : fnScope.block) === node; + if (isDirectlyInsideEffect) { + setStateInsideEffectWithoutDeps = key; + } + }); + }); + if (setStateInsideEffectWithoutDeps) { + const { suggestedDependencies } = collectRecommendations({ + dependencies, + declaredDependencies: [], + stableDependencies, + externalDependencies: new Set(), + isEffect: true, + }); + reportProblem({ + node: reactiveHook, + message: `React Hook ${reactiveHookName} contains a call to '${setStateInsideEffectWithoutDeps}'. ` + + `Without a list of dependencies, this can lead to an infinite chain of updates. ` + + `To fix this, pass [` + + suggestedDependencies.join(', ') + + `] as a second argument to the ${reactiveHookName} Hook.`, + suggest: [ + { + desc: `Add dependencies array: [${suggestedDependencies.join(', ')}]`, + fix(fixer) { + return fixer.insertTextAfter(node, `, [${suggestedDependencies.join(', ')}]`); + }, + }, + ], + }); + } + return; + } + if (isAutoDepsHook && + declaredDependenciesNode.type === 'Literal' && + declaredDependenciesNode.value === null) { + return; + } + const declaredDependencies = []; + const externalDependencies = new Set(); + const isArrayExpression = declaredDependenciesNode.type === 'ArrayExpression'; + const isTSAsArrayExpression = declaredDependenciesNode.type === 'TSAsExpression' && + declaredDependenciesNode.expression.type === 'ArrayExpression'; + if (!isArrayExpression && !isTSAsArrayExpression) { + reportProblem({ + node: declaredDependenciesNode, + message: `React Hook ${getSourceCode().getText(reactiveHook)} was passed a ` + + 'dependency list that is not an array literal. This means we ' + + "can't statically verify whether you've passed the correct " + + 'dependencies.', + }); + } + else { + const arrayExpression = isTSAsArrayExpression + ? declaredDependenciesNode.expression + : declaredDependenciesNode; + arrayExpression.elements.forEach(declaredDependencyNode => { + if (declaredDependencyNode === null) { + return; + } + if (declaredDependencyNode.type === 'SpreadElement') { + reportProblem({ + node: declaredDependencyNode, + message: `React Hook ${getSourceCode().getText(reactiveHook)} has a spread ` + + "element in its dependency array. This means we can't " + + "statically verify whether you've passed the " + + 'correct dependencies.', + }); + return; + } + if (useEffectEventVariables.has(declaredDependencyNode)) { + reportProblem({ + node: declaredDependencyNode, + message: 'Functions returned from `useEffectEvent` must not be included in the dependency array. ' + + `Remove \`${getSourceCode().getText(declaredDependencyNode)}\` from the list.`, + suggest: [ + { + desc: `Remove the dependency \`${getSourceCode().getText(declaredDependencyNode)}\``, + fix(fixer) { + return fixer.removeRange(declaredDependencyNode.range); + }, + }, + ], + }); + } + let declaredDependency; + try { + declaredDependency = analyzePropertyChain(declaredDependencyNode, null); + } + catch (error) { + if (error instanceof Error && + /Unsupported node type/.test(error.message)) { + if (declaredDependencyNode.type === 'Literal') { + if (declaredDependencyNode.value && + dependencies.has(declaredDependencyNode.value)) { + reportProblem({ + node: declaredDependencyNode, + message: `The ${declaredDependencyNode.raw} literal is not a valid dependency ` + + `because it never changes. ` + + `Did you mean to include ${declaredDependencyNode.value} in the array instead?`, + }); + } + else { + reportProblem({ + node: declaredDependencyNode, + message: `The ${declaredDependencyNode.raw} literal is not a valid dependency ` + + 'because it never changes. You can safely remove it.', + }); + } + } + else { + reportProblem({ + node: declaredDependencyNode, + message: `React Hook ${getSourceCode().getText(reactiveHook)} has a ` + + `complex expression in the dependency array. ` + + 'Extract it to a separate variable so it can be statically checked.', + }); + } + return; + } + else { + throw error; + } + } + let maybeID = declaredDependencyNode; + while (maybeID.type === 'MemberExpression' || + maybeID.type === 'OptionalMemberExpression' || + maybeID.type === 'ChainExpression') { + maybeID = maybeID.object || maybeID.expression.object; + } + const isDeclaredInComponent = !componentScope.through.some(ref => ref.identifier === maybeID); + declaredDependencies.push({ + key: declaredDependency, + node: declaredDependencyNode, + }); + if (!isDeclaredInComponent) { + externalDependencies.add(declaredDependency); + } + }); + } + const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies, } = collectRecommendations({ + dependencies, + declaredDependencies, + stableDependencies, + externalDependencies, + isEffect, + }); + let suggestedDeps = suggestedDependencies; + const problemCount = duplicateDependencies.size + + missingDependencies.size + + unnecessaryDependencies.size; + if (problemCount === 0) { + const constructions = scanForConstructions({ + declaredDependencies, + declaredDependenciesNode, + componentScope, + scope, + }); + constructions.forEach(({ construction, isUsedOutsideOfHook, depType }) => { + var _a; + const wrapperHook = depType === 'function' ? 'useCallback' : 'useMemo'; + const constructionType = depType === 'function' ? 'definition' : 'initialization'; + const defaultAdvice = `wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`; + const advice = isUsedOutsideOfHook + ? `To fix this, ${defaultAdvice}` + : `Move it inside the ${reactiveHookName} callback. Alternatively, ${defaultAdvice}`; + const causation = depType === 'conditional' || depType === 'logical expression' + ? 'could make' + : 'makes'; + const message = `The '${construction.name.name}' ${depType} ${causation} the dependencies of ` + + `${reactiveHookName} Hook (at line ${(_a = declaredDependenciesNode.loc) === null || _a === void 0 ? void 0 : _a.start.line}) ` + + `change on every render. ${advice}`; + let suggest; + if (isUsedOutsideOfHook && + construction.type === 'Variable' && + depType === 'function') { + suggest = [ + { + desc: `Wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`, + fix(fixer) { + const [before, after] = wrapperHook === 'useMemo' + ? [`useMemo(() => { return `, '; })'] + : ['useCallback(', ')']; + return [ + fixer.insertTextBefore(construction.node.init, before), + fixer.insertTextAfter(construction.node.init, after), + ]; + }, + }, + ]; + } + reportProblem({ + node: construction.node, + message, + suggest, + }); + }); + return; + } + if (!isEffect && missingDependencies.size > 0) { + suggestedDeps = collectRecommendations({ + dependencies, + declaredDependencies: [], + stableDependencies, + externalDependencies, + isEffect, + }).suggestedDependencies; + } + function areDeclaredDepsAlphabetized() { + if (declaredDependencies.length === 0) { + return true; + } + const declaredDepKeys = declaredDependencies.map(dep => dep.key); + const sortedDeclaredDepKeys = declaredDepKeys.slice().sort(); + return declaredDepKeys.join(',') === sortedDeclaredDepKeys.join(','); + } + if (areDeclaredDepsAlphabetized()) { + suggestedDeps.sort(); + } + function formatDependency(path) { + const members = path.split('.'); + let finalPath = ''; + for (let i = 0; i < members.length; i++) { + if (i !== 0) { + const pathSoFar = members.slice(0, i + 1).join('.'); + const isOptional = optionalChains.get(pathSoFar) === true; + finalPath += isOptional ? '?.' : '.'; + } + finalPath += members[i]; + } + return finalPath; + } + function getWarningMessage(deps, singlePrefix, label, fixVerb) { + if (deps.size === 0) { + return null; + } + return ((deps.size > 1 ? '' : singlePrefix + ' ') + + label + + ' ' + + (deps.size > 1 ? 'dependencies' : 'dependency') + + ': ' + + joinEnglish(Array.from(deps) + .sort() + .map(name => "'" + formatDependency(name) + "'")) + + `. Either ${fixVerb} ${deps.size > 1 ? 'them' : 'it'} or remove the dependency array.`); + } + let extraWarning = ''; + if (unnecessaryDependencies.size > 0) { + let badRef = null; + Array.from(unnecessaryDependencies.keys()).forEach(key => { + if (badRef !== null) { + return; + } + if (key.endsWith('.current')) { + badRef = key; + } + }); + if (badRef !== null) { + extraWarning = + ` Mutable values like '${badRef}' aren't valid dependencies ` + + "because mutating them doesn't re-render the component."; + } + else if (externalDependencies.size > 0) { + const dep = Array.from(externalDependencies)[0]; + if (!scope.set.has(dep)) { + extraWarning = + ` Outer scope values like '${dep}' aren't valid dependencies ` + + `because mutating them doesn't re-render the component.`; + } + } + } + if (!extraWarning && missingDependencies.has('props')) { + const propDep = dependencies.get('props'); + if (propDep == null) { + return; + } + const refs = propDep.references; + if (!Array.isArray(refs)) { + return; + } + let isPropsOnlyUsedInMembers = true; + for (const ref of refs) { + const id = fastFindReferenceWithParent(componentScope.block, ref.identifier); + if (!id) { + isPropsOnlyUsedInMembers = false; + break; + } + const parent = id.parent; + if (parent == null) { + isPropsOnlyUsedInMembers = false; + break; + } + if (parent.type !== 'MemberExpression' && + parent.type !== 'OptionalMemberExpression') { + isPropsOnlyUsedInMembers = false; + break; + } + } + if (isPropsOnlyUsedInMembers) { + extraWarning = + ` However, 'props' will change when *any* prop changes, so the ` + + `preferred fix is to destructure the 'props' object outside of ` + + `the ${reactiveHookName} call and refer to those specific props ` + + `inside ${getSourceCode().getText(reactiveHook)}.`; + } + } + if (!extraWarning && missingDependencies.size > 0) { + let missingCallbackDep = null; + missingDependencies.forEach(missingDep => { + var _a; + if (missingCallbackDep) { + return; + } + const topScopeRef = componentScope.set.get(missingDep); + const usedDep = dependencies.get(missingDep); + if (!(usedDep === null || usedDep === void 0 ? void 0 : usedDep.references) || + ((_a = usedDep === null || usedDep === void 0 ? void 0 : usedDep.references[0]) === null || _a === void 0 ? void 0 : _a.resolved) !== topScopeRef) { + return; + } + const def = topScopeRef === null || topScopeRef === void 0 ? void 0 : topScopeRef.defs[0]; + if (def == null || def.name == null || def.type !== 'Parameter') { + return; + } + let isFunctionCall = false; + let id; + for (const reference of usedDep.references) { + id = reference.identifier; + if (id != null && + id.parent != null && + (id.parent.type === 'CallExpression' || + id.parent.type === 'OptionalCallExpression') && + id.parent.callee === id) { + isFunctionCall = true; + break; + } + } + if (!isFunctionCall) { + return; + } + missingCallbackDep = missingDep; + }); + if (missingCallbackDep !== null) { + extraWarning = + ` If '${missingCallbackDep}' changes too often, ` + + `find the parent component that defines it ` + + `and wrap that definition in useCallback.`; + } + } + if (!extraWarning && missingDependencies.size > 0) { + let setStateRecommendation = null; + for (const missingDep of missingDependencies) { + if (setStateRecommendation !== null) { + break; + } + const usedDep = dependencies.get(missingDep); + const references = usedDep.references; + let id; + let maybeCall; + for (const reference of references) { + id = reference.identifier; + maybeCall = id.parent; + while (maybeCall != null && maybeCall !== componentScope.block) { + if (maybeCall.type === 'CallExpression') { + const correspondingStateVariable = setStateCallSites.get(maybeCall.callee); + if (correspondingStateVariable != null) { + if ('name' in correspondingStateVariable && + correspondingStateVariable.name === missingDep) { + setStateRecommendation = { + missingDep, + setter: 'name' in maybeCall.callee ? maybeCall.callee.name : '', + form: 'updater', + }; + } + else if (stateVariables.has(id)) { + setStateRecommendation = { + missingDep, + setter: 'name' in maybeCall.callee ? maybeCall.callee.name : '', + form: 'reducer', + }; + } + else { + const resolved = reference.resolved; + if (resolved != null) { + const def = resolved.defs[0]; + if (def != null && def.type === 'Parameter') { + setStateRecommendation = { + missingDep, + setter: 'name' in maybeCall.callee + ? maybeCall.callee.name + : '', + form: 'inlineReducer', + }; + } + } + } + break; + } + } + maybeCall = maybeCall.parent; + } + if (setStateRecommendation !== null) { + break; + } + } + } + if (setStateRecommendation !== null) { + switch (setStateRecommendation.form) { + case 'reducer': + extraWarning = + ` You can also replace multiple useState variables with useReducer ` + + `if '${setStateRecommendation.setter}' needs the ` + + `current value of '${setStateRecommendation.missingDep}'.`; + break; + case 'inlineReducer': + extraWarning = + ` If '${setStateRecommendation.setter}' needs the ` + + `current value of '${setStateRecommendation.missingDep}', ` + + `you can also switch to useReducer instead of useState and ` + + `read '${setStateRecommendation.missingDep}' in the reducer.`; + break; + case 'updater': + extraWarning = + ` You can also do a functional update '${setStateRecommendation.setter}(${setStateRecommendation.missingDep.slice(0, 1)} => ...)' if you only need '${setStateRecommendation.missingDep}'` + ` in the '${setStateRecommendation.setter}' call.`; + break; + default: + throw new Error('Unknown case.'); + } + } + } + reportProblem({ + node: declaredDependenciesNode, + message: `React Hook ${getSourceCode().getText(reactiveHook)} has ` + + (getWarningMessage(missingDependencies, 'a', 'missing', 'include') || + getWarningMessage(unnecessaryDependencies, 'an', 'unnecessary', 'exclude') || + getWarningMessage(duplicateDependencies, 'a', 'duplicate', 'omit')) + + extraWarning, + suggest: [ + { + desc: `Update the dependencies array to be: [${suggestedDeps + .map(formatDependency) + .join(', ')}]`, + fix(fixer) { + return fixer.replaceText(declaredDependenciesNode, `[${suggestedDeps.map(formatDependency).join(', ')}]`); + }, + }, + ], + }); + } + function visitCallExpression(node) { + const callbackIndex = getReactiveHookCallbackIndex(node.callee, options); + if (callbackIndex === -1) { + return; + } + let callback = node.arguments[callbackIndex]; + const reactiveHook = node.callee; + const nodeWithoutNamespace = getNodeWithoutReactNamespace$1(reactiveHook); + const reactiveHookName = 'name' in nodeWithoutNamespace ? nodeWithoutNamespace.name : ''; + const maybeNode = node.arguments[callbackIndex + 1]; + const declaredDependenciesNode = maybeNode && + !(maybeNode.type === 'Identifier' && maybeNode.name === 'undefined') + ? maybeNode + : undefined; + const isEffect = /Effect($|[^a-z])/g.test(reactiveHookName); + if (!callback) { + reportProblem({ + node: reactiveHook, + message: `React Hook ${reactiveHookName} requires an effect callback. ` + + `Did you forget to pass a callback to the hook?`, + }); + return; + } + if (!maybeNode && isEffect && options.requireExplicitEffectDeps) { + reportProblem({ + node: reactiveHook, + message: `React Hook ${reactiveHookName} always requires dependencies. ` + + `Please add a dependency array or an explicit \`undefined\``, + }); + } + const isAutoDepsHook = options.experimental_autoDependenciesHooks.includes(reactiveHookName); + if ((!declaredDependenciesNode || + (isAutoDepsHook && + declaredDependenciesNode.type === 'Literal' && + declaredDependenciesNode.value === null)) && + !isEffect) { + if (reactiveHookName === 'useMemo' || + reactiveHookName === 'useCallback') { + reportProblem({ + node: reactiveHook, + message: `React Hook ${reactiveHookName} does nothing when called with ` + + `only one argument. Did you forget to pass an array of ` + + `dependencies?`, + }); + } + return; + } + while (callback.type === 'TSAsExpression' || + callback.type === 'AsExpression') { + callback = callback.expression; + } + switch (callback.type) { + case 'FunctionExpression': + case 'ArrowFunctionExpression': + visitFunctionWithDependencies(callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook); + return; + case 'Identifier': + if (!declaredDependenciesNode || + (isAutoDepsHook && + declaredDependenciesNode.type === 'Literal' && + declaredDependenciesNode.value === null)) { + return; + } + if ('elements' in declaredDependenciesNode && + declaredDependenciesNode.elements && + declaredDependenciesNode.elements.some(el => el && el.type === 'Identifier' && el.name === callback.name)) { + return; + } + const variable = getScope(callback).set.get(callback.name); + if (variable == null || variable.defs == null) { + return; + } + const def = variable.defs[0]; + if (!def || !def.node) { + break; + } + if (def.type === 'Parameter') { + reportProblem({ + node: reactiveHook, + message: getUnknownDependenciesMessage(reactiveHookName), + }); + return; + } + if (def.type !== 'Variable' && def.type !== 'FunctionName') { + break; + } + switch (def.node.type) { + case 'FunctionDeclaration': + visitFunctionWithDependencies(def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook); + return; + case 'VariableDeclarator': + const init = def.node.init; + if (!init) { + break; + } + switch (init.type) { + case 'ArrowFunctionExpression': + case 'FunctionExpression': + visitFunctionWithDependencies(init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook); + return; + } + break; + } + break; + default: + reportProblem({ + node: reactiveHook, + message: getUnknownDependenciesMessage(reactiveHookName), + }); + return; + } + reportProblem({ + node: reactiveHook, + message: `React Hook ${reactiveHookName} has a missing dependency: '${callback.name}'. ` + + `Either include it or remove the dependency array.`, + suggest: [ + { + desc: `Update the dependencies array to be: [${callback.name}]`, + fix(fixer) { + return fixer.replaceText(declaredDependenciesNode, `[${callback.name}]`); + }, + }, + ], + }); + } + return { + CallExpression: visitCallExpression, + }; + }, +}; +function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect, }) { + const depTree = createDepTree(); + function createDepTree() { + return { + isUsed: false, + isSatisfiedRecursively: false, + isSubtreeUsed: false, + children: new Map(), + }; + } + dependencies.forEach((_, key) => { + const node = getOrCreateNodeByPath(depTree, key); + node.isUsed = true; + markAllParentsByPath(depTree, key, parent => { + parent.isSubtreeUsed = true; + }); + }); + declaredDependencies.forEach(({ key }) => { + const node = getOrCreateNodeByPath(depTree, key); + node.isSatisfiedRecursively = true; + }); + stableDependencies.forEach(key => { + const node = getOrCreateNodeByPath(depTree, key); + node.isSatisfiedRecursively = true; + }); + function getOrCreateNodeByPath(rootNode, path) { + const keys = path.split('.'); + let node = rootNode; + for (const key of keys) { + let child = node.children.get(key); + if (!child) { + child = createDepTree(); + node.children.set(key, child); + } + node = child; + } + return node; + } + function markAllParentsByPath(rootNode, path, fn) { + const keys = path.split('.'); + let node = rootNode; + for (const key of keys) { + const child = node.children.get(key); + if (!child) { + return; + } + fn(child); + node = child; + } + } + const missingDependencies = new Set(); + const satisfyingDependencies = new Set(); + scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, key => key); + function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) { + node.children.forEach((child, key) => { + const path = keyToPath(key); + if (child.isSatisfiedRecursively) { + if (child.isSubtreeUsed) { + satisfyingPaths.add(path); + } + return; + } + if (child.isUsed) { + missingPaths.add(path); + return; + } + scanTreeRecursively(child, missingPaths, satisfyingPaths, childKey => path + '.' + childKey); + }); + } + const suggestedDependencies = []; + const unnecessaryDependencies = new Set(); + const duplicateDependencies = new Set(); + declaredDependencies.forEach(({ key }) => { + if (satisfyingDependencies.has(key)) { + if (suggestedDependencies.indexOf(key) === -1) { + suggestedDependencies.push(key); + } + else { + duplicateDependencies.add(key); + } + } + else { + if (isEffect && + !key.endsWith('.current') && + !externalDependencies.has(key)) { + if (suggestedDependencies.indexOf(key) === -1) { + suggestedDependencies.push(key); + } + } + else { + unnecessaryDependencies.add(key); + } + } + }); + missingDependencies.forEach(key => { + suggestedDependencies.push(key); + }); + return { + suggestedDependencies, + unnecessaryDependencies, + duplicateDependencies, + missingDependencies, + }; +} +function getConstructionExpressionType(node) { + switch (node.type) { + case 'ObjectExpression': + return 'object'; + case 'ArrayExpression': + return 'array'; + case 'ArrowFunctionExpression': + case 'FunctionExpression': + return 'function'; + case 'ClassExpression': + return 'class'; + case 'ConditionalExpression': + if (getConstructionExpressionType(node.consequent) != null || + getConstructionExpressionType(node.alternate) != null) { + return 'conditional'; + } + return null; + case 'LogicalExpression': + if (getConstructionExpressionType(node.left) != null || + getConstructionExpressionType(node.right) != null) { + return 'logical expression'; + } + return null; + case 'JSXFragment': + return 'JSX fragment'; + case 'JSXElement': + return 'JSX element'; + case 'AssignmentExpression': + if (getConstructionExpressionType(node.right) != null) { + return 'assignment expression'; + } + return null; + case 'NewExpression': + return 'object construction'; + case 'Literal': + if (node.value instanceof RegExp) { + return 'regular expression'; + } + return null; + case 'TypeCastExpression': + case 'AsExpression': + case 'TSAsExpression': + return getConstructionExpressionType(node.expression); + } + return null; +} +function scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope, }) { + const constructions = declaredDependencies + .map(({ key }) => { + const ref = componentScope.variables.find(v => v.name === key); + if (ref == null) { + return null; + } + const node = ref.defs[0]; + if (node == null) { + return null; + } + if (node.type === 'Variable' && + node.node.type === 'VariableDeclarator' && + node.node.id.type === 'Identifier' && + node.node.init != null) { + const constantExpressionType = getConstructionExpressionType(node.node.init); + if (constantExpressionType) { + return [ref, constantExpressionType]; + } + } + if (node.type === 'FunctionName' && + node.node.type === 'FunctionDeclaration') { + return [ref, 'function']; + } + if (node.type === 'ClassName' && node.node.type === 'ClassDeclaration') { + return [ref, 'class']; + } + return null; + }) + .filter(Boolean); + function isUsedOutsideOfHook(ref) { + let foundWriteExpr = false; + for (const reference of ref.references) { + if (reference.writeExpr) { + if (foundWriteExpr) { + return true; + } + else { + foundWriteExpr = true; + continue; + } + } + let currentScope = reference.from; + while (currentScope !== scope && currentScope != null) { + currentScope = currentScope.upper; + } + if (currentScope !== scope) { + if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) { + return true; + } + } + } + return false; + } + return constructions.map(([ref, depType]) => ({ + construction: ref.defs[0], + depType, + isUsedOutsideOfHook: isUsedOutsideOfHook(ref), + })); +} +function getDependency(node) { + if (node.parent && + (node.parent.type === 'MemberExpression' || + node.parent.type === 'OptionalMemberExpression') && + node.parent.object === node && + 'name' in node.parent.property && + node.parent.property.name !== 'current' && + !node.parent.computed && + !(node.parent.parent != null && + (node.parent.parent.type === 'CallExpression' || + node.parent.parent.type === 'OptionalCallExpression') && + node.parent.parent.callee === node.parent)) { + return getDependency(node.parent); + } + else if (node.type === 'MemberExpression' && + node.parent && + node.parent.type === 'AssignmentExpression' && + node.parent.left === node) { + return node.object; + } + else { + return node; + } +} +function markNode(node, optionalChains, result) { + if (optionalChains) { + if ('optional' in node && node.optional) { + if (!optionalChains.has(result)) { + optionalChains.set(result, true); + } + } + else { + optionalChains.set(result, false); + } + } +} +function analyzePropertyChain(node, optionalChains) { + if (node.type === 'Identifier' || node.type === 'JSXIdentifier') { + const result = node.name; + if (optionalChains) { + optionalChains.set(result, false); + } + return result; + } + else if (node.type === 'MemberExpression' && !node.computed) { + const object = analyzePropertyChain(node.object, optionalChains); + const property = analyzePropertyChain(node.property, null); + const result = `${object}.${property}`; + markNode(node, optionalChains, result); + return result; + } + else if (node.type === 'OptionalMemberExpression' && !node.computed) { + const object = analyzePropertyChain(node.object, optionalChains); + const property = analyzePropertyChain(node.property, null); + const result = `${object}.${property}`; + markNode(node, optionalChains, result); + return result; + } + else if (node.type === 'ChainExpression' && + (!('computed' in node) || !node.computed)) { + const expression = node.expression; + if (expression.type === 'CallExpression') { + throw new Error(`Unsupported node type: ${expression.type}`); + } + const object = analyzePropertyChain(expression.object, optionalChains); + const property = analyzePropertyChain(expression.property, null); + const result = `${object}.${property}`; + markNode(expression, optionalChains, result); + return result; + } + else { + throw new Error(`Unsupported node type: ${node.type}`); + } +} +function getNodeWithoutReactNamespace$1(node) { + if (node.type === 'MemberExpression' && + node.object.type === 'Identifier' && + node.object.name === 'React' && + node.property.type === 'Identifier' && + !node.computed) { + return node.property; + } + return node; +} +function getReactiveHookCallbackIndex(calleeNode, options) { + const node = getNodeWithoutReactNamespace$1(calleeNode); + if (node.type !== 'Identifier') { + return -1; + } + switch (node.name) { + case 'useEffect': + case 'useLayoutEffect': + case 'useCallback': + case 'useMemo': + return 0; + case 'useImperativeHandle': + return 1; + default: + if (node === calleeNode && options && options.additionalHooks) { + let name; + try { + name = analyzePropertyChain(node, null); + } + catch (error) { + if (error instanceof Error && + /Unsupported node type/.test(error.message)) { + return 0; + } + else { + throw error; + } + } + return options.additionalHooks.test(name) ? 0 : -1; + } + else { + return -1; + } + } +} +function fastFindReferenceWithParent(start, target) { + const queue = [start]; + let item; + while (queue.length) { + item = queue.shift(); + if (isSameIdentifier(item, target)) { + return item; + } + if (!isAncestorNodeOf(item, target)) { + continue; + } + for (const [key, value] of Object.entries(item)) { + if (key === 'parent') { + continue; + } + if (isNodeLike(value)) { + value.parent = item; + queue.push(value); + } + else if (Array.isArray(value)) { + value.forEach(val => { + if (isNodeLike(val)) { + val.parent = item; + queue.push(val); + } + }); + } + } + } + return null; +} +function joinEnglish(arr) { + let s = ''; + for (let i = 0; i < arr.length; i++) { + s += arr[i]; + if (i === 0 && arr.length === 2) { + s += ' and '; + } + else if (i === arr.length - 2 && arr.length > 2) { + s += ', and '; + } + else if (i < arr.length - 1) { + s += ', '; + } + } + return s; +} +function isNodeLike(val) { + return (typeof val === 'object' && + val !== null && + !Array.isArray(val) && + 'type' in val && + typeof val.type === 'string'); +} +function isSameIdentifier(a, b) { + return ((a.type === 'Identifier' || a.type === 'JSXIdentifier') && + a.type === b.type && + a.name === b.name && + !!a.range && + !!b.range && + a.range[0] === b.range[0] && + a.range[1] === b.range[1]); +} +function isAncestorNodeOf(a, b) { + return (!!a.range && + !!b.range && + a.range[0] <= b.range[0] && + a.range[1] >= b.range[1]); +} +function isUseEffectEventIdentifier$1(node) { + return node.type === 'Identifier' && node.name === 'useEffectEvent'; +} +function getUnknownDependenciesMessage(reactiveHookName) { + return (`React Hook ${reactiveHookName} received a function whose dependencies ` + + `are unknown. Pass an inline function instead.`); +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var invariant_1; +var hasRequiredInvariant; + +function requireInvariant () { + if (hasRequiredInvariant) return invariant_1; + hasRequiredInvariant = 1; + + var invariant = function(condition, format, a, b, c, d, e, f) { + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + invariant_1 = invariant; + return invariant_1; +} + +var invariantExports = requireInvariant(); +var invariant = /*@__PURE__*/getDefaultExportFromCjs(invariantExports); + +var lib$3 = {}; + +var isReactComponent = {}; + +var buildMatchMemberExpression = {}; + +var matchesPattern = {}; + +var generated$3 = {}; + +var shallowEqual = {}; + +var hasRequiredShallowEqual; + +function requireShallowEqual () { + if (hasRequiredShallowEqual) return shallowEqual; + hasRequiredShallowEqual = 1; + + Object.defineProperty(shallowEqual, "__esModule", { + value: true + }); + shallowEqual.default = shallowEqual$1; + function shallowEqual$1(actual, expected) { + const keys = Object.keys(expected); + for (const key of keys) { + if (actual[key] !== expected[key]) { + return false; + } + } + return true; + } + + + return shallowEqual; +} + +var deprecationWarning = {}; + +var hasRequiredDeprecationWarning; + +function requireDeprecationWarning () { + if (hasRequiredDeprecationWarning) return deprecationWarning; + hasRequiredDeprecationWarning = 1; + + Object.defineProperty(deprecationWarning, "__esModule", { + value: true + }); + deprecationWarning.default = deprecationWarning$1; + const warnings = new Set(); + function deprecationWarning$1(oldName, newName, prefix = "") { + if (warnings.has(oldName)) return; + warnings.add(oldName); + const { + internal, + trace + } = captureShortStackTrace(1, 2); + if (internal) { + return; + } + console.warn(`${prefix}\`${oldName}\` has been deprecated, please migrate to \`${newName}\`\n${trace}`); + } + function captureShortStackTrace(skip, length) { + const { + stackTraceLimit, + prepareStackTrace + } = Error; + let stackTrace; + Error.stackTraceLimit = 1 + skip + length; + Error.prepareStackTrace = function (err, stack) { + stackTrace = stack; + }; + Error.stackTraceLimit = stackTraceLimit; + Error.prepareStackTrace = prepareStackTrace; + if (!stackTrace) return { + internal: false, + trace: "" + }; + const shortStackTrace = stackTrace.slice(1 + skip, 1 + skip + length); + return { + internal: /[\\/]@babel[\\/]/.test(shortStackTrace[1].getFileName()), + trace: shortStackTrace.map(frame => ` at ${frame}`).join("\n") + }; + } + + + return deprecationWarning; +} + +var hasRequiredGenerated$3; + +function requireGenerated$3 () { + if (hasRequiredGenerated$3) return generated$3; + hasRequiredGenerated$3 = 1; + + Object.defineProperty(generated$3, "__esModule", { + value: true + }); + generated$3.isAccessor = isAccessor; + generated$3.isAnyTypeAnnotation = isAnyTypeAnnotation; + generated$3.isArgumentPlaceholder = isArgumentPlaceholder; + generated$3.isArrayExpression = isArrayExpression; + generated$3.isArrayPattern = isArrayPattern; + generated$3.isArrayTypeAnnotation = isArrayTypeAnnotation; + generated$3.isArrowFunctionExpression = isArrowFunctionExpression; + generated$3.isAssignmentExpression = isAssignmentExpression; + generated$3.isAssignmentPattern = isAssignmentPattern; + generated$3.isAwaitExpression = isAwaitExpression; + generated$3.isBigIntLiteral = isBigIntLiteral; + generated$3.isBinary = isBinary; + generated$3.isBinaryExpression = isBinaryExpression; + generated$3.isBindExpression = isBindExpression; + generated$3.isBlock = isBlock; + generated$3.isBlockParent = isBlockParent; + generated$3.isBlockStatement = isBlockStatement; + generated$3.isBooleanLiteral = isBooleanLiteral; + generated$3.isBooleanLiteralTypeAnnotation = isBooleanLiteralTypeAnnotation; + generated$3.isBooleanTypeAnnotation = isBooleanTypeAnnotation; + generated$3.isBreakStatement = isBreakStatement; + generated$3.isCallExpression = isCallExpression; + generated$3.isCatchClause = isCatchClause; + generated$3.isClass = isClass; + generated$3.isClassAccessorProperty = isClassAccessorProperty; + generated$3.isClassBody = isClassBody; + generated$3.isClassDeclaration = isClassDeclaration; + generated$3.isClassExpression = isClassExpression; + generated$3.isClassImplements = isClassImplements; + generated$3.isClassMethod = isClassMethod; + generated$3.isClassPrivateMethod = isClassPrivateMethod; + generated$3.isClassPrivateProperty = isClassPrivateProperty; + generated$3.isClassProperty = isClassProperty; + generated$3.isCompletionStatement = isCompletionStatement; + generated$3.isConditional = isConditional; + generated$3.isConditionalExpression = isConditionalExpression; + generated$3.isContinueStatement = isContinueStatement; + generated$3.isDebuggerStatement = isDebuggerStatement; + generated$3.isDecimalLiteral = isDecimalLiteral; + generated$3.isDeclaration = isDeclaration; + generated$3.isDeclareClass = isDeclareClass; + generated$3.isDeclareExportAllDeclaration = isDeclareExportAllDeclaration; + generated$3.isDeclareExportDeclaration = isDeclareExportDeclaration; + generated$3.isDeclareFunction = isDeclareFunction; + generated$3.isDeclareInterface = isDeclareInterface; + generated$3.isDeclareModule = isDeclareModule; + generated$3.isDeclareModuleExports = isDeclareModuleExports; + generated$3.isDeclareOpaqueType = isDeclareOpaqueType; + generated$3.isDeclareTypeAlias = isDeclareTypeAlias; + generated$3.isDeclareVariable = isDeclareVariable; + generated$3.isDeclaredPredicate = isDeclaredPredicate; + generated$3.isDecorator = isDecorator; + generated$3.isDirective = isDirective; + generated$3.isDirectiveLiteral = isDirectiveLiteral; + generated$3.isDoExpression = isDoExpression; + generated$3.isDoWhileStatement = isDoWhileStatement; + generated$3.isEmptyStatement = isEmptyStatement; + generated$3.isEmptyTypeAnnotation = isEmptyTypeAnnotation; + generated$3.isEnumBody = isEnumBody; + generated$3.isEnumBooleanBody = isEnumBooleanBody; + generated$3.isEnumBooleanMember = isEnumBooleanMember; + generated$3.isEnumDeclaration = isEnumDeclaration; + generated$3.isEnumDefaultedMember = isEnumDefaultedMember; + generated$3.isEnumMember = isEnumMember; + generated$3.isEnumNumberBody = isEnumNumberBody; + generated$3.isEnumNumberMember = isEnumNumberMember; + generated$3.isEnumStringBody = isEnumStringBody; + generated$3.isEnumStringMember = isEnumStringMember; + generated$3.isEnumSymbolBody = isEnumSymbolBody; + generated$3.isExistsTypeAnnotation = isExistsTypeAnnotation; + generated$3.isExportAllDeclaration = isExportAllDeclaration; + generated$3.isExportDeclaration = isExportDeclaration; + generated$3.isExportDefaultDeclaration = isExportDefaultDeclaration; + generated$3.isExportDefaultSpecifier = isExportDefaultSpecifier; + generated$3.isExportNamedDeclaration = isExportNamedDeclaration; + generated$3.isExportNamespaceSpecifier = isExportNamespaceSpecifier; + generated$3.isExportSpecifier = isExportSpecifier; + generated$3.isExpression = isExpression; + generated$3.isExpressionStatement = isExpressionStatement; + generated$3.isExpressionWrapper = isExpressionWrapper; + generated$3.isFile = isFile; + generated$3.isFlow = isFlow; + generated$3.isFlowBaseAnnotation = isFlowBaseAnnotation; + generated$3.isFlowDeclaration = isFlowDeclaration; + generated$3.isFlowPredicate = isFlowPredicate; + generated$3.isFlowType = isFlowType; + generated$3.isFor = isFor; + generated$3.isForInStatement = isForInStatement; + generated$3.isForOfStatement = isForOfStatement; + generated$3.isForStatement = isForStatement; + generated$3.isForXStatement = isForXStatement; + generated$3.isFunction = isFunction; + generated$3.isFunctionDeclaration = isFunctionDeclaration; + generated$3.isFunctionExpression = isFunctionExpression; + generated$3.isFunctionParent = isFunctionParent; + generated$3.isFunctionTypeAnnotation = isFunctionTypeAnnotation; + generated$3.isFunctionTypeParam = isFunctionTypeParam; + generated$3.isGenericTypeAnnotation = isGenericTypeAnnotation; + generated$3.isIdentifier = isIdentifier; + generated$3.isIfStatement = isIfStatement; + generated$3.isImmutable = isImmutable; + generated$3.isImport = isImport; + generated$3.isImportAttribute = isImportAttribute; + generated$3.isImportDeclaration = isImportDeclaration; + generated$3.isImportDefaultSpecifier = isImportDefaultSpecifier; + generated$3.isImportExpression = isImportExpression; + generated$3.isImportNamespaceSpecifier = isImportNamespaceSpecifier; + generated$3.isImportOrExportDeclaration = isImportOrExportDeclaration; + generated$3.isImportSpecifier = isImportSpecifier; + generated$3.isIndexedAccessType = isIndexedAccessType; + generated$3.isInferredPredicate = isInferredPredicate; + generated$3.isInterfaceDeclaration = isInterfaceDeclaration; + generated$3.isInterfaceExtends = isInterfaceExtends; + generated$3.isInterfaceTypeAnnotation = isInterfaceTypeAnnotation; + generated$3.isInterpreterDirective = isInterpreterDirective; + generated$3.isIntersectionTypeAnnotation = isIntersectionTypeAnnotation; + generated$3.isJSX = isJSX; + generated$3.isJSXAttribute = isJSXAttribute; + generated$3.isJSXClosingElement = isJSXClosingElement; + generated$3.isJSXClosingFragment = isJSXClosingFragment; + generated$3.isJSXElement = isJSXElement; + generated$3.isJSXEmptyExpression = isJSXEmptyExpression; + generated$3.isJSXExpressionContainer = isJSXExpressionContainer; + generated$3.isJSXFragment = isJSXFragment; + generated$3.isJSXIdentifier = isJSXIdentifier; + generated$3.isJSXMemberExpression = isJSXMemberExpression; + generated$3.isJSXNamespacedName = isJSXNamespacedName; + generated$3.isJSXOpeningElement = isJSXOpeningElement; + generated$3.isJSXOpeningFragment = isJSXOpeningFragment; + generated$3.isJSXSpreadAttribute = isJSXSpreadAttribute; + generated$3.isJSXSpreadChild = isJSXSpreadChild; + generated$3.isJSXText = isJSXText; + generated$3.isLVal = isLVal; + generated$3.isLabeledStatement = isLabeledStatement; + generated$3.isLiteral = isLiteral; + generated$3.isLogicalExpression = isLogicalExpression; + generated$3.isLoop = isLoop; + generated$3.isMemberExpression = isMemberExpression; + generated$3.isMetaProperty = isMetaProperty; + generated$3.isMethod = isMethod; + generated$3.isMiscellaneous = isMiscellaneous; + generated$3.isMixedTypeAnnotation = isMixedTypeAnnotation; + generated$3.isModuleDeclaration = isModuleDeclaration; + generated$3.isModuleExpression = isModuleExpression; + generated$3.isModuleSpecifier = isModuleSpecifier; + generated$3.isNewExpression = isNewExpression; + generated$3.isNoop = isNoop; + generated$3.isNullLiteral = isNullLiteral; + generated$3.isNullLiteralTypeAnnotation = isNullLiteralTypeAnnotation; + generated$3.isNullableTypeAnnotation = isNullableTypeAnnotation; + generated$3.isNumberLiteral = isNumberLiteral; + generated$3.isNumberLiteralTypeAnnotation = isNumberLiteralTypeAnnotation; + generated$3.isNumberTypeAnnotation = isNumberTypeAnnotation; + generated$3.isNumericLiteral = isNumericLiteral; + generated$3.isObjectExpression = isObjectExpression; + generated$3.isObjectMember = isObjectMember; + generated$3.isObjectMethod = isObjectMethod; + generated$3.isObjectPattern = isObjectPattern; + generated$3.isObjectProperty = isObjectProperty; + generated$3.isObjectTypeAnnotation = isObjectTypeAnnotation; + generated$3.isObjectTypeCallProperty = isObjectTypeCallProperty; + generated$3.isObjectTypeIndexer = isObjectTypeIndexer; + generated$3.isObjectTypeInternalSlot = isObjectTypeInternalSlot; + generated$3.isObjectTypeProperty = isObjectTypeProperty; + generated$3.isObjectTypeSpreadProperty = isObjectTypeSpreadProperty; + generated$3.isOpaqueType = isOpaqueType; + generated$3.isOptionalCallExpression = isOptionalCallExpression; + generated$3.isOptionalIndexedAccessType = isOptionalIndexedAccessType; + generated$3.isOptionalMemberExpression = isOptionalMemberExpression; + generated$3.isParenthesizedExpression = isParenthesizedExpression; + generated$3.isPattern = isPattern; + generated$3.isPatternLike = isPatternLike; + generated$3.isPipelineBareFunction = isPipelineBareFunction; + generated$3.isPipelinePrimaryTopicReference = isPipelinePrimaryTopicReference; + generated$3.isPipelineTopicExpression = isPipelineTopicExpression; + generated$3.isPlaceholder = isPlaceholder; + generated$3.isPrivate = isPrivate; + generated$3.isPrivateName = isPrivateName; + generated$3.isProgram = isProgram; + generated$3.isProperty = isProperty; + generated$3.isPureish = isPureish; + generated$3.isQualifiedTypeIdentifier = isQualifiedTypeIdentifier; + generated$3.isRecordExpression = isRecordExpression; + generated$3.isRegExpLiteral = isRegExpLiteral; + generated$3.isRegexLiteral = isRegexLiteral; + generated$3.isRestElement = isRestElement; + generated$3.isRestProperty = isRestProperty; + generated$3.isReturnStatement = isReturnStatement; + generated$3.isScopable = isScopable; + generated$3.isSequenceExpression = isSequenceExpression; + generated$3.isSpreadElement = isSpreadElement; + generated$3.isSpreadProperty = isSpreadProperty; + generated$3.isStandardized = isStandardized; + generated$3.isStatement = isStatement; + generated$3.isStaticBlock = isStaticBlock; + generated$3.isStringLiteral = isStringLiteral; + generated$3.isStringLiteralTypeAnnotation = isStringLiteralTypeAnnotation; + generated$3.isStringTypeAnnotation = isStringTypeAnnotation; + generated$3.isSuper = isSuper; + generated$3.isSwitchCase = isSwitchCase; + generated$3.isSwitchStatement = isSwitchStatement; + generated$3.isSymbolTypeAnnotation = isSymbolTypeAnnotation; + generated$3.isTSAnyKeyword = isTSAnyKeyword; + generated$3.isTSArrayType = isTSArrayType; + generated$3.isTSAsExpression = isTSAsExpression; + generated$3.isTSBaseType = isTSBaseType; + generated$3.isTSBigIntKeyword = isTSBigIntKeyword; + generated$3.isTSBooleanKeyword = isTSBooleanKeyword; + generated$3.isTSCallSignatureDeclaration = isTSCallSignatureDeclaration; + generated$3.isTSConditionalType = isTSConditionalType; + generated$3.isTSConstructSignatureDeclaration = isTSConstructSignatureDeclaration; + generated$3.isTSConstructorType = isTSConstructorType; + generated$3.isTSDeclareFunction = isTSDeclareFunction; + generated$3.isTSDeclareMethod = isTSDeclareMethod; + generated$3.isTSEntityName = isTSEntityName; + generated$3.isTSEnumDeclaration = isTSEnumDeclaration; + generated$3.isTSEnumMember = isTSEnumMember; + generated$3.isTSExportAssignment = isTSExportAssignment; + generated$3.isTSExpressionWithTypeArguments = isTSExpressionWithTypeArguments; + generated$3.isTSExternalModuleReference = isTSExternalModuleReference; + generated$3.isTSFunctionType = isTSFunctionType; + generated$3.isTSImportEqualsDeclaration = isTSImportEqualsDeclaration; + generated$3.isTSImportType = isTSImportType; + generated$3.isTSIndexSignature = isTSIndexSignature; + generated$3.isTSIndexedAccessType = isTSIndexedAccessType; + generated$3.isTSInferType = isTSInferType; + generated$3.isTSInstantiationExpression = isTSInstantiationExpression; + generated$3.isTSInterfaceBody = isTSInterfaceBody; + generated$3.isTSInterfaceDeclaration = isTSInterfaceDeclaration; + generated$3.isTSIntersectionType = isTSIntersectionType; + generated$3.isTSIntrinsicKeyword = isTSIntrinsicKeyword; + generated$3.isTSLiteralType = isTSLiteralType; + generated$3.isTSMappedType = isTSMappedType; + generated$3.isTSMethodSignature = isTSMethodSignature; + generated$3.isTSModuleBlock = isTSModuleBlock; + generated$3.isTSModuleDeclaration = isTSModuleDeclaration; + generated$3.isTSNamedTupleMember = isTSNamedTupleMember; + generated$3.isTSNamespaceExportDeclaration = isTSNamespaceExportDeclaration; + generated$3.isTSNeverKeyword = isTSNeverKeyword; + generated$3.isTSNonNullExpression = isTSNonNullExpression; + generated$3.isTSNullKeyword = isTSNullKeyword; + generated$3.isTSNumberKeyword = isTSNumberKeyword; + generated$3.isTSObjectKeyword = isTSObjectKeyword; + generated$3.isTSOptionalType = isTSOptionalType; + generated$3.isTSParameterProperty = isTSParameterProperty; + generated$3.isTSParenthesizedType = isTSParenthesizedType; + generated$3.isTSPropertySignature = isTSPropertySignature; + generated$3.isTSQualifiedName = isTSQualifiedName; + generated$3.isTSRestType = isTSRestType; + generated$3.isTSSatisfiesExpression = isTSSatisfiesExpression; + generated$3.isTSStringKeyword = isTSStringKeyword; + generated$3.isTSSymbolKeyword = isTSSymbolKeyword; + generated$3.isTSThisType = isTSThisType; + generated$3.isTSTupleType = isTSTupleType; + generated$3.isTSType = isTSType; + generated$3.isTSTypeAliasDeclaration = isTSTypeAliasDeclaration; + generated$3.isTSTypeAnnotation = isTSTypeAnnotation; + generated$3.isTSTypeAssertion = isTSTypeAssertion; + generated$3.isTSTypeElement = isTSTypeElement; + generated$3.isTSTypeLiteral = isTSTypeLiteral; + generated$3.isTSTypeOperator = isTSTypeOperator; + generated$3.isTSTypeParameter = isTSTypeParameter; + generated$3.isTSTypeParameterDeclaration = isTSTypeParameterDeclaration; + generated$3.isTSTypeParameterInstantiation = isTSTypeParameterInstantiation; + generated$3.isTSTypePredicate = isTSTypePredicate; + generated$3.isTSTypeQuery = isTSTypeQuery; + generated$3.isTSTypeReference = isTSTypeReference; + generated$3.isTSUndefinedKeyword = isTSUndefinedKeyword; + generated$3.isTSUnionType = isTSUnionType; + generated$3.isTSUnknownKeyword = isTSUnknownKeyword; + generated$3.isTSVoidKeyword = isTSVoidKeyword; + generated$3.isTaggedTemplateExpression = isTaggedTemplateExpression; + generated$3.isTemplateElement = isTemplateElement; + generated$3.isTemplateLiteral = isTemplateLiteral; + generated$3.isTerminatorless = isTerminatorless; + generated$3.isThisExpression = isThisExpression; + generated$3.isThisTypeAnnotation = isThisTypeAnnotation; + generated$3.isThrowStatement = isThrowStatement; + generated$3.isTopicReference = isTopicReference; + generated$3.isTryStatement = isTryStatement; + generated$3.isTupleExpression = isTupleExpression; + generated$3.isTupleTypeAnnotation = isTupleTypeAnnotation; + generated$3.isTypeAlias = isTypeAlias; + generated$3.isTypeAnnotation = isTypeAnnotation; + generated$3.isTypeCastExpression = isTypeCastExpression; + generated$3.isTypeParameter = isTypeParameter; + generated$3.isTypeParameterDeclaration = isTypeParameterDeclaration; + generated$3.isTypeParameterInstantiation = isTypeParameterInstantiation; + generated$3.isTypeScript = isTypeScript; + generated$3.isTypeofTypeAnnotation = isTypeofTypeAnnotation; + generated$3.isUnaryExpression = isUnaryExpression; + generated$3.isUnaryLike = isUnaryLike; + generated$3.isUnionTypeAnnotation = isUnionTypeAnnotation; + generated$3.isUpdateExpression = isUpdateExpression; + generated$3.isUserWhitespacable = isUserWhitespacable; + generated$3.isV8IntrinsicIdentifier = isV8IntrinsicIdentifier; + generated$3.isVariableDeclaration = isVariableDeclaration; + generated$3.isVariableDeclarator = isVariableDeclarator; + generated$3.isVariance = isVariance; + generated$3.isVoidTypeAnnotation = isVoidTypeAnnotation; + generated$3.isWhile = isWhile; + generated$3.isWhileStatement = isWhileStatement; + generated$3.isWithStatement = isWithStatement; + generated$3.isYieldExpression = isYieldExpression; + var _shallowEqual = requireShallowEqual(); + var _deprecationWarning = requireDeprecationWarning(); + function isArrayExpression(node, opts) { + if (!node) return false; + if (node.type !== "ArrayExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isAssignmentExpression(node, opts) { + if (!node) return false; + if (node.type !== "AssignmentExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBinaryExpression(node, opts) { + if (!node) return false; + if (node.type !== "BinaryExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isInterpreterDirective(node, opts) { + if (!node) return false; + if (node.type !== "InterpreterDirective") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDirective(node, opts) { + if (!node) return false; + if (node.type !== "Directive") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDirectiveLiteral(node, opts) { + if (!node) return false; + if (node.type !== "DirectiveLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBlockStatement(node, opts) { + if (!node) return false; + if (node.type !== "BlockStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBreakStatement(node, opts) { + if (!node) return false; + if (node.type !== "BreakStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isCallExpression(node, opts) { + if (!node) return false; + if (node.type !== "CallExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isCatchClause(node, opts) { + if (!node) return false; + if (node.type !== "CatchClause") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isConditionalExpression(node, opts) { + if (!node) return false; + if (node.type !== "ConditionalExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isContinueStatement(node, opts) { + if (!node) return false; + if (node.type !== "ContinueStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDebuggerStatement(node, opts) { + if (!node) return false; + if (node.type !== "DebuggerStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDoWhileStatement(node, opts) { + if (!node) return false; + if (node.type !== "DoWhileStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEmptyStatement(node, opts) { + if (!node) return false; + if (node.type !== "EmptyStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExpressionStatement(node, opts) { + if (!node) return false; + if (node.type !== "ExpressionStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFile(node, opts) { + if (!node) return false; + if (node.type !== "File") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isForInStatement(node, opts) { + if (!node) return false; + if (node.type !== "ForInStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isForStatement(node, opts) { + if (!node) return false; + if (node.type !== "ForStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunctionDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "FunctionDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunctionExpression(node, opts) { + if (!node) return false; + if (node.type !== "FunctionExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isIdentifier(node, opts) { + if (!node) return false; + if (node.type !== "Identifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isIfStatement(node, opts) { + if (!node) return false; + if (node.type !== "IfStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isLabeledStatement(node, opts) { + if (!node) return false; + if (node.type !== "LabeledStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStringLiteral(node, opts) { + if (!node) return false; + if (node.type !== "StringLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNumericLiteral(node, opts) { + if (!node) return false; + if (node.type !== "NumericLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNullLiteral(node, opts) { + if (!node) return false; + if (node.type !== "NullLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBooleanLiteral(node, opts) { + if (!node) return false; + if (node.type !== "BooleanLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isRegExpLiteral(node, opts) { + if (!node) return false; + if (node.type !== "RegExpLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isLogicalExpression(node, opts) { + if (!node) return false; + if (node.type !== "LogicalExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isMemberExpression(node, opts) { + if (!node) return false; + if (node.type !== "MemberExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNewExpression(node, opts) { + if (!node) return false; + if (node.type !== "NewExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isProgram(node, opts) { + if (!node) return false; + if (node.type !== "Program") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectExpression(node, opts) { + if (!node) return false; + if (node.type !== "ObjectExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectMethod(node, opts) { + if (!node) return false; + if (node.type !== "ObjectMethod") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectProperty(node, opts) { + if (!node) return false; + if (node.type !== "ObjectProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isRestElement(node, opts) { + if (!node) return false; + if (node.type !== "RestElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isReturnStatement(node, opts) { + if (!node) return false; + if (node.type !== "ReturnStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSequenceExpression(node, opts) { + if (!node) return false; + if (node.type !== "SequenceExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isParenthesizedExpression(node, opts) { + if (!node) return false; + if (node.type !== "ParenthesizedExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSwitchCase(node, opts) { + if (!node) return false; + if (node.type !== "SwitchCase") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSwitchStatement(node, opts) { + if (!node) return false; + if (node.type !== "SwitchStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isThisExpression(node, opts) { + if (!node) return false; + if (node.type !== "ThisExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isThrowStatement(node, opts) { + if (!node) return false; + if (node.type !== "ThrowStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTryStatement(node, opts) { + if (!node) return false; + if (node.type !== "TryStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isUnaryExpression(node, opts) { + if (!node) return false; + if (node.type !== "UnaryExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isUpdateExpression(node, opts) { + if (!node) return false; + if (node.type !== "UpdateExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isVariableDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "VariableDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isVariableDeclarator(node, opts) { + if (!node) return false; + if (node.type !== "VariableDeclarator") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isWhileStatement(node, opts) { + if (!node) return false; + if (node.type !== "WhileStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isWithStatement(node, opts) { + if (!node) return false; + if (node.type !== "WithStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isAssignmentPattern(node, opts) { + if (!node) return false; + if (node.type !== "AssignmentPattern") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isArrayPattern(node, opts) { + if (!node) return false; + if (node.type !== "ArrayPattern") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isArrowFunctionExpression(node, opts) { + if (!node) return false; + if (node.type !== "ArrowFunctionExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassBody(node, opts) { + if (!node) return false; + if (node.type !== "ClassBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassExpression(node, opts) { + if (!node) return false; + if (node.type !== "ClassExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "ClassDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportAllDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "ExportAllDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportDefaultDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "ExportDefaultDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportNamedDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "ExportNamedDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ExportSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isForOfStatement(node, opts) { + if (!node) return false; + if (node.type !== "ForOfStatement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "ImportDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportDefaultSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ImportDefaultSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportNamespaceSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ImportNamespaceSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ImportSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportExpression(node, opts) { + if (!node) return false; + if (node.type !== "ImportExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isMetaProperty(node, opts) { + if (!node) return false; + if (node.type !== "MetaProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassMethod(node, opts) { + if (!node) return false; + if (node.type !== "ClassMethod") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectPattern(node, opts) { + if (!node) return false; + if (node.type !== "ObjectPattern") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSpreadElement(node, opts) { + if (!node) return false; + if (node.type !== "SpreadElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSuper(node, opts) { + if (!node) return false; + if (node.type !== "Super") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTaggedTemplateExpression(node, opts) { + if (!node) return false; + if (node.type !== "TaggedTemplateExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTemplateElement(node, opts) { + if (!node) return false; + if (node.type !== "TemplateElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTemplateLiteral(node, opts) { + if (!node) return false; + if (node.type !== "TemplateLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isYieldExpression(node, opts) { + if (!node) return false; + if (node.type !== "YieldExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isAwaitExpression(node, opts) { + if (!node) return false; + if (node.type !== "AwaitExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImport(node, opts) { + if (!node) return false; + if (node.type !== "Import") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBigIntLiteral(node, opts) { + if (!node) return false; + if (node.type !== "BigIntLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportNamespaceSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ExportNamespaceSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isOptionalMemberExpression(node, opts) { + if (!node) return false; + if (node.type !== "OptionalMemberExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isOptionalCallExpression(node, opts) { + if (!node) return false; + if (node.type !== "OptionalCallExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassProperty(node, opts) { + if (!node) return false; + if (node.type !== "ClassProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassAccessorProperty(node, opts) { + if (!node) return false; + if (node.type !== "ClassAccessorProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassPrivateProperty(node, opts) { + if (!node) return false; + if (node.type !== "ClassPrivateProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassPrivateMethod(node, opts) { + if (!node) return false; + if (node.type !== "ClassPrivateMethod") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPrivateName(node, opts) { + if (!node) return false; + if (node.type !== "PrivateName") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStaticBlock(node, opts) { + if (!node) return false; + if (node.type !== "StaticBlock") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isAnyTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "AnyTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isArrayTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "ArrayTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBooleanTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "BooleanTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBooleanLiteralTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "BooleanLiteralTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNullLiteralTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "NullLiteralTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClassImplements(node, opts) { + if (!node) return false; + if (node.type !== "ClassImplements") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareClass(node, opts) { + if (!node) return false; + if (node.type !== "DeclareClass") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareFunction(node, opts) { + if (!node) return false; + if (node.type !== "DeclareFunction") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareInterface(node, opts) { + if (!node) return false; + if (node.type !== "DeclareInterface") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareModule(node, opts) { + if (!node) return false; + if (node.type !== "DeclareModule") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareModuleExports(node, opts) { + if (!node) return false; + if (node.type !== "DeclareModuleExports") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareTypeAlias(node, opts) { + if (!node) return false; + if (node.type !== "DeclareTypeAlias") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareOpaqueType(node, opts) { + if (!node) return false; + if (node.type !== "DeclareOpaqueType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareVariable(node, opts) { + if (!node) return false; + if (node.type !== "DeclareVariable") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareExportDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "DeclareExportDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclareExportAllDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "DeclareExportAllDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclaredPredicate(node, opts) { + if (!node) return false; + if (node.type !== "DeclaredPredicate") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExistsTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "ExistsTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunctionTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "FunctionTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunctionTypeParam(node, opts) { + if (!node) return false; + if (node.type !== "FunctionTypeParam") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isGenericTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "GenericTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isInferredPredicate(node, opts) { + if (!node) return false; + if (node.type !== "InferredPredicate") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isInterfaceExtends(node, opts) { + if (!node) return false; + if (node.type !== "InterfaceExtends") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isInterfaceDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "InterfaceDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isInterfaceTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "InterfaceTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isIntersectionTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "IntersectionTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isMixedTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "MixedTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEmptyTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "EmptyTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNullableTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "NullableTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNumberLiteralTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "NumberLiteralTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNumberTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "NumberTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeInternalSlot(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeInternalSlot") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeCallProperty(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeCallProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeIndexer(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeIndexer") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeProperty(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectTypeSpreadProperty(node, opts) { + if (!node) return false; + if (node.type !== "ObjectTypeSpreadProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isOpaqueType(node, opts) { + if (!node) return false; + if (node.type !== "OpaqueType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isQualifiedTypeIdentifier(node, opts) { + if (!node) return false; + if (node.type !== "QualifiedTypeIdentifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStringLiteralTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "StringLiteralTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStringTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "StringTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSymbolTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "SymbolTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isThisTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "ThisTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTupleTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "TupleTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeofTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "TypeofTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeAlias(node, opts) { + if (!node) return false; + if (node.type !== "TypeAlias") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "TypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeCastExpression(node, opts) { + if (!node) return false; + if (node.type !== "TypeCastExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeParameter(node, opts) { + if (!node) return false; + if (node.type !== "TypeParameter") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeParameterDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TypeParameterDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeParameterInstantiation(node, opts) { + if (!node) return false; + if (node.type !== "TypeParameterInstantiation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isUnionTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "UnionTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isVariance(node, opts) { + if (!node) return false; + if (node.type !== "Variance") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isVoidTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "VoidTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "EnumDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumBooleanBody(node, opts) { + if (!node) return false; + if (node.type !== "EnumBooleanBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumNumberBody(node, opts) { + if (!node) return false; + if (node.type !== "EnumNumberBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumStringBody(node, opts) { + if (!node) return false; + if (node.type !== "EnumStringBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumSymbolBody(node, opts) { + if (!node) return false; + if (node.type !== "EnumSymbolBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumBooleanMember(node, opts) { + if (!node) return false; + if (node.type !== "EnumBooleanMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumNumberMember(node, opts) { + if (!node) return false; + if (node.type !== "EnumNumberMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumStringMember(node, opts) { + if (!node) return false; + if (node.type !== "EnumStringMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumDefaultedMember(node, opts) { + if (!node) return false; + if (node.type !== "EnumDefaultedMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isIndexedAccessType(node, opts) { + if (!node) return false; + if (node.type !== "IndexedAccessType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isOptionalIndexedAccessType(node, opts) { + if (!node) return false; + if (node.type !== "OptionalIndexedAccessType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXAttribute(node, opts) { + if (!node) return false; + if (node.type !== "JSXAttribute") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXClosingElement(node, opts) { + if (!node) return false; + if (node.type !== "JSXClosingElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXElement(node, opts) { + if (!node) return false; + if (node.type !== "JSXElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXEmptyExpression(node, opts) { + if (!node) return false; + if (node.type !== "JSXEmptyExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXExpressionContainer(node, opts) { + if (!node) return false; + if (node.type !== "JSXExpressionContainer") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXSpreadChild(node, opts) { + if (!node) return false; + if (node.type !== "JSXSpreadChild") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXIdentifier(node, opts) { + if (!node) return false; + if (node.type !== "JSXIdentifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXMemberExpression(node, opts) { + if (!node) return false; + if (node.type !== "JSXMemberExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXNamespacedName(node, opts) { + if (!node) return false; + if (node.type !== "JSXNamespacedName") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXOpeningElement(node, opts) { + if (!node) return false; + if (node.type !== "JSXOpeningElement") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXSpreadAttribute(node, opts) { + if (!node) return false; + if (node.type !== "JSXSpreadAttribute") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXText(node, opts) { + if (!node) return false; + if (node.type !== "JSXText") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXFragment(node, opts) { + if (!node) return false; + if (node.type !== "JSXFragment") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXOpeningFragment(node, opts) { + if (!node) return false; + if (node.type !== "JSXOpeningFragment") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSXClosingFragment(node, opts) { + if (!node) return false; + if (node.type !== "JSXClosingFragment") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNoop(node, opts) { + if (!node) return false; + if (node.type !== "Noop") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPlaceholder(node, opts) { + if (!node) return false; + if (node.type !== "Placeholder") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isV8IntrinsicIdentifier(node, opts) { + if (!node) return false; + if (node.type !== "V8IntrinsicIdentifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isArgumentPlaceholder(node, opts) { + if (!node) return false; + if (node.type !== "ArgumentPlaceholder") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBindExpression(node, opts) { + if (!node) return false; + if (node.type !== "BindExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportAttribute(node, opts) { + if (!node) return false; + if (node.type !== "ImportAttribute") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDecorator(node, opts) { + if (!node) return false; + if (node.type !== "Decorator") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDoExpression(node, opts) { + if (!node) return false; + if (node.type !== "DoExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportDefaultSpecifier(node, opts) { + if (!node) return false; + if (node.type !== "ExportDefaultSpecifier") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isRecordExpression(node, opts) { + if (!node) return false; + if (node.type !== "RecordExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTupleExpression(node, opts) { + if (!node) return false; + if (node.type !== "TupleExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDecimalLiteral(node, opts) { + if (!node) return false; + if (node.type !== "DecimalLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isModuleExpression(node, opts) { + if (!node) return false; + if (node.type !== "ModuleExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTopicReference(node, opts) { + if (!node) return false; + if (node.type !== "TopicReference") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPipelineTopicExpression(node, opts) { + if (!node) return false; + if (node.type !== "PipelineTopicExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPipelineBareFunction(node, opts) { + if (!node) return false; + if (node.type !== "PipelineBareFunction") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPipelinePrimaryTopicReference(node, opts) { + if (!node) return false; + if (node.type !== "PipelinePrimaryTopicReference") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSParameterProperty(node, opts) { + if (!node) return false; + if (node.type !== "TSParameterProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSDeclareFunction(node, opts) { + if (!node) return false; + if (node.type !== "TSDeclareFunction") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSDeclareMethod(node, opts) { + if (!node) return false; + if (node.type !== "TSDeclareMethod") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSQualifiedName(node, opts) { + if (!node) return false; + if (node.type !== "TSQualifiedName") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSCallSignatureDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSCallSignatureDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSConstructSignatureDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSConstructSignatureDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSPropertySignature(node, opts) { + if (!node) return false; + if (node.type !== "TSPropertySignature") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSMethodSignature(node, opts) { + if (!node) return false; + if (node.type !== "TSMethodSignature") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSIndexSignature(node, opts) { + if (!node) return false; + if (node.type !== "TSIndexSignature") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSAnyKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSAnyKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSBooleanKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSBooleanKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSBigIntKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSBigIntKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSIntrinsicKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSIntrinsicKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNeverKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSNeverKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNullKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSNullKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNumberKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSNumberKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSObjectKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSObjectKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSStringKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSStringKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSSymbolKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSSymbolKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSUndefinedKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSUndefinedKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSUnknownKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSUnknownKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSVoidKeyword(node, opts) { + if (!node) return false; + if (node.type !== "TSVoidKeyword") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSThisType(node, opts) { + if (!node) return false; + if (node.type !== "TSThisType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSFunctionType(node, opts) { + if (!node) return false; + if (node.type !== "TSFunctionType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSConstructorType(node, opts) { + if (!node) return false; + if (node.type !== "TSConstructorType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeReference(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeReference") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypePredicate(node, opts) { + if (!node) return false; + if (node.type !== "TSTypePredicate") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeQuery(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeQuery") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeLiteral(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSArrayType(node, opts) { + if (!node) return false; + if (node.type !== "TSArrayType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTupleType(node, opts) { + if (!node) return false; + if (node.type !== "TSTupleType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSOptionalType(node, opts) { + if (!node) return false; + if (node.type !== "TSOptionalType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSRestType(node, opts) { + if (!node) return false; + if (node.type !== "TSRestType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNamedTupleMember(node, opts) { + if (!node) return false; + if (node.type !== "TSNamedTupleMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSUnionType(node, opts) { + if (!node) return false; + if (node.type !== "TSUnionType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSIntersectionType(node, opts) { + if (!node) return false; + if (node.type !== "TSIntersectionType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSConditionalType(node, opts) { + if (!node) return false; + if (node.type !== "TSConditionalType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSInferType(node, opts) { + if (!node) return false; + if (node.type !== "TSInferType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSParenthesizedType(node, opts) { + if (!node) return false; + if (node.type !== "TSParenthesizedType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeOperator(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeOperator") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSIndexedAccessType(node, opts) { + if (!node) return false; + if (node.type !== "TSIndexedAccessType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSMappedType(node, opts) { + if (!node) return false; + if (node.type !== "TSMappedType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSLiteralType(node, opts) { + if (!node) return false; + if (node.type !== "TSLiteralType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSExpressionWithTypeArguments(node, opts) { + if (!node) return false; + if (node.type !== "TSExpressionWithTypeArguments") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSInterfaceDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSInterfaceDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSInterfaceBody(node, opts) { + if (!node) return false; + if (node.type !== "TSInterfaceBody") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeAliasDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeAliasDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSInstantiationExpression(node, opts) { + if (!node) return false; + if (node.type !== "TSInstantiationExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSAsExpression(node, opts) { + if (!node) return false; + if (node.type !== "TSAsExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSSatisfiesExpression(node, opts) { + if (!node) return false; + if (node.type !== "TSSatisfiesExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeAssertion(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeAssertion") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSEnumDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSEnumDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSEnumMember(node, opts) { + if (!node) return false; + if (node.type !== "TSEnumMember") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSModuleDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSModuleDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSModuleBlock(node, opts) { + if (!node) return false; + if (node.type !== "TSModuleBlock") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSImportType(node, opts) { + if (!node) return false; + if (node.type !== "TSImportType") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSImportEqualsDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSImportEqualsDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSExternalModuleReference(node, opts) { + if (!node) return false; + if (node.type !== "TSExternalModuleReference") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNonNullExpression(node, opts) { + if (!node) return false; + if (node.type !== "TSNonNullExpression") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSExportAssignment(node, opts) { + if (!node) return false; + if (node.type !== "TSExportAssignment") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSNamespaceExportDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSNamespaceExportDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeAnnotation(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeAnnotation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeParameterInstantiation(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeParameterInstantiation") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeParameterDeclaration(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeParameterDeclaration") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeParameter(node, opts) { + if (!node) return false; + if (node.type !== "TSTypeParameter") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStandardized(node, opts) { + if (!node) return false; + switch (node.type) { + case "ArrayExpression": + case "AssignmentExpression": + case "BinaryExpression": + case "InterpreterDirective": + case "Directive": + case "DirectiveLiteral": + case "BlockStatement": + case "BreakStatement": + case "CallExpression": + case "CatchClause": + case "ConditionalExpression": + case "ContinueStatement": + case "DebuggerStatement": + case "DoWhileStatement": + case "EmptyStatement": + case "ExpressionStatement": + case "File": + case "ForInStatement": + case "ForStatement": + case "FunctionDeclaration": + case "FunctionExpression": + case "Identifier": + case "IfStatement": + case "LabeledStatement": + case "StringLiteral": + case "NumericLiteral": + case "NullLiteral": + case "BooleanLiteral": + case "RegExpLiteral": + case "LogicalExpression": + case "MemberExpression": + case "NewExpression": + case "Program": + case "ObjectExpression": + case "ObjectMethod": + case "ObjectProperty": + case "RestElement": + case "ReturnStatement": + case "SequenceExpression": + case "ParenthesizedExpression": + case "SwitchCase": + case "SwitchStatement": + case "ThisExpression": + case "ThrowStatement": + case "TryStatement": + case "UnaryExpression": + case "UpdateExpression": + case "VariableDeclaration": + case "VariableDeclarator": + case "WhileStatement": + case "WithStatement": + case "AssignmentPattern": + case "ArrayPattern": + case "ArrowFunctionExpression": + case "ClassBody": + case "ClassExpression": + case "ClassDeclaration": + case "ExportAllDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + case "ExportSpecifier": + case "ForOfStatement": + case "ImportDeclaration": + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "ImportSpecifier": + case "ImportExpression": + case "MetaProperty": + case "ClassMethod": + case "ObjectPattern": + case "SpreadElement": + case "Super": + case "TaggedTemplateExpression": + case "TemplateElement": + case "TemplateLiteral": + case "YieldExpression": + case "AwaitExpression": + case "Import": + case "BigIntLiteral": + case "ExportNamespaceSpecifier": + case "OptionalMemberExpression": + case "OptionalCallExpression": + case "ClassProperty": + case "ClassAccessorProperty": + case "ClassPrivateProperty": + case "ClassPrivateMethod": + case "PrivateName": + case "StaticBlock": + break; + case "Placeholder": + switch (node.expectedNode) { + case "Identifier": + case "StringLiteral": + case "BlockStatement": + case "ClassBody": + break; + default: + return false; + } + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExpression(node, opts) { + if (!node) return false; + switch (node.type) { + case "ArrayExpression": + case "AssignmentExpression": + case "BinaryExpression": + case "CallExpression": + case "ConditionalExpression": + case "FunctionExpression": + case "Identifier": + case "StringLiteral": + case "NumericLiteral": + case "NullLiteral": + case "BooleanLiteral": + case "RegExpLiteral": + case "LogicalExpression": + case "MemberExpression": + case "NewExpression": + case "ObjectExpression": + case "SequenceExpression": + case "ParenthesizedExpression": + case "ThisExpression": + case "UnaryExpression": + case "UpdateExpression": + case "ArrowFunctionExpression": + case "ClassExpression": + case "ImportExpression": + case "MetaProperty": + case "Super": + case "TaggedTemplateExpression": + case "TemplateLiteral": + case "YieldExpression": + case "AwaitExpression": + case "Import": + case "BigIntLiteral": + case "OptionalMemberExpression": + case "OptionalCallExpression": + case "TypeCastExpression": + case "JSXElement": + case "JSXFragment": + case "BindExpression": + case "DoExpression": + case "RecordExpression": + case "TupleExpression": + case "DecimalLiteral": + case "ModuleExpression": + case "TopicReference": + case "PipelineTopicExpression": + case "PipelineBareFunction": + case "PipelinePrimaryTopicReference": + case "TSInstantiationExpression": + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + break; + case "Placeholder": + switch (node.expectedNode) { + case "Expression": + case "Identifier": + case "StringLiteral": + break; + default: + return false; + } + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBinary(node, opts) { + if (!node) return false; + switch (node.type) { + case "BinaryExpression": + case "LogicalExpression": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isScopable(node, opts) { + if (!node) return false; + switch (node.type) { + case "BlockStatement": + case "CatchClause": + case "DoWhileStatement": + case "ForInStatement": + case "ForStatement": + case "FunctionDeclaration": + case "FunctionExpression": + case "Program": + case "ObjectMethod": + case "SwitchStatement": + case "WhileStatement": + case "ArrowFunctionExpression": + case "ClassExpression": + case "ClassDeclaration": + case "ForOfStatement": + case "ClassMethod": + case "ClassPrivateMethod": + case "StaticBlock": + case "TSModuleBlock": + break; + case "Placeholder": + if (node.expectedNode === "BlockStatement") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBlockParent(node, opts) { + if (!node) return false; + switch (node.type) { + case "BlockStatement": + case "CatchClause": + case "DoWhileStatement": + case "ForInStatement": + case "ForStatement": + case "FunctionDeclaration": + case "FunctionExpression": + case "Program": + case "ObjectMethod": + case "SwitchStatement": + case "WhileStatement": + case "ArrowFunctionExpression": + case "ForOfStatement": + case "ClassMethod": + case "ClassPrivateMethod": + case "StaticBlock": + case "TSModuleBlock": + break; + case "Placeholder": + if (node.expectedNode === "BlockStatement") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isBlock(node, opts) { + if (!node) return false; + switch (node.type) { + case "BlockStatement": + case "Program": + case "TSModuleBlock": + break; + case "Placeholder": + if (node.expectedNode === "BlockStatement") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isStatement(node, opts) { + if (!node) return false; + switch (node.type) { + case "BlockStatement": + case "BreakStatement": + case "ContinueStatement": + case "DebuggerStatement": + case "DoWhileStatement": + case "EmptyStatement": + case "ExpressionStatement": + case "ForInStatement": + case "ForStatement": + case "FunctionDeclaration": + case "IfStatement": + case "LabeledStatement": + case "ReturnStatement": + case "SwitchStatement": + case "ThrowStatement": + case "TryStatement": + case "VariableDeclaration": + case "WhileStatement": + case "WithStatement": + case "ClassDeclaration": + case "ExportAllDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + case "ForOfStatement": + case "ImportDeclaration": + case "DeclareClass": + case "DeclareFunction": + case "DeclareInterface": + case "DeclareModule": + case "DeclareModuleExports": + case "DeclareTypeAlias": + case "DeclareOpaqueType": + case "DeclareVariable": + case "DeclareExportDeclaration": + case "DeclareExportAllDeclaration": + case "InterfaceDeclaration": + case "OpaqueType": + case "TypeAlias": + case "EnumDeclaration": + case "TSDeclareFunction": + case "TSInterfaceDeclaration": + case "TSTypeAliasDeclaration": + case "TSEnumDeclaration": + case "TSModuleDeclaration": + case "TSImportEqualsDeclaration": + case "TSExportAssignment": + case "TSNamespaceExportDeclaration": + break; + case "Placeholder": + switch (node.expectedNode) { + case "Statement": + case "Declaration": + case "BlockStatement": + break; + default: + return false; + } + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTerminatorless(node, opts) { + if (!node) return false; + switch (node.type) { + case "BreakStatement": + case "ContinueStatement": + case "ReturnStatement": + case "ThrowStatement": + case "YieldExpression": + case "AwaitExpression": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isCompletionStatement(node, opts) { + if (!node) return false; + switch (node.type) { + case "BreakStatement": + case "ContinueStatement": + case "ReturnStatement": + case "ThrowStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isConditional(node, opts) { + if (!node) return false; + switch (node.type) { + case "ConditionalExpression": + case "IfStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isLoop(node, opts) { + if (!node) return false; + switch (node.type) { + case "DoWhileStatement": + case "ForInStatement": + case "ForStatement": + case "WhileStatement": + case "ForOfStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isWhile(node, opts) { + if (!node) return false; + switch (node.type) { + case "DoWhileStatement": + case "WhileStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExpressionWrapper(node, opts) { + if (!node) return false; + switch (node.type) { + case "ExpressionStatement": + case "ParenthesizedExpression": + case "TypeCastExpression": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFor(node, opts) { + if (!node) return false; + switch (node.type) { + case "ForInStatement": + case "ForStatement": + case "ForOfStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isForXStatement(node, opts) { + if (!node) return false; + switch (node.type) { + case "ForInStatement": + case "ForOfStatement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunction(node, opts) { + if (!node) return false; + switch (node.type) { + case "FunctionDeclaration": + case "FunctionExpression": + case "ObjectMethod": + case "ArrowFunctionExpression": + case "ClassMethod": + case "ClassPrivateMethod": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFunctionParent(node, opts) { + if (!node) return false; + switch (node.type) { + case "FunctionDeclaration": + case "FunctionExpression": + case "ObjectMethod": + case "ArrowFunctionExpression": + case "ClassMethod": + case "ClassPrivateMethod": + case "StaticBlock": + case "TSModuleBlock": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPureish(node, opts) { + if (!node) return false; + switch (node.type) { + case "FunctionDeclaration": + case "FunctionExpression": + case "StringLiteral": + case "NumericLiteral": + case "NullLiteral": + case "BooleanLiteral": + case "RegExpLiteral": + case "ArrowFunctionExpression": + case "BigIntLiteral": + case "DecimalLiteral": + break; + case "Placeholder": + if (node.expectedNode === "StringLiteral") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isDeclaration(node, opts) { + if (!node) return false; + switch (node.type) { + case "FunctionDeclaration": + case "VariableDeclaration": + case "ClassDeclaration": + case "ExportAllDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + case "ImportDeclaration": + case "DeclareClass": + case "DeclareFunction": + case "DeclareInterface": + case "DeclareModule": + case "DeclareModuleExports": + case "DeclareTypeAlias": + case "DeclareOpaqueType": + case "DeclareVariable": + case "DeclareExportDeclaration": + case "DeclareExportAllDeclaration": + case "InterfaceDeclaration": + case "OpaqueType": + case "TypeAlias": + case "EnumDeclaration": + case "TSDeclareFunction": + case "TSInterfaceDeclaration": + case "TSTypeAliasDeclaration": + case "TSEnumDeclaration": + case "TSModuleDeclaration": + break; + case "Placeholder": + if (node.expectedNode === "Declaration") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPatternLike(node, opts) { + if (!node) return false; + switch (node.type) { + case "Identifier": + case "RestElement": + case "AssignmentPattern": + case "ArrayPattern": + case "ObjectPattern": + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + break; + case "Placeholder": + switch (node.expectedNode) { + case "Pattern": + case "Identifier": + break; + default: + return false; + } + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isLVal(node, opts) { + if (!node) return false; + switch (node.type) { + case "Identifier": + case "MemberExpression": + case "RestElement": + case "AssignmentPattern": + case "ArrayPattern": + case "ObjectPattern": + case "TSParameterProperty": + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + break; + case "Placeholder": + switch (node.expectedNode) { + case "Pattern": + case "Identifier": + break; + default: + return false; + } + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSEntityName(node, opts) { + if (!node) return false; + switch (node.type) { + case "Identifier": + case "TSQualifiedName": + break; + case "Placeholder": + if (node.expectedNode === "Identifier") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isLiteral(node, opts) { + if (!node) return false; + switch (node.type) { + case "StringLiteral": + case "NumericLiteral": + case "NullLiteral": + case "BooleanLiteral": + case "RegExpLiteral": + case "TemplateLiteral": + case "BigIntLiteral": + case "DecimalLiteral": + break; + case "Placeholder": + if (node.expectedNode === "StringLiteral") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImmutable(node, opts) { + if (!node) return false; + switch (node.type) { + case "StringLiteral": + case "NumericLiteral": + case "NullLiteral": + case "BooleanLiteral": + case "BigIntLiteral": + case "JSXAttribute": + case "JSXClosingElement": + case "JSXElement": + case "JSXExpressionContainer": + case "JSXSpreadChild": + case "JSXOpeningElement": + case "JSXText": + case "JSXFragment": + case "JSXOpeningFragment": + case "JSXClosingFragment": + case "DecimalLiteral": + break; + case "Placeholder": + if (node.expectedNode === "StringLiteral") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isUserWhitespacable(node, opts) { + if (!node) return false; + switch (node.type) { + case "ObjectMethod": + case "ObjectProperty": + case "ObjectTypeInternalSlot": + case "ObjectTypeCallProperty": + case "ObjectTypeIndexer": + case "ObjectTypeProperty": + case "ObjectTypeSpreadProperty": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isMethod(node, opts) { + if (!node) return false; + switch (node.type) { + case "ObjectMethod": + case "ClassMethod": + case "ClassPrivateMethod": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isObjectMember(node, opts) { + if (!node) return false; + switch (node.type) { + case "ObjectMethod": + case "ObjectProperty": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isProperty(node, opts) { + if (!node) return false; + switch (node.type) { + case "ObjectProperty": + case "ClassProperty": + case "ClassAccessorProperty": + case "ClassPrivateProperty": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isUnaryLike(node, opts) { + if (!node) return false; + switch (node.type) { + case "UnaryExpression": + case "SpreadElement": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPattern(node, opts) { + if (!node) return false; + switch (node.type) { + case "AssignmentPattern": + case "ArrayPattern": + case "ObjectPattern": + break; + case "Placeholder": + if (node.expectedNode === "Pattern") break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isClass(node, opts) { + if (!node) return false; + switch (node.type) { + case "ClassExpression": + case "ClassDeclaration": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isImportOrExportDeclaration(node, opts) { + if (!node) return false; + switch (node.type) { + case "ExportAllDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + case "ImportDeclaration": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isExportDeclaration(node, opts) { + if (!node) return false; + switch (node.type) { + case "ExportAllDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isModuleSpecifier(node, opts) { + if (!node) return false; + switch (node.type) { + case "ExportSpecifier": + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "ImportSpecifier": + case "ExportNamespaceSpecifier": + case "ExportDefaultSpecifier": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isAccessor(node, opts) { + if (!node) return false; + switch (node.type) { + case "ClassAccessorProperty": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isPrivate(node, opts) { + if (!node) return false; + switch (node.type) { + case "ClassPrivateProperty": + case "ClassPrivateMethod": + case "PrivateName": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFlow(node, opts) { + if (!node) return false; + switch (node.type) { + case "AnyTypeAnnotation": + case "ArrayTypeAnnotation": + case "BooleanTypeAnnotation": + case "BooleanLiteralTypeAnnotation": + case "NullLiteralTypeAnnotation": + case "ClassImplements": + case "DeclareClass": + case "DeclareFunction": + case "DeclareInterface": + case "DeclareModule": + case "DeclareModuleExports": + case "DeclareTypeAlias": + case "DeclareOpaqueType": + case "DeclareVariable": + case "DeclareExportDeclaration": + case "DeclareExportAllDeclaration": + case "DeclaredPredicate": + case "ExistsTypeAnnotation": + case "FunctionTypeAnnotation": + case "FunctionTypeParam": + case "GenericTypeAnnotation": + case "InferredPredicate": + case "InterfaceExtends": + case "InterfaceDeclaration": + case "InterfaceTypeAnnotation": + case "IntersectionTypeAnnotation": + case "MixedTypeAnnotation": + case "EmptyTypeAnnotation": + case "NullableTypeAnnotation": + case "NumberLiteralTypeAnnotation": + case "NumberTypeAnnotation": + case "ObjectTypeAnnotation": + case "ObjectTypeInternalSlot": + case "ObjectTypeCallProperty": + case "ObjectTypeIndexer": + case "ObjectTypeProperty": + case "ObjectTypeSpreadProperty": + case "OpaqueType": + case "QualifiedTypeIdentifier": + case "StringLiteralTypeAnnotation": + case "StringTypeAnnotation": + case "SymbolTypeAnnotation": + case "ThisTypeAnnotation": + case "TupleTypeAnnotation": + case "TypeofTypeAnnotation": + case "TypeAlias": + case "TypeAnnotation": + case "TypeCastExpression": + case "TypeParameter": + case "TypeParameterDeclaration": + case "TypeParameterInstantiation": + case "UnionTypeAnnotation": + case "Variance": + case "VoidTypeAnnotation": + case "EnumDeclaration": + case "EnumBooleanBody": + case "EnumNumberBody": + case "EnumStringBody": + case "EnumSymbolBody": + case "EnumBooleanMember": + case "EnumNumberMember": + case "EnumStringMember": + case "EnumDefaultedMember": + case "IndexedAccessType": + case "OptionalIndexedAccessType": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFlowType(node, opts) { + if (!node) return false; + switch (node.type) { + case "AnyTypeAnnotation": + case "ArrayTypeAnnotation": + case "BooleanTypeAnnotation": + case "BooleanLiteralTypeAnnotation": + case "NullLiteralTypeAnnotation": + case "ExistsTypeAnnotation": + case "FunctionTypeAnnotation": + case "GenericTypeAnnotation": + case "InterfaceTypeAnnotation": + case "IntersectionTypeAnnotation": + case "MixedTypeAnnotation": + case "EmptyTypeAnnotation": + case "NullableTypeAnnotation": + case "NumberLiteralTypeAnnotation": + case "NumberTypeAnnotation": + case "ObjectTypeAnnotation": + case "StringLiteralTypeAnnotation": + case "StringTypeAnnotation": + case "SymbolTypeAnnotation": + case "ThisTypeAnnotation": + case "TupleTypeAnnotation": + case "TypeofTypeAnnotation": + case "UnionTypeAnnotation": + case "VoidTypeAnnotation": + case "IndexedAccessType": + case "OptionalIndexedAccessType": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFlowBaseAnnotation(node, opts) { + if (!node) return false; + switch (node.type) { + case "AnyTypeAnnotation": + case "BooleanTypeAnnotation": + case "NullLiteralTypeAnnotation": + case "MixedTypeAnnotation": + case "EmptyTypeAnnotation": + case "NumberTypeAnnotation": + case "StringTypeAnnotation": + case "SymbolTypeAnnotation": + case "ThisTypeAnnotation": + case "VoidTypeAnnotation": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFlowDeclaration(node, opts) { + if (!node) return false; + switch (node.type) { + case "DeclareClass": + case "DeclareFunction": + case "DeclareInterface": + case "DeclareModule": + case "DeclareModuleExports": + case "DeclareTypeAlias": + case "DeclareOpaqueType": + case "DeclareVariable": + case "DeclareExportDeclaration": + case "DeclareExportAllDeclaration": + case "InterfaceDeclaration": + case "OpaqueType": + case "TypeAlias": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isFlowPredicate(node, opts) { + if (!node) return false; + switch (node.type) { + case "DeclaredPredicate": + case "InferredPredicate": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumBody(node, opts) { + if (!node) return false; + switch (node.type) { + case "EnumBooleanBody": + case "EnumNumberBody": + case "EnumStringBody": + case "EnumSymbolBody": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isEnumMember(node, opts) { + if (!node) return false; + switch (node.type) { + case "EnumBooleanMember": + case "EnumNumberMember": + case "EnumStringMember": + case "EnumDefaultedMember": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isJSX(node, opts) { + if (!node) return false; + switch (node.type) { + case "JSXAttribute": + case "JSXClosingElement": + case "JSXElement": + case "JSXEmptyExpression": + case "JSXExpressionContainer": + case "JSXSpreadChild": + case "JSXIdentifier": + case "JSXMemberExpression": + case "JSXNamespacedName": + case "JSXOpeningElement": + case "JSXSpreadAttribute": + case "JSXText": + case "JSXFragment": + case "JSXOpeningFragment": + case "JSXClosingFragment": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isMiscellaneous(node, opts) { + if (!node) return false; + switch (node.type) { + case "Noop": + case "Placeholder": + case "V8IntrinsicIdentifier": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTypeScript(node, opts) { + if (!node) return false; + switch (node.type) { + case "TSParameterProperty": + case "TSDeclareFunction": + case "TSDeclareMethod": + case "TSQualifiedName": + case "TSCallSignatureDeclaration": + case "TSConstructSignatureDeclaration": + case "TSPropertySignature": + case "TSMethodSignature": + case "TSIndexSignature": + case "TSAnyKeyword": + case "TSBooleanKeyword": + case "TSBigIntKeyword": + case "TSIntrinsicKeyword": + case "TSNeverKeyword": + case "TSNullKeyword": + case "TSNumberKeyword": + case "TSObjectKeyword": + case "TSStringKeyword": + case "TSSymbolKeyword": + case "TSUndefinedKeyword": + case "TSUnknownKeyword": + case "TSVoidKeyword": + case "TSThisType": + case "TSFunctionType": + case "TSConstructorType": + case "TSTypeReference": + case "TSTypePredicate": + case "TSTypeQuery": + case "TSTypeLiteral": + case "TSArrayType": + case "TSTupleType": + case "TSOptionalType": + case "TSRestType": + case "TSNamedTupleMember": + case "TSUnionType": + case "TSIntersectionType": + case "TSConditionalType": + case "TSInferType": + case "TSParenthesizedType": + case "TSTypeOperator": + case "TSIndexedAccessType": + case "TSMappedType": + case "TSLiteralType": + case "TSExpressionWithTypeArguments": + case "TSInterfaceDeclaration": + case "TSInterfaceBody": + case "TSTypeAliasDeclaration": + case "TSInstantiationExpression": + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSEnumDeclaration": + case "TSEnumMember": + case "TSModuleDeclaration": + case "TSModuleBlock": + case "TSImportType": + case "TSImportEqualsDeclaration": + case "TSExternalModuleReference": + case "TSNonNullExpression": + case "TSExportAssignment": + case "TSNamespaceExportDeclaration": + case "TSTypeAnnotation": + case "TSTypeParameterInstantiation": + case "TSTypeParameterDeclaration": + case "TSTypeParameter": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSTypeElement(node, opts) { + if (!node) return false; + switch (node.type) { + case "TSCallSignatureDeclaration": + case "TSConstructSignatureDeclaration": + case "TSPropertySignature": + case "TSMethodSignature": + case "TSIndexSignature": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSType(node, opts) { + if (!node) return false; + switch (node.type) { + case "TSAnyKeyword": + case "TSBooleanKeyword": + case "TSBigIntKeyword": + case "TSIntrinsicKeyword": + case "TSNeverKeyword": + case "TSNullKeyword": + case "TSNumberKeyword": + case "TSObjectKeyword": + case "TSStringKeyword": + case "TSSymbolKeyword": + case "TSUndefinedKeyword": + case "TSUnknownKeyword": + case "TSVoidKeyword": + case "TSThisType": + case "TSFunctionType": + case "TSConstructorType": + case "TSTypeReference": + case "TSTypePredicate": + case "TSTypeQuery": + case "TSTypeLiteral": + case "TSArrayType": + case "TSTupleType": + case "TSOptionalType": + case "TSRestType": + case "TSUnionType": + case "TSIntersectionType": + case "TSConditionalType": + case "TSInferType": + case "TSParenthesizedType": + case "TSTypeOperator": + case "TSIndexedAccessType": + case "TSMappedType": + case "TSLiteralType": + case "TSExpressionWithTypeArguments": + case "TSImportType": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isTSBaseType(node, opts) { + if (!node) return false; + switch (node.type) { + case "TSAnyKeyword": + case "TSBooleanKeyword": + case "TSBigIntKeyword": + case "TSIntrinsicKeyword": + case "TSNeverKeyword": + case "TSNullKeyword": + case "TSNumberKeyword": + case "TSObjectKeyword": + case "TSStringKeyword": + case "TSSymbolKeyword": + case "TSUndefinedKeyword": + case "TSUnknownKeyword": + case "TSVoidKeyword": + case "TSThisType": + case "TSLiteralType": + break; + default: + return false; + } + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isNumberLiteral(node, opts) { + (0, _deprecationWarning.default)("isNumberLiteral", "isNumericLiteral"); + if (!node) return false; + if (node.type !== "NumberLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isRegexLiteral(node, opts) { + (0, _deprecationWarning.default)("isRegexLiteral", "isRegExpLiteral"); + if (!node) return false; + if (node.type !== "RegexLiteral") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isRestProperty(node, opts) { + (0, _deprecationWarning.default)("isRestProperty", "isRestElement"); + if (!node) return false; + if (node.type !== "RestProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isSpreadProperty(node, opts) { + (0, _deprecationWarning.default)("isSpreadProperty", "isSpreadElement"); + if (!node) return false; + if (node.type !== "SpreadProperty") return false; + return opts == null || (0, _shallowEqual.default)(node, opts); + } + function isModuleDeclaration(node, opts) { + (0, _deprecationWarning.default)("isModuleDeclaration", "isImportOrExportDeclaration"); + return isImportOrExportDeclaration(node, opts); + } + + + return generated$3; +} + +var hasRequiredMatchesPattern; + +function requireMatchesPattern () { + if (hasRequiredMatchesPattern) return matchesPattern; + hasRequiredMatchesPattern = 1; + + Object.defineProperty(matchesPattern, "__esModule", { + value: true + }); + matchesPattern.default = matchesPattern$1; + var _index = requireGenerated$3(); + function matchesPattern$1(member, match, allowPartial) { + if (!(0, _index.isMemberExpression)(member)) return false; + const parts = Array.isArray(match) ? match : match.split("."); + const nodes = []; + let node; + for (node = member; (0, _index.isMemberExpression)(node); node = node.object) { + nodes.push(node.property); + } + nodes.push(node); + if (nodes.length < parts.length) return false; + if (!allowPartial && nodes.length > parts.length) return false; + for (let i = 0, j = nodes.length - 1; i < parts.length; i++, j--) { + const node = nodes[j]; + let value; + if ((0, _index.isIdentifier)(node)) { + value = node.name; + } else if ((0, _index.isStringLiteral)(node)) { + value = node.value; + } else if ((0, _index.isThisExpression)(node)) { + value = "this"; + } else { + return false; + } + if (parts[i] !== value) return false; + } + return true; + } + + + return matchesPattern; +} + +var hasRequiredBuildMatchMemberExpression; + +function requireBuildMatchMemberExpression () { + if (hasRequiredBuildMatchMemberExpression) return buildMatchMemberExpression; + hasRequiredBuildMatchMemberExpression = 1; + + Object.defineProperty(buildMatchMemberExpression, "__esModule", { + value: true + }); + buildMatchMemberExpression.default = buildMatchMemberExpression$1; + var _matchesPattern = requireMatchesPattern(); + function buildMatchMemberExpression$1(match, allowPartial) { + const parts = match.split("."); + return member => (0, _matchesPattern.default)(member, parts, allowPartial); + } + + + return buildMatchMemberExpression; +} + +var hasRequiredIsReactComponent; + +function requireIsReactComponent () { + if (hasRequiredIsReactComponent) return isReactComponent; + hasRequiredIsReactComponent = 1; + + Object.defineProperty(isReactComponent, "__esModule", { + value: true + }); + isReactComponent.default = void 0; + var _buildMatchMemberExpression = requireBuildMatchMemberExpression(); + const isReactComponent$1 = (0, _buildMatchMemberExpression.default)("React.Component"); + isReactComponent.default = isReactComponent$1; + + + return isReactComponent; +} + +var isCompatTag = {}; + +var hasRequiredIsCompatTag; + +function requireIsCompatTag () { + if (hasRequiredIsCompatTag) return isCompatTag; + hasRequiredIsCompatTag = 1; + + Object.defineProperty(isCompatTag, "__esModule", { + value: true + }); + isCompatTag.default = isCompatTag$1; + function isCompatTag$1(tagName) { + return !!tagName && /^[a-z]/.test(tagName); + } + + + return isCompatTag; +} + +var buildChildren = {}; + +var cleanJSXElementLiteralChild = {}; + +var generated$2 = {}; + +var validate$1 = {}; + +var definitions = {}; + +var core = {}; + +var is = {}; + +var isType = {}; + +var hasRequiredIsType; + +function requireIsType () { + if (hasRequiredIsType) return isType; + hasRequiredIsType = 1; + + Object.defineProperty(isType, "__esModule", { + value: true + }); + isType.default = isType$1; + var _index = requireDefinitions(); + function isType$1(nodeType, targetType) { + if (nodeType === targetType) return true; + if (nodeType == null) return false; + if (_index.ALIAS_KEYS[targetType]) return false; + const aliases = _index.FLIPPED_ALIAS_KEYS[targetType]; + if (aliases) { + if (aliases[0] === nodeType) return true; + for (const alias of aliases) { + if (nodeType === alias) return true; + } + } + return false; + } + + + return isType; +} + +var isPlaceholderType = {}; + +var hasRequiredIsPlaceholderType; + +function requireIsPlaceholderType () { + if (hasRequiredIsPlaceholderType) return isPlaceholderType; + hasRequiredIsPlaceholderType = 1; + + Object.defineProperty(isPlaceholderType, "__esModule", { + value: true + }); + isPlaceholderType.default = isPlaceholderType$1; + var _index = requireDefinitions(); + function isPlaceholderType$1(placeholderType, targetType) { + if (placeholderType === targetType) return true; + const aliases = _index.PLACEHOLDERS_ALIAS[placeholderType]; + if (aliases) { + for (const alias of aliases) { + if (targetType === alias) return true; + } + } + return false; + } + + + return isPlaceholderType; +} + +var hasRequiredIs; + +function requireIs () { + if (hasRequiredIs) return is; + hasRequiredIs = 1; + + Object.defineProperty(is, "__esModule", { + value: true + }); + is.default = is$1; + var _shallowEqual = requireShallowEqual(); + var _isType = requireIsType(); + var _isPlaceholderType = requireIsPlaceholderType(); + var _index = requireDefinitions(); + function is$1(type, node, opts) { + if (!node) return false; + const matches = (0, _isType.default)(node.type, type); + if (!matches) { + if (!opts && node.type === "Placeholder" && type in _index.FLIPPED_ALIAS_KEYS) { + return (0, _isPlaceholderType.default)(node.expectedNode, type); + } + return false; + } + if (opts === undefined) { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + + return is; +} + +var isValidIdentifier = {}; + +var lib$2 = {}; + +var identifier = {}; + +var hasRequiredIdentifier; + +function requireIdentifier () { + if (hasRequiredIdentifier) return identifier; + hasRequiredIdentifier = 1; + + Object.defineProperty(identifier, "__esModule", { + value: true + }); + identifier.isIdentifierChar = isIdentifierChar; + identifier.isIdentifierName = isIdentifierName; + identifier.isIdentifierStart = isIdentifierStart; + let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + let nonASCIIidentifierChars = "\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65"; + const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 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, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; + const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + function isInAstralSet(code, set) { + let pos = 0x10000; + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + return false; + } + function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes); + } + function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); + } + function isIdentifierName(name) { + let isFirst = true; + for (let i = 0; i < name.length; i++) { + let cp = name.charCodeAt(i); + if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) { + const trail = name.charCodeAt(++i); + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + if (isFirst) { + isFirst = false; + if (!isIdentifierStart(cp)) { + return false; + } + } else if (!isIdentifierChar(cp)) { + return false; + } + } + return !isFirst; + } + + + return identifier; +} + +var keyword = {}; + +var hasRequiredKeyword; + +function requireKeyword () { + if (hasRequiredKeyword) return keyword; + hasRequiredKeyword = 1; + + Object.defineProperty(keyword, "__esModule", { + value: true + }); + keyword.isKeyword = isKeyword; + keyword.isReservedWord = isReservedWord; + keyword.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; + keyword.isStrictBindReservedWord = isStrictBindReservedWord; + keyword.isStrictReservedWord = isStrictReservedWord; + const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] + }; + const keywords = new Set(reservedWords.keyword); + const reservedWordsStrictSet = new Set(reservedWords.strict); + const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); + function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; + } + function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); + } + function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); + } + function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); + } + function isKeyword(word) { + return keywords.has(word); + } + + + return keyword; +} + +var hasRequiredLib$3; + +function requireLib$3 () { + if (hasRequiredLib$3) return lib$2; + hasRequiredLib$3 = 1; + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "isIdentifierChar", { + enumerable: true, + get: function () { + return _identifier.isIdentifierChar; + } + }); + Object.defineProperty(exports, "isIdentifierName", { + enumerable: true, + get: function () { + return _identifier.isIdentifierName; + } + }); + Object.defineProperty(exports, "isIdentifierStart", { + enumerable: true, + get: function () { + return _identifier.isIdentifierStart; + } + }); + Object.defineProperty(exports, "isKeyword", { + enumerable: true, + get: function () { + return _keyword.isKeyword; + } + }); + Object.defineProperty(exports, "isReservedWord", { + enumerable: true, + get: function () { + return _keyword.isReservedWord; + } + }); + Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindOnlyReservedWord; + } + }); + Object.defineProperty(exports, "isStrictBindReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindReservedWord; + } + }); + Object.defineProperty(exports, "isStrictReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictReservedWord; + } + }); + var _identifier = requireIdentifier(); + var _keyword = requireKeyword(); + + +} (lib$2)); + return lib$2; +} + +var hasRequiredIsValidIdentifier; + +function requireIsValidIdentifier () { + if (hasRequiredIsValidIdentifier) return isValidIdentifier; + hasRequiredIsValidIdentifier = 1; + + Object.defineProperty(isValidIdentifier, "__esModule", { + value: true + }); + isValidIdentifier.default = isValidIdentifier$1; + var _helperValidatorIdentifier = requireLib$3(); + function isValidIdentifier$1(name, reserved = true) { + if (typeof name !== "string") return false; + if (reserved) { + if ((0, _helperValidatorIdentifier.isKeyword)(name) || (0, _helperValidatorIdentifier.isStrictReservedWord)(name, true)) { + return false; + } + } + return (0, _helperValidatorIdentifier.isIdentifierName)(name); + } + + + return isValidIdentifier; +} + +var lib$1 = {}; + +var hasRequiredLib$2; + +function requireLib$2 () { + if (hasRequiredLib$2) return lib$1; + hasRequiredLib$2 = 1; + + Object.defineProperty(lib$1, "__esModule", { + value: true + }); + lib$1.readCodePoint = readCodePoint; + lib$1.readInt = readInt; + lib$1.readStringContents = readStringContents; + var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; + }; + const forbiddenNumericSeparatorSiblings = { + decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]), + hex: new Set([46, 88, 95, 120]) + }; + const isAllowedNumericSeparatorSibling = { + bin: ch => ch === 48 || ch === 49, + oct: ch => ch >= 48 && ch <= 55, + dec: ch => ch >= 48 && ch <= 57, + hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 + }; + function readStringContents(type, input, pos, lineStart, curLine, errors) { + const initialPos = pos; + const initialLineStart = lineStart; + const initialCurLine = curLine; + let out = ""; + let firstInvalidLoc = null; + let chunkStart = pos; + const { + length + } = input; + for (;;) { + if (pos >= length) { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + out += input.slice(chunkStart, pos); + break; + } + const ch = input.charCodeAt(pos); + if (isStringEnd(type, ch, input, pos)) { + out += input.slice(chunkStart, pos); + break; + } + if (ch === 92) { + out += input.slice(chunkStart, pos); + const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors); + if (res.ch === null && !firstInvalidLoc) { + firstInvalidLoc = { + pos, + lineStart, + curLine + }; + } else { + out += res.ch; + } + ({ + pos, + lineStart, + curLine + } = res); + chunkStart = pos; + } else if (ch === 8232 || ch === 8233) { + ++pos; + ++curLine; + lineStart = pos; + } else if (ch === 10 || ch === 13) { + if (type === "template") { + out += input.slice(chunkStart, pos) + "\n"; + ++pos; + if (ch === 13 && input.charCodeAt(pos) === 10) { + ++pos; + } + ++curLine; + chunkStart = lineStart = pos; + } else { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + } + } else { + ++pos; + } + } + return { + pos, + str: out, + firstInvalidLoc, + lineStart, + curLine, + containsInvalid: !!firstInvalidLoc + }; + } + function isStringEnd(type, ch, input, pos) { + if (type === "template") { + return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; + } + return ch === (type === "double" ? 34 : 39); + } + function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { + const throwOnInvalid = !inTemplate; + pos++; + const res = ch => ({ + pos, + ch, + lineStart, + curLine + }); + const ch = input.charCodeAt(pos++); + switch (ch) { + case 110: + return res("\n"); + case 114: + return res("\r"); + case 120: + { + let code; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCharCode(code)); + } + case 117: + { + let code; + ({ + code, + pos + } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCodePoint(code)); + } + case 116: + return res("\t"); + case 98: + return res("\b"); + case 118: + return res("\u000b"); + case 102: + return res("\f"); + case 13: + if (input.charCodeAt(pos) === 10) { + ++pos; + } + case 10: + lineStart = pos; + ++curLine; + case 8232: + case 8233: + return res(""); + case 56: + case 57: + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(pos - 1, lineStart, curLine); + } + default: + if (ch >= 48 && ch <= 55) { + const startPos = pos - 1; + const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2)); + let octalStr = match[0]; + let octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + pos += octalStr.length - 1; + const next = input.charCodeAt(pos); + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(startPos, lineStart, curLine); + } + } + return res(String.fromCharCode(octal)); + } + return res(String.fromCharCode(ch)); + } + } + function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { + const initialPos = pos; + let n; + ({ + n, + pos + } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid)); + if (n === null) { + if (throwOnInvalid) { + errors.invalidEscapeSequence(initialPos, lineStart, curLine); + } else { + pos = initialPos - 1; + } + } + return { + code: n, + pos + }; + } + function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) { + const start = pos; + const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; + let invalid = false; + let total = 0; + for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { + const code = input.charCodeAt(pos); + let val; + if (code === 95 && allowNumSeparator !== "bail") { + const prev = input.charCodeAt(pos - 1); + const next = input.charCodeAt(pos + 1); + if (!allowNumSeparator) { + if (bailOnError) return { + n: null, + pos + }; + errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); + } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { + if (bailOnError) return { + n: null, + pos + }; + errors.unexpectedNumericSeparator(pos, lineStart, curLine); + } + ++pos; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + if (val <= 9 && bailOnError) { + return { + n: null, + pos + }; + } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { + val = 0; + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } + } + ++pos; + total = total * radix + val; + } + if (pos === start || len != null && pos - start !== len || invalid) { + return { + n: null, + pos + }; + } + return { + n: total, + pos + }; + } + function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { + const ch = input.charCodeAt(pos); + let code; + if (ch === 123) { + ++pos; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); + ++pos; + if (code !== null && code > 0x10ffff) { + if (throwOnInvalid) { + errors.invalidCodePoint(pos, lineStart, curLine); + } else { + return { + code: null, + pos + }; + } + } + } else { + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); + } + return { + code, + pos + }; + } + + + return lib$1; +} + +var constants = {}; + +var hasRequiredConstants; + +function requireConstants () { + if (hasRequiredConstants) return constants; + hasRequiredConstants = 1; + + Object.defineProperty(constants, "__esModule", { + value: true + }); + constants.UPDATE_OPERATORS = constants.UNARY_OPERATORS = constants.STRING_UNARY_OPERATORS = constants.STATEMENT_OR_BLOCK_KEYS = constants.NUMBER_UNARY_OPERATORS = constants.NUMBER_BINARY_OPERATORS = constants.NOT_LOCAL_BINDING = constants.LOGICAL_OPERATORS = constants.INHERIT_KEYS = constants.FOR_INIT_KEYS = constants.FLATTENABLE_KEYS = constants.EQUALITY_BINARY_OPERATORS = constants.COMPARISON_BINARY_OPERATORS = constants.COMMENT_KEYS = constants.BOOLEAN_UNARY_OPERATORS = constants.BOOLEAN_NUMBER_BINARY_OPERATORS = constants.BOOLEAN_BINARY_OPERATORS = constants.BLOCK_SCOPED_SYMBOL = constants.BINARY_OPERATORS = constants.ASSIGNMENT_OPERATORS = void 0; + constants.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; + constants.FLATTENABLE_KEYS = ["body", "expressions"]; + constants.FOR_INIT_KEYS = ["left", "init"]; + constants.COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; + const LOGICAL_OPERATORS = constants.LOGICAL_OPERATORS = ["||", "&&", "??"]; + constants.UPDATE_OPERATORS = ["++", "--"]; + const BOOLEAN_NUMBER_BINARY_OPERATORS = constants.BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; + const EQUALITY_BINARY_OPERATORS = constants.EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; + const COMPARISON_BINARY_OPERATORS = constants.COMPARISON_BINARY_OPERATORS = [...EQUALITY_BINARY_OPERATORS, "in", "instanceof"]; + const BOOLEAN_BINARY_OPERATORS = constants.BOOLEAN_BINARY_OPERATORS = [...COMPARISON_BINARY_OPERATORS, ...BOOLEAN_NUMBER_BINARY_OPERATORS]; + const NUMBER_BINARY_OPERATORS = constants.NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; + constants.BINARY_OPERATORS = ["+", ...NUMBER_BINARY_OPERATORS, ...BOOLEAN_BINARY_OPERATORS, "|>"]; + constants.ASSIGNMENT_OPERATORS = ["=", "+=", ...NUMBER_BINARY_OPERATORS.map(op => op + "="), ...LOGICAL_OPERATORS.map(op => op + "=")]; + const BOOLEAN_UNARY_OPERATORS = constants.BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; + const NUMBER_UNARY_OPERATORS = constants.NUMBER_UNARY_OPERATORS = ["+", "-", "~"]; + const STRING_UNARY_OPERATORS = constants.STRING_UNARY_OPERATORS = ["typeof"]; + constants.UNARY_OPERATORS = ["void", "throw", ...BOOLEAN_UNARY_OPERATORS, ...NUMBER_UNARY_OPERATORS, ...STRING_UNARY_OPERATORS]; + constants.INHERIT_KEYS = { + optional: ["typeAnnotation", "typeParameters", "returnType"], + force: ["start", "loc", "end"] + }; + constants.BLOCK_SCOPED_SYMBOL = Symbol.for("var used to be block scoped"); + constants.NOT_LOCAL_BINDING = Symbol.for("should not be considered a local binding"); + + + return constants; +} + +var utils = {}; + +var hasRequiredUtils; + +function requireUtils () { + if (hasRequiredUtils) return utils; + hasRequiredUtils = 1; + + Object.defineProperty(utils, "__esModule", { + value: true + }); + utils.VISITOR_KEYS = utils.NODE_PARENT_VALIDATIONS = utils.NODE_FIELDS = utils.FLIPPED_ALIAS_KEYS = utils.DEPRECATED_KEYS = utils.BUILDER_KEYS = utils.ALIAS_KEYS = void 0; + utils.arrayOf = arrayOf; + utils.arrayOfType = arrayOfType; + utils.assertEach = assertEach; + utils.assertNodeOrValueType = assertNodeOrValueType; + utils.assertNodeType = assertNodeType; + utils.assertOneOf = assertOneOf; + utils.assertOptionalChainStart = assertOptionalChainStart; + utils.assertShape = assertShape; + utils.assertValueType = assertValueType; + utils.chain = chain; + utils.default = defineType; + utils.defineAliasedType = defineAliasedType; + utils.validate = validate; + utils.validateArrayOfType = validateArrayOfType; + utils.validateOptional = validateOptional; + utils.validateOptionalType = validateOptionalType; + utils.validateType = validateType; + var _is = requireIs(); + var _validate = requireValidate(); + const VISITOR_KEYS = utils.VISITOR_KEYS = {}; + const ALIAS_KEYS = utils.ALIAS_KEYS = {}; + const FLIPPED_ALIAS_KEYS = utils.FLIPPED_ALIAS_KEYS = {}; + const NODE_FIELDS = utils.NODE_FIELDS = {}; + const BUILDER_KEYS = utils.BUILDER_KEYS = {}; + const DEPRECATED_KEYS = utils.DEPRECATED_KEYS = {}; + const NODE_PARENT_VALIDATIONS = utils.NODE_PARENT_VALIDATIONS = {}; + function getType(val) { + if (Array.isArray(val)) { + return "array"; + } else if (val === null) { + return "null"; + } else { + return typeof val; + } + } + function validate(validate) { + return { + validate + }; + } + function validateType(...typeNames) { + return validate(assertNodeType(...typeNames)); + } + function validateOptional(validate) { + return { + validate, + optional: true + }; + } + function validateOptionalType(...typeNames) { + return { + validate: assertNodeType(...typeNames), + optional: true + }; + } + function arrayOf(elementType) { + return chain(assertValueType("array"), assertEach(elementType)); + } + function arrayOfType(...typeNames) { + return arrayOf(assertNodeType(...typeNames)); + } + function validateArrayOfType(...typeNames) { + return validate(arrayOfType(...typeNames)); + } + function assertEach(callback) { + const childValidator = process.env.BABEL_TYPES_8_BREAKING ? _validate.validateChild : () => {}; + function validator(node, key, val) { + if (!Array.isArray(val)) return; + for (let i = 0; i < val.length; i++) { + const subkey = `${key}[${i}]`; + const v = val[i]; + callback(node, subkey, v); + childValidator(node, subkey, v); + } + } + validator.each = callback; + return validator; + } + function assertOneOf(...values) { + function validate(node, key, val) { + if (!values.includes(val)) { + throw new TypeError(`Property ${key} expected value to be one of ${JSON.stringify(values)} but got ${JSON.stringify(val)}`); + } + } + validate.oneOf = values; + return validate; + } + function assertNodeType(...types) { + function validate(node, key, val) { + for (const type of types) { + if ((0, _is.default)(type, val)) { + (0, _validate.validateChild)(node, key, val); + return; + } + } + throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val == null ? void 0 : val.type)}`); + } + validate.oneOfNodeTypes = types; + return validate; + } + function assertNodeOrValueType(...types) { + function validate(node, key, val) { + for (const type of types) { + if (getType(val) === type || (0, _is.default)(type, val)) { + (0, _validate.validateChild)(node, key, val); + return; + } + } + throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val == null ? void 0 : val.type)}`); + } + validate.oneOfNodeOrValueTypes = types; + return validate; + } + function assertValueType(type) { + function validate(node, key, val) { + const valid = getType(val) === type; + if (!valid) { + throw new TypeError(`Property ${key} expected type of ${type} but got ${getType(val)}`); + } + } + validate.type = type; + return validate; + } + function assertShape(shape) { + function validate(node, key, val) { + const errors = []; + for (const property of Object.keys(shape)) { + try { + (0, _validate.validateField)(node, property, val[property], shape[property]); + } catch (error) { + if (error instanceof TypeError) { + errors.push(error.message); + continue; + } + throw error; + } + } + if (errors.length) { + throw new TypeError(`Property ${key} of ${node.type} expected to have the following:\n${errors.join("\n")}`); + } + } + validate.shapeOf = shape; + return validate; + } + function assertOptionalChainStart() { + function validate(node) { + var _current; + let current = node; + while (node) { + const { + type + } = current; + if (type === "OptionalCallExpression") { + if (current.optional) return; + current = current.callee; + continue; + } + if (type === "OptionalMemberExpression") { + if (current.optional) return; + current = current.object; + continue; + } + break; + } + throw new TypeError(`Non-optional ${node.type} must chain from an optional OptionalMemberExpression or OptionalCallExpression. Found chain from ${(_current = current) == null ? void 0 : _current.type}`); + } + return validate; + } + function chain(...fns) { + function validate(...args) { + for (const fn of fns) { + fn(...args); + } + } + validate.chainOf = fns; + if (fns.length >= 2 && "type" in fns[0] && fns[0].type === "array" && !("each" in fns[1])) { + throw new Error(`An assertValueType("array") validator can only be followed by an assertEach(...) validator.`); + } + return validate; + } + const validTypeOpts = new Set(["aliases", "builder", "deprecatedAlias", "fields", "inherits", "visitor", "validate"]); + const validFieldKeys = new Set(["default", "optional", "deprecated", "validate"]); + const store = {}; + function defineAliasedType(...aliases) { + return (type, opts = {}) => { + let defined = opts.aliases; + if (!defined) { + var _store$opts$inherits$, _defined; + if (opts.inherits) defined = (_store$opts$inherits$ = store[opts.inherits].aliases) == null ? void 0 : _store$opts$inherits$.slice(); + (_defined = defined) != null ? _defined : defined = []; + opts.aliases = defined; + } + const additional = aliases.filter(a => !defined.includes(a)); + defined.unshift(...additional); + defineType(type, opts); + }; + } + function defineType(type, opts = {}) { + const inherits = opts.inherits && store[opts.inherits] || {}; + let fields = opts.fields; + if (!fields) { + fields = {}; + if (inherits.fields) { + const keys = Object.getOwnPropertyNames(inherits.fields); + for (const key of keys) { + const field = inherits.fields[key]; + const def = field.default; + if (Array.isArray(def) ? def.length > 0 : def && typeof def === "object") { + throw new Error("field defaults can only be primitives or empty arrays currently"); + } + fields[key] = { + default: Array.isArray(def) ? [] : def, + optional: field.optional, + deprecated: field.deprecated, + validate: field.validate + }; + } + } + } + const visitor = opts.visitor || inherits.visitor || []; + const aliases = opts.aliases || inherits.aliases || []; + const builder = opts.builder || inherits.builder || opts.visitor || []; + for (const k of Object.keys(opts)) { + if (!validTypeOpts.has(k)) { + throw new Error(`Unknown type option "${k}" on ${type}`); + } + } + if (opts.deprecatedAlias) { + DEPRECATED_KEYS[opts.deprecatedAlias] = type; + } + for (const key of visitor.concat(builder)) { + fields[key] = fields[key] || {}; + } + for (const key of Object.keys(fields)) { + const field = fields[key]; + if (field.default !== undefined && !builder.includes(key)) { + field.optional = true; + } + if (field.default === undefined) { + field.default = null; + } else if (!field.validate && field.default != null) { + field.validate = assertValueType(getType(field.default)); + } + for (const k of Object.keys(field)) { + if (!validFieldKeys.has(k)) { + throw new Error(`Unknown field key "${k}" on ${type}.${key}`); + } + } + } + VISITOR_KEYS[type] = opts.visitor = visitor; + BUILDER_KEYS[type] = opts.builder = builder; + NODE_FIELDS[type] = opts.fields = fields; + ALIAS_KEYS[type] = opts.aliases = aliases; + aliases.forEach(alias => { + FLIPPED_ALIAS_KEYS[alias] = FLIPPED_ALIAS_KEYS[alias] || []; + FLIPPED_ALIAS_KEYS[alias].push(type); + }); + if (opts.validate) { + NODE_PARENT_VALIDATIONS[type] = opts.validate; + } + store[type] = opts; + } + + + return utils; +} + +var hasRequiredCore; + +function requireCore () { + if (hasRequiredCore) return core; + hasRequiredCore = 1; + + Object.defineProperty(core, "__esModule", { + value: true + }); + core.patternLikeCommon = core.importAttributes = core.functionTypeAnnotationCommon = core.functionDeclarationCommon = core.functionCommon = core.classMethodOrPropertyCommon = core.classMethodOrDeclareMethodCommon = void 0; + var _is = requireIs(); + var _isValidIdentifier = requireIsValidIdentifier(); + var _helperValidatorIdentifier = requireLib$3(); + var _helperStringParser = requireLib$2(); + var _index = requireConstants(); + var _utils = requireUtils(); + const defineType = (0, _utils.defineAliasedType)("Standardized"); + defineType("ArrayExpression", { + fields: { + elements: { + validate: (0, _utils.arrayOf)((0, _utils.assertNodeOrValueType)("null", "Expression", "SpreadElement")), + default: !process.env.BABEL_TYPES_8_BREAKING ? [] : undefined + } + }, + visitor: ["elements"], + aliases: ["Expression"] + }); + defineType("AssignmentExpression", { + fields: { + operator: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertValueType)("string") : Object.assign(function () { + const identifier = (0, _utils.assertOneOf)(..._index.ASSIGNMENT_OPERATORS); + const pattern = (0, _utils.assertOneOf)("="); + return function (node, key, val) { + const validator = (0, _is.default)("Pattern", node.left) ? pattern : identifier; + validator(node, key, val); + }; + }(), { + type: "string" + }) + }, + left: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal", "OptionalMemberExpression") : (0, _utils.assertNodeType)("Identifier", "MemberExpression", "OptionalMemberExpression", "ArrayPattern", "ObjectPattern", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + builder: ["operator", "left", "right"], + visitor: ["left", "right"], + aliases: ["Expression"] + }); + defineType("BinaryExpression", { + builder: ["operator", "left", "right"], + fields: { + operator: { + validate: (0, _utils.assertOneOf)(..._index.BINARY_OPERATORS) + }, + left: { + validate: function () { + const expression = (0, _utils.assertNodeType)("Expression"); + const inOp = (0, _utils.assertNodeType)("Expression", "PrivateName"); + const validator = Object.assign(function (node, key, val) { + const validator = node.operator === "in" ? inOp : expression; + validator(node, key, val); + }, { + oneOfNodeTypes: ["Expression", "PrivateName"] + }); + return validator; + }() + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + visitor: ["left", "right"], + aliases: ["Binary", "Expression"] + }); + defineType("InterpreterDirective", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + defineType("Directive", { + visitor: ["value"], + fields: { + value: { + validate: (0, _utils.assertNodeType)("DirectiveLiteral") + } + } + }); + defineType("DirectiveLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + defineType("BlockStatement", { + builder: ["body", "directives"], + visitor: ["directives", "body"], + fields: { + directives: { + validate: (0, _utils.arrayOfType)("Directive"), + default: [] + }, + body: (0, _utils.validateArrayOfType)("Statement") + }, + aliases: ["Scopable", "BlockParent", "Block", "Statement"] + }); + defineType("BreakStatement", { + visitor: ["label"], + fields: { + label: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + } + }, + aliases: ["Statement", "Terminatorless", "CompletionStatement"] + }); + defineType("CallExpression", { + visitor: ["callee", "arguments", "typeParameters", "typeArguments"], + builder: ["callee", "arguments"], + aliases: ["Expression"], + fields: Object.assign({ + callee: { + validate: (0, _utils.assertNodeType)("Expression", "Super", "V8IntrinsicIdentifier") + }, + arguments: (0, _utils.validateArrayOfType)("Expression", "SpreadElement", "ArgumentPlaceholder") + }, !process.env.BABEL_TYPES_8_BREAKING ? { + optional: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + } : {}, { + typeArguments: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TSTypeParameterInstantiation"), + optional: true + } + }) + }); + defineType("CatchClause", { + visitor: ["param", "body"], + fields: { + param: { + validate: (0, _utils.assertNodeType)("Identifier", "ArrayPattern", "ObjectPattern"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }, + aliases: ["Scopable", "BlockParent"] + }); + defineType("ConditionalExpression", { + visitor: ["test", "consequent", "alternate"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + consequent: { + validate: (0, _utils.assertNodeType)("Expression") + }, + alternate: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + aliases: ["Expression", "Conditional"] + }); + defineType("ContinueStatement", { + visitor: ["label"], + fields: { + label: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + } + }, + aliases: ["Statement", "Terminatorless", "CompletionStatement"] + }); + defineType("DebuggerStatement", { + aliases: ["Statement"] + }); + defineType("DoWhileStatement", { + builder: ["test", "body"], + visitor: ["body", "test"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + }, + aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"] + }); + defineType("EmptyStatement", { + aliases: ["Statement"] + }); + defineType("ExpressionStatement", { + visitor: ["expression"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + aliases: ["Statement", "ExpressionWrapper"] + }); + defineType("File", { + builder: ["program", "comments", "tokens"], + visitor: ["program"], + fields: { + program: { + validate: (0, _utils.assertNodeType)("Program") + }, + comments: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? Object.assign(() => {}, { + each: { + oneOfNodeTypes: ["CommentBlock", "CommentLine"] + } + }) : (0, _utils.assertEach)((0, _utils.assertNodeType)("CommentBlock", "CommentLine")), + optional: true + }, + tokens: { + validate: (0, _utils.assertEach)(Object.assign(() => {}, { + type: "any" + })), + optional: true + } + } + }); + defineType("ForInStatement", { + visitor: ["left", "right", "body"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], + fields: { + left: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("VariableDeclaration", "LVal") : (0, _utils.assertNodeType)("VariableDeclaration", "Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + defineType("ForStatement", { + visitor: ["init", "test", "update", "body"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"], + fields: { + init: { + validate: (0, _utils.assertNodeType)("VariableDeclaration", "Expression"), + optional: true + }, + test: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + update: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + const functionCommon = () => ({ + params: (0, _utils.validateArrayOfType)("Identifier", "Pattern", "RestElement"), + generator: { + default: false + }, + async: { + default: false + } + }); + core.functionCommon = functionCommon; + const functionTypeAnnotationCommon = () => ({ + returnType: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), + optional: true + } + }); + core.functionTypeAnnotationCommon = functionTypeAnnotationCommon; + const functionDeclarationCommon = () => Object.assign({}, functionCommon(), { + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + id: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + } + }); + core.functionDeclarationCommon = functionDeclarationCommon; + defineType("FunctionDeclaration", { + builder: ["id", "params", "body", "generator", "async"], + visitor: ["id", "typeParameters", "params", "returnType", "body"], + fields: Object.assign({}, functionDeclarationCommon(), functionTypeAnnotationCommon(), { + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + }, + predicate: { + validate: (0, _utils.assertNodeType)("DeclaredPredicate", "InferredPredicate"), + optional: true + } + }), + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"], + validate: !process.env.BABEL_TYPES_8_BREAKING ? undefined : function () { + const identifier = (0, _utils.assertNodeType)("Identifier"); + return function (parent, key, node) { + if (!(0, _is.default)("ExportDefaultDeclaration", parent)) { + identifier(node, "id", node.id); + } + }; + }() + }); + defineType("FunctionExpression", { + inherits: "FunctionDeclaration", + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], + fields: Object.assign({}, functionCommon(), functionTypeAnnotationCommon(), { + id: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + }, + predicate: { + validate: (0, _utils.assertNodeType)("DeclaredPredicate", "InferredPredicate"), + optional: true + } + }) + }); + const patternLikeCommon = () => ({ + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + optional: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + } + }); + core.patternLikeCommon = patternLikeCommon; + defineType("Identifier", { + builder: ["name"], + visitor: ["typeAnnotation", "decorators"], + aliases: ["Expression", "PatternLike", "LVal", "TSEntityName"], + fields: Object.assign({}, patternLikeCommon(), { + name: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertValueType)("string"), Object.assign(function (node, key, val) { + if (!(0, _isValidIdentifier.default)(val, false)) { + throw new TypeError(`"${val}" is not a valid identifier name`); + } + }, { + type: "string" + })) : (0, _utils.assertValueType)("string") + } + }), + validate: process.env.BABEL_TYPES_8_BREAKING ? function (parent, key, node) { + const match = /\.(\w+)$/.exec(key); + if (!match) return; + const [, parentKey] = match; + const nonComp = { + computed: false + }; + if (parentKey === "property") { + if ((0, _is.default)("MemberExpression", parent, nonComp)) return; + if ((0, _is.default)("OptionalMemberExpression", parent, nonComp)) return; + } else if (parentKey === "key") { + if ((0, _is.default)("Property", parent, nonComp)) return; + if ((0, _is.default)("Method", parent, nonComp)) return; + } else if (parentKey === "exported") { + if ((0, _is.default)("ExportSpecifier", parent)) return; + } else if (parentKey === "imported") { + if ((0, _is.default)("ImportSpecifier", parent, { + imported: node + })) return; + } else if (parentKey === "meta") { + if ((0, _is.default)("MetaProperty", parent, { + meta: node + })) return; + } + if (((0, _helperValidatorIdentifier.isKeyword)(node.name) || (0, _helperValidatorIdentifier.isReservedWord)(node.name, false)) && node.name !== "this") { + throw new TypeError(`"${node.name}" is not a valid identifier`); + } + } : undefined + }); + defineType("IfStatement", { + visitor: ["test", "consequent", "alternate"], + aliases: ["Statement", "Conditional"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + consequent: { + validate: (0, _utils.assertNodeType)("Statement") + }, + alternate: { + optional: true, + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + defineType("LabeledStatement", { + visitor: ["label", "body"], + aliases: ["Statement"], + fields: { + label: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + defineType("StringLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + defineType("NumericLiteral", { + builder: ["value"], + deprecatedAlias: "NumberLiteral", + fields: { + value: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("number"), Object.assign(function (node, key, val) { + }, { + type: "number" + })) + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + defineType("NullLiteral", { + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + defineType("BooleanLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("boolean") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + defineType("RegExpLiteral", { + builder: ["pattern", "flags"], + deprecatedAlias: "RegexLiteral", + aliases: ["Expression", "Pureish", "Literal"], + fields: { + pattern: { + validate: (0, _utils.assertValueType)("string") + }, + flags: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertValueType)("string"), Object.assign(function (node, key, val) { + const invalid = /[^gimsuy]/.exec(val); + if (invalid) { + throw new TypeError(`"${invalid[0]}" is not a valid RegExp flag`); + } + }, { + type: "string" + })) : (0, _utils.assertValueType)("string"), + default: "" + } + } + }); + defineType("LogicalExpression", { + builder: ["operator", "left", "right"], + visitor: ["left", "right"], + aliases: ["Binary", "Expression"], + fields: { + operator: { + validate: (0, _utils.assertOneOf)(..._index.LOGICAL_OPERATORS) + }, + left: { + validate: (0, _utils.assertNodeType)("Expression") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("MemberExpression", { + builder: ["object", "property", "computed", ...(!process.env.BABEL_TYPES_8_BREAKING ? ["optional"] : [])], + visitor: ["object", "property"], + aliases: ["Expression", "LVal"], + fields: Object.assign({ + object: { + validate: (0, _utils.assertNodeType)("Expression", "Super") + }, + property: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier", "PrivateName"); + const computed = (0, _utils.assertNodeType)("Expression"); + const validator = function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + validator.oneOfNodeTypes = ["Expression", "Identifier", "PrivateName"]; + return validator; + }() + }, + computed: { + default: false + } + }, !process.env.BABEL_TYPES_8_BREAKING ? { + optional: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + } : {}) + }); + defineType("NewExpression", { + inherits: "CallExpression" + }); + defineType("Program", { + visitor: ["directives", "body"], + builder: ["body", "directives", "sourceType", "interpreter"], + fields: { + sourceType: { + validate: (0, _utils.assertOneOf)("script", "module"), + default: "script" + }, + interpreter: { + validate: (0, _utils.assertNodeType)("InterpreterDirective"), + default: null, + optional: true + }, + directives: { + validate: (0, _utils.arrayOfType)("Directive"), + default: [] + }, + body: (0, _utils.validateArrayOfType)("Statement") + }, + aliases: ["Scopable", "BlockParent", "Block"] + }); + defineType("ObjectExpression", { + visitor: ["properties"], + aliases: ["Expression"], + fields: { + properties: (0, _utils.validateArrayOfType)("ObjectMethod", "ObjectProperty", "SpreadElement") + } + }); + defineType("ObjectMethod", { + builder: ["kind", "key", "params", "body", "computed", "generator", "async"], + visitor: ["decorators", "key", "typeParameters", "params", "returnType", "body"], + fields: Object.assign({}, functionCommon(), functionTypeAnnotationCommon(), { + kind: Object.assign({ + validate: (0, _utils.assertOneOf)("method", "get", "set") + }, !process.env.BABEL_TYPES_8_BREAKING ? { + default: "method" + } : {}), + computed: { + default: false + }, + key: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral"); + const computed = (0, _utils.assertNodeType)("Expression"); + const validator = function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + validator.oneOfNodeTypes = ["Expression", "Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral"]; + return validator; + }() + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }), + aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"] + }); + defineType("ObjectProperty", { + builder: ["key", "value", "computed", "shorthand", ...(!process.env.BABEL_TYPES_8_BREAKING ? ["decorators"] : [])], + fields: { + computed: { + default: false + }, + key: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "DecimalLiteral", "PrivateName"); + const computed = (0, _utils.assertNodeType)("Expression"); + const validator = Object.assign(function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }, { + oneOfNodeTypes: ["Expression", "Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "DecimalLiteral", "PrivateName"] + }); + return validator; + }() + }, + value: { + validate: (0, _utils.assertNodeType)("Expression", "PatternLike") + }, + shorthand: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertValueType)("boolean"), Object.assign(function (node, key, shorthand) { + if (!shorthand) return; + if (node.computed) { + throw new TypeError("Property shorthand of ObjectProperty cannot be true if computed is true"); + } + if (!(0, _is.default)("Identifier", node.key)) { + throw new TypeError("Property shorthand of ObjectProperty cannot be true if key is not an Identifier"); + } + }, { + type: "boolean" + })) : (0, _utils.assertValueType)("boolean"), + default: false + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + } + }, + visitor: ["key", "value", "decorators"], + aliases: ["UserWhitespacable", "Property", "ObjectMember"], + validate: !process.env.BABEL_TYPES_8_BREAKING ? undefined : function () { + const pattern = (0, _utils.assertNodeType)("Identifier", "Pattern", "TSAsExpression", "TSSatisfiesExpression", "TSNonNullExpression", "TSTypeAssertion"); + const expression = (0, _utils.assertNodeType)("Expression"); + return function (parent, key, node) { + const validator = (0, _is.default)("ObjectPattern", parent) ? pattern : expression; + validator(node, "value", node.value); + }; + }() + }); + defineType("RestElement", { + visitor: ["argument", "typeAnnotation"], + builder: ["argument"], + aliases: ["LVal", "PatternLike"], + deprecatedAlias: "RestProperty", + fields: Object.assign({}, patternLikeCommon(), { + argument: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal") : (0, _utils.assertNodeType)("Identifier", "ArrayPattern", "ObjectPattern", "MemberExpression", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression") + } + }), + validate: process.env.BABEL_TYPES_8_BREAKING ? function (parent, key) { + const match = /(\w+)\[(\d+)\]/.exec(key); + if (!match) throw new Error("Internal Babel error: malformed key."); + const [, listKey, index] = match; + if (parent[listKey].length > +index + 1) { + throw new TypeError(`RestElement must be last element of ${listKey}`); + } + } : undefined + }); + defineType("ReturnStatement", { + visitor: ["argument"], + aliases: ["Statement", "Terminatorless", "CompletionStatement"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + } + } + }); + defineType("SequenceExpression", { + visitor: ["expressions"], + fields: { + expressions: (0, _utils.validateArrayOfType)("Expression") + }, + aliases: ["Expression"] + }); + defineType("ParenthesizedExpression", { + visitor: ["expression"], + aliases: ["Expression", "ExpressionWrapper"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("SwitchCase", { + visitor: ["test", "consequent"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + consequent: (0, _utils.validateArrayOfType)("Statement") + } + }); + defineType("SwitchStatement", { + visitor: ["discriminant", "cases"], + aliases: ["Statement", "BlockParent", "Scopable"], + fields: { + discriminant: { + validate: (0, _utils.assertNodeType)("Expression") + }, + cases: (0, _utils.validateArrayOfType)("SwitchCase") + } + }); + defineType("ThisExpression", { + aliases: ["Expression"] + }); + defineType("ThrowStatement", { + visitor: ["argument"], + aliases: ["Statement", "Terminatorless", "CompletionStatement"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("TryStatement", { + visitor: ["block", "handler", "finalizer"], + aliases: ["Statement"], + fields: { + block: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertNodeType)("BlockStatement"), Object.assign(function (node) { + if (!node.handler && !node.finalizer) { + throw new TypeError("TryStatement expects either a handler or finalizer, or both"); + } + }, { + oneOfNodeTypes: ["BlockStatement"] + })) : (0, _utils.assertNodeType)("BlockStatement") + }, + handler: { + optional: true, + validate: (0, _utils.assertNodeType)("CatchClause") + }, + finalizer: { + optional: true, + validate: (0, _utils.assertNodeType)("BlockStatement") + } + } + }); + defineType("UnaryExpression", { + builder: ["operator", "argument", "prefix"], + fields: { + prefix: { + default: true + }, + argument: { + validate: (0, _utils.assertNodeType)("Expression") + }, + operator: { + validate: (0, _utils.assertOneOf)(..._index.UNARY_OPERATORS) + } + }, + visitor: ["argument"], + aliases: ["UnaryLike", "Expression"] + }); + defineType("UpdateExpression", { + builder: ["operator", "argument", "prefix"], + fields: { + prefix: { + default: false + }, + argument: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("Expression") : (0, _utils.assertNodeType)("Identifier", "MemberExpression") + }, + operator: { + validate: (0, _utils.assertOneOf)(..._index.UPDATE_OPERATORS) + } + }, + visitor: ["argument"], + aliases: ["Expression"] + }); + defineType("VariableDeclaration", { + builder: ["kind", "declarations"], + visitor: ["declarations"], + aliases: ["Statement", "Declaration"], + fields: { + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + kind: { + validate: (0, _utils.assertOneOf)("var", "let", "const", "using", "await using") + }, + declarations: (0, _utils.validateArrayOfType)("VariableDeclarator") + }, + validate: process.env.BABEL_TYPES_8_BREAKING ? (() => { + const withoutInit = (0, _utils.assertNodeType)("Identifier"); + return function (parent, key, node) { + if ((0, _is.default)("ForXStatement", parent, { + left: node + })) { + if (node.declarations.length !== 1) { + throw new TypeError(`Exactly one VariableDeclarator is required in the VariableDeclaration of a ${parent.type}`); + } + } else { + node.declarations.forEach(decl => { + if (!decl.init) withoutInit(decl, "id", decl.id); + }); + } + }; + })() : undefined + }); + defineType("VariableDeclarator", { + visitor: ["id", "init"], + fields: { + id: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal") : (0, _utils.assertNodeType)("Identifier", "ArrayPattern", "ObjectPattern") + }, + definite: { + optional: true, + validate: (0, _utils.assertValueType)("boolean") + }, + init: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("WhileStatement", { + visitor: ["test", "body"], + aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + defineType("WithStatement", { + visitor: ["object", "body"], + aliases: ["Statement"], + fields: { + object: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + defineType("AssignmentPattern", { + visitor: ["left", "right", "decorators"], + builder: ["left", "right"], + aliases: ["Pattern", "PatternLike", "LVal"], + fields: Object.assign({}, patternLikeCommon(), { + left: { + validate: (0, _utils.assertNodeType)("Identifier", "ObjectPattern", "ArrayPattern", "MemberExpression", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + } + }) + }); + defineType("ArrayPattern", { + visitor: ["elements", "typeAnnotation"], + builder: ["elements"], + aliases: ["Pattern", "PatternLike", "LVal"], + fields: Object.assign({}, patternLikeCommon(), { + elements: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeOrValueType)("null", "PatternLike", "LVal"))) + } + }) + }); + defineType("ArrowFunctionExpression", { + builder: ["params", "body", "async"], + visitor: ["typeParameters", "params", "returnType", "body"], + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], + fields: Object.assign({}, functionCommon(), functionTypeAnnotationCommon(), { + expression: { + validate: (0, _utils.assertValueType)("boolean") + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement", "Expression") + }, + predicate: { + validate: (0, _utils.assertNodeType)("DeclaredPredicate", "InferredPredicate"), + optional: true + } + }) + }); + defineType("ClassBody", { + visitor: ["body"], + fields: { + body: (0, _utils.validateArrayOfType)("ClassMethod", "ClassPrivateMethod", "ClassProperty", "ClassPrivateProperty", "ClassAccessorProperty", "TSDeclareMethod", "TSIndexSignature", "StaticBlock") + } + }); + defineType("ClassExpression", { + builder: ["id", "superClass", "body", "decorators"], + visitor: ["decorators", "id", "typeParameters", "superClass", "superTypeParameters", "mixins", "implements", "body"], + aliases: ["Scopable", "Class", "Expression"], + fields: { + id: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("ClassBody") + }, + superClass: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + }, + superTypeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + }, + implements: { + validate: (0, _utils.arrayOfType)("TSExpressionWithTypeArguments", "ClassImplements"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + mixins: { + validate: (0, _utils.assertNodeType)("InterfaceExtends"), + optional: true + } + } + }); + defineType("ClassDeclaration", { + inherits: "ClassExpression", + aliases: ["Scopable", "Class", "Statement", "Declaration"], + fields: { + id: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("ClassBody") + }, + superClass: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + }, + superTypeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + }, + implements: { + validate: (0, _utils.arrayOfType)("TSExpressionWithTypeArguments", "ClassImplements"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + mixins: { + validate: (0, _utils.assertNodeType)("InterfaceExtends"), + optional: true + }, + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + abstract: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + }, + validate: !process.env.BABEL_TYPES_8_BREAKING ? undefined : function () { + const identifier = (0, _utils.assertNodeType)("Identifier"); + return function (parent, key, node) { + if (!(0, _is.default)("ExportDefaultDeclaration", parent)) { + identifier(node, "id", node.id); + } + }; + }() + }); + const importAttributes = core.importAttributes = { + attributes: { + optional: true, + validate: (0, _utils.arrayOfType)("ImportAttribute") + }, + assertions: { + deprecated: true, + optional: true, + validate: (0, _utils.arrayOfType)("ImportAttribute") + } + }; + defineType("ExportAllDeclaration", { + builder: ["source"], + visitor: ["source", "attributes", "assertions"], + aliases: ["Statement", "Declaration", "ImportOrExportDeclaration", "ExportDeclaration"], + fields: Object.assign({ + source: { + validate: (0, _utils.assertNodeType)("StringLiteral") + }, + exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("type", "value")) + }, importAttributes) + }); + defineType("ExportDefaultDeclaration", { + visitor: ["declaration"], + aliases: ["Statement", "Declaration", "ImportOrExportDeclaration", "ExportDeclaration"], + fields: { + declaration: (0, _utils.validateType)("TSDeclareFunction", "FunctionDeclaration", "ClassDeclaration", "Expression"), + exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("value")) + } + }); + defineType("ExportNamedDeclaration", { + builder: ["declaration", "specifiers", "source"], + visitor: process.env ? ["declaration", "specifiers", "source", "attributes"] : ["declaration", "specifiers", "source", "attributes", "assertions"], + aliases: ["Statement", "Declaration", "ImportOrExportDeclaration", "ExportDeclaration"], + fields: Object.assign({ + declaration: { + optional: true, + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertNodeType)("Declaration"), Object.assign(function (node, key, val) { + if (val && node.specifiers.length) { + throw new TypeError("Only declaration or specifiers is allowed on ExportNamedDeclaration"); + } + if (val && node.source) { + throw new TypeError("Cannot export a declaration from a source"); + } + }, { + oneOfNodeTypes: ["Declaration"] + })) : (0, _utils.assertNodeType)("Declaration") + } + }, importAttributes, { + specifiers: { + default: [], + validate: (0, _utils.arrayOf)(function () { + const sourced = (0, _utils.assertNodeType)("ExportSpecifier", "ExportDefaultSpecifier", "ExportNamespaceSpecifier"); + const sourceless = (0, _utils.assertNodeType)("ExportSpecifier"); + if (!process.env.BABEL_TYPES_8_BREAKING) return sourced; + return Object.assign(function (node, key, val) { + const validator = node.source ? sourced : sourceless; + validator(node, key, val); + }, { + oneOfNodeTypes: ["ExportSpecifier", "ExportDefaultSpecifier", "ExportNamespaceSpecifier"] + }); + }()) + }, + source: { + validate: (0, _utils.assertNodeType)("StringLiteral"), + optional: true + }, + exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("type", "value")) + }) + }); + defineType("ExportSpecifier", { + visitor: ["local", "exported"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + exported: { + validate: (0, _utils.assertNodeType)("Identifier", "StringLiteral") + }, + exportKind: { + validate: (0, _utils.assertOneOf)("type", "value"), + optional: true + } + } + }); + defineType("ForOfStatement", { + visitor: ["left", "right", "body"], + builder: ["left", "right", "body", "await"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], + fields: { + left: { + validate: function () { + if (!process.env.BABEL_TYPES_8_BREAKING) { + return (0, _utils.assertNodeType)("VariableDeclaration", "LVal"); + } + const declaration = (0, _utils.assertNodeType)("VariableDeclaration"); + const lval = (0, _utils.assertNodeType)("Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression"); + return Object.assign(function (node, key, val) { + if ((0, _is.default)("VariableDeclaration", val)) { + declaration(node, key, val); + } else { + lval(node, key, val); + } + }, { + oneOfNodeTypes: ["VariableDeclaration", "Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern", "TSAsExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSNonNullExpression"] + }); + }() + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + }, + await: { + default: false + } + } + }); + defineType("ImportDeclaration", { + builder: ["specifiers", "source"], + visitor: ["specifiers", "source", "attributes", "assertions"], + aliases: ["Statement", "Declaration", "ImportOrExportDeclaration"], + fields: Object.assign({}, importAttributes, { + module: { + optional: true, + validate: (0, _utils.assertValueType)("boolean") + }, + phase: { + default: null, + validate: (0, _utils.assertOneOf)("source", "defer") + }, + specifiers: (0, _utils.validateArrayOfType)("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier"), + source: { + validate: (0, _utils.assertNodeType)("StringLiteral") + }, + importKind: { + validate: (0, _utils.assertOneOf)("type", "typeof", "value"), + optional: true + } + }) + }); + defineType("ImportDefaultSpecifier", { + visitor: ["local"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + defineType("ImportNamespaceSpecifier", { + visitor: ["local"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + defineType("ImportSpecifier", { + visitor: ["imported", "local"], + builder: ["local", "imported"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + imported: { + validate: (0, _utils.assertNodeType)("Identifier", "StringLiteral") + }, + importKind: { + validate: (0, _utils.assertOneOf)("type", "typeof", "value"), + optional: true + } + } + }); + defineType("ImportExpression", { + visitor: ["source", "options"], + aliases: ["Expression"], + fields: { + phase: { + default: null, + validate: (0, _utils.assertOneOf)("source", "defer") + }, + source: { + validate: (0, _utils.assertNodeType)("Expression") + }, + options: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + } + } + }); + defineType("MetaProperty", { + visitor: ["meta", "property"], + aliases: ["Expression"], + fields: { + meta: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertNodeType)("Identifier"), Object.assign(function (node, key, val) { + let property; + switch (val.name) { + case "function": + property = "sent"; + break; + case "new": + property = "target"; + break; + case "import": + property = "meta"; + break; + } + if (!(0, _is.default)("Identifier", node.property, { + name: property + })) { + throw new TypeError("Unrecognised MetaProperty"); + } + }, { + oneOfNodeTypes: ["Identifier"] + })) : (0, _utils.assertNodeType)("Identifier") + }, + property: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + const classMethodOrPropertyCommon = () => ({ + abstract: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + accessibility: { + validate: (0, _utils.assertOneOf)("public", "private", "protected"), + optional: true + }, + static: { + default: false + }, + override: { + default: false + }, + computed: { + default: false + }, + optional: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + key: { + validate: (0, _utils.chain)(function () { + const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral"); + const computed = (0, _utils.assertNodeType)("Expression"); + return function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + }(), (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "Expression")) + } + }); + core.classMethodOrPropertyCommon = classMethodOrPropertyCommon; + const classMethodOrDeclareMethodCommon = () => Object.assign({}, functionCommon(), classMethodOrPropertyCommon(), { + params: (0, _utils.validateArrayOfType)("Identifier", "Pattern", "RestElement", "TSParameterProperty"), + kind: { + validate: (0, _utils.assertOneOf)("get", "set", "method", "constructor"), + default: "method" + }, + access: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("public", "private", "protected")), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + } + }); + core.classMethodOrDeclareMethodCommon = classMethodOrDeclareMethodCommon; + defineType("ClassMethod", { + aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], + builder: ["kind", "key", "params", "body", "computed", "static", "generator", "async"], + visitor: ["decorators", "key", "typeParameters", "params", "returnType", "body"], + fields: Object.assign({}, classMethodOrDeclareMethodCommon(), functionTypeAnnotationCommon(), { + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }) + }); + defineType("ObjectPattern", { + visitor: ["properties", "typeAnnotation", "decorators"], + builder: ["properties"], + aliases: ["Pattern", "PatternLike", "LVal"], + fields: Object.assign({}, patternLikeCommon(), { + properties: (0, _utils.validateArrayOfType)("RestElement", "ObjectProperty") + }) + }); + defineType("SpreadElement", { + visitor: ["argument"], + aliases: ["UnaryLike"], + deprecatedAlias: "SpreadProperty", + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("Super", { + aliases: ["Expression"] + }); + defineType("TaggedTemplateExpression", { + visitor: ["tag", "typeParameters", "quasi"], + builder: ["tag", "quasi"], + aliases: ["Expression"], + fields: { + tag: { + validate: (0, _utils.assertNodeType)("Expression") + }, + quasi: { + validate: (0, _utils.assertNodeType)("TemplateLiteral") + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + } + } + }); + defineType("TemplateElement", { + builder: ["value", "tail"], + fields: { + value: { + validate: (0, _utils.chain)((0, _utils.assertShape)({ + raw: { + validate: (0, _utils.assertValueType)("string") + }, + cooked: { + validate: (0, _utils.assertValueType)("string"), + optional: true + } + }), function templateElementCookedValidator(node) { + const raw = node.value.raw; + let unterminatedCalled = false; + const error = () => { + throw new Error("Internal @babel/types error."); + }; + const { + str, + firstInvalidLoc + } = (0, _helperStringParser.readStringContents)("template", raw, 0, 0, 0, { + unterminated() { + unterminatedCalled = true; + }, + strictNumericEscape: error, + invalidEscapeSequence: error, + numericSeparatorInEscapeSequence: error, + unexpectedNumericSeparator: error, + invalidDigit: error, + invalidCodePoint: error + }); + if (!unterminatedCalled) throw new Error("Invalid raw"); + node.value.cooked = firstInvalidLoc ? null : str; + }) + }, + tail: { + default: false + } + } + }); + defineType("TemplateLiteral", { + visitor: ["quasis", "expressions"], + aliases: ["Expression", "Literal"], + fields: { + quasis: (0, _utils.validateArrayOfType)("TemplateElement"), + expressions: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "TSType")), function (node, key, val) { + if (node.quasis.length !== val.length + 1) { + throw new TypeError(`Number of ${node.type} quasis should be exactly one more than the number of expressions.\nExpected ${val.length + 1} quasis but got ${node.quasis.length}`); + } + }) + } + } + }); + defineType("YieldExpression", { + builder: ["argument", "delegate"], + visitor: ["argument"], + aliases: ["Expression", "Terminatorless"], + fields: { + delegate: { + validate: process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.chain)((0, _utils.assertValueType)("boolean"), Object.assign(function (node, key, val) { + if (val && !node.argument) { + throw new TypeError("Property delegate of YieldExpression cannot be true if there is no argument"); + } + }, { + type: "boolean" + })) : (0, _utils.assertValueType)("boolean"), + default: false + }, + argument: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("AwaitExpression", { + builder: ["argument"], + visitor: ["argument"], + aliases: ["Expression", "Terminatorless"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("Import", { + aliases: ["Expression"] + }); + defineType("BigIntLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + defineType("ExportNamespaceSpecifier", { + visitor: ["exported"], + aliases: ["ModuleSpecifier"], + fields: { + exported: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + defineType("OptionalMemberExpression", { + builder: ["object", "property", "computed", "optional"], + visitor: ["object", "property"], + aliases: ["Expression"], + fields: { + object: { + validate: (0, _utils.assertNodeType)("Expression") + }, + property: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier"); + const computed = (0, _utils.assertNodeType)("Expression"); + const validator = Object.assign(function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }, { + oneOfNodeTypes: ["Expression", "Identifier"] + }); + return validator; + }() + }, + computed: { + default: false + }, + optional: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertValueType)("boolean") : (0, _utils.chain)((0, _utils.assertValueType)("boolean"), (0, _utils.assertOptionalChainStart)()) + } + } + }); + defineType("OptionalCallExpression", { + visitor: ["callee", "arguments", "typeParameters", "typeArguments"], + builder: ["callee", "arguments", "optional"], + aliases: ["Expression"], + fields: { + callee: { + validate: (0, _utils.assertNodeType)("Expression") + }, + arguments: (0, _utils.validateArrayOfType)("Expression", "SpreadElement", "ArgumentPlaceholder"), + optional: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertValueType)("boolean") : (0, _utils.chain)((0, _utils.assertValueType)("boolean"), (0, _utils.assertOptionalChainStart)()) + }, + typeArguments: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TSTypeParameterInstantiation"), + optional: true + } + } + }); + defineType("ClassProperty", { + visitor: ["decorators", "key", "typeAnnotation", "value"], + builder: ["key", "value", "typeAnnotation", "decorators", "computed", "static"], + aliases: ["Property"], + fields: Object.assign({}, classMethodOrPropertyCommon(), { + value: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + definite: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + readonly: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + variance: { + validate: (0, _utils.assertNodeType)("Variance"), + optional: true + } + }) + }); + defineType("ClassAccessorProperty", { + visitor: ["decorators", "key", "typeAnnotation", "value"], + builder: ["key", "value", "typeAnnotation", "decorators", "computed", "static"], + aliases: ["Property", "Accessor"], + fields: Object.assign({}, classMethodOrPropertyCommon(), { + key: { + validate: (0, _utils.chain)(function () { + const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "PrivateName"); + const computed = (0, _utils.assertNodeType)("Expression"); + return function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + }(), (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "Expression", "PrivateName")) + }, + value: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + definite: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + readonly: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + variance: { + validate: (0, _utils.assertNodeType)("Variance"), + optional: true + } + }) + }); + defineType("ClassPrivateProperty", { + visitor: ["decorators", "key", "typeAnnotation", "value"], + builder: ["key", "value", "decorators", "static"], + aliases: ["Property", "Private"], + fields: { + key: { + validate: (0, _utils.assertNodeType)("PrivateName") + }, + value: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + }, + static: { + validate: (0, _utils.assertValueType)("boolean"), + default: false + }, + readonly: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + definite: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + variance: { + validate: (0, _utils.assertNodeType)("Variance"), + optional: true + } + } + }); + defineType("ClassPrivateMethod", { + builder: ["kind", "key", "params", "body", "static"], + visitor: ["decorators", "key", "typeParameters", "params", "returnType", "body"], + aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method", "Private"], + fields: Object.assign({}, classMethodOrDeclareMethodCommon(), functionTypeAnnotationCommon(), { + kind: { + validate: (0, _utils.assertOneOf)("get", "set", "method"), + default: "method" + }, + key: { + validate: (0, _utils.assertNodeType)("PrivateName") + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }) + }); + defineType("PrivateName", { + visitor: ["id"], + aliases: ["Private"], + fields: { + id: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + defineType("StaticBlock", { + visitor: ["body"], + fields: { + body: (0, _utils.validateArrayOfType)("Statement") + }, + aliases: ["Scopable", "BlockParent", "FunctionParent"] + }); + + + return core; +} + +var flow = {}; + +var hasRequiredFlow; + +function requireFlow () { + if (hasRequiredFlow) return flow; + hasRequiredFlow = 1; + + var _core = requireCore(); + var _utils = requireUtils(); + const defineType = (0, _utils.defineAliasedType)("Flow"); + const defineInterfaceishType = name => { + const isDeclareClass = name === "DeclareClass"; + defineType(name, { + builder: ["id", "typeParameters", "extends", "body"], + visitor: ["id", "typeParameters", "extends", ...(isDeclareClass ? ["mixins", "implements"] : []), "body"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: Object.assign({ + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")) + }, isDeclareClass ? { + mixins: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")), + implements: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ClassImplements")) + } : {}, { + body: (0, _utils.validateType)("ObjectTypeAnnotation") + }) + }); + }; + defineType("AnyTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("ArrayTypeAnnotation", { + visitor: ["elementType"], + aliases: ["FlowType"], + fields: { + elementType: (0, _utils.validateType)("FlowType") + } + }); + defineType("BooleanTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("BooleanLiteralTypeAnnotation", { + builder: ["value"], + aliases: ["FlowType"], + fields: { + value: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("NullLiteralTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("ClassImplements", { + visitor: ["id", "typeParameters"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") + } + }); + defineInterfaceishType("DeclareClass"); + defineType("DeclareFunction", { + visitor: ["id"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + predicate: (0, _utils.validateOptionalType)("DeclaredPredicate") + } + }); + defineInterfaceishType("DeclareInterface"); + defineType("DeclareModule", { + builder: ["id", "body", "kind"], + visitor: ["id", "body"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier", "StringLiteral"), + body: (0, _utils.validateType)("BlockStatement"), + kind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("CommonJS", "ES")) + } + }); + defineType("DeclareModuleExports", { + visitor: ["typeAnnotation"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + typeAnnotation: (0, _utils.validateType)("TypeAnnotation") + } + }); + defineType("DeclareTypeAlias", { + visitor: ["id", "typeParameters", "right"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + right: (0, _utils.validateType)("FlowType") + } + }); + defineType("DeclareOpaqueType", { + visitor: ["id", "typeParameters", "supertype"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + supertype: (0, _utils.validateOptionalType)("FlowType"), + impltype: (0, _utils.validateOptionalType)("FlowType") + } + }); + defineType("DeclareVariable", { + visitor: ["id"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier") + } + }); + defineType("DeclareExportDeclaration", { + visitor: ["declaration", "specifiers", "source", "attributes"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: Object.assign({ + declaration: (0, _utils.validateOptionalType)("Flow"), + specifiers: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ExportSpecifier", "ExportNamespaceSpecifier")), + source: (0, _utils.validateOptionalType)("StringLiteral"), + default: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) + }, _core.importAttributes) + }); + defineType("DeclareExportAllDeclaration", { + visitor: ["source", "attributes"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: Object.assign({ + source: (0, _utils.validateType)("StringLiteral"), + exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("type", "value")) + }, _core.importAttributes) + }); + defineType("DeclaredPredicate", { + visitor: ["value"], + aliases: ["FlowPredicate"], + fields: { + value: (0, _utils.validateType)("Flow") + } + }); + defineType("ExistsTypeAnnotation", { + aliases: ["FlowType"] + }); + defineType("FunctionTypeAnnotation", { + visitor: ["typeParameters", "params", "rest", "returnType"], + aliases: ["FlowType"], + fields: { + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + params: (0, _utils.validateArrayOfType)("FunctionTypeParam"), + rest: (0, _utils.validateOptionalType)("FunctionTypeParam"), + this: (0, _utils.validateOptionalType)("FunctionTypeParam"), + returnType: (0, _utils.validateType)("FlowType") + } + }); + defineType("FunctionTypeParam", { + visitor: ["name", "typeAnnotation"], + fields: { + name: (0, _utils.validateOptionalType)("Identifier"), + typeAnnotation: (0, _utils.validateType)("FlowType"), + optional: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("GenericTypeAnnotation", { + visitor: ["id", "typeParameters"], + aliases: ["FlowType"], + fields: { + id: (0, _utils.validateType)("Identifier", "QualifiedTypeIdentifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") + } + }); + defineType("InferredPredicate", { + aliases: ["FlowPredicate"] + }); + defineType("InterfaceExtends", { + visitor: ["id", "typeParameters"], + fields: { + id: (0, _utils.validateType)("Identifier", "QualifiedTypeIdentifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") + } + }); + defineInterfaceishType("InterfaceDeclaration"); + defineType("InterfaceTypeAnnotation", { + visitor: ["extends", "body"], + aliases: ["FlowType"], + fields: { + extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")), + body: (0, _utils.validateType)("ObjectTypeAnnotation") + } + }); + defineType("IntersectionTypeAnnotation", { + visitor: ["types"], + aliases: ["FlowType"], + fields: { + types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + defineType("MixedTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("EmptyTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("NullableTypeAnnotation", { + visitor: ["typeAnnotation"], + aliases: ["FlowType"], + fields: { + typeAnnotation: (0, _utils.validateType)("FlowType") + } + }); + defineType("NumberLiteralTypeAnnotation", { + builder: ["value"], + aliases: ["FlowType"], + fields: { + value: (0, _utils.validate)((0, _utils.assertValueType)("number")) + } + }); + defineType("NumberTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("ObjectTypeAnnotation", { + visitor: ["properties", "indexers", "callProperties", "internalSlots"], + aliases: ["FlowType"], + builder: ["properties", "indexers", "callProperties", "internalSlots", "exact"], + fields: { + properties: (0, _utils.validate)((0, _utils.arrayOfType)("ObjectTypeProperty", "ObjectTypeSpreadProperty")), + indexers: { + validate: (0, _utils.arrayOfType)("ObjectTypeIndexer"), + optional: true, + default: [] + }, + callProperties: { + validate: (0, _utils.arrayOfType)("ObjectTypeCallProperty"), + optional: true, + default: [] + }, + internalSlots: { + validate: (0, _utils.arrayOfType)("ObjectTypeInternalSlot"), + optional: true, + default: [] + }, + exact: { + validate: (0, _utils.assertValueType)("boolean"), + default: false + }, + inexact: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("ObjectTypeInternalSlot", { + visitor: ["id", "value"], + builder: ["id", "value", "optional", "static", "method"], + aliases: ["UserWhitespacable"], + fields: { + id: (0, _utils.validateType)("Identifier"), + value: (0, _utils.validateType)("FlowType"), + optional: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + method: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("ObjectTypeCallProperty", { + visitor: ["value"], + aliases: ["UserWhitespacable"], + fields: { + value: (0, _utils.validateType)("FlowType"), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("ObjectTypeIndexer", { + visitor: ["variance", "id", "key", "value"], + builder: ["id", "key", "value", "variance"], + aliases: ["UserWhitespacable"], + fields: { + id: (0, _utils.validateOptionalType)("Identifier"), + key: (0, _utils.validateType)("FlowType"), + value: (0, _utils.validateType)("FlowType"), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + variance: (0, _utils.validateOptionalType)("Variance") + } + }); + defineType("ObjectTypeProperty", { + visitor: ["key", "value", "variance"], + aliases: ["UserWhitespacable"], + fields: { + key: (0, _utils.validateType)("Identifier", "StringLiteral"), + value: (0, _utils.validateType)("FlowType"), + kind: (0, _utils.validate)((0, _utils.assertOneOf)("init", "get", "set")), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + proto: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + optional: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + variance: (0, _utils.validateOptionalType)("Variance"), + method: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("ObjectTypeSpreadProperty", { + visitor: ["argument"], + aliases: ["UserWhitespacable"], + fields: { + argument: (0, _utils.validateType)("FlowType") + } + }); + defineType("OpaqueType", { + visitor: ["id", "typeParameters", "supertype", "impltype"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + supertype: (0, _utils.validateOptionalType)("FlowType"), + impltype: (0, _utils.validateType)("FlowType") + } + }); + defineType("QualifiedTypeIdentifier", { + visitor: ["qualification", "id"], + builder: ["id", "qualification"], + fields: { + id: (0, _utils.validateType)("Identifier"), + qualification: (0, _utils.validateType)("Identifier", "QualifiedTypeIdentifier") + } + }); + defineType("StringLiteralTypeAnnotation", { + builder: ["value"], + aliases: ["FlowType"], + fields: { + value: (0, _utils.validate)((0, _utils.assertValueType)("string")) + } + }); + defineType("StringTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("SymbolTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("ThisTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("TupleTypeAnnotation", { + visitor: ["types"], + aliases: ["FlowType"], + fields: { + types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + defineType("TypeofTypeAnnotation", { + visitor: ["argument"], + aliases: ["FlowType"], + fields: { + argument: (0, _utils.validateType)("FlowType") + } + }); + defineType("TypeAlias", { + visitor: ["id", "typeParameters", "right"], + aliases: ["FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + right: (0, _utils.validateType)("FlowType") + } + }); + defineType("TypeAnnotation", { + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("FlowType") + } + }); + defineType("TypeCastExpression", { + visitor: ["expression", "typeAnnotation"], + aliases: ["ExpressionWrapper", "Expression"], + fields: { + expression: (0, _utils.validateType)("Expression"), + typeAnnotation: (0, _utils.validateType)("TypeAnnotation") + } + }); + defineType("TypeParameter", { + visitor: ["bound", "default", "variance"], + fields: { + name: (0, _utils.validate)((0, _utils.assertValueType)("string")), + bound: (0, _utils.validateOptionalType)("TypeAnnotation"), + default: (0, _utils.validateOptionalType)("FlowType"), + variance: (0, _utils.validateOptionalType)("Variance") + } + }); + defineType("TypeParameterDeclaration", { + visitor: ["params"], + fields: { + params: (0, _utils.validate)((0, _utils.arrayOfType)("TypeParameter")) + } + }); + defineType("TypeParameterInstantiation", { + visitor: ["params"], + fields: { + params: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + defineType("UnionTypeAnnotation", { + visitor: ["types"], + aliases: ["FlowType"], + fields: { + types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + defineType("Variance", { + builder: ["kind"], + fields: { + kind: (0, _utils.validate)((0, _utils.assertOneOf)("minus", "plus")) + } + }); + defineType("VoidTypeAnnotation", { + aliases: ["FlowType", "FlowBaseAnnotation"] + }); + defineType("EnumDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "body"], + fields: { + id: (0, _utils.validateType)("Identifier"), + body: (0, _utils.validateType)("EnumBooleanBody", "EnumNumberBody", "EnumStringBody", "EnumSymbolBody") + } + }); + defineType("EnumBooleanBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + explicitType: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + members: (0, _utils.validateArrayOfType)("EnumBooleanMember"), + hasUnknownMembers: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("EnumNumberBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + explicitType: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + members: (0, _utils.validateArrayOfType)("EnumNumberMember"), + hasUnknownMembers: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("EnumStringBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + explicitType: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + members: (0, _utils.validateArrayOfType)("EnumStringMember", "EnumDefaultedMember"), + hasUnknownMembers: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("EnumSymbolBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + members: (0, _utils.validateArrayOfType)("EnumDefaultedMember"), + hasUnknownMembers: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + defineType("EnumBooleanMember", { + aliases: ["EnumMember"], + visitor: ["id"], + fields: { + id: (0, _utils.validateType)("Identifier"), + init: (0, _utils.validateType)("BooleanLiteral") + } + }); + defineType("EnumNumberMember", { + aliases: ["EnumMember"], + visitor: ["id", "init"], + fields: { + id: (0, _utils.validateType)("Identifier"), + init: (0, _utils.validateType)("NumericLiteral") + } + }); + defineType("EnumStringMember", { + aliases: ["EnumMember"], + visitor: ["id", "init"], + fields: { + id: (0, _utils.validateType)("Identifier"), + init: (0, _utils.validateType)("StringLiteral") + } + }); + defineType("EnumDefaultedMember", { + aliases: ["EnumMember"], + visitor: ["id"], + fields: { + id: (0, _utils.validateType)("Identifier") + } + }); + defineType("IndexedAccessType", { + visitor: ["objectType", "indexType"], + aliases: ["FlowType"], + fields: { + objectType: (0, _utils.validateType)("FlowType"), + indexType: (0, _utils.validateType)("FlowType") + } + }); + defineType("OptionalIndexedAccessType", { + visitor: ["objectType", "indexType"], + aliases: ["FlowType"], + fields: { + objectType: (0, _utils.validateType)("FlowType"), + indexType: (0, _utils.validateType)("FlowType"), + optional: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + + + return flow; +} + +var jsx = {}; + +var hasRequiredJsx; + +function requireJsx () { + if (hasRequiredJsx) return jsx; + hasRequiredJsx = 1; + + var _utils = requireUtils(); + const defineType = (0, _utils.defineAliasedType)("JSX"); + defineType("JSXAttribute", { + visitor: ["name", "value"], + aliases: ["Immutable"], + fields: { + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXNamespacedName") + }, + value: { + optional: true, + validate: (0, _utils.assertNodeType)("JSXElement", "JSXFragment", "StringLiteral", "JSXExpressionContainer") + } + } + }); + defineType("JSXClosingElement", { + visitor: ["name"], + aliases: ["Immutable"], + fields: { + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression", "JSXNamespacedName") + } + } + }); + defineType("JSXElement", { + builder: ["openingElement", "closingElement", "children", "selfClosing"], + visitor: ["openingElement", "children", "closingElement"], + aliases: ["Immutable", "Expression"], + fields: Object.assign({ + openingElement: { + validate: (0, _utils.assertNodeType)("JSXOpeningElement") + }, + closingElement: { + optional: true, + validate: (0, _utils.assertNodeType)("JSXClosingElement") + }, + children: (0, _utils.validateArrayOfType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment") + }, { + selfClosing: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + }) + }); + defineType("JSXEmptyExpression", {}); + defineType("JSXExpressionContainer", { + visitor: ["expression"], + aliases: ["Immutable"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression", "JSXEmptyExpression") + } + } + }); + defineType("JSXSpreadChild", { + visitor: ["expression"], + aliases: ["Immutable"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("JSXIdentifier", { + builder: ["name"], + fields: { + name: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + defineType("JSXMemberExpression", { + visitor: ["object", "property"], + fields: { + object: { + validate: (0, _utils.assertNodeType)("JSXMemberExpression", "JSXIdentifier") + }, + property: { + validate: (0, _utils.assertNodeType)("JSXIdentifier") + } + } + }); + defineType("JSXNamespacedName", { + visitor: ["namespace", "name"], + fields: { + namespace: { + validate: (0, _utils.assertNodeType)("JSXIdentifier") + }, + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier") + } + } + }); + defineType("JSXOpeningElement", { + builder: ["name", "attributes", "selfClosing"], + visitor: ["name", "attributes"], + aliases: ["Immutable"], + fields: { + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression", "JSXNamespacedName") + }, + selfClosing: { + default: false + }, + attributes: (0, _utils.validateArrayOfType)("JSXAttribute", "JSXSpreadAttribute"), + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + } + } + }); + defineType("JSXSpreadAttribute", { + visitor: ["argument"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + defineType("JSXText", { + aliases: ["Immutable"], + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + defineType("JSXFragment", { + builder: ["openingFragment", "closingFragment", "children"], + visitor: ["openingFragment", "children", "closingFragment"], + aliases: ["Immutable", "Expression"], + fields: { + openingFragment: { + validate: (0, _utils.assertNodeType)("JSXOpeningFragment") + }, + closingFragment: { + validate: (0, _utils.assertNodeType)("JSXClosingFragment") + }, + children: (0, _utils.validateArrayOfType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment") + } + }); + defineType("JSXOpeningFragment", { + aliases: ["Immutable"] + }); + defineType("JSXClosingFragment", { + aliases: ["Immutable"] + }); + + + return jsx; +} + +var misc = {}; + +var placeholders = {}; + +var hasRequiredPlaceholders; + +function requirePlaceholders () { + if (hasRequiredPlaceholders) return placeholders; + hasRequiredPlaceholders = 1; + + Object.defineProperty(placeholders, "__esModule", { + value: true + }); + placeholders.PLACEHOLDERS_FLIPPED_ALIAS = placeholders.PLACEHOLDERS_ALIAS = placeholders.PLACEHOLDERS = void 0; + var _utils = requireUtils(); + const PLACEHOLDERS = placeholders.PLACEHOLDERS = ["Identifier", "StringLiteral", "Expression", "Statement", "Declaration", "BlockStatement", "ClassBody", "Pattern"]; + const PLACEHOLDERS_ALIAS = placeholders.PLACEHOLDERS_ALIAS = { + Declaration: ["Statement"], + Pattern: ["PatternLike", "LVal"] + }; + for (const type of PLACEHOLDERS) { + const alias = _utils.ALIAS_KEYS[type]; + if (alias != null && alias.length) PLACEHOLDERS_ALIAS[type] = alias; + } + const PLACEHOLDERS_FLIPPED_ALIAS = placeholders.PLACEHOLDERS_FLIPPED_ALIAS = {}; + Object.keys(PLACEHOLDERS_ALIAS).forEach(type => { + PLACEHOLDERS_ALIAS[type].forEach(alias => { + if (!hasOwnProperty.call(PLACEHOLDERS_FLIPPED_ALIAS, alias)) { + PLACEHOLDERS_FLIPPED_ALIAS[alias] = []; + } + PLACEHOLDERS_FLIPPED_ALIAS[alias].push(type); + }); + }); + + + return placeholders; +} + +var hasRequiredMisc; + +function requireMisc () { + if (hasRequiredMisc) return misc; + hasRequiredMisc = 1; + + var _utils = requireUtils(); + var _placeholders = requirePlaceholders(); + var _core = requireCore(); + const defineType = (0, _utils.defineAliasedType)("Miscellaneous"); + { + defineType("Noop", { + visitor: [] + }); + } + defineType("Placeholder", { + visitor: [], + builder: ["expectedNode", "name"], + fields: Object.assign({ + name: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + expectedNode: { + validate: (0, _utils.assertOneOf)(..._placeholders.PLACEHOLDERS) + } + }, (0, _core.patternLikeCommon)()) + }); + defineType("V8IntrinsicIdentifier", { + builder: ["name"], + fields: { + name: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + + + return misc; +} + +var experimental = {}; + +var hasRequiredExperimental; + +function requireExperimental () { + if (hasRequiredExperimental) return experimental; + hasRequiredExperimental = 1; + + var _utils = requireUtils(); + (0, _utils.default)("ArgumentPlaceholder", {}); + (0, _utils.default)("BindExpression", { + visitor: ["object", "callee"], + aliases: ["Expression"], + fields: !process.env.BABEL_TYPES_8_BREAKING ? { + object: { + validate: Object.assign(() => {}, { + oneOfNodeTypes: ["Expression"] + }) + }, + callee: { + validate: Object.assign(() => {}, { + oneOfNodeTypes: ["Expression"] + }) + } + } : { + object: { + validate: (0, _utils.assertNodeType)("Expression") + }, + callee: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("ImportAttribute", { + visitor: ["key", "value"], + fields: { + key: { + validate: (0, _utils.assertNodeType)("Identifier", "StringLiteral") + }, + value: { + validate: (0, _utils.assertNodeType)("StringLiteral") + } + } + }); + (0, _utils.default)("Decorator", { + visitor: ["expression"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("DoExpression", { + visitor: ["body"], + builder: ["body", "async"], + aliases: ["Expression"], + fields: { + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + }, + async: { + validate: (0, _utils.assertValueType)("boolean"), + default: false + } + } + }); + (0, _utils.default)("ExportDefaultSpecifier", { + visitor: ["exported"], + aliases: ["ModuleSpecifier"], + fields: { + exported: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + (0, _utils.default)("RecordExpression", { + visitor: ["properties"], + aliases: ["Expression"], + fields: { + properties: (0, _utils.validateArrayOfType)("ObjectProperty", "SpreadElement") + } + }); + (0, _utils.default)("TupleExpression", { + fields: { + elements: { + validate: (0, _utils.arrayOfType)("Expression", "SpreadElement"), + default: [] + } + }, + visitor: ["elements"], + aliases: ["Expression"] + }); + { + (0, _utils.default)("DecimalLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + } + (0, _utils.default)("ModuleExpression", { + visitor: ["body"], + fields: { + body: { + validate: (0, _utils.assertNodeType)("Program") + } + }, + aliases: ["Expression"] + }); + (0, _utils.default)("TopicReference", { + aliases: ["Expression"] + }); + (0, _utils.default)("PipelineTopicExpression", { + builder: ["expression"], + visitor: ["expression"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + aliases: ["Expression"] + }); + (0, _utils.default)("PipelineBareFunction", { + builder: ["callee"], + visitor: ["callee"], + fields: { + callee: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + aliases: ["Expression"] + }); + (0, _utils.default)("PipelinePrimaryTopicReference", { + aliases: ["Expression"] + }); + + + return experimental; +} + +var typescript = {}; + +var hasRequiredTypescript; + +function requireTypescript () { + if (hasRequiredTypescript) return typescript; + hasRequiredTypescript = 1; + + var _utils = requireUtils(); + var _core = requireCore(); + var _is = requireIs(); + const defineType = (0, _utils.defineAliasedType)("TypeScript"); + const bool = (0, _utils.assertValueType)("boolean"); + const tSFunctionTypeAnnotationCommon = () => ({ + returnType: { + validate: (0, _utils.assertNodeType)("TSTypeAnnotation", "Noop"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TSTypeParameterDeclaration", "Noop"), + optional: true + } + }); + defineType("TSParameterProperty", { + aliases: ["LVal"], + visitor: ["parameter"], + fields: { + accessibility: { + validate: (0, _utils.assertOneOf)("public", "private", "protected"), + optional: true + }, + readonly: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + parameter: { + validate: (0, _utils.assertNodeType)("Identifier", "AssignmentPattern") + }, + override: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + decorators: { + validate: (0, _utils.arrayOfType)("Decorator"), + optional: true + } + } + }); + defineType("TSDeclareFunction", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "typeParameters", "params", "returnType"], + fields: Object.assign({}, (0, _core.functionDeclarationCommon)(), tSFunctionTypeAnnotationCommon()) + }); + defineType("TSDeclareMethod", { + visitor: ["decorators", "key", "typeParameters", "params", "returnType"], + fields: Object.assign({}, (0, _core.classMethodOrDeclareMethodCommon)(), tSFunctionTypeAnnotationCommon()) + }); + defineType("TSQualifiedName", { + aliases: ["TSEntityName"], + visitor: ["left", "right"], + fields: { + left: (0, _utils.validateType)("TSEntityName"), + right: (0, _utils.validateType)("Identifier") + } + }); + const signatureDeclarationCommon = () => ({ + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), + ["parameters"]: (0, _utils.validateArrayOfType)("ArrayPattern", "Identifier", "ObjectPattern", "RestElement"), + ["typeAnnotation"]: (0, _utils.validateOptionalType)("TSTypeAnnotation") + }); + const callConstructSignatureDeclaration = { + aliases: ["TSTypeElement"], + visitor: ["typeParameters", "parameters", "typeAnnotation"], + fields: signatureDeclarationCommon() + }; + defineType("TSCallSignatureDeclaration", callConstructSignatureDeclaration); + defineType("TSConstructSignatureDeclaration", callConstructSignatureDeclaration); + const namedTypeElementCommon = () => ({ + key: (0, _utils.validateType)("Expression"), + computed: { + default: false + }, + optional: (0, _utils.validateOptional)(bool) + }); + defineType("TSPropertySignature", { + aliases: ["TSTypeElement"], + visitor: ["key", "typeAnnotation"], + fields: Object.assign({}, namedTypeElementCommon(), { + readonly: (0, _utils.validateOptional)(bool), + typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation"), + kind: { + validate: (0, _utils.assertOneOf)("get", "set") + } + }) + }); + defineType("TSMethodSignature", { + aliases: ["TSTypeElement"], + visitor: ["key", "typeParameters", "parameters", "typeAnnotation"], + fields: Object.assign({}, signatureDeclarationCommon(), namedTypeElementCommon(), { + kind: { + validate: (0, _utils.assertOneOf)("method", "get", "set") + } + }) + }); + defineType("TSIndexSignature", { + aliases: ["TSTypeElement"], + visitor: ["parameters", "typeAnnotation"], + fields: { + readonly: (0, _utils.validateOptional)(bool), + static: (0, _utils.validateOptional)(bool), + parameters: (0, _utils.validateArrayOfType)("Identifier"), + typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation") + } + }); + const tsKeywordTypes = ["TSAnyKeyword", "TSBooleanKeyword", "TSBigIntKeyword", "TSIntrinsicKeyword", "TSNeverKeyword", "TSNullKeyword", "TSNumberKeyword", "TSObjectKeyword", "TSStringKeyword", "TSSymbolKeyword", "TSUndefinedKeyword", "TSUnknownKeyword", "TSVoidKeyword"]; + for (const type of tsKeywordTypes) { + defineType(type, { + aliases: ["TSType", "TSBaseType"], + visitor: [], + fields: {} + }); + } + defineType("TSThisType", { + aliases: ["TSType", "TSBaseType"], + visitor: [], + fields: {} + }); + const fnOrCtrBase = { + aliases: ["TSType"], + visitor: ["typeParameters", "parameters", "typeAnnotation"] + }; + defineType("TSFunctionType", Object.assign({}, fnOrCtrBase, { + fields: signatureDeclarationCommon() + })); + defineType("TSConstructorType", Object.assign({}, fnOrCtrBase, { + fields: Object.assign({}, signatureDeclarationCommon(), { + abstract: (0, _utils.validateOptional)(bool) + }) + })); + defineType("TSTypeReference", { + aliases: ["TSType"], + visitor: ["typeName", "typeParameters"], + fields: { + typeName: (0, _utils.validateType)("TSEntityName"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") + } + }); + defineType("TSTypePredicate", { + aliases: ["TSType"], + visitor: ["parameterName", "typeAnnotation"], + builder: ["parameterName", "typeAnnotation", "asserts"], + fields: { + parameterName: (0, _utils.validateType)("Identifier", "TSThisType"), + typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation"), + asserts: (0, _utils.validateOptional)(bool) + } + }); + defineType("TSTypeQuery", { + aliases: ["TSType"], + visitor: ["exprName", "typeParameters"], + fields: { + exprName: (0, _utils.validateType)("TSEntityName", "TSImportType"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") + } + }); + defineType("TSTypeLiteral", { + aliases: ["TSType"], + visitor: ["members"], + fields: { + members: (0, _utils.validateArrayOfType)("TSTypeElement") + } + }); + defineType("TSArrayType", { + aliases: ["TSType"], + visitor: ["elementType"], + fields: { + elementType: (0, _utils.validateType)("TSType") + } + }); + defineType("TSTupleType", { + aliases: ["TSType"], + visitor: ["elementTypes"], + fields: { + elementTypes: (0, _utils.validateArrayOfType)("TSType", "TSNamedTupleMember") + } + }); + defineType("TSOptionalType", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + defineType("TSRestType", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + defineType("TSNamedTupleMember", { + visitor: ["label", "elementType"], + builder: ["label", "elementType", "optional"], + fields: { + label: (0, _utils.validateType)("Identifier"), + optional: { + validate: bool, + default: false + }, + elementType: (0, _utils.validateType)("TSType") + } + }); + const unionOrIntersection = { + aliases: ["TSType"], + visitor: ["types"], + fields: { + types: (0, _utils.validateArrayOfType)("TSType") + } + }; + defineType("TSUnionType", unionOrIntersection); + defineType("TSIntersectionType", unionOrIntersection); + defineType("TSConditionalType", { + aliases: ["TSType"], + visitor: ["checkType", "extendsType", "trueType", "falseType"], + fields: { + checkType: (0, _utils.validateType)("TSType"), + extendsType: (0, _utils.validateType)("TSType"), + trueType: (0, _utils.validateType)("TSType"), + falseType: (0, _utils.validateType)("TSType") + } + }); + defineType("TSInferType", { + aliases: ["TSType"], + visitor: ["typeParameter"], + fields: { + typeParameter: (0, _utils.validateType)("TSTypeParameter") + } + }); + defineType("TSParenthesizedType", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + defineType("TSTypeOperator", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + operator: (0, _utils.validate)((0, _utils.assertValueType)("string")), + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + defineType("TSIndexedAccessType", { + aliases: ["TSType"], + visitor: ["objectType", "indexType"], + fields: { + objectType: (0, _utils.validateType)("TSType"), + indexType: (0, _utils.validateType)("TSType") + } + }); + defineType("TSMappedType", { + aliases: ["TSType"], + visitor: ["typeParameter", "nameType", "typeAnnotation"], + builder: ["typeParameter", "typeAnnotation", "nameType"], + fields: Object.assign({}, { + typeParameter: (0, _utils.validateType)("TSTypeParameter") + }, { + readonly: (0, _utils.validateOptional)((0, _utils.assertOneOf)(true, false, "+", "-")), + optional: (0, _utils.validateOptional)((0, _utils.assertOneOf)(true, false, "+", "-")), + typeAnnotation: (0, _utils.validateOptionalType)("TSType"), + nameType: (0, _utils.validateOptionalType)("TSType") + }) + }); + defineType("TSLiteralType", { + aliases: ["TSType", "TSBaseType"], + visitor: ["literal"], + fields: { + literal: { + validate: function () { + const unaryExpression = (0, _utils.assertNodeType)("NumericLiteral", "BigIntLiteral"); + const unaryOperator = (0, _utils.assertOneOf)("-"); + const literal = (0, _utils.assertNodeType)("NumericLiteral", "StringLiteral", "BooleanLiteral", "BigIntLiteral", "TemplateLiteral"); + function validator(parent, key, node) { + if ((0, _is.default)("UnaryExpression", node)) { + unaryOperator(node, "operator", node.operator); + unaryExpression(node, "argument", node.argument); + } else { + literal(parent, key, node); + } + } + validator.oneOfNodeTypes = ["NumericLiteral", "StringLiteral", "BooleanLiteral", "BigIntLiteral", "TemplateLiteral", "UnaryExpression"]; + return validator; + }() + } + } + }); + const expressionWithTypeArguments = { + aliases: ["TSType"], + visitor: ["expression", "typeParameters"], + fields: { + expression: (0, _utils.validateType)("TSEntityName"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") + } + }; + { + defineType("TSExpressionWithTypeArguments", expressionWithTypeArguments); + } + defineType("TSInterfaceDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "typeParameters", "extends", "body"], + fields: { + declare: (0, _utils.validateOptional)(bool), + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), + extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("TSExpressionWithTypeArguments")), + body: (0, _utils.validateType)("TSInterfaceBody") + } + }); + defineType("TSInterfaceBody", { + visitor: ["body"], + fields: { + body: (0, _utils.validateArrayOfType)("TSTypeElement") + } + }); + defineType("TSTypeAliasDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "typeParameters", "typeAnnotation"], + fields: { + declare: (0, _utils.validateOptional)(bool), + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + defineType("TSInstantiationExpression", { + aliases: ["Expression"], + visitor: ["expression", "typeParameters"], + fields: { + expression: (0, _utils.validateType)("Expression"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") + } + }); + const TSTypeExpression = { + aliases: ["Expression", "LVal", "PatternLike"], + visitor: ["expression", "typeAnnotation"], + fields: { + expression: (0, _utils.validateType)("Expression"), + typeAnnotation: (0, _utils.validateType)("TSType") + } + }; + defineType("TSAsExpression", TSTypeExpression); + defineType("TSSatisfiesExpression", TSTypeExpression); + defineType("TSTypeAssertion", { + aliases: ["Expression", "LVal", "PatternLike"], + visitor: ["typeAnnotation", "expression"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType"), + expression: (0, _utils.validateType)("Expression") + } + }); + defineType("TSEnumDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "members"], + fields: { + declare: (0, _utils.validateOptional)(bool), + const: (0, _utils.validateOptional)(bool), + id: (0, _utils.validateType)("Identifier"), + members: (0, _utils.validateArrayOfType)("TSEnumMember"), + initializer: (0, _utils.validateOptionalType)("Expression") + } + }); + defineType("TSEnumMember", { + visitor: ["id", "initializer"], + fields: { + id: (0, _utils.validateType)("Identifier", "StringLiteral"), + initializer: (0, _utils.validateOptionalType)("Expression") + } + }); + defineType("TSModuleDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "body"], + fields: Object.assign({ + kind: { + validate: (0, _utils.assertOneOf)("global", "module", "namespace") + }, + declare: (0, _utils.validateOptional)(bool) + }, { + global: (0, _utils.validateOptional)(bool) + }, { + id: (0, _utils.validateType)("Identifier", "StringLiteral"), + body: (0, _utils.validateType)("TSModuleBlock", "TSModuleDeclaration") + }) + }); + defineType("TSModuleBlock", { + aliases: ["Scopable", "Block", "BlockParent", "FunctionParent"], + visitor: ["body"], + fields: { + body: (0, _utils.validateArrayOfType)("Statement") + } + }); + defineType("TSImportType", { + aliases: ["TSType"], + visitor: ["argument", "qualifier", "typeParameters"], + fields: { + argument: (0, _utils.validateType)("StringLiteral"), + qualifier: (0, _utils.validateOptionalType)("TSEntityName"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation"), + options: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + } + } + }); + defineType("TSImportEqualsDeclaration", { + aliases: ["Statement"], + visitor: ["id", "moduleReference"], + fields: { + isExport: (0, _utils.validate)(bool), + id: (0, _utils.validateType)("Identifier"), + moduleReference: (0, _utils.validateType)("TSEntityName", "TSExternalModuleReference"), + importKind: { + validate: (0, _utils.assertOneOf)("type", "value"), + optional: true + } + } + }); + defineType("TSExternalModuleReference", { + visitor: ["expression"], + fields: { + expression: (0, _utils.validateType)("StringLiteral") + } + }); + defineType("TSNonNullExpression", { + aliases: ["Expression", "LVal", "PatternLike"], + visitor: ["expression"], + fields: { + expression: (0, _utils.validateType)("Expression") + } + }); + defineType("TSExportAssignment", { + aliases: ["Statement"], + visitor: ["expression"], + fields: { + expression: (0, _utils.validateType)("Expression") + } + }); + defineType("TSNamespaceExportDeclaration", { + aliases: ["Statement"], + visitor: ["id"], + fields: { + id: (0, _utils.validateType)("Identifier") + } + }); + defineType("TSTypeAnnotation", { + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TSType") + } + } + }); + defineType("TSTypeParameterInstantiation", { + visitor: ["params"], + fields: { + params: (0, _utils.validateArrayOfType)("TSType") + } + }); + defineType("TSTypeParameterDeclaration", { + visitor: ["params"], + fields: { + params: (0, _utils.validateArrayOfType)("TSTypeParameter") + } + }); + defineType("TSTypeParameter", { + builder: ["constraint", "default", "name"], + visitor: ["constraint", "default"], + fields: { + name: { + validate: (0, _utils.assertValueType)("string") + }, + in: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + out: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + const: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + constraint: { + validate: (0, _utils.assertNodeType)("TSType"), + optional: true + }, + default: { + validate: (0, _utils.assertNodeType)("TSType"), + optional: true + } + } + }); + + + return typescript; +} + +var deprecatedAliases = {}; + +var hasRequiredDeprecatedAliases; + +function requireDeprecatedAliases () { + if (hasRequiredDeprecatedAliases) return deprecatedAliases; + hasRequiredDeprecatedAliases = 1; + + Object.defineProperty(deprecatedAliases, "__esModule", { + value: true + }); + deprecatedAliases.DEPRECATED_ALIASES = void 0; + deprecatedAliases.DEPRECATED_ALIASES = { + ModuleDeclaration: "ImportOrExportDeclaration" + }; + + + return deprecatedAliases; +} + +var hasRequiredDefinitions; + +function requireDefinitions () { + if (hasRequiredDefinitions) return definitions; + hasRequiredDefinitions = 1; + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "ALIAS_KEYS", { + enumerable: true, + get: function () { + return _utils.ALIAS_KEYS; + } + }); + Object.defineProperty(exports, "BUILDER_KEYS", { + enumerable: true, + get: function () { + return _utils.BUILDER_KEYS; + } + }); + Object.defineProperty(exports, "DEPRECATED_ALIASES", { + enumerable: true, + get: function () { + return _deprecatedAliases.DEPRECATED_ALIASES; + } + }); + Object.defineProperty(exports, "DEPRECATED_KEYS", { + enumerable: true, + get: function () { + return _utils.DEPRECATED_KEYS; + } + }); + Object.defineProperty(exports, "FLIPPED_ALIAS_KEYS", { + enumerable: true, + get: function () { + return _utils.FLIPPED_ALIAS_KEYS; + } + }); + Object.defineProperty(exports, "NODE_FIELDS", { + enumerable: true, + get: function () { + return _utils.NODE_FIELDS; + } + }); + Object.defineProperty(exports, "NODE_PARENT_VALIDATIONS", { + enumerable: true, + get: function () { + return _utils.NODE_PARENT_VALIDATIONS; + } + }); + Object.defineProperty(exports, "PLACEHOLDERS", { + enumerable: true, + get: function () { + return _placeholders.PLACEHOLDERS; + } + }); + Object.defineProperty(exports, "PLACEHOLDERS_ALIAS", { + enumerable: true, + get: function () { + return _placeholders.PLACEHOLDERS_ALIAS; + } + }); + Object.defineProperty(exports, "PLACEHOLDERS_FLIPPED_ALIAS", { + enumerable: true, + get: function () { + return _placeholders.PLACEHOLDERS_FLIPPED_ALIAS; + } + }); + exports.TYPES = void 0; + Object.defineProperty(exports, "VISITOR_KEYS", { + enumerable: true, + get: function () { + return _utils.VISITOR_KEYS; + } + }); + requireCore(); + requireFlow(); + requireJsx(); + requireMisc(); + requireExperimental(); + requireTypescript(); + var _utils = requireUtils(); + var _placeholders = requirePlaceholders(); + var _deprecatedAliases = requireDeprecatedAliases(); + Object.keys(_deprecatedAliases.DEPRECATED_ALIASES).forEach(deprecatedAlias => { + _utils.FLIPPED_ALIAS_KEYS[deprecatedAlias] = _utils.FLIPPED_ALIAS_KEYS[_deprecatedAliases.DEPRECATED_ALIASES[deprecatedAlias]]; + }); + exports.TYPES = [].concat(Object.keys(_utils.VISITOR_KEYS), Object.keys(_utils.FLIPPED_ALIAS_KEYS), Object.keys(_utils.DEPRECATED_KEYS)); + + +} (definitions)); + return definitions; +} + +var hasRequiredValidate; + +function requireValidate () { + if (hasRequiredValidate) return validate$1; + hasRequiredValidate = 1; + + Object.defineProperty(validate$1, "__esModule", { + value: true + }); + validate$1.default = validate; + validate$1.validateChild = validateChild; + validate$1.validateField = validateField; + validate$1.validateInternal = validateInternal; + var _index = requireDefinitions(); + function validate(node, key, val) { + if (!node) return; + const fields = _index.NODE_FIELDS[node.type]; + if (!fields) return; + const field = fields[key]; + validateField(node, key, val, field); + validateChild(node, key, val); + } + function validateInternal(field, node, key, val, maybeNode) { + if (!(field != null && field.validate)) return; + if (field.optional && val == null) return; + field.validate(node, key, val); + if (maybeNode) { + var _NODE_PARENT_VALIDATI; + const type = val.type; + if (type == null) return; + (_NODE_PARENT_VALIDATI = _index.NODE_PARENT_VALIDATIONS[type]) == null || _NODE_PARENT_VALIDATI.call(_index.NODE_PARENT_VALIDATIONS, node, key, val); + } + } + function validateField(node, key, val, field) { + if (!(field != null && field.validate)) return; + if (field.optional && val == null) return; + field.validate(node, key, val); + } + function validateChild(node, key, val) { + var _NODE_PARENT_VALIDATI2; + const type = val == null ? void 0 : val.type; + if (type == null) return; + (_NODE_PARENT_VALIDATI2 = _index.NODE_PARENT_VALIDATIONS[type]) == null || _NODE_PARENT_VALIDATI2.call(_index.NODE_PARENT_VALIDATIONS, node, key, val); + } + + + return validate$1; +} + +var hasRequiredGenerated$2; + +function requireGenerated$2 () { + if (hasRequiredGenerated$2) return generated$2; + hasRequiredGenerated$2 = 1; + + Object.defineProperty(generated$2, "__esModule", { + value: true + }); + generated$2.anyTypeAnnotation = anyTypeAnnotation; + generated$2.argumentPlaceholder = argumentPlaceholder; + generated$2.arrayExpression = arrayExpression; + generated$2.arrayPattern = arrayPattern; + generated$2.arrayTypeAnnotation = arrayTypeAnnotation; + generated$2.arrowFunctionExpression = arrowFunctionExpression; + generated$2.assignmentExpression = assignmentExpression; + generated$2.assignmentPattern = assignmentPattern; + generated$2.awaitExpression = awaitExpression; + generated$2.bigIntLiteral = bigIntLiteral; + generated$2.binaryExpression = binaryExpression; + generated$2.bindExpression = bindExpression; + generated$2.blockStatement = blockStatement; + generated$2.booleanLiteral = booleanLiteral; + generated$2.booleanLiteralTypeAnnotation = booleanLiteralTypeAnnotation; + generated$2.booleanTypeAnnotation = booleanTypeAnnotation; + generated$2.breakStatement = breakStatement; + generated$2.callExpression = callExpression; + generated$2.catchClause = catchClause; + generated$2.classAccessorProperty = classAccessorProperty; + generated$2.classBody = classBody; + generated$2.classDeclaration = classDeclaration; + generated$2.classExpression = classExpression; + generated$2.classImplements = classImplements; + generated$2.classMethod = classMethod; + generated$2.classPrivateMethod = classPrivateMethod; + generated$2.classPrivateProperty = classPrivateProperty; + generated$2.classProperty = classProperty; + generated$2.conditionalExpression = conditionalExpression; + generated$2.continueStatement = continueStatement; + generated$2.debuggerStatement = debuggerStatement; + generated$2.decimalLiteral = decimalLiteral; + generated$2.declareClass = declareClass; + generated$2.declareExportAllDeclaration = declareExportAllDeclaration; + generated$2.declareExportDeclaration = declareExportDeclaration; + generated$2.declareFunction = declareFunction; + generated$2.declareInterface = declareInterface; + generated$2.declareModule = declareModule; + generated$2.declareModuleExports = declareModuleExports; + generated$2.declareOpaqueType = declareOpaqueType; + generated$2.declareTypeAlias = declareTypeAlias; + generated$2.declareVariable = declareVariable; + generated$2.declaredPredicate = declaredPredicate; + generated$2.decorator = decorator; + generated$2.directive = directive; + generated$2.directiveLiteral = directiveLiteral; + generated$2.doExpression = doExpression; + generated$2.doWhileStatement = doWhileStatement; + generated$2.emptyStatement = emptyStatement; + generated$2.emptyTypeAnnotation = emptyTypeAnnotation; + generated$2.enumBooleanBody = enumBooleanBody; + generated$2.enumBooleanMember = enumBooleanMember; + generated$2.enumDeclaration = enumDeclaration; + generated$2.enumDefaultedMember = enumDefaultedMember; + generated$2.enumNumberBody = enumNumberBody; + generated$2.enumNumberMember = enumNumberMember; + generated$2.enumStringBody = enumStringBody; + generated$2.enumStringMember = enumStringMember; + generated$2.enumSymbolBody = enumSymbolBody; + generated$2.existsTypeAnnotation = existsTypeAnnotation; + generated$2.exportAllDeclaration = exportAllDeclaration; + generated$2.exportDefaultDeclaration = exportDefaultDeclaration; + generated$2.exportDefaultSpecifier = exportDefaultSpecifier; + generated$2.exportNamedDeclaration = exportNamedDeclaration; + generated$2.exportNamespaceSpecifier = exportNamespaceSpecifier; + generated$2.exportSpecifier = exportSpecifier; + generated$2.expressionStatement = expressionStatement; + generated$2.file = file; + generated$2.forInStatement = forInStatement; + generated$2.forOfStatement = forOfStatement; + generated$2.forStatement = forStatement; + generated$2.functionDeclaration = functionDeclaration; + generated$2.functionExpression = functionExpression; + generated$2.functionTypeAnnotation = functionTypeAnnotation; + generated$2.functionTypeParam = functionTypeParam; + generated$2.genericTypeAnnotation = genericTypeAnnotation; + generated$2.identifier = identifier; + generated$2.ifStatement = ifStatement; + generated$2.import = _import; + generated$2.importAttribute = importAttribute; + generated$2.importDeclaration = importDeclaration; + generated$2.importDefaultSpecifier = importDefaultSpecifier; + generated$2.importExpression = importExpression; + generated$2.importNamespaceSpecifier = importNamespaceSpecifier; + generated$2.importSpecifier = importSpecifier; + generated$2.indexedAccessType = indexedAccessType; + generated$2.inferredPredicate = inferredPredicate; + generated$2.interfaceDeclaration = interfaceDeclaration; + generated$2.interfaceExtends = interfaceExtends; + generated$2.interfaceTypeAnnotation = interfaceTypeAnnotation; + generated$2.interpreterDirective = interpreterDirective; + generated$2.intersectionTypeAnnotation = intersectionTypeAnnotation; + generated$2.jSXAttribute = generated$2.jsxAttribute = jsxAttribute; + generated$2.jSXClosingElement = generated$2.jsxClosingElement = jsxClosingElement; + generated$2.jSXClosingFragment = generated$2.jsxClosingFragment = jsxClosingFragment; + generated$2.jSXElement = generated$2.jsxElement = jsxElement; + generated$2.jSXEmptyExpression = generated$2.jsxEmptyExpression = jsxEmptyExpression; + generated$2.jSXExpressionContainer = generated$2.jsxExpressionContainer = jsxExpressionContainer; + generated$2.jSXFragment = generated$2.jsxFragment = jsxFragment; + generated$2.jSXIdentifier = generated$2.jsxIdentifier = jsxIdentifier; + generated$2.jSXMemberExpression = generated$2.jsxMemberExpression = jsxMemberExpression; + generated$2.jSXNamespacedName = generated$2.jsxNamespacedName = jsxNamespacedName; + generated$2.jSXOpeningElement = generated$2.jsxOpeningElement = jsxOpeningElement; + generated$2.jSXOpeningFragment = generated$2.jsxOpeningFragment = jsxOpeningFragment; + generated$2.jSXSpreadAttribute = generated$2.jsxSpreadAttribute = jsxSpreadAttribute; + generated$2.jSXSpreadChild = generated$2.jsxSpreadChild = jsxSpreadChild; + generated$2.jSXText = generated$2.jsxText = jsxText; + generated$2.labeledStatement = labeledStatement; + generated$2.logicalExpression = logicalExpression; + generated$2.memberExpression = memberExpression; + generated$2.metaProperty = metaProperty; + generated$2.mixedTypeAnnotation = mixedTypeAnnotation; + generated$2.moduleExpression = moduleExpression; + generated$2.newExpression = newExpression; + generated$2.noop = noop; + generated$2.nullLiteral = nullLiteral; + generated$2.nullLiteralTypeAnnotation = nullLiteralTypeAnnotation; + generated$2.nullableTypeAnnotation = nullableTypeAnnotation; + generated$2.numberLiteral = NumberLiteral; + generated$2.numberLiteralTypeAnnotation = numberLiteralTypeAnnotation; + generated$2.numberTypeAnnotation = numberTypeAnnotation; + generated$2.numericLiteral = numericLiteral; + generated$2.objectExpression = objectExpression; + generated$2.objectMethod = objectMethod; + generated$2.objectPattern = objectPattern; + generated$2.objectProperty = objectProperty; + generated$2.objectTypeAnnotation = objectTypeAnnotation; + generated$2.objectTypeCallProperty = objectTypeCallProperty; + generated$2.objectTypeIndexer = objectTypeIndexer; + generated$2.objectTypeInternalSlot = objectTypeInternalSlot; + generated$2.objectTypeProperty = objectTypeProperty; + generated$2.objectTypeSpreadProperty = objectTypeSpreadProperty; + generated$2.opaqueType = opaqueType; + generated$2.optionalCallExpression = optionalCallExpression; + generated$2.optionalIndexedAccessType = optionalIndexedAccessType; + generated$2.optionalMemberExpression = optionalMemberExpression; + generated$2.parenthesizedExpression = parenthesizedExpression; + generated$2.pipelineBareFunction = pipelineBareFunction; + generated$2.pipelinePrimaryTopicReference = pipelinePrimaryTopicReference; + generated$2.pipelineTopicExpression = pipelineTopicExpression; + generated$2.placeholder = placeholder; + generated$2.privateName = privateName; + generated$2.program = program; + generated$2.qualifiedTypeIdentifier = qualifiedTypeIdentifier; + generated$2.recordExpression = recordExpression; + generated$2.regExpLiteral = regExpLiteral; + generated$2.regexLiteral = RegexLiteral; + generated$2.restElement = restElement; + generated$2.restProperty = RestProperty; + generated$2.returnStatement = returnStatement; + generated$2.sequenceExpression = sequenceExpression; + generated$2.spreadElement = spreadElement; + generated$2.spreadProperty = SpreadProperty; + generated$2.staticBlock = staticBlock; + generated$2.stringLiteral = stringLiteral; + generated$2.stringLiteralTypeAnnotation = stringLiteralTypeAnnotation; + generated$2.stringTypeAnnotation = stringTypeAnnotation; + generated$2.super = _super; + generated$2.switchCase = switchCase; + generated$2.switchStatement = switchStatement; + generated$2.symbolTypeAnnotation = symbolTypeAnnotation; + generated$2.taggedTemplateExpression = taggedTemplateExpression; + generated$2.templateElement = templateElement; + generated$2.templateLiteral = templateLiteral; + generated$2.thisExpression = thisExpression; + generated$2.thisTypeAnnotation = thisTypeAnnotation; + generated$2.throwStatement = throwStatement; + generated$2.topicReference = topicReference; + generated$2.tryStatement = tryStatement; + generated$2.tSAnyKeyword = generated$2.tsAnyKeyword = tsAnyKeyword; + generated$2.tSArrayType = generated$2.tsArrayType = tsArrayType; + generated$2.tSAsExpression = generated$2.tsAsExpression = tsAsExpression; + generated$2.tSBigIntKeyword = generated$2.tsBigIntKeyword = tsBigIntKeyword; + generated$2.tSBooleanKeyword = generated$2.tsBooleanKeyword = tsBooleanKeyword; + generated$2.tSCallSignatureDeclaration = generated$2.tsCallSignatureDeclaration = tsCallSignatureDeclaration; + generated$2.tSConditionalType = generated$2.tsConditionalType = tsConditionalType; + generated$2.tSConstructSignatureDeclaration = generated$2.tsConstructSignatureDeclaration = tsConstructSignatureDeclaration; + generated$2.tSConstructorType = generated$2.tsConstructorType = tsConstructorType; + generated$2.tSDeclareFunction = generated$2.tsDeclareFunction = tsDeclareFunction; + generated$2.tSDeclareMethod = generated$2.tsDeclareMethod = tsDeclareMethod; + generated$2.tSEnumDeclaration = generated$2.tsEnumDeclaration = tsEnumDeclaration; + generated$2.tSEnumMember = generated$2.tsEnumMember = tsEnumMember; + generated$2.tSExportAssignment = generated$2.tsExportAssignment = tsExportAssignment; + generated$2.tSExpressionWithTypeArguments = generated$2.tsExpressionWithTypeArguments = tsExpressionWithTypeArguments; + generated$2.tSExternalModuleReference = generated$2.tsExternalModuleReference = tsExternalModuleReference; + generated$2.tSFunctionType = generated$2.tsFunctionType = tsFunctionType; + generated$2.tSImportEqualsDeclaration = generated$2.tsImportEqualsDeclaration = tsImportEqualsDeclaration; + generated$2.tSImportType = generated$2.tsImportType = tsImportType; + generated$2.tSIndexSignature = generated$2.tsIndexSignature = tsIndexSignature; + generated$2.tSIndexedAccessType = generated$2.tsIndexedAccessType = tsIndexedAccessType; + generated$2.tSInferType = generated$2.tsInferType = tsInferType; + generated$2.tSInstantiationExpression = generated$2.tsInstantiationExpression = tsInstantiationExpression; + generated$2.tSInterfaceBody = generated$2.tsInterfaceBody = tsInterfaceBody; + generated$2.tSInterfaceDeclaration = generated$2.tsInterfaceDeclaration = tsInterfaceDeclaration; + generated$2.tSIntersectionType = generated$2.tsIntersectionType = tsIntersectionType; + generated$2.tSIntrinsicKeyword = generated$2.tsIntrinsicKeyword = tsIntrinsicKeyword; + generated$2.tSLiteralType = generated$2.tsLiteralType = tsLiteralType; + generated$2.tSMappedType = generated$2.tsMappedType = tsMappedType; + generated$2.tSMethodSignature = generated$2.tsMethodSignature = tsMethodSignature; + generated$2.tSModuleBlock = generated$2.tsModuleBlock = tsModuleBlock; + generated$2.tSModuleDeclaration = generated$2.tsModuleDeclaration = tsModuleDeclaration; + generated$2.tSNamedTupleMember = generated$2.tsNamedTupleMember = tsNamedTupleMember; + generated$2.tSNamespaceExportDeclaration = generated$2.tsNamespaceExportDeclaration = tsNamespaceExportDeclaration; + generated$2.tSNeverKeyword = generated$2.tsNeverKeyword = tsNeverKeyword; + generated$2.tSNonNullExpression = generated$2.tsNonNullExpression = tsNonNullExpression; + generated$2.tSNullKeyword = generated$2.tsNullKeyword = tsNullKeyword; + generated$2.tSNumberKeyword = generated$2.tsNumberKeyword = tsNumberKeyword; + generated$2.tSObjectKeyword = generated$2.tsObjectKeyword = tsObjectKeyword; + generated$2.tSOptionalType = generated$2.tsOptionalType = tsOptionalType; + generated$2.tSParameterProperty = generated$2.tsParameterProperty = tsParameterProperty; + generated$2.tSParenthesizedType = generated$2.tsParenthesizedType = tsParenthesizedType; + generated$2.tSPropertySignature = generated$2.tsPropertySignature = tsPropertySignature; + generated$2.tSQualifiedName = generated$2.tsQualifiedName = tsQualifiedName; + generated$2.tSRestType = generated$2.tsRestType = tsRestType; + generated$2.tSSatisfiesExpression = generated$2.tsSatisfiesExpression = tsSatisfiesExpression; + generated$2.tSStringKeyword = generated$2.tsStringKeyword = tsStringKeyword; + generated$2.tSSymbolKeyword = generated$2.tsSymbolKeyword = tsSymbolKeyword; + generated$2.tSThisType = generated$2.tsThisType = tsThisType; + generated$2.tSTupleType = generated$2.tsTupleType = tsTupleType; + generated$2.tSTypeAliasDeclaration = generated$2.tsTypeAliasDeclaration = tsTypeAliasDeclaration; + generated$2.tSTypeAnnotation = generated$2.tsTypeAnnotation = tsTypeAnnotation; + generated$2.tSTypeAssertion = generated$2.tsTypeAssertion = tsTypeAssertion; + generated$2.tSTypeLiteral = generated$2.tsTypeLiteral = tsTypeLiteral; + generated$2.tSTypeOperator = generated$2.tsTypeOperator = tsTypeOperator; + generated$2.tSTypeParameter = generated$2.tsTypeParameter = tsTypeParameter; + generated$2.tSTypeParameterDeclaration = generated$2.tsTypeParameterDeclaration = tsTypeParameterDeclaration; + generated$2.tSTypeParameterInstantiation = generated$2.tsTypeParameterInstantiation = tsTypeParameterInstantiation; + generated$2.tSTypePredicate = generated$2.tsTypePredicate = tsTypePredicate; + generated$2.tSTypeQuery = generated$2.tsTypeQuery = tsTypeQuery; + generated$2.tSTypeReference = generated$2.tsTypeReference = tsTypeReference; + generated$2.tSUndefinedKeyword = generated$2.tsUndefinedKeyword = tsUndefinedKeyword; + generated$2.tSUnionType = generated$2.tsUnionType = tsUnionType; + generated$2.tSUnknownKeyword = generated$2.tsUnknownKeyword = tsUnknownKeyword; + generated$2.tSVoidKeyword = generated$2.tsVoidKeyword = tsVoidKeyword; + generated$2.tupleExpression = tupleExpression; + generated$2.tupleTypeAnnotation = tupleTypeAnnotation; + generated$2.typeAlias = typeAlias; + generated$2.typeAnnotation = typeAnnotation; + generated$2.typeCastExpression = typeCastExpression; + generated$2.typeParameter = typeParameter; + generated$2.typeParameterDeclaration = typeParameterDeclaration; + generated$2.typeParameterInstantiation = typeParameterInstantiation; + generated$2.typeofTypeAnnotation = typeofTypeAnnotation; + generated$2.unaryExpression = unaryExpression; + generated$2.unionTypeAnnotation = unionTypeAnnotation; + generated$2.updateExpression = updateExpression; + generated$2.v8IntrinsicIdentifier = v8IntrinsicIdentifier; + generated$2.variableDeclaration = variableDeclaration; + generated$2.variableDeclarator = variableDeclarator; + generated$2.variance = variance; + generated$2.voidTypeAnnotation = voidTypeAnnotation; + generated$2.whileStatement = whileStatement; + generated$2.withStatement = withStatement; + generated$2.yieldExpression = yieldExpression; + var _validate = requireValidate(); + var _deprecationWarning = requireDeprecationWarning(); + var utils = requireUtils(); + const { + validateInternal: validate + } = _validate; + const { + NODE_FIELDS + } = utils; + function arrayExpression(elements = []) { + const node = { + type: "ArrayExpression", + elements + }; + const defs = NODE_FIELDS.ArrayExpression; + validate(defs.elements, node, "elements", elements, 1); + return node; + } + function assignmentExpression(operator, left, right) { + const node = { + type: "AssignmentExpression", + operator, + left, + right + }; + const defs = NODE_FIELDS.AssignmentExpression; + validate(defs.operator, node, "operator", operator); + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function binaryExpression(operator, left, right) { + const node = { + type: "BinaryExpression", + operator, + left, + right + }; + const defs = NODE_FIELDS.BinaryExpression; + validate(defs.operator, node, "operator", operator); + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function interpreterDirective(value) { + const node = { + type: "InterpreterDirective", + value + }; + const defs = NODE_FIELDS.InterpreterDirective; + validate(defs.value, node, "value", value); + return node; + } + function directive(value) { + const node = { + type: "Directive", + value + }; + const defs = NODE_FIELDS.Directive; + validate(defs.value, node, "value", value, 1); + return node; + } + function directiveLiteral(value) { + const node = { + type: "DirectiveLiteral", + value + }; + const defs = NODE_FIELDS.DirectiveLiteral; + validate(defs.value, node, "value", value); + return node; + } + function blockStatement(body, directives = []) { + const node = { + type: "BlockStatement", + body, + directives + }; + const defs = NODE_FIELDS.BlockStatement; + validate(defs.body, node, "body", body, 1); + validate(defs.directives, node, "directives", directives, 1); + return node; + } + function breakStatement(label = null) { + const node = { + type: "BreakStatement", + label + }; + const defs = NODE_FIELDS.BreakStatement; + validate(defs.label, node, "label", label, 1); + return node; + } + function callExpression(callee, _arguments) { + const node = { + type: "CallExpression", + callee, + arguments: _arguments + }; + const defs = NODE_FIELDS.CallExpression; + validate(defs.callee, node, "callee", callee, 1); + validate(defs.arguments, node, "arguments", _arguments, 1); + return node; + } + function catchClause(param = null, body) { + const node = { + type: "CatchClause", + param, + body + }; + const defs = NODE_FIELDS.CatchClause; + validate(defs.param, node, "param", param, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function conditionalExpression(test, consequent, alternate) { + const node = { + type: "ConditionalExpression", + test, + consequent, + alternate + }; + const defs = NODE_FIELDS.ConditionalExpression; + validate(defs.test, node, "test", test, 1); + validate(defs.consequent, node, "consequent", consequent, 1); + validate(defs.alternate, node, "alternate", alternate, 1); + return node; + } + function continueStatement(label = null) { + const node = { + type: "ContinueStatement", + label + }; + const defs = NODE_FIELDS.ContinueStatement; + validate(defs.label, node, "label", label, 1); + return node; + } + function debuggerStatement() { + return { + type: "DebuggerStatement" + }; + } + function doWhileStatement(test, body) { + const node = { + type: "DoWhileStatement", + test, + body + }; + const defs = NODE_FIELDS.DoWhileStatement; + validate(defs.test, node, "test", test, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function emptyStatement() { + return { + type: "EmptyStatement" + }; + } + function expressionStatement(expression) { + const node = { + type: "ExpressionStatement", + expression + }; + const defs = NODE_FIELDS.ExpressionStatement; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function file(program, comments = null, tokens = null) { + const node = { + type: "File", + program, + comments, + tokens + }; + const defs = NODE_FIELDS.File; + validate(defs.program, node, "program", program, 1); + validate(defs.comments, node, "comments", comments, 1); + validate(defs.tokens, node, "tokens", tokens); + return node; + } + function forInStatement(left, right, body) { + const node = { + type: "ForInStatement", + left, + right, + body + }; + const defs = NODE_FIELDS.ForInStatement; + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function forStatement(init = null, test = null, update = null, body) { + const node = { + type: "ForStatement", + init, + test, + update, + body + }; + const defs = NODE_FIELDS.ForStatement; + validate(defs.init, node, "init", init, 1); + validate(defs.test, node, "test", test, 1); + validate(defs.update, node, "update", update, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function functionDeclaration(id = null, params, body, generator = false, async = false) { + const node = { + type: "FunctionDeclaration", + id, + params, + body, + generator, + async + }; + const defs = NODE_FIELDS.FunctionDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.generator, node, "generator", generator); + validate(defs.async, node, "async", async); + return node; + } + function functionExpression(id = null, params, body, generator = false, async = false) { + const node = { + type: "FunctionExpression", + id, + params, + body, + generator, + async + }; + const defs = NODE_FIELDS.FunctionExpression; + validate(defs.id, node, "id", id, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.generator, node, "generator", generator); + validate(defs.async, node, "async", async); + return node; + } + function identifier(name) { + const node = { + type: "Identifier", + name + }; + const defs = NODE_FIELDS.Identifier; + validate(defs.name, node, "name", name); + return node; + } + function ifStatement(test, consequent, alternate = null) { + const node = { + type: "IfStatement", + test, + consequent, + alternate + }; + const defs = NODE_FIELDS.IfStatement; + validate(defs.test, node, "test", test, 1); + validate(defs.consequent, node, "consequent", consequent, 1); + validate(defs.alternate, node, "alternate", alternate, 1); + return node; + } + function labeledStatement(label, body) { + const node = { + type: "LabeledStatement", + label, + body + }; + const defs = NODE_FIELDS.LabeledStatement; + validate(defs.label, node, "label", label, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function stringLiteral(value) { + const node = { + type: "StringLiteral", + value + }; + const defs = NODE_FIELDS.StringLiteral; + validate(defs.value, node, "value", value); + return node; + } + function numericLiteral(value) { + const node = { + type: "NumericLiteral", + value + }; + const defs = NODE_FIELDS.NumericLiteral; + validate(defs.value, node, "value", value); + return node; + } + function nullLiteral() { + return { + type: "NullLiteral" + }; + } + function booleanLiteral(value) { + const node = { + type: "BooleanLiteral", + value + }; + const defs = NODE_FIELDS.BooleanLiteral; + validate(defs.value, node, "value", value); + return node; + } + function regExpLiteral(pattern, flags = "") { + const node = { + type: "RegExpLiteral", + pattern, + flags + }; + const defs = NODE_FIELDS.RegExpLiteral; + validate(defs.pattern, node, "pattern", pattern); + validate(defs.flags, node, "flags", flags); + return node; + } + function logicalExpression(operator, left, right) { + const node = { + type: "LogicalExpression", + operator, + left, + right + }; + const defs = NODE_FIELDS.LogicalExpression; + validate(defs.operator, node, "operator", operator); + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function memberExpression(object, property, computed = false, optional = null) { + const node = { + type: "MemberExpression", + object, + property, + computed, + optional + }; + const defs = NODE_FIELDS.MemberExpression; + validate(defs.object, node, "object", object, 1); + validate(defs.property, node, "property", property, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.optional, node, "optional", optional); + return node; + } + function newExpression(callee, _arguments) { + const node = { + type: "NewExpression", + callee, + arguments: _arguments + }; + const defs = NODE_FIELDS.NewExpression; + validate(defs.callee, node, "callee", callee, 1); + validate(defs.arguments, node, "arguments", _arguments, 1); + return node; + } + function program(body, directives = [], sourceType = "script", interpreter = null) { + const node = { + type: "Program", + body, + directives, + sourceType, + interpreter + }; + const defs = NODE_FIELDS.Program; + validate(defs.body, node, "body", body, 1); + validate(defs.directives, node, "directives", directives, 1); + validate(defs.sourceType, node, "sourceType", sourceType); + validate(defs.interpreter, node, "interpreter", interpreter, 1); + return node; + } + function objectExpression(properties) { + const node = { + type: "ObjectExpression", + properties + }; + const defs = NODE_FIELDS.ObjectExpression; + validate(defs.properties, node, "properties", properties, 1); + return node; + } + function objectMethod(kind = "method", key, params, body, computed = false, generator = false, async = false) { + const node = { + type: "ObjectMethod", + kind, + key, + params, + body, + computed, + generator, + async + }; + const defs = NODE_FIELDS.ObjectMethod; + validate(defs.kind, node, "kind", kind); + validate(defs.key, node, "key", key, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.generator, node, "generator", generator); + validate(defs.async, node, "async", async); + return node; + } + function objectProperty(key, value, computed = false, shorthand = false, decorators = null) { + const node = { + type: "ObjectProperty", + key, + value, + computed, + shorthand, + decorators + }; + const defs = NODE_FIELDS.ObjectProperty; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.shorthand, node, "shorthand", shorthand); + validate(defs.decorators, node, "decorators", decorators, 1); + return node; + } + function restElement(argument) { + const node = { + type: "RestElement", + argument + }; + const defs = NODE_FIELDS.RestElement; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function returnStatement(argument = null) { + const node = { + type: "ReturnStatement", + argument + }; + const defs = NODE_FIELDS.ReturnStatement; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function sequenceExpression(expressions) { + const node = { + type: "SequenceExpression", + expressions + }; + const defs = NODE_FIELDS.SequenceExpression; + validate(defs.expressions, node, "expressions", expressions, 1); + return node; + } + function parenthesizedExpression(expression) { + const node = { + type: "ParenthesizedExpression", + expression + }; + const defs = NODE_FIELDS.ParenthesizedExpression; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function switchCase(test = null, consequent) { + const node = { + type: "SwitchCase", + test, + consequent + }; + const defs = NODE_FIELDS.SwitchCase; + validate(defs.test, node, "test", test, 1); + validate(defs.consequent, node, "consequent", consequent, 1); + return node; + } + function switchStatement(discriminant, cases) { + const node = { + type: "SwitchStatement", + discriminant, + cases + }; + const defs = NODE_FIELDS.SwitchStatement; + validate(defs.discriminant, node, "discriminant", discriminant, 1); + validate(defs.cases, node, "cases", cases, 1); + return node; + } + function thisExpression() { + return { + type: "ThisExpression" + }; + } + function throwStatement(argument) { + const node = { + type: "ThrowStatement", + argument + }; + const defs = NODE_FIELDS.ThrowStatement; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function tryStatement(block, handler = null, finalizer = null) { + const node = { + type: "TryStatement", + block, + handler, + finalizer + }; + const defs = NODE_FIELDS.TryStatement; + validate(defs.block, node, "block", block, 1); + validate(defs.handler, node, "handler", handler, 1); + validate(defs.finalizer, node, "finalizer", finalizer, 1); + return node; + } + function unaryExpression(operator, argument, prefix = true) { + const node = { + type: "UnaryExpression", + operator, + argument, + prefix + }; + const defs = NODE_FIELDS.UnaryExpression; + validate(defs.operator, node, "operator", operator); + validate(defs.argument, node, "argument", argument, 1); + validate(defs.prefix, node, "prefix", prefix); + return node; + } + function updateExpression(operator, argument, prefix = false) { + const node = { + type: "UpdateExpression", + operator, + argument, + prefix + }; + const defs = NODE_FIELDS.UpdateExpression; + validate(defs.operator, node, "operator", operator); + validate(defs.argument, node, "argument", argument, 1); + validate(defs.prefix, node, "prefix", prefix); + return node; + } + function variableDeclaration(kind, declarations) { + const node = { + type: "VariableDeclaration", + kind, + declarations + }; + const defs = NODE_FIELDS.VariableDeclaration; + validate(defs.kind, node, "kind", kind); + validate(defs.declarations, node, "declarations", declarations, 1); + return node; + } + function variableDeclarator(id, init = null) { + const node = { + type: "VariableDeclarator", + id, + init + }; + const defs = NODE_FIELDS.VariableDeclarator; + validate(defs.id, node, "id", id, 1); + validate(defs.init, node, "init", init, 1); + return node; + } + function whileStatement(test, body) { + const node = { + type: "WhileStatement", + test, + body + }; + const defs = NODE_FIELDS.WhileStatement; + validate(defs.test, node, "test", test, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function withStatement(object, body) { + const node = { + type: "WithStatement", + object, + body + }; + const defs = NODE_FIELDS.WithStatement; + validate(defs.object, node, "object", object, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function assignmentPattern(left, right) { + const node = { + type: "AssignmentPattern", + left, + right + }; + const defs = NODE_FIELDS.AssignmentPattern; + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function arrayPattern(elements) { + const node = { + type: "ArrayPattern", + elements + }; + const defs = NODE_FIELDS.ArrayPattern; + validate(defs.elements, node, "elements", elements, 1); + return node; + } + function arrowFunctionExpression(params, body, async = false) { + const node = { + type: "ArrowFunctionExpression", + params, + body, + async, + expression: null + }; + const defs = NODE_FIELDS.ArrowFunctionExpression; + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.async, node, "async", async); + return node; + } + function classBody(body) { + const node = { + type: "ClassBody", + body + }; + const defs = NODE_FIELDS.ClassBody; + validate(defs.body, node, "body", body, 1); + return node; + } + function classExpression(id = null, superClass = null, body, decorators = null) { + const node = { + type: "ClassExpression", + id, + superClass, + body, + decorators + }; + const defs = NODE_FIELDS.ClassExpression; + validate(defs.id, node, "id", id, 1); + validate(defs.superClass, node, "superClass", superClass, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.decorators, node, "decorators", decorators, 1); + return node; + } + function classDeclaration(id = null, superClass = null, body, decorators = null) { + const node = { + type: "ClassDeclaration", + id, + superClass, + body, + decorators + }; + const defs = NODE_FIELDS.ClassDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.superClass, node, "superClass", superClass, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.decorators, node, "decorators", decorators, 1); + return node; + } + function exportAllDeclaration(source) { + const node = { + type: "ExportAllDeclaration", + source + }; + const defs = NODE_FIELDS.ExportAllDeclaration; + validate(defs.source, node, "source", source, 1); + return node; + } + function exportDefaultDeclaration(declaration) { + const node = { + type: "ExportDefaultDeclaration", + declaration + }; + const defs = NODE_FIELDS.ExportDefaultDeclaration; + validate(defs.declaration, node, "declaration", declaration, 1); + return node; + } + function exportNamedDeclaration(declaration = null, specifiers = [], source = null) { + const node = { + type: "ExportNamedDeclaration", + declaration, + specifiers, + source + }; + const defs = NODE_FIELDS.ExportNamedDeclaration; + validate(defs.declaration, node, "declaration", declaration, 1); + validate(defs.specifiers, node, "specifiers", specifiers, 1); + validate(defs.source, node, "source", source, 1); + return node; + } + function exportSpecifier(local, exported) { + const node = { + type: "ExportSpecifier", + local, + exported + }; + const defs = NODE_FIELDS.ExportSpecifier; + validate(defs.local, node, "local", local, 1); + validate(defs.exported, node, "exported", exported, 1); + return node; + } + function forOfStatement(left, right, body, _await = false) { + const node = { + type: "ForOfStatement", + left, + right, + body, + await: _await + }; + const defs = NODE_FIELDS.ForOfStatement; + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.await, node, "await", _await); + return node; + } + function importDeclaration(specifiers, source) { + const node = { + type: "ImportDeclaration", + specifiers, + source + }; + const defs = NODE_FIELDS.ImportDeclaration; + validate(defs.specifiers, node, "specifiers", specifiers, 1); + validate(defs.source, node, "source", source, 1); + return node; + } + function importDefaultSpecifier(local) { + const node = { + type: "ImportDefaultSpecifier", + local + }; + const defs = NODE_FIELDS.ImportDefaultSpecifier; + validate(defs.local, node, "local", local, 1); + return node; + } + function importNamespaceSpecifier(local) { + const node = { + type: "ImportNamespaceSpecifier", + local + }; + const defs = NODE_FIELDS.ImportNamespaceSpecifier; + validate(defs.local, node, "local", local, 1); + return node; + } + function importSpecifier(local, imported) { + const node = { + type: "ImportSpecifier", + local, + imported + }; + const defs = NODE_FIELDS.ImportSpecifier; + validate(defs.local, node, "local", local, 1); + validate(defs.imported, node, "imported", imported, 1); + return node; + } + function importExpression(source, options = null) { + const node = { + type: "ImportExpression", + source, + options + }; + const defs = NODE_FIELDS.ImportExpression; + validate(defs.source, node, "source", source, 1); + validate(defs.options, node, "options", options, 1); + return node; + } + function metaProperty(meta, property) { + const node = { + type: "MetaProperty", + meta, + property + }; + const defs = NODE_FIELDS.MetaProperty; + validate(defs.meta, node, "meta", meta, 1); + validate(defs.property, node, "property", property, 1); + return node; + } + function classMethod(kind = "method", key, params, body, computed = false, _static = false, generator = false, async = false) { + const node = { + type: "ClassMethod", + kind, + key, + params, + body, + computed, + static: _static, + generator, + async + }; + const defs = NODE_FIELDS.ClassMethod; + validate(defs.kind, node, "kind", kind); + validate(defs.key, node, "key", key, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.static, node, "static", _static); + validate(defs.generator, node, "generator", generator); + validate(defs.async, node, "async", async); + return node; + } + function objectPattern(properties) { + const node = { + type: "ObjectPattern", + properties + }; + const defs = NODE_FIELDS.ObjectPattern; + validate(defs.properties, node, "properties", properties, 1); + return node; + } + function spreadElement(argument) { + const node = { + type: "SpreadElement", + argument + }; + const defs = NODE_FIELDS.SpreadElement; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function _super() { + return { + type: "Super" + }; + } + function taggedTemplateExpression(tag, quasi) { + const node = { + type: "TaggedTemplateExpression", + tag, + quasi + }; + const defs = NODE_FIELDS.TaggedTemplateExpression; + validate(defs.tag, node, "tag", tag, 1); + validate(defs.quasi, node, "quasi", quasi, 1); + return node; + } + function templateElement(value, tail = false) { + const node = { + type: "TemplateElement", + value, + tail + }; + const defs = NODE_FIELDS.TemplateElement; + validate(defs.value, node, "value", value); + validate(defs.tail, node, "tail", tail); + return node; + } + function templateLiteral(quasis, expressions) { + const node = { + type: "TemplateLiteral", + quasis, + expressions + }; + const defs = NODE_FIELDS.TemplateLiteral; + validate(defs.quasis, node, "quasis", quasis, 1); + validate(defs.expressions, node, "expressions", expressions, 1); + return node; + } + function yieldExpression(argument = null, delegate = false) { + const node = { + type: "YieldExpression", + argument, + delegate + }; + const defs = NODE_FIELDS.YieldExpression; + validate(defs.argument, node, "argument", argument, 1); + validate(defs.delegate, node, "delegate", delegate); + return node; + } + function awaitExpression(argument) { + const node = { + type: "AwaitExpression", + argument + }; + const defs = NODE_FIELDS.AwaitExpression; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function _import() { + return { + type: "Import" + }; + } + function bigIntLiteral(value) { + const node = { + type: "BigIntLiteral", + value + }; + const defs = NODE_FIELDS.BigIntLiteral; + validate(defs.value, node, "value", value); + return node; + } + function exportNamespaceSpecifier(exported) { + const node = { + type: "ExportNamespaceSpecifier", + exported + }; + const defs = NODE_FIELDS.ExportNamespaceSpecifier; + validate(defs.exported, node, "exported", exported, 1); + return node; + } + function optionalMemberExpression(object, property, computed = false, optional) { + const node = { + type: "OptionalMemberExpression", + object, + property, + computed, + optional + }; + const defs = NODE_FIELDS.OptionalMemberExpression; + validate(defs.object, node, "object", object, 1); + validate(defs.property, node, "property", property, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.optional, node, "optional", optional); + return node; + } + function optionalCallExpression(callee, _arguments, optional) { + const node = { + type: "OptionalCallExpression", + callee, + arguments: _arguments, + optional + }; + const defs = NODE_FIELDS.OptionalCallExpression; + validate(defs.callee, node, "callee", callee, 1); + validate(defs.arguments, node, "arguments", _arguments, 1); + validate(defs.optional, node, "optional", optional); + return node; + } + function classProperty(key, value = null, typeAnnotation = null, decorators = null, computed = false, _static = false) { + const node = { + type: "ClassProperty", + key, + value, + typeAnnotation, + decorators, + computed, + static: _static + }; + const defs = NODE_FIELDS.ClassProperty; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + validate(defs.decorators, node, "decorators", decorators, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.static, node, "static", _static); + return node; + } + function classAccessorProperty(key, value = null, typeAnnotation = null, decorators = null, computed = false, _static = false) { + const node = { + type: "ClassAccessorProperty", + key, + value, + typeAnnotation, + decorators, + computed, + static: _static + }; + const defs = NODE_FIELDS.ClassAccessorProperty; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + validate(defs.decorators, node, "decorators", decorators, 1); + validate(defs.computed, node, "computed", computed); + validate(defs.static, node, "static", _static); + return node; + } + function classPrivateProperty(key, value = null, decorators = null, _static = false) { + const node = { + type: "ClassPrivateProperty", + key, + value, + decorators, + static: _static + }; + const defs = NODE_FIELDS.ClassPrivateProperty; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.decorators, node, "decorators", decorators, 1); + validate(defs.static, node, "static", _static); + return node; + } + function classPrivateMethod(kind = "method", key, params, body, _static = false) { + const node = { + type: "ClassPrivateMethod", + kind, + key, + params, + body, + static: _static + }; + const defs = NODE_FIELDS.ClassPrivateMethod; + validate(defs.kind, node, "kind", kind); + validate(defs.key, node, "key", key, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.static, node, "static", _static); + return node; + } + function privateName(id) { + const node = { + type: "PrivateName", + id + }; + const defs = NODE_FIELDS.PrivateName; + validate(defs.id, node, "id", id, 1); + return node; + } + function staticBlock(body) { + const node = { + type: "StaticBlock", + body + }; + const defs = NODE_FIELDS.StaticBlock; + validate(defs.body, node, "body", body, 1); + return node; + } + function anyTypeAnnotation() { + return { + type: "AnyTypeAnnotation" + }; + } + function arrayTypeAnnotation(elementType) { + const node = { + type: "ArrayTypeAnnotation", + elementType + }; + const defs = NODE_FIELDS.ArrayTypeAnnotation; + validate(defs.elementType, node, "elementType", elementType, 1); + return node; + } + function booleanTypeAnnotation() { + return { + type: "BooleanTypeAnnotation" + }; + } + function booleanLiteralTypeAnnotation(value) { + const node = { + type: "BooleanLiteralTypeAnnotation", + value + }; + const defs = NODE_FIELDS.BooleanLiteralTypeAnnotation; + validate(defs.value, node, "value", value); + return node; + } + function nullLiteralTypeAnnotation() { + return { + type: "NullLiteralTypeAnnotation" + }; + } + function classImplements(id, typeParameters = null) { + const node = { + type: "ClassImplements", + id, + typeParameters + }; + const defs = NODE_FIELDS.ClassImplements; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function declareClass(id, typeParameters = null, _extends = null, body) { + const node = { + type: "DeclareClass", + id, + typeParameters, + extends: _extends, + body + }; + const defs = NODE_FIELDS.DeclareClass; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.extends, node, "extends", _extends, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function declareFunction(id) { + const node = { + type: "DeclareFunction", + id + }; + const defs = NODE_FIELDS.DeclareFunction; + validate(defs.id, node, "id", id, 1); + return node; + } + function declareInterface(id, typeParameters = null, _extends = null, body) { + const node = { + type: "DeclareInterface", + id, + typeParameters, + extends: _extends, + body + }; + const defs = NODE_FIELDS.DeclareInterface; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.extends, node, "extends", _extends, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function declareModule(id, body, kind = null) { + const node = { + type: "DeclareModule", + id, + body, + kind + }; + const defs = NODE_FIELDS.DeclareModule; + validate(defs.id, node, "id", id, 1); + validate(defs.body, node, "body", body, 1); + validate(defs.kind, node, "kind", kind); + return node; + } + function declareModuleExports(typeAnnotation) { + const node = { + type: "DeclareModuleExports", + typeAnnotation + }; + const defs = NODE_FIELDS.DeclareModuleExports; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function declareTypeAlias(id, typeParameters = null, right) { + const node = { + type: "DeclareTypeAlias", + id, + typeParameters, + right + }; + const defs = NODE_FIELDS.DeclareTypeAlias; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function declareOpaqueType(id, typeParameters = null, supertype = null) { + const node = { + type: "DeclareOpaqueType", + id, + typeParameters, + supertype + }; + const defs = NODE_FIELDS.DeclareOpaqueType; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.supertype, node, "supertype", supertype, 1); + return node; + } + function declareVariable(id) { + const node = { + type: "DeclareVariable", + id + }; + const defs = NODE_FIELDS.DeclareVariable; + validate(defs.id, node, "id", id, 1); + return node; + } + function declareExportDeclaration(declaration = null, specifiers = null, source = null, attributes = null) { + const node = { + type: "DeclareExportDeclaration", + declaration, + specifiers, + source, + attributes + }; + const defs = NODE_FIELDS.DeclareExportDeclaration; + validate(defs.declaration, node, "declaration", declaration, 1); + validate(defs.specifiers, node, "specifiers", specifiers, 1); + validate(defs.source, node, "source", source, 1); + validate(defs.attributes, node, "attributes", attributes, 1); + return node; + } + function declareExportAllDeclaration(source, attributes = null) { + const node = { + type: "DeclareExportAllDeclaration", + source, + attributes + }; + const defs = NODE_FIELDS.DeclareExportAllDeclaration; + validate(defs.source, node, "source", source, 1); + validate(defs.attributes, node, "attributes", attributes, 1); + return node; + } + function declaredPredicate(value) { + const node = { + type: "DeclaredPredicate", + value + }; + const defs = NODE_FIELDS.DeclaredPredicate; + validate(defs.value, node, "value", value, 1); + return node; + } + function existsTypeAnnotation() { + return { + type: "ExistsTypeAnnotation" + }; + } + function functionTypeAnnotation(typeParameters = null, params, rest = null, returnType) { + const node = { + type: "FunctionTypeAnnotation", + typeParameters, + params, + rest, + returnType + }; + const defs = NODE_FIELDS.FunctionTypeAnnotation; + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.rest, node, "rest", rest, 1); + validate(defs.returnType, node, "returnType", returnType, 1); + return node; + } + function functionTypeParam(name = null, typeAnnotation) { + const node = { + type: "FunctionTypeParam", + name, + typeAnnotation + }; + const defs = NODE_FIELDS.FunctionTypeParam; + validate(defs.name, node, "name", name, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function genericTypeAnnotation(id, typeParameters = null) { + const node = { + type: "GenericTypeAnnotation", + id, + typeParameters + }; + const defs = NODE_FIELDS.GenericTypeAnnotation; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function inferredPredicate() { + return { + type: "InferredPredicate" + }; + } + function interfaceExtends(id, typeParameters = null) { + const node = { + type: "InterfaceExtends", + id, + typeParameters + }; + const defs = NODE_FIELDS.InterfaceExtends; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function interfaceDeclaration(id, typeParameters = null, _extends = null, body) { + const node = { + type: "InterfaceDeclaration", + id, + typeParameters, + extends: _extends, + body + }; + const defs = NODE_FIELDS.InterfaceDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.extends, node, "extends", _extends, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function interfaceTypeAnnotation(_extends = null, body) { + const node = { + type: "InterfaceTypeAnnotation", + extends: _extends, + body + }; + const defs = NODE_FIELDS.InterfaceTypeAnnotation; + validate(defs.extends, node, "extends", _extends, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function intersectionTypeAnnotation(types) { + const node = { + type: "IntersectionTypeAnnotation", + types + }; + const defs = NODE_FIELDS.IntersectionTypeAnnotation; + validate(defs.types, node, "types", types, 1); + return node; + } + function mixedTypeAnnotation() { + return { + type: "MixedTypeAnnotation" + }; + } + function emptyTypeAnnotation() { + return { + type: "EmptyTypeAnnotation" + }; + } + function nullableTypeAnnotation(typeAnnotation) { + const node = { + type: "NullableTypeAnnotation", + typeAnnotation + }; + const defs = NODE_FIELDS.NullableTypeAnnotation; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function numberLiteralTypeAnnotation(value) { + const node = { + type: "NumberLiteralTypeAnnotation", + value + }; + const defs = NODE_FIELDS.NumberLiteralTypeAnnotation; + validate(defs.value, node, "value", value); + return node; + } + function numberTypeAnnotation() { + return { + type: "NumberTypeAnnotation" + }; + } + function objectTypeAnnotation(properties, indexers = [], callProperties = [], internalSlots = [], exact = false) { + const node = { + type: "ObjectTypeAnnotation", + properties, + indexers, + callProperties, + internalSlots, + exact + }; + const defs = NODE_FIELDS.ObjectTypeAnnotation; + validate(defs.properties, node, "properties", properties, 1); + validate(defs.indexers, node, "indexers", indexers, 1); + validate(defs.callProperties, node, "callProperties", callProperties, 1); + validate(defs.internalSlots, node, "internalSlots", internalSlots, 1); + validate(defs.exact, node, "exact", exact); + return node; + } + function objectTypeInternalSlot(id, value, optional, _static, method) { + const node = { + type: "ObjectTypeInternalSlot", + id, + value, + optional, + static: _static, + method + }; + const defs = NODE_FIELDS.ObjectTypeInternalSlot; + validate(defs.id, node, "id", id, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.optional, node, "optional", optional); + validate(defs.static, node, "static", _static); + validate(defs.method, node, "method", method); + return node; + } + function objectTypeCallProperty(value) { + const node = { + type: "ObjectTypeCallProperty", + value, + static: null + }; + const defs = NODE_FIELDS.ObjectTypeCallProperty; + validate(defs.value, node, "value", value, 1); + return node; + } + function objectTypeIndexer(id = null, key, value, variance = null) { + const node = { + type: "ObjectTypeIndexer", + id, + key, + value, + variance, + static: null + }; + const defs = NODE_FIELDS.ObjectTypeIndexer; + validate(defs.id, node, "id", id, 1); + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.variance, node, "variance", variance, 1); + return node; + } + function objectTypeProperty(key, value, variance = null) { + const node = { + type: "ObjectTypeProperty", + key, + value, + variance, + kind: null, + method: null, + optional: null, + proto: null, + static: null + }; + const defs = NODE_FIELDS.ObjectTypeProperty; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + validate(defs.variance, node, "variance", variance, 1); + return node; + } + function objectTypeSpreadProperty(argument) { + const node = { + type: "ObjectTypeSpreadProperty", + argument + }; + const defs = NODE_FIELDS.ObjectTypeSpreadProperty; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function opaqueType(id, typeParameters = null, supertype = null, impltype) { + const node = { + type: "OpaqueType", + id, + typeParameters, + supertype, + impltype + }; + const defs = NODE_FIELDS.OpaqueType; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.supertype, node, "supertype", supertype, 1); + validate(defs.impltype, node, "impltype", impltype, 1); + return node; + } + function qualifiedTypeIdentifier(id, qualification) { + const node = { + type: "QualifiedTypeIdentifier", + id, + qualification + }; + const defs = NODE_FIELDS.QualifiedTypeIdentifier; + validate(defs.id, node, "id", id, 1); + validate(defs.qualification, node, "qualification", qualification, 1); + return node; + } + function stringLiteralTypeAnnotation(value) { + const node = { + type: "StringLiteralTypeAnnotation", + value + }; + const defs = NODE_FIELDS.StringLiteralTypeAnnotation; + validate(defs.value, node, "value", value); + return node; + } + function stringTypeAnnotation() { + return { + type: "StringTypeAnnotation" + }; + } + function symbolTypeAnnotation() { + return { + type: "SymbolTypeAnnotation" + }; + } + function thisTypeAnnotation() { + return { + type: "ThisTypeAnnotation" + }; + } + function tupleTypeAnnotation(types) { + const node = { + type: "TupleTypeAnnotation", + types + }; + const defs = NODE_FIELDS.TupleTypeAnnotation; + validate(defs.types, node, "types", types, 1); + return node; + } + function typeofTypeAnnotation(argument) { + const node = { + type: "TypeofTypeAnnotation", + argument + }; + const defs = NODE_FIELDS.TypeofTypeAnnotation; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function typeAlias(id, typeParameters = null, right) { + const node = { + type: "TypeAlias", + id, + typeParameters, + right + }; + const defs = NODE_FIELDS.TypeAlias; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function typeAnnotation(typeAnnotation) { + const node = { + type: "TypeAnnotation", + typeAnnotation + }; + const defs = NODE_FIELDS.TypeAnnotation; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function typeCastExpression(expression, typeAnnotation) { + const node = { + type: "TypeCastExpression", + expression, + typeAnnotation + }; + const defs = NODE_FIELDS.TypeCastExpression; + validate(defs.expression, node, "expression", expression, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function typeParameter(bound = null, _default = null, variance = null) { + const node = { + type: "TypeParameter", + bound, + default: _default, + variance, + name: null + }; + const defs = NODE_FIELDS.TypeParameter; + validate(defs.bound, node, "bound", bound, 1); + validate(defs.default, node, "default", _default, 1); + validate(defs.variance, node, "variance", variance, 1); + return node; + } + function typeParameterDeclaration(params) { + const node = { + type: "TypeParameterDeclaration", + params + }; + const defs = NODE_FIELDS.TypeParameterDeclaration; + validate(defs.params, node, "params", params, 1); + return node; + } + function typeParameterInstantiation(params) { + const node = { + type: "TypeParameterInstantiation", + params + }; + const defs = NODE_FIELDS.TypeParameterInstantiation; + validate(defs.params, node, "params", params, 1); + return node; + } + function unionTypeAnnotation(types) { + const node = { + type: "UnionTypeAnnotation", + types + }; + const defs = NODE_FIELDS.UnionTypeAnnotation; + validate(defs.types, node, "types", types, 1); + return node; + } + function variance(kind) { + const node = { + type: "Variance", + kind + }; + const defs = NODE_FIELDS.Variance; + validate(defs.kind, node, "kind", kind); + return node; + } + function voidTypeAnnotation() { + return { + type: "VoidTypeAnnotation" + }; + } + function enumDeclaration(id, body) { + const node = { + type: "EnumDeclaration", + id, + body + }; + const defs = NODE_FIELDS.EnumDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function enumBooleanBody(members) { + const node = { + type: "EnumBooleanBody", + members, + explicitType: null, + hasUnknownMembers: null + }; + const defs = NODE_FIELDS.EnumBooleanBody; + validate(defs.members, node, "members", members, 1); + return node; + } + function enumNumberBody(members) { + const node = { + type: "EnumNumberBody", + members, + explicitType: null, + hasUnknownMembers: null + }; + const defs = NODE_FIELDS.EnumNumberBody; + validate(defs.members, node, "members", members, 1); + return node; + } + function enumStringBody(members) { + const node = { + type: "EnumStringBody", + members, + explicitType: null, + hasUnknownMembers: null + }; + const defs = NODE_FIELDS.EnumStringBody; + validate(defs.members, node, "members", members, 1); + return node; + } + function enumSymbolBody(members) { + const node = { + type: "EnumSymbolBody", + members, + hasUnknownMembers: null + }; + const defs = NODE_FIELDS.EnumSymbolBody; + validate(defs.members, node, "members", members, 1); + return node; + } + function enumBooleanMember(id) { + const node = { + type: "EnumBooleanMember", + id, + init: null + }; + const defs = NODE_FIELDS.EnumBooleanMember; + validate(defs.id, node, "id", id, 1); + return node; + } + function enumNumberMember(id, init) { + const node = { + type: "EnumNumberMember", + id, + init + }; + const defs = NODE_FIELDS.EnumNumberMember; + validate(defs.id, node, "id", id, 1); + validate(defs.init, node, "init", init, 1); + return node; + } + function enumStringMember(id, init) { + const node = { + type: "EnumStringMember", + id, + init + }; + const defs = NODE_FIELDS.EnumStringMember; + validate(defs.id, node, "id", id, 1); + validate(defs.init, node, "init", init, 1); + return node; + } + function enumDefaultedMember(id) { + const node = { + type: "EnumDefaultedMember", + id + }; + const defs = NODE_FIELDS.EnumDefaultedMember; + validate(defs.id, node, "id", id, 1); + return node; + } + function indexedAccessType(objectType, indexType) { + const node = { + type: "IndexedAccessType", + objectType, + indexType + }; + const defs = NODE_FIELDS.IndexedAccessType; + validate(defs.objectType, node, "objectType", objectType, 1); + validate(defs.indexType, node, "indexType", indexType, 1); + return node; + } + function optionalIndexedAccessType(objectType, indexType) { + const node = { + type: "OptionalIndexedAccessType", + objectType, + indexType, + optional: null + }; + const defs = NODE_FIELDS.OptionalIndexedAccessType; + validate(defs.objectType, node, "objectType", objectType, 1); + validate(defs.indexType, node, "indexType", indexType, 1); + return node; + } + function jsxAttribute(name, value = null) { + const node = { + type: "JSXAttribute", + name, + value + }; + const defs = NODE_FIELDS.JSXAttribute; + validate(defs.name, node, "name", name, 1); + validate(defs.value, node, "value", value, 1); + return node; + } + function jsxClosingElement(name) { + const node = { + type: "JSXClosingElement", + name + }; + const defs = NODE_FIELDS.JSXClosingElement; + validate(defs.name, node, "name", name, 1); + return node; + } + function jsxElement(openingElement, closingElement = null, children, selfClosing = null) { + const node = { + type: "JSXElement", + openingElement, + closingElement, + children, + selfClosing + }; + const defs = NODE_FIELDS.JSXElement; + validate(defs.openingElement, node, "openingElement", openingElement, 1); + validate(defs.closingElement, node, "closingElement", closingElement, 1); + validate(defs.children, node, "children", children, 1); + validate(defs.selfClosing, node, "selfClosing", selfClosing); + return node; + } + function jsxEmptyExpression() { + return { + type: "JSXEmptyExpression" + }; + } + function jsxExpressionContainer(expression) { + const node = { + type: "JSXExpressionContainer", + expression + }; + const defs = NODE_FIELDS.JSXExpressionContainer; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function jsxSpreadChild(expression) { + const node = { + type: "JSXSpreadChild", + expression + }; + const defs = NODE_FIELDS.JSXSpreadChild; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function jsxIdentifier(name) { + const node = { + type: "JSXIdentifier", + name + }; + const defs = NODE_FIELDS.JSXIdentifier; + validate(defs.name, node, "name", name); + return node; + } + function jsxMemberExpression(object, property) { + const node = { + type: "JSXMemberExpression", + object, + property + }; + const defs = NODE_FIELDS.JSXMemberExpression; + validate(defs.object, node, "object", object, 1); + validate(defs.property, node, "property", property, 1); + return node; + } + function jsxNamespacedName(namespace, name) { + const node = { + type: "JSXNamespacedName", + namespace, + name + }; + const defs = NODE_FIELDS.JSXNamespacedName; + validate(defs.namespace, node, "namespace", namespace, 1); + validate(defs.name, node, "name", name, 1); + return node; + } + function jsxOpeningElement(name, attributes, selfClosing = false) { + const node = { + type: "JSXOpeningElement", + name, + attributes, + selfClosing + }; + const defs = NODE_FIELDS.JSXOpeningElement; + validate(defs.name, node, "name", name, 1); + validate(defs.attributes, node, "attributes", attributes, 1); + validate(defs.selfClosing, node, "selfClosing", selfClosing); + return node; + } + function jsxSpreadAttribute(argument) { + const node = { + type: "JSXSpreadAttribute", + argument + }; + const defs = NODE_FIELDS.JSXSpreadAttribute; + validate(defs.argument, node, "argument", argument, 1); + return node; + } + function jsxText(value) { + const node = { + type: "JSXText", + value + }; + const defs = NODE_FIELDS.JSXText; + validate(defs.value, node, "value", value); + return node; + } + function jsxFragment(openingFragment, closingFragment, children) { + const node = { + type: "JSXFragment", + openingFragment, + closingFragment, + children + }; + const defs = NODE_FIELDS.JSXFragment; + validate(defs.openingFragment, node, "openingFragment", openingFragment, 1); + validate(defs.closingFragment, node, "closingFragment", closingFragment, 1); + validate(defs.children, node, "children", children, 1); + return node; + } + function jsxOpeningFragment() { + return { + type: "JSXOpeningFragment" + }; + } + function jsxClosingFragment() { + return { + type: "JSXClosingFragment" + }; + } + function noop() { + return { + type: "Noop" + }; + } + function placeholder(expectedNode, name) { + const node = { + type: "Placeholder", + expectedNode, + name + }; + const defs = NODE_FIELDS.Placeholder; + validate(defs.expectedNode, node, "expectedNode", expectedNode); + validate(defs.name, node, "name", name, 1); + return node; + } + function v8IntrinsicIdentifier(name) { + const node = { + type: "V8IntrinsicIdentifier", + name + }; + const defs = NODE_FIELDS.V8IntrinsicIdentifier; + validate(defs.name, node, "name", name); + return node; + } + function argumentPlaceholder() { + return { + type: "ArgumentPlaceholder" + }; + } + function bindExpression(object, callee) { + const node = { + type: "BindExpression", + object, + callee + }; + const defs = NODE_FIELDS.BindExpression; + validate(defs.object, node, "object", object, 1); + validate(defs.callee, node, "callee", callee, 1); + return node; + } + function importAttribute(key, value) { + const node = { + type: "ImportAttribute", + key, + value + }; + const defs = NODE_FIELDS.ImportAttribute; + validate(defs.key, node, "key", key, 1); + validate(defs.value, node, "value", value, 1); + return node; + } + function decorator(expression) { + const node = { + type: "Decorator", + expression + }; + const defs = NODE_FIELDS.Decorator; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function doExpression(body, async = false) { + const node = { + type: "DoExpression", + body, + async + }; + const defs = NODE_FIELDS.DoExpression; + validate(defs.body, node, "body", body, 1); + validate(defs.async, node, "async", async); + return node; + } + function exportDefaultSpecifier(exported) { + const node = { + type: "ExportDefaultSpecifier", + exported + }; + const defs = NODE_FIELDS.ExportDefaultSpecifier; + validate(defs.exported, node, "exported", exported, 1); + return node; + } + function recordExpression(properties) { + const node = { + type: "RecordExpression", + properties + }; + const defs = NODE_FIELDS.RecordExpression; + validate(defs.properties, node, "properties", properties, 1); + return node; + } + function tupleExpression(elements = []) { + const node = { + type: "TupleExpression", + elements + }; + const defs = NODE_FIELDS.TupleExpression; + validate(defs.elements, node, "elements", elements, 1); + return node; + } + function decimalLiteral(value) { + const node = { + type: "DecimalLiteral", + value + }; + const defs = NODE_FIELDS.DecimalLiteral; + validate(defs.value, node, "value", value); + return node; + } + function moduleExpression(body) { + const node = { + type: "ModuleExpression", + body + }; + const defs = NODE_FIELDS.ModuleExpression; + validate(defs.body, node, "body", body, 1); + return node; + } + function topicReference() { + return { + type: "TopicReference" + }; + } + function pipelineTopicExpression(expression) { + const node = { + type: "PipelineTopicExpression", + expression + }; + const defs = NODE_FIELDS.PipelineTopicExpression; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function pipelineBareFunction(callee) { + const node = { + type: "PipelineBareFunction", + callee + }; + const defs = NODE_FIELDS.PipelineBareFunction; + validate(defs.callee, node, "callee", callee, 1); + return node; + } + function pipelinePrimaryTopicReference() { + return { + type: "PipelinePrimaryTopicReference" + }; + } + function tsParameterProperty(parameter) { + const node = { + type: "TSParameterProperty", + parameter + }; + const defs = NODE_FIELDS.TSParameterProperty; + validate(defs.parameter, node, "parameter", parameter, 1); + return node; + } + function tsDeclareFunction(id = null, typeParameters = null, params, returnType = null) { + const node = { + type: "TSDeclareFunction", + id, + typeParameters, + params, + returnType + }; + const defs = NODE_FIELDS.TSDeclareFunction; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.returnType, node, "returnType", returnType, 1); + return node; + } + function tsDeclareMethod(decorators = null, key, typeParameters = null, params, returnType = null) { + const node = { + type: "TSDeclareMethod", + decorators, + key, + typeParameters, + params, + returnType + }; + const defs = NODE_FIELDS.TSDeclareMethod; + validate(defs.decorators, node, "decorators", decorators, 1); + validate(defs.key, node, "key", key, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.params, node, "params", params, 1); + validate(defs.returnType, node, "returnType", returnType, 1); + return node; + } + function tsQualifiedName(left, right) { + const node = { + type: "TSQualifiedName", + left, + right + }; + const defs = NODE_FIELDS.TSQualifiedName; + validate(defs.left, node, "left", left, 1); + validate(defs.right, node, "right", right, 1); + return node; + } + function tsCallSignatureDeclaration(typeParameters = null, parameters, typeAnnotation = null) { + const node = { + type: "TSCallSignatureDeclaration", + typeParameters, + parameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSCallSignatureDeclaration; + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsConstructSignatureDeclaration(typeParameters = null, parameters, typeAnnotation = null) { + const node = { + type: "TSConstructSignatureDeclaration", + typeParameters, + parameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSConstructSignatureDeclaration; + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsPropertySignature(key, typeAnnotation = null) { + const node = { + type: "TSPropertySignature", + key, + typeAnnotation, + kind: null + }; + const defs = NODE_FIELDS.TSPropertySignature; + validate(defs.key, node, "key", key, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsMethodSignature(key, typeParameters = null, parameters, typeAnnotation = null) { + const node = { + type: "TSMethodSignature", + key, + typeParameters, + parameters, + typeAnnotation, + kind: null + }; + const defs = NODE_FIELDS.TSMethodSignature; + validate(defs.key, node, "key", key, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsIndexSignature(parameters, typeAnnotation = null) { + const node = { + type: "TSIndexSignature", + parameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSIndexSignature; + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsAnyKeyword() { + return { + type: "TSAnyKeyword" + }; + } + function tsBooleanKeyword() { + return { + type: "TSBooleanKeyword" + }; + } + function tsBigIntKeyword() { + return { + type: "TSBigIntKeyword" + }; + } + function tsIntrinsicKeyword() { + return { + type: "TSIntrinsicKeyword" + }; + } + function tsNeverKeyword() { + return { + type: "TSNeverKeyword" + }; + } + function tsNullKeyword() { + return { + type: "TSNullKeyword" + }; + } + function tsNumberKeyword() { + return { + type: "TSNumberKeyword" + }; + } + function tsObjectKeyword() { + return { + type: "TSObjectKeyword" + }; + } + function tsStringKeyword() { + return { + type: "TSStringKeyword" + }; + } + function tsSymbolKeyword() { + return { + type: "TSSymbolKeyword" + }; + } + function tsUndefinedKeyword() { + return { + type: "TSUndefinedKeyword" + }; + } + function tsUnknownKeyword() { + return { + type: "TSUnknownKeyword" + }; + } + function tsVoidKeyword() { + return { + type: "TSVoidKeyword" + }; + } + function tsThisType() { + return { + type: "TSThisType" + }; + } + function tsFunctionType(typeParameters = null, parameters, typeAnnotation = null) { + const node = { + type: "TSFunctionType", + typeParameters, + parameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSFunctionType; + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsConstructorType(typeParameters = null, parameters, typeAnnotation = null) { + const node = { + type: "TSConstructorType", + typeParameters, + parameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSConstructorType; + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.parameters, node, "parameters", parameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsTypeReference(typeName, typeParameters = null) { + const node = { + type: "TSTypeReference", + typeName, + typeParameters + }; + const defs = NODE_FIELDS.TSTypeReference; + validate(defs.typeName, node, "typeName", typeName, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function tsTypePredicate(parameterName, typeAnnotation = null, asserts = null) { + const node = { + type: "TSTypePredicate", + parameterName, + typeAnnotation, + asserts + }; + const defs = NODE_FIELDS.TSTypePredicate; + validate(defs.parameterName, node, "parameterName", parameterName, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + validate(defs.asserts, node, "asserts", asserts); + return node; + } + function tsTypeQuery(exprName, typeParameters = null) { + const node = { + type: "TSTypeQuery", + exprName, + typeParameters + }; + const defs = NODE_FIELDS.TSTypeQuery; + validate(defs.exprName, node, "exprName", exprName, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function tsTypeLiteral(members) { + const node = { + type: "TSTypeLiteral", + members + }; + const defs = NODE_FIELDS.TSTypeLiteral; + validate(defs.members, node, "members", members, 1); + return node; + } + function tsArrayType(elementType) { + const node = { + type: "TSArrayType", + elementType + }; + const defs = NODE_FIELDS.TSArrayType; + validate(defs.elementType, node, "elementType", elementType, 1); + return node; + } + function tsTupleType(elementTypes) { + const node = { + type: "TSTupleType", + elementTypes + }; + const defs = NODE_FIELDS.TSTupleType; + validate(defs.elementTypes, node, "elementTypes", elementTypes, 1); + return node; + } + function tsOptionalType(typeAnnotation) { + const node = { + type: "TSOptionalType", + typeAnnotation + }; + const defs = NODE_FIELDS.TSOptionalType; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsRestType(typeAnnotation) { + const node = { + type: "TSRestType", + typeAnnotation + }; + const defs = NODE_FIELDS.TSRestType; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsNamedTupleMember(label, elementType, optional = false) { + const node = { + type: "TSNamedTupleMember", + label, + elementType, + optional + }; + const defs = NODE_FIELDS.TSNamedTupleMember; + validate(defs.label, node, "label", label, 1); + validate(defs.elementType, node, "elementType", elementType, 1); + validate(defs.optional, node, "optional", optional); + return node; + } + function tsUnionType(types) { + const node = { + type: "TSUnionType", + types + }; + const defs = NODE_FIELDS.TSUnionType; + validate(defs.types, node, "types", types, 1); + return node; + } + function tsIntersectionType(types) { + const node = { + type: "TSIntersectionType", + types + }; + const defs = NODE_FIELDS.TSIntersectionType; + validate(defs.types, node, "types", types, 1); + return node; + } + function tsConditionalType(checkType, extendsType, trueType, falseType) { + const node = { + type: "TSConditionalType", + checkType, + extendsType, + trueType, + falseType + }; + const defs = NODE_FIELDS.TSConditionalType; + validate(defs.checkType, node, "checkType", checkType, 1); + validate(defs.extendsType, node, "extendsType", extendsType, 1); + validate(defs.trueType, node, "trueType", trueType, 1); + validate(defs.falseType, node, "falseType", falseType, 1); + return node; + } + function tsInferType(typeParameter) { + const node = { + type: "TSInferType", + typeParameter + }; + const defs = NODE_FIELDS.TSInferType; + validate(defs.typeParameter, node, "typeParameter", typeParameter, 1); + return node; + } + function tsParenthesizedType(typeAnnotation) { + const node = { + type: "TSParenthesizedType", + typeAnnotation + }; + const defs = NODE_FIELDS.TSParenthesizedType; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsTypeOperator(typeAnnotation) { + const node = { + type: "TSTypeOperator", + typeAnnotation, + operator: null + }; + const defs = NODE_FIELDS.TSTypeOperator; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsIndexedAccessType(objectType, indexType) { + const node = { + type: "TSIndexedAccessType", + objectType, + indexType + }; + const defs = NODE_FIELDS.TSIndexedAccessType; + validate(defs.objectType, node, "objectType", objectType, 1); + validate(defs.indexType, node, "indexType", indexType, 1); + return node; + } + function tsMappedType(typeParameter, typeAnnotation = null, nameType = null) { + const node = { + type: "TSMappedType", + typeParameter, + typeAnnotation, + nameType + }; + const defs = NODE_FIELDS.TSMappedType; + validate(defs.typeParameter, node, "typeParameter", typeParameter, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + validate(defs.nameType, node, "nameType", nameType, 1); + return node; + } + function tsLiteralType(literal) { + const node = { + type: "TSLiteralType", + literal + }; + const defs = NODE_FIELDS.TSLiteralType; + validate(defs.literal, node, "literal", literal, 1); + return node; + } + function tsExpressionWithTypeArguments(expression, typeParameters = null) { + const node = { + type: "TSExpressionWithTypeArguments", + expression, + typeParameters + }; + const defs = NODE_FIELDS.TSExpressionWithTypeArguments; + validate(defs.expression, node, "expression", expression, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function tsInterfaceDeclaration(id, typeParameters = null, _extends = null, body) { + const node = { + type: "TSInterfaceDeclaration", + id, + typeParameters, + extends: _extends, + body + }; + const defs = NODE_FIELDS.TSInterfaceDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.extends, node, "extends", _extends, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function tsInterfaceBody(body) { + const node = { + type: "TSInterfaceBody", + body + }; + const defs = NODE_FIELDS.TSInterfaceBody; + validate(defs.body, node, "body", body, 1); + return node; + } + function tsTypeAliasDeclaration(id, typeParameters = null, typeAnnotation) { + const node = { + type: "TSTypeAliasDeclaration", + id, + typeParameters, + typeAnnotation + }; + const defs = NODE_FIELDS.TSTypeAliasDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsInstantiationExpression(expression, typeParameters = null) { + const node = { + type: "TSInstantiationExpression", + expression, + typeParameters + }; + const defs = NODE_FIELDS.TSInstantiationExpression; + validate(defs.expression, node, "expression", expression, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function tsAsExpression(expression, typeAnnotation) { + const node = { + type: "TSAsExpression", + expression, + typeAnnotation + }; + const defs = NODE_FIELDS.TSAsExpression; + validate(defs.expression, node, "expression", expression, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsSatisfiesExpression(expression, typeAnnotation) { + const node = { + type: "TSSatisfiesExpression", + expression, + typeAnnotation + }; + const defs = NODE_FIELDS.TSSatisfiesExpression; + validate(defs.expression, node, "expression", expression, 1); + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsTypeAssertion(typeAnnotation, expression) { + const node = { + type: "TSTypeAssertion", + typeAnnotation, + expression + }; + const defs = NODE_FIELDS.TSTypeAssertion; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function tsEnumDeclaration(id, members) { + const node = { + type: "TSEnumDeclaration", + id, + members + }; + const defs = NODE_FIELDS.TSEnumDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.members, node, "members", members, 1); + return node; + } + function tsEnumMember(id, initializer = null) { + const node = { + type: "TSEnumMember", + id, + initializer + }; + const defs = NODE_FIELDS.TSEnumMember; + validate(defs.id, node, "id", id, 1); + validate(defs.initializer, node, "initializer", initializer, 1); + return node; + } + function tsModuleDeclaration(id, body) { + const node = { + type: "TSModuleDeclaration", + id, + body, + kind: null + }; + const defs = NODE_FIELDS.TSModuleDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.body, node, "body", body, 1); + return node; + } + function tsModuleBlock(body) { + const node = { + type: "TSModuleBlock", + body + }; + const defs = NODE_FIELDS.TSModuleBlock; + validate(defs.body, node, "body", body, 1); + return node; + } + function tsImportType(argument, qualifier = null, typeParameters = null) { + const node = { + type: "TSImportType", + argument, + qualifier, + typeParameters + }; + const defs = NODE_FIELDS.TSImportType; + validate(defs.argument, node, "argument", argument, 1); + validate(defs.qualifier, node, "qualifier", qualifier, 1); + validate(defs.typeParameters, node, "typeParameters", typeParameters, 1); + return node; + } + function tsImportEqualsDeclaration(id, moduleReference) { + const node = { + type: "TSImportEqualsDeclaration", + id, + moduleReference, + isExport: null + }; + const defs = NODE_FIELDS.TSImportEqualsDeclaration; + validate(defs.id, node, "id", id, 1); + validate(defs.moduleReference, node, "moduleReference", moduleReference, 1); + return node; + } + function tsExternalModuleReference(expression) { + const node = { + type: "TSExternalModuleReference", + expression + }; + const defs = NODE_FIELDS.TSExternalModuleReference; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function tsNonNullExpression(expression) { + const node = { + type: "TSNonNullExpression", + expression + }; + const defs = NODE_FIELDS.TSNonNullExpression; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function tsExportAssignment(expression) { + const node = { + type: "TSExportAssignment", + expression + }; + const defs = NODE_FIELDS.TSExportAssignment; + validate(defs.expression, node, "expression", expression, 1); + return node; + } + function tsNamespaceExportDeclaration(id) { + const node = { + type: "TSNamespaceExportDeclaration", + id + }; + const defs = NODE_FIELDS.TSNamespaceExportDeclaration; + validate(defs.id, node, "id", id, 1); + return node; + } + function tsTypeAnnotation(typeAnnotation) { + const node = { + type: "TSTypeAnnotation", + typeAnnotation + }; + const defs = NODE_FIELDS.TSTypeAnnotation; + validate(defs.typeAnnotation, node, "typeAnnotation", typeAnnotation, 1); + return node; + } + function tsTypeParameterInstantiation(params) { + const node = { + type: "TSTypeParameterInstantiation", + params + }; + const defs = NODE_FIELDS.TSTypeParameterInstantiation; + validate(defs.params, node, "params", params, 1); + return node; + } + function tsTypeParameterDeclaration(params) { + const node = { + type: "TSTypeParameterDeclaration", + params + }; + const defs = NODE_FIELDS.TSTypeParameterDeclaration; + validate(defs.params, node, "params", params, 1); + return node; + } + function tsTypeParameter(constraint = null, _default = null, name) { + const node = { + type: "TSTypeParameter", + constraint, + default: _default, + name + }; + const defs = NODE_FIELDS.TSTypeParameter; + validate(defs.constraint, node, "constraint", constraint, 1); + validate(defs.default, node, "default", _default, 1); + validate(defs.name, node, "name", name); + return node; + } + function NumberLiteral(value) { + (0, _deprecationWarning.default)("NumberLiteral", "NumericLiteral", "The node type "); + return numericLiteral(value); + } + function RegexLiteral(pattern, flags = "") { + (0, _deprecationWarning.default)("RegexLiteral", "RegExpLiteral", "The node type "); + return regExpLiteral(pattern, flags); + } + function RestProperty(argument) { + (0, _deprecationWarning.default)("RestProperty", "RestElement", "The node type "); + return restElement(argument); + } + function SpreadProperty(argument) { + (0, _deprecationWarning.default)("SpreadProperty", "SpreadElement", "The node type "); + return spreadElement(argument); + } + + + return generated$2; +} + +var hasRequiredCleanJSXElementLiteralChild; + +function requireCleanJSXElementLiteralChild () { + if (hasRequiredCleanJSXElementLiteralChild) return cleanJSXElementLiteralChild; + hasRequiredCleanJSXElementLiteralChild = 1; + + Object.defineProperty(cleanJSXElementLiteralChild, "__esModule", { + value: true + }); + cleanJSXElementLiteralChild.default = cleanJSXElementLiteralChild$1; + var _index = requireGenerated$2(); + var _index2 = requireLib$1(); + function cleanJSXElementLiteralChild$1(child, args) { + const lines = child.value.split(/\r\n|\n|\r/); + let lastNonEmptyLine = 0; + for (let i = 0; i < lines.length; i++) { + if (/[^ \t]/.exec(lines[i])) { + lastNonEmptyLine = i; + } + } + let str = ""; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const isFirstLine = i === 0; + const isLastLine = i === lines.length - 1; + const isLastNonEmptyLine = i === lastNonEmptyLine; + let trimmedLine = line.replace(/\t/g, " "); + if (!isFirstLine) { + trimmedLine = trimmedLine.replace(/^ +/, ""); + } + if (!isLastLine) { + trimmedLine = trimmedLine.replace(/ +$/, ""); + } + if (trimmedLine) { + if (!isLastNonEmptyLine) { + trimmedLine += " "; + } + str += trimmedLine; + } + } + if (str) args.push((0, _index2.inherits)((0, _index.stringLiteral)(str), child)); + } + + + return cleanJSXElementLiteralChild; +} + +var hasRequiredBuildChildren; + +function requireBuildChildren () { + if (hasRequiredBuildChildren) return buildChildren; + hasRequiredBuildChildren = 1; + + Object.defineProperty(buildChildren, "__esModule", { + value: true + }); + buildChildren.default = buildChildren$1; + var _index = requireGenerated$3(); + var _cleanJSXElementLiteralChild = requireCleanJSXElementLiteralChild(); + function buildChildren$1(node) { + const elements = []; + for (let i = 0; i < node.children.length; i++) { + let child = node.children[i]; + if ((0, _index.isJSXText)(child)) { + (0, _cleanJSXElementLiteralChild.default)(child, elements); + continue; + } + if ((0, _index.isJSXExpressionContainer)(child)) child = child.expression; + if ((0, _index.isJSXEmptyExpression)(child)) continue; + elements.push(child); + } + return elements; + } + + + return buildChildren; +} + +var assertNode = {}; + +var isNode = {}; + +var hasRequiredIsNode; + +function requireIsNode () { + if (hasRequiredIsNode) return isNode; + hasRequiredIsNode = 1; + + Object.defineProperty(isNode, "__esModule", { + value: true + }); + isNode.default = isNode$1; + var _index = requireDefinitions(); + function isNode$1(node) { + return !!(node && _index.VISITOR_KEYS[node.type]); + } + + + return isNode; +} + +var hasRequiredAssertNode; + +function requireAssertNode () { + if (hasRequiredAssertNode) return assertNode; + hasRequiredAssertNode = 1; + + Object.defineProperty(assertNode, "__esModule", { + value: true + }); + assertNode.default = assertNode$1; + var _isNode = requireIsNode(); + function assertNode$1(node) { + if (!(0, _isNode.default)(node)) { + var _node$type; + const type = (_node$type = node == null ? void 0 : node.type) != null ? _node$type : JSON.stringify(node); + throw new TypeError(`Not a valid node of type "${type}"`); + } + } + + + return assertNode; +} + +var generated$1 = {}; + +var hasRequiredGenerated$1; + +function requireGenerated$1 () { + if (hasRequiredGenerated$1) return generated$1; + hasRequiredGenerated$1 = 1; + + Object.defineProperty(generated$1, "__esModule", { + value: true + }); + generated$1.assertAccessor = assertAccessor; + generated$1.assertAnyTypeAnnotation = assertAnyTypeAnnotation; + generated$1.assertArgumentPlaceholder = assertArgumentPlaceholder; + generated$1.assertArrayExpression = assertArrayExpression; + generated$1.assertArrayPattern = assertArrayPattern; + generated$1.assertArrayTypeAnnotation = assertArrayTypeAnnotation; + generated$1.assertArrowFunctionExpression = assertArrowFunctionExpression; + generated$1.assertAssignmentExpression = assertAssignmentExpression; + generated$1.assertAssignmentPattern = assertAssignmentPattern; + generated$1.assertAwaitExpression = assertAwaitExpression; + generated$1.assertBigIntLiteral = assertBigIntLiteral; + generated$1.assertBinary = assertBinary; + generated$1.assertBinaryExpression = assertBinaryExpression; + generated$1.assertBindExpression = assertBindExpression; + generated$1.assertBlock = assertBlock; + generated$1.assertBlockParent = assertBlockParent; + generated$1.assertBlockStatement = assertBlockStatement; + generated$1.assertBooleanLiteral = assertBooleanLiteral; + generated$1.assertBooleanLiteralTypeAnnotation = assertBooleanLiteralTypeAnnotation; + generated$1.assertBooleanTypeAnnotation = assertBooleanTypeAnnotation; + generated$1.assertBreakStatement = assertBreakStatement; + generated$1.assertCallExpression = assertCallExpression; + generated$1.assertCatchClause = assertCatchClause; + generated$1.assertClass = assertClass; + generated$1.assertClassAccessorProperty = assertClassAccessorProperty; + generated$1.assertClassBody = assertClassBody; + generated$1.assertClassDeclaration = assertClassDeclaration; + generated$1.assertClassExpression = assertClassExpression; + generated$1.assertClassImplements = assertClassImplements; + generated$1.assertClassMethod = assertClassMethod; + generated$1.assertClassPrivateMethod = assertClassPrivateMethod; + generated$1.assertClassPrivateProperty = assertClassPrivateProperty; + generated$1.assertClassProperty = assertClassProperty; + generated$1.assertCompletionStatement = assertCompletionStatement; + generated$1.assertConditional = assertConditional; + generated$1.assertConditionalExpression = assertConditionalExpression; + generated$1.assertContinueStatement = assertContinueStatement; + generated$1.assertDebuggerStatement = assertDebuggerStatement; + generated$1.assertDecimalLiteral = assertDecimalLiteral; + generated$1.assertDeclaration = assertDeclaration; + generated$1.assertDeclareClass = assertDeclareClass; + generated$1.assertDeclareExportAllDeclaration = assertDeclareExportAllDeclaration; + generated$1.assertDeclareExportDeclaration = assertDeclareExportDeclaration; + generated$1.assertDeclareFunction = assertDeclareFunction; + generated$1.assertDeclareInterface = assertDeclareInterface; + generated$1.assertDeclareModule = assertDeclareModule; + generated$1.assertDeclareModuleExports = assertDeclareModuleExports; + generated$1.assertDeclareOpaqueType = assertDeclareOpaqueType; + generated$1.assertDeclareTypeAlias = assertDeclareTypeAlias; + generated$1.assertDeclareVariable = assertDeclareVariable; + generated$1.assertDeclaredPredicate = assertDeclaredPredicate; + generated$1.assertDecorator = assertDecorator; + generated$1.assertDirective = assertDirective; + generated$1.assertDirectiveLiteral = assertDirectiveLiteral; + generated$1.assertDoExpression = assertDoExpression; + generated$1.assertDoWhileStatement = assertDoWhileStatement; + generated$1.assertEmptyStatement = assertEmptyStatement; + generated$1.assertEmptyTypeAnnotation = assertEmptyTypeAnnotation; + generated$1.assertEnumBody = assertEnumBody; + generated$1.assertEnumBooleanBody = assertEnumBooleanBody; + generated$1.assertEnumBooleanMember = assertEnumBooleanMember; + generated$1.assertEnumDeclaration = assertEnumDeclaration; + generated$1.assertEnumDefaultedMember = assertEnumDefaultedMember; + generated$1.assertEnumMember = assertEnumMember; + generated$1.assertEnumNumberBody = assertEnumNumberBody; + generated$1.assertEnumNumberMember = assertEnumNumberMember; + generated$1.assertEnumStringBody = assertEnumStringBody; + generated$1.assertEnumStringMember = assertEnumStringMember; + generated$1.assertEnumSymbolBody = assertEnumSymbolBody; + generated$1.assertExistsTypeAnnotation = assertExistsTypeAnnotation; + generated$1.assertExportAllDeclaration = assertExportAllDeclaration; + generated$1.assertExportDeclaration = assertExportDeclaration; + generated$1.assertExportDefaultDeclaration = assertExportDefaultDeclaration; + generated$1.assertExportDefaultSpecifier = assertExportDefaultSpecifier; + generated$1.assertExportNamedDeclaration = assertExportNamedDeclaration; + generated$1.assertExportNamespaceSpecifier = assertExportNamespaceSpecifier; + generated$1.assertExportSpecifier = assertExportSpecifier; + generated$1.assertExpression = assertExpression; + generated$1.assertExpressionStatement = assertExpressionStatement; + generated$1.assertExpressionWrapper = assertExpressionWrapper; + generated$1.assertFile = assertFile; + generated$1.assertFlow = assertFlow; + generated$1.assertFlowBaseAnnotation = assertFlowBaseAnnotation; + generated$1.assertFlowDeclaration = assertFlowDeclaration; + generated$1.assertFlowPredicate = assertFlowPredicate; + generated$1.assertFlowType = assertFlowType; + generated$1.assertFor = assertFor; + generated$1.assertForInStatement = assertForInStatement; + generated$1.assertForOfStatement = assertForOfStatement; + generated$1.assertForStatement = assertForStatement; + generated$1.assertForXStatement = assertForXStatement; + generated$1.assertFunction = assertFunction; + generated$1.assertFunctionDeclaration = assertFunctionDeclaration; + generated$1.assertFunctionExpression = assertFunctionExpression; + generated$1.assertFunctionParent = assertFunctionParent; + generated$1.assertFunctionTypeAnnotation = assertFunctionTypeAnnotation; + generated$1.assertFunctionTypeParam = assertFunctionTypeParam; + generated$1.assertGenericTypeAnnotation = assertGenericTypeAnnotation; + generated$1.assertIdentifier = assertIdentifier; + generated$1.assertIfStatement = assertIfStatement; + generated$1.assertImmutable = assertImmutable; + generated$1.assertImport = assertImport; + generated$1.assertImportAttribute = assertImportAttribute; + generated$1.assertImportDeclaration = assertImportDeclaration; + generated$1.assertImportDefaultSpecifier = assertImportDefaultSpecifier; + generated$1.assertImportExpression = assertImportExpression; + generated$1.assertImportNamespaceSpecifier = assertImportNamespaceSpecifier; + generated$1.assertImportOrExportDeclaration = assertImportOrExportDeclaration; + generated$1.assertImportSpecifier = assertImportSpecifier; + generated$1.assertIndexedAccessType = assertIndexedAccessType; + generated$1.assertInferredPredicate = assertInferredPredicate; + generated$1.assertInterfaceDeclaration = assertInterfaceDeclaration; + generated$1.assertInterfaceExtends = assertInterfaceExtends; + generated$1.assertInterfaceTypeAnnotation = assertInterfaceTypeAnnotation; + generated$1.assertInterpreterDirective = assertInterpreterDirective; + generated$1.assertIntersectionTypeAnnotation = assertIntersectionTypeAnnotation; + generated$1.assertJSX = assertJSX; + generated$1.assertJSXAttribute = assertJSXAttribute; + generated$1.assertJSXClosingElement = assertJSXClosingElement; + generated$1.assertJSXClosingFragment = assertJSXClosingFragment; + generated$1.assertJSXElement = assertJSXElement; + generated$1.assertJSXEmptyExpression = assertJSXEmptyExpression; + generated$1.assertJSXExpressionContainer = assertJSXExpressionContainer; + generated$1.assertJSXFragment = assertJSXFragment; + generated$1.assertJSXIdentifier = assertJSXIdentifier; + generated$1.assertJSXMemberExpression = assertJSXMemberExpression; + generated$1.assertJSXNamespacedName = assertJSXNamespacedName; + generated$1.assertJSXOpeningElement = assertJSXOpeningElement; + generated$1.assertJSXOpeningFragment = assertJSXOpeningFragment; + generated$1.assertJSXSpreadAttribute = assertJSXSpreadAttribute; + generated$1.assertJSXSpreadChild = assertJSXSpreadChild; + generated$1.assertJSXText = assertJSXText; + generated$1.assertLVal = assertLVal; + generated$1.assertLabeledStatement = assertLabeledStatement; + generated$1.assertLiteral = assertLiteral; + generated$1.assertLogicalExpression = assertLogicalExpression; + generated$1.assertLoop = assertLoop; + generated$1.assertMemberExpression = assertMemberExpression; + generated$1.assertMetaProperty = assertMetaProperty; + generated$1.assertMethod = assertMethod; + generated$1.assertMiscellaneous = assertMiscellaneous; + generated$1.assertMixedTypeAnnotation = assertMixedTypeAnnotation; + generated$1.assertModuleDeclaration = assertModuleDeclaration; + generated$1.assertModuleExpression = assertModuleExpression; + generated$1.assertModuleSpecifier = assertModuleSpecifier; + generated$1.assertNewExpression = assertNewExpression; + generated$1.assertNoop = assertNoop; + generated$1.assertNullLiteral = assertNullLiteral; + generated$1.assertNullLiteralTypeAnnotation = assertNullLiteralTypeAnnotation; + generated$1.assertNullableTypeAnnotation = assertNullableTypeAnnotation; + generated$1.assertNumberLiteral = assertNumberLiteral; + generated$1.assertNumberLiteralTypeAnnotation = assertNumberLiteralTypeAnnotation; + generated$1.assertNumberTypeAnnotation = assertNumberTypeAnnotation; + generated$1.assertNumericLiteral = assertNumericLiteral; + generated$1.assertObjectExpression = assertObjectExpression; + generated$1.assertObjectMember = assertObjectMember; + generated$1.assertObjectMethod = assertObjectMethod; + generated$1.assertObjectPattern = assertObjectPattern; + generated$1.assertObjectProperty = assertObjectProperty; + generated$1.assertObjectTypeAnnotation = assertObjectTypeAnnotation; + generated$1.assertObjectTypeCallProperty = assertObjectTypeCallProperty; + generated$1.assertObjectTypeIndexer = assertObjectTypeIndexer; + generated$1.assertObjectTypeInternalSlot = assertObjectTypeInternalSlot; + generated$1.assertObjectTypeProperty = assertObjectTypeProperty; + generated$1.assertObjectTypeSpreadProperty = assertObjectTypeSpreadProperty; + generated$1.assertOpaqueType = assertOpaqueType; + generated$1.assertOptionalCallExpression = assertOptionalCallExpression; + generated$1.assertOptionalIndexedAccessType = assertOptionalIndexedAccessType; + generated$1.assertOptionalMemberExpression = assertOptionalMemberExpression; + generated$1.assertParenthesizedExpression = assertParenthesizedExpression; + generated$1.assertPattern = assertPattern; + generated$1.assertPatternLike = assertPatternLike; + generated$1.assertPipelineBareFunction = assertPipelineBareFunction; + generated$1.assertPipelinePrimaryTopicReference = assertPipelinePrimaryTopicReference; + generated$1.assertPipelineTopicExpression = assertPipelineTopicExpression; + generated$1.assertPlaceholder = assertPlaceholder; + generated$1.assertPrivate = assertPrivate; + generated$1.assertPrivateName = assertPrivateName; + generated$1.assertProgram = assertProgram; + generated$1.assertProperty = assertProperty; + generated$1.assertPureish = assertPureish; + generated$1.assertQualifiedTypeIdentifier = assertQualifiedTypeIdentifier; + generated$1.assertRecordExpression = assertRecordExpression; + generated$1.assertRegExpLiteral = assertRegExpLiteral; + generated$1.assertRegexLiteral = assertRegexLiteral; + generated$1.assertRestElement = assertRestElement; + generated$1.assertRestProperty = assertRestProperty; + generated$1.assertReturnStatement = assertReturnStatement; + generated$1.assertScopable = assertScopable; + generated$1.assertSequenceExpression = assertSequenceExpression; + generated$1.assertSpreadElement = assertSpreadElement; + generated$1.assertSpreadProperty = assertSpreadProperty; + generated$1.assertStandardized = assertStandardized; + generated$1.assertStatement = assertStatement; + generated$1.assertStaticBlock = assertStaticBlock; + generated$1.assertStringLiteral = assertStringLiteral; + generated$1.assertStringLiteralTypeAnnotation = assertStringLiteralTypeAnnotation; + generated$1.assertStringTypeAnnotation = assertStringTypeAnnotation; + generated$1.assertSuper = assertSuper; + generated$1.assertSwitchCase = assertSwitchCase; + generated$1.assertSwitchStatement = assertSwitchStatement; + generated$1.assertSymbolTypeAnnotation = assertSymbolTypeAnnotation; + generated$1.assertTSAnyKeyword = assertTSAnyKeyword; + generated$1.assertTSArrayType = assertTSArrayType; + generated$1.assertTSAsExpression = assertTSAsExpression; + generated$1.assertTSBaseType = assertTSBaseType; + generated$1.assertTSBigIntKeyword = assertTSBigIntKeyword; + generated$1.assertTSBooleanKeyword = assertTSBooleanKeyword; + generated$1.assertTSCallSignatureDeclaration = assertTSCallSignatureDeclaration; + generated$1.assertTSConditionalType = assertTSConditionalType; + generated$1.assertTSConstructSignatureDeclaration = assertTSConstructSignatureDeclaration; + generated$1.assertTSConstructorType = assertTSConstructorType; + generated$1.assertTSDeclareFunction = assertTSDeclareFunction; + generated$1.assertTSDeclareMethod = assertTSDeclareMethod; + generated$1.assertTSEntityName = assertTSEntityName; + generated$1.assertTSEnumDeclaration = assertTSEnumDeclaration; + generated$1.assertTSEnumMember = assertTSEnumMember; + generated$1.assertTSExportAssignment = assertTSExportAssignment; + generated$1.assertTSExpressionWithTypeArguments = assertTSExpressionWithTypeArguments; + generated$1.assertTSExternalModuleReference = assertTSExternalModuleReference; + generated$1.assertTSFunctionType = assertTSFunctionType; + generated$1.assertTSImportEqualsDeclaration = assertTSImportEqualsDeclaration; + generated$1.assertTSImportType = assertTSImportType; + generated$1.assertTSIndexSignature = assertTSIndexSignature; + generated$1.assertTSIndexedAccessType = assertTSIndexedAccessType; + generated$1.assertTSInferType = assertTSInferType; + generated$1.assertTSInstantiationExpression = assertTSInstantiationExpression; + generated$1.assertTSInterfaceBody = assertTSInterfaceBody; + generated$1.assertTSInterfaceDeclaration = assertTSInterfaceDeclaration; + generated$1.assertTSIntersectionType = assertTSIntersectionType; + generated$1.assertTSIntrinsicKeyword = assertTSIntrinsicKeyword; + generated$1.assertTSLiteralType = assertTSLiteralType; + generated$1.assertTSMappedType = assertTSMappedType; + generated$1.assertTSMethodSignature = assertTSMethodSignature; + generated$1.assertTSModuleBlock = assertTSModuleBlock; + generated$1.assertTSModuleDeclaration = assertTSModuleDeclaration; + generated$1.assertTSNamedTupleMember = assertTSNamedTupleMember; + generated$1.assertTSNamespaceExportDeclaration = assertTSNamespaceExportDeclaration; + generated$1.assertTSNeverKeyword = assertTSNeverKeyword; + generated$1.assertTSNonNullExpression = assertTSNonNullExpression; + generated$1.assertTSNullKeyword = assertTSNullKeyword; + generated$1.assertTSNumberKeyword = assertTSNumberKeyword; + generated$1.assertTSObjectKeyword = assertTSObjectKeyword; + generated$1.assertTSOptionalType = assertTSOptionalType; + generated$1.assertTSParameterProperty = assertTSParameterProperty; + generated$1.assertTSParenthesizedType = assertTSParenthesizedType; + generated$1.assertTSPropertySignature = assertTSPropertySignature; + generated$1.assertTSQualifiedName = assertTSQualifiedName; + generated$1.assertTSRestType = assertTSRestType; + generated$1.assertTSSatisfiesExpression = assertTSSatisfiesExpression; + generated$1.assertTSStringKeyword = assertTSStringKeyword; + generated$1.assertTSSymbolKeyword = assertTSSymbolKeyword; + generated$1.assertTSThisType = assertTSThisType; + generated$1.assertTSTupleType = assertTSTupleType; + generated$1.assertTSType = assertTSType; + generated$1.assertTSTypeAliasDeclaration = assertTSTypeAliasDeclaration; + generated$1.assertTSTypeAnnotation = assertTSTypeAnnotation; + generated$1.assertTSTypeAssertion = assertTSTypeAssertion; + generated$1.assertTSTypeElement = assertTSTypeElement; + generated$1.assertTSTypeLiteral = assertTSTypeLiteral; + generated$1.assertTSTypeOperator = assertTSTypeOperator; + generated$1.assertTSTypeParameter = assertTSTypeParameter; + generated$1.assertTSTypeParameterDeclaration = assertTSTypeParameterDeclaration; + generated$1.assertTSTypeParameterInstantiation = assertTSTypeParameterInstantiation; + generated$1.assertTSTypePredicate = assertTSTypePredicate; + generated$1.assertTSTypeQuery = assertTSTypeQuery; + generated$1.assertTSTypeReference = assertTSTypeReference; + generated$1.assertTSUndefinedKeyword = assertTSUndefinedKeyword; + generated$1.assertTSUnionType = assertTSUnionType; + generated$1.assertTSUnknownKeyword = assertTSUnknownKeyword; + generated$1.assertTSVoidKeyword = assertTSVoidKeyword; + generated$1.assertTaggedTemplateExpression = assertTaggedTemplateExpression; + generated$1.assertTemplateElement = assertTemplateElement; + generated$1.assertTemplateLiteral = assertTemplateLiteral; + generated$1.assertTerminatorless = assertTerminatorless; + generated$1.assertThisExpression = assertThisExpression; + generated$1.assertThisTypeAnnotation = assertThisTypeAnnotation; + generated$1.assertThrowStatement = assertThrowStatement; + generated$1.assertTopicReference = assertTopicReference; + generated$1.assertTryStatement = assertTryStatement; + generated$1.assertTupleExpression = assertTupleExpression; + generated$1.assertTupleTypeAnnotation = assertTupleTypeAnnotation; + generated$1.assertTypeAlias = assertTypeAlias; + generated$1.assertTypeAnnotation = assertTypeAnnotation; + generated$1.assertTypeCastExpression = assertTypeCastExpression; + generated$1.assertTypeParameter = assertTypeParameter; + generated$1.assertTypeParameterDeclaration = assertTypeParameterDeclaration; + generated$1.assertTypeParameterInstantiation = assertTypeParameterInstantiation; + generated$1.assertTypeScript = assertTypeScript; + generated$1.assertTypeofTypeAnnotation = assertTypeofTypeAnnotation; + generated$1.assertUnaryExpression = assertUnaryExpression; + generated$1.assertUnaryLike = assertUnaryLike; + generated$1.assertUnionTypeAnnotation = assertUnionTypeAnnotation; + generated$1.assertUpdateExpression = assertUpdateExpression; + generated$1.assertUserWhitespacable = assertUserWhitespacable; + generated$1.assertV8IntrinsicIdentifier = assertV8IntrinsicIdentifier; + generated$1.assertVariableDeclaration = assertVariableDeclaration; + generated$1.assertVariableDeclarator = assertVariableDeclarator; + generated$1.assertVariance = assertVariance; + generated$1.assertVoidTypeAnnotation = assertVoidTypeAnnotation; + generated$1.assertWhile = assertWhile; + generated$1.assertWhileStatement = assertWhileStatement; + generated$1.assertWithStatement = assertWithStatement; + generated$1.assertYieldExpression = assertYieldExpression; + var _is = requireIs(); + var _deprecationWarning = requireDeprecationWarning(); + function assert(type, node, opts) { + if (!(0, _is.default)(type, node, opts)) { + throw new Error(`Expected type "${type}" with option ${JSON.stringify(opts)}, ` + `but instead got "${node.type}".`); + } + } + function assertArrayExpression(node, opts) { + assert("ArrayExpression", node, opts); + } + function assertAssignmentExpression(node, opts) { + assert("AssignmentExpression", node, opts); + } + function assertBinaryExpression(node, opts) { + assert("BinaryExpression", node, opts); + } + function assertInterpreterDirective(node, opts) { + assert("InterpreterDirective", node, opts); + } + function assertDirective(node, opts) { + assert("Directive", node, opts); + } + function assertDirectiveLiteral(node, opts) { + assert("DirectiveLiteral", node, opts); + } + function assertBlockStatement(node, opts) { + assert("BlockStatement", node, opts); + } + function assertBreakStatement(node, opts) { + assert("BreakStatement", node, opts); + } + function assertCallExpression(node, opts) { + assert("CallExpression", node, opts); + } + function assertCatchClause(node, opts) { + assert("CatchClause", node, opts); + } + function assertConditionalExpression(node, opts) { + assert("ConditionalExpression", node, opts); + } + function assertContinueStatement(node, opts) { + assert("ContinueStatement", node, opts); + } + function assertDebuggerStatement(node, opts) { + assert("DebuggerStatement", node, opts); + } + function assertDoWhileStatement(node, opts) { + assert("DoWhileStatement", node, opts); + } + function assertEmptyStatement(node, opts) { + assert("EmptyStatement", node, opts); + } + function assertExpressionStatement(node, opts) { + assert("ExpressionStatement", node, opts); + } + function assertFile(node, opts) { + assert("File", node, opts); + } + function assertForInStatement(node, opts) { + assert("ForInStatement", node, opts); + } + function assertForStatement(node, opts) { + assert("ForStatement", node, opts); + } + function assertFunctionDeclaration(node, opts) { + assert("FunctionDeclaration", node, opts); + } + function assertFunctionExpression(node, opts) { + assert("FunctionExpression", node, opts); + } + function assertIdentifier(node, opts) { + assert("Identifier", node, opts); + } + function assertIfStatement(node, opts) { + assert("IfStatement", node, opts); + } + function assertLabeledStatement(node, opts) { + assert("LabeledStatement", node, opts); + } + function assertStringLiteral(node, opts) { + assert("StringLiteral", node, opts); + } + function assertNumericLiteral(node, opts) { + assert("NumericLiteral", node, opts); + } + function assertNullLiteral(node, opts) { + assert("NullLiteral", node, opts); + } + function assertBooleanLiteral(node, opts) { + assert("BooleanLiteral", node, opts); + } + function assertRegExpLiteral(node, opts) { + assert("RegExpLiteral", node, opts); + } + function assertLogicalExpression(node, opts) { + assert("LogicalExpression", node, opts); + } + function assertMemberExpression(node, opts) { + assert("MemberExpression", node, opts); + } + function assertNewExpression(node, opts) { + assert("NewExpression", node, opts); + } + function assertProgram(node, opts) { + assert("Program", node, opts); + } + function assertObjectExpression(node, opts) { + assert("ObjectExpression", node, opts); + } + function assertObjectMethod(node, opts) { + assert("ObjectMethod", node, opts); + } + function assertObjectProperty(node, opts) { + assert("ObjectProperty", node, opts); + } + function assertRestElement(node, opts) { + assert("RestElement", node, opts); + } + function assertReturnStatement(node, opts) { + assert("ReturnStatement", node, opts); + } + function assertSequenceExpression(node, opts) { + assert("SequenceExpression", node, opts); + } + function assertParenthesizedExpression(node, opts) { + assert("ParenthesizedExpression", node, opts); + } + function assertSwitchCase(node, opts) { + assert("SwitchCase", node, opts); + } + function assertSwitchStatement(node, opts) { + assert("SwitchStatement", node, opts); + } + function assertThisExpression(node, opts) { + assert("ThisExpression", node, opts); + } + function assertThrowStatement(node, opts) { + assert("ThrowStatement", node, opts); + } + function assertTryStatement(node, opts) { + assert("TryStatement", node, opts); + } + function assertUnaryExpression(node, opts) { + assert("UnaryExpression", node, opts); + } + function assertUpdateExpression(node, opts) { + assert("UpdateExpression", node, opts); + } + function assertVariableDeclaration(node, opts) { + assert("VariableDeclaration", node, opts); + } + function assertVariableDeclarator(node, opts) { + assert("VariableDeclarator", node, opts); + } + function assertWhileStatement(node, opts) { + assert("WhileStatement", node, opts); + } + function assertWithStatement(node, opts) { + assert("WithStatement", node, opts); + } + function assertAssignmentPattern(node, opts) { + assert("AssignmentPattern", node, opts); + } + function assertArrayPattern(node, opts) { + assert("ArrayPattern", node, opts); + } + function assertArrowFunctionExpression(node, opts) { + assert("ArrowFunctionExpression", node, opts); + } + function assertClassBody(node, opts) { + assert("ClassBody", node, opts); + } + function assertClassExpression(node, opts) { + assert("ClassExpression", node, opts); + } + function assertClassDeclaration(node, opts) { + assert("ClassDeclaration", node, opts); + } + function assertExportAllDeclaration(node, opts) { + assert("ExportAllDeclaration", node, opts); + } + function assertExportDefaultDeclaration(node, opts) { + assert("ExportDefaultDeclaration", node, opts); + } + function assertExportNamedDeclaration(node, opts) { + assert("ExportNamedDeclaration", node, opts); + } + function assertExportSpecifier(node, opts) { + assert("ExportSpecifier", node, opts); + } + function assertForOfStatement(node, opts) { + assert("ForOfStatement", node, opts); + } + function assertImportDeclaration(node, opts) { + assert("ImportDeclaration", node, opts); + } + function assertImportDefaultSpecifier(node, opts) { + assert("ImportDefaultSpecifier", node, opts); + } + function assertImportNamespaceSpecifier(node, opts) { + assert("ImportNamespaceSpecifier", node, opts); + } + function assertImportSpecifier(node, opts) { + assert("ImportSpecifier", node, opts); + } + function assertImportExpression(node, opts) { + assert("ImportExpression", node, opts); + } + function assertMetaProperty(node, opts) { + assert("MetaProperty", node, opts); + } + function assertClassMethod(node, opts) { + assert("ClassMethod", node, opts); + } + function assertObjectPattern(node, opts) { + assert("ObjectPattern", node, opts); + } + function assertSpreadElement(node, opts) { + assert("SpreadElement", node, opts); + } + function assertSuper(node, opts) { + assert("Super", node, opts); + } + function assertTaggedTemplateExpression(node, opts) { + assert("TaggedTemplateExpression", node, opts); + } + function assertTemplateElement(node, opts) { + assert("TemplateElement", node, opts); + } + function assertTemplateLiteral(node, opts) { + assert("TemplateLiteral", node, opts); + } + function assertYieldExpression(node, opts) { + assert("YieldExpression", node, opts); + } + function assertAwaitExpression(node, opts) { + assert("AwaitExpression", node, opts); + } + function assertImport(node, opts) { + assert("Import", node, opts); + } + function assertBigIntLiteral(node, opts) { + assert("BigIntLiteral", node, opts); + } + function assertExportNamespaceSpecifier(node, opts) { + assert("ExportNamespaceSpecifier", node, opts); + } + function assertOptionalMemberExpression(node, opts) { + assert("OptionalMemberExpression", node, opts); + } + function assertOptionalCallExpression(node, opts) { + assert("OptionalCallExpression", node, opts); + } + function assertClassProperty(node, opts) { + assert("ClassProperty", node, opts); + } + function assertClassAccessorProperty(node, opts) { + assert("ClassAccessorProperty", node, opts); + } + function assertClassPrivateProperty(node, opts) { + assert("ClassPrivateProperty", node, opts); + } + function assertClassPrivateMethod(node, opts) { + assert("ClassPrivateMethod", node, opts); + } + function assertPrivateName(node, opts) { + assert("PrivateName", node, opts); + } + function assertStaticBlock(node, opts) { + assert("StaticBlock", node, opts); + } + function assertAnyTypeAnnotation(node, opts) { + assert("AnyTypeAnnotation", node, opts); + } + function assertArrayTypeAnnotation(node, opts) { + assert("ArrayTypeAnnotation", node, opts); + } + function assertBooleanTypeAnnotation(node, opts) { + assert("BooleanTypeAnnotation", node, opts); + } + function assertBooleanLiteralTypeAnnotation(node, opts) { + assert("BooleanLiteralTypeAnnotation", node, opts); + } + function assertNullLiteralTypeAnnotation(node, opts) { + assert("NullLiteralTypeAnnotation", node, opts); + } + function assertClassImplements(node, opts) { + assert("ClassImplements", node, opts); + } + function assertDeclareClass(node, opts) { + assert("DeclareClass", node, opts); + } + function assertDeclareFunction(node, opts) { + assert("DeclareFunction", node, opts); + } + function assertDeclareInterface(node, opts) { + assert("DeclareInterface", node, opts); + } + function assertDeclareModule(node, opts) { + assert("DeclareModule", node, opts); + } + function assertDeclareModuleExports(node, opts) { + assert("DeclareModuleExports", node, opts); + } + function assertDeclareTypeAlias(node, opts) { + assert("DeclareTypeAlias", node, opts); + } + function assertDeclareOpaqueType(node, opts) { + assert("DeclareOpaqueType", node, opts); + } + function assertDeclareVariable(node, opts) { + assert("DeclareVariable", node, opts); + } + function assertDeclareExportDeclaration(node, opts) { + assert("DeclareExportDeclaration", node, opts); + } + function assertDeclareExportAllDeclaration(node, opts) { + assert("DeclareExportAllDeclaration", node, opts); + } + function assertDeclaredPredicate(node, opts) { + assert("DeclaredPredicate", node, opts); + } + function assertExistsTypeAnnotation(node, opts) { + assert("ExistsTypeAnnotation", node, opts); + } + function assertFunctionTypeAnnotation(node, opts) { + assert("FunctionTypeAnnotation", node, opts); + } + function assertFunctionTypeParam(node, opts) { + assert("FunctionTypeParam", node, opts); + } + function assertGenericTypeAnnotation(node, opts) { + assert("GenericTypeAnnotation", node, opts); + } + function assertInferredPredicate(node, opts) { + assert("InferredPredicate", node, opts); + } + function assertInterfaceExtends(node, opts) { + assert("InterfaceExtends", node, opts); + } + function assertInterfaceDeclaration(node, opts) { + assert("InterfaceDeclaration", node, opts); + } + function assertInterfaceTypeAnnotation(node, opts) { + assert("InterfaceTypeAnnotation", node, opts); + } + function assertIntersectionTypeAnnotation(node, opts) { + assert("IntersectionTypeAnnotation", node, opts); + } + function assertMixedTypeAnnotation(node, opts) { + assert("MixedTypeAnnotation", node, opts); + } + function assertEmptyTypeAnnotation(node, opts) { + assert("EmptyTypeAnnotation", node, opts); + } + function assertNullableTypeAnnotation(node, opts) { + assert("NullableTypeAnnotation", node, opts); + } + function assertNumberLiteralTypeAnnotation(node, opts) { + assert("NumberLiteralTypeAnnotation", node, opts); + } + function assertNumberTypeAnnotation(node, opts) { + assert("NumberTypeAnnotation", node, opts); + } + function assertObjectTypeAnnotation(node, opts) { + assert("ObjectTypeAnnotation", node, opts); + } + function assertObjectTypeInternalSlot(node, opts) { + assert("ObjectTypeInternalSlot", node, opts); + } + function assertObjectTypeCallProperty(node, opts) { + assert("ObjectTypeCallProperty", node, opts); + } + function assertObjectTypeIndexer(node, opts) { + assert("ObjectTypeIndexer", node, opts); + } + function assertObjectTypeProperty(node, opts) { + assert("ObjectTypeProperty", node, opts); + } + function assertObjectTypeSpreadProperty(node, opts) { + assert("ObjectTypeSpreadProperty", node, opts); + } + function assertOpaqueType(node, opts) { + assert("OpaqueType", node, opts); + } + function assertQualifiedTypeIdentifier(node, opts) { + assert("QualifiedTypeIdentifier", node, opts); + } + function assertStringLiteralTypeAnnotation(node, opts) { + assert("StringLiteralTypeAnnotation", node, opts); + } + function assertStringTypeAnnotation(node, opts) { + assert("StringTypeAnnotation", node, opts); + } + function assertSymbolTypeAnnotation(node, opts) { + assert("SymbolTypeAnnotation", node, opts); + } + function assertThisTypeAnnotation(node, opts) { + assert("ThisTypeAnnotation", node, opts); + } + function assertTupleTypeAnnotation(node, opts) { + assert("TupleTypeAnnotation", node, opts); + } + function assertTypeofTypeAnnotation(node, opts) { + assert("TypeofTypeAnnotation", node, opts); + } + function assertTypeAlias(node, opts) { + assert("TypeAlias", node, opts); + } + function assertTypeAnnotation(node, opts) { + assert("TypeAnnotation", node, opts); + } + function assertTypeCastExpression(node, opts) { + assert("TypeCastExpression", node, opts); + } + function assertTypeParameter(node, opts) { + assert("TypeParameter", node, opts); + } + function assertTypeParameterDeclaration(node, opts) { + assert("TypeParameterDeclaration", node, opts); + } + function assertTypeParameterInstantiation(node, opts) { + assert("TypeParameterInstantiation", node, opts); + } + function assertUnionTypeAnnotation(node, opts) { + assert("UnionTypeAnnotation", node, opts); + } + function assertVariance(node, opts) { + assert("Variance", node, opts); + } + function assertVoidTypeAnnotation(node, opts) { + assert("VoidTypeAnnotation", node, opts); + } + function assertEnumDeclaration(node, opts) { + assert("EnumDeclaration", node, opts); + } + function assertEnumBooleanBody(node, opts) { + assert("EnumBooleanBody", node, opts); + } + function assertEnumNumberBody(node, opts) { + assert("EnumNumberBody", node, opts); + } + function assertEnumStringBody(node, opts) { + assert("EnumStringBody", node, opts); + } + function assertEnumSymbolBody(node, opts) { + assert("EnumSymbolBody", node, opts); + } + function assertEnumBooleanMember(node, opts) { + assert("EnumBooleanMember", node, opts); + } + function assertEnumNumberMember(node, opts) { + assert("EnumNumberMember", node, opts); + } + function assertEnumStringMember(node, opts) { + assert("EnumStringMember", node, opts); + } + function assertEnumDefaultedMember(node, opts) { + assert("EnumDefaultedMember", node, opts); + } + function assertIndexedAccessType(node, opts) { + assert("IndexedAccessType", node, opts); + } + function assertOptionalIndexedAccessType(node, opts) { + assert("OptionalIndexedAccessType", node, opts); + } + function assertJSXAttribute(node, opts) { + assert("JSXAttribute", node, opts); + } + function assertJSXClosingElement(node, opts) { + assert("JSXClosingElement", node, opts); + } + function assertJSXElement(node, opts) { + assert("JSXElement", node, opts); + } + function assertJSXEmptyExpression(node, opts) { + assert("JSXEmptyExpression", node, opts); + } + function assertJSXExpressionContainer(node, opts) { + assert("JSXExpressionContainer", node, opts); + } + function assertJSXSpreadChild(node, opts) { + assert("JSXSpreadChild", node, opts); + } + function assertJSXIdentifier(node, opts) { + assert("JSXIdentifier", node, opts); + } + function assertJSXMemberExpression(node, opts) { + assert("JSXMemberExpression", node, opts); + } + function assertJSXNamespacedName(node, opts) { + assert("JSXNamespacedName", node, opts); + } + function assertJSXOpeningElement(node, opts) { + assert("JSXOpeningElement", node, opts); + } + function assertJSXSpreadAttribute(node, opts) { + assert("JSXSpreadAttribute", node, opts); + } + function assertJSXText(node, opts) { + assert("JSXText", node, opts); + } + function assertJSXFragment(node, opts) { + assert("JSXFragment", node, opts); + } + function assertJSXOpeningFragment(node, opts) { + assert("JSXOpeningFragment", node, opts); + } + function assertJSXClosingFragment(node, opts) { + assert("JSXClosingFragment", node, opts); + } + function assertNoop(node, opts) { + assert("Noop", node, opts); + } + function assertPlaceholder(node, opts) { + assert("Placeholder", node, opts); + } + function assertV8IntrinsicIdentifier(node, opts) { + assert("V8IntrinsicIdentifier", node, opts); + } + function assertArgumentPlaceholder(node, opts) { + assert("ArgumentPlaceholder", node, opts); + } + function assertBindExpression(node, opts) { + assert("BindExpression", node, opts); + } + function assertImportAttribute(node, opts) { + assert("ImportAttribute", node, opts); + } + function assertDecorator(node, opts) { + assert("Decorator", node, opts); + } + function assertDoExpression(node, opts) { + assert("DoExpression", node, opts); + } + function assertExportDefaultSpecifier(node, opts) { + assert("ExportDefaultSpecifier", node, opts); + } + function assertRecordExpression(node, opts) { + assert("RecordExpression", node, opts); + } + function assertTupleExpression(node, opts) { + assert("TupleExpression", node, opts); + } + function assertDecimalLiteral(node, opts) { + assert("DecimalLiteral", node, opts); + } + function assertModuleExpression(node, opts) { + assert("ModuleExpression", node, opts); + } + function assertTopicReference(node, opts) { + assert("TopicReference", node, opts); + } + function assertPipelineTopicExpression(node, opts) { + assert("PipelineTopicExpression", node, opts); + } + function assertPipelineBareFunction(node, opts) { + assert("PipelineBareFunction", node, opts); + } + function assertPipelinePrimaryTopicReference(node, opts) { + assert("PipelinePrimaryTopicReference", node, opts); + } + function assertTSParameterProperty(node, opts) { + assert("TSParameterProperty", node, opts); + } + function assertTSDeclareFunction(node, opts) { + assert("TSDeclareFunction", node, opts); + } + function assertTSDeclareMethod(node, opts) { + assert("TSDeclareMethod", node, opts); + } + function assertTSQualifiedName(node, opts) { + assert("TSQualifiedName", node, opts); + } + function assertTSCallSignatureDeclaration(node, opts) { + assert("TSCallSignatureDeclaration", node, opts); + } + function assertTSConstructSignatureDeclaration(node, opts) { + assert("TSConstructSignatureDeclaration", node, opts); + } + function assertTSPropertySignature(node, opts) { + assert("TSPropertySignature", node, opts); + } + function assertTSMethodSignature(node, opts) { + assert("TSMethodSignature", node, opts); + } + function assertTSIndexSignature(node, opts) { + assert("TSIndexSignature", node, opts); + } + function assertTSAnyKeyword(node, opts) { + assert("TSAnyKeyword", node, opts); + } + function assertTSBooleanKeyword(node, opts) { + assert("TSBooleanKeyword", node, opts); + } + function assertTSBigIntKeyword(node, opts) { + assert("TSBigIntKeyword", node, opts); + } + function assertTSIntrinsicKeyword(node, opts) { + assert("TSIntrinsicKeyword", node, opts); + } + function assertTSNeverKeyword(node, opts) { + assert("TSNeverKeyword", node, opts); + } + function assertTSNullKeyword(node, opts) { + assert("TSNullKeyword", node, opts); + } + function assertTSNumberKeyword(node, opts) { + assert("TSNumberKeyword", node, opts); + } + function assertTSObjectKeyword(node, opts) { + assert("TSObjectKeyword", node, opts); + } + function assertTSStringKeyword(node, opts) { + assert("TSStringKeyword", node, opts); + } + function assertTSSymbolKeyword(node, opts) { + assert("TSSymbolKeyword", node, opts); + } + function assertTSUndefinedKeyword(node, opts) { + assert("TSUndefinedKeyword", node, opts); + } + function assertTSUnknownKeyword(node, opts) { + assert("TSUnknownKeyword", node, opts); + } + function assertTSVoidKeyword(node, opts) { + assert("TSVoidKeyword", node, opts); + } + function assertTSThisType(node, opts) { + assert("TSThisType", node, opts); + } + function assertTSFunctionType(node, opts) { + assert("TSFunctionType", node, opts); + } + function assertTSConstructorType(node, opts) { + assert("TSConstructorType", node, opts); + } + function assertTSTypeReference(node, opts) { + assert("TSTypeReference", node, opts); + } + function assertTSTypePredicate(node, opts) { + assert("TSTypePredicate", node, opts); + } + function assertTSTypeQuery(node, opts) { + assert("TSTypeQuery", node, opts); + } + function assertTSTypeLiteral(node, opts) { + assert("TSTypeLiteral", node, opts); + } + function assertTSArrayType(node, opts) { + assert("TSArrayType", node, opts); + } + function assertTSTupleType(node, opts) { + assert("TSTupleType", node, opts); + } + function assertTSOptionalType(node, opts) { + assert("TSOptionalType", node, opts); + } + function assertTSRestType(node, opts) { + assert("TSRestType", node, opts); + } + function assertTSNamedTupleMember(node, opts) { + assert("TSNamedTupleMember", node, opts); + } + function assertTSUnionType(node, opts) { + assert("TSUnionType", node, opts); + } + function assertTSIntersectionType(node, opts) { + assert("TSIntersectionType", node, opts); + } + function assertTSConditionalType(node, opts) { + assert("TSConditionalType", node, opts); + } + function assertTSInferType(node, opts) { + assert("TSInferType", node, opts); + } + function assertTSParenthesizedType(node, opts) { + assert("TSParenthesizedType", node, opts); + } + function assertTSTypeOperator(node, opts) { + assert("TSTypeOperator", node, opts); + } + function assertTSIndexedAccessType(node, opts) { + assert("TSIndexedAccessType", node, opts); + } + function assertTSMappedType(node, opts) { + assert("TSMappedType", node, opts); + } + function assertTSLiteralType(node, opts) { + assert("TSLiteralType", node, opts); + } + function assertTSExpressionWithTypeArguments(node, opts) { + assert("TSExpressionWithTypeArguments", node, opts); + } + function assertTSInterfaceDeclaration(node, opts) { + assert("TSInterfaceDeclaration", node, opts); + } + function assertTSInterfaceBody(node, opts) { + assert("TSInterfaceBody", node, opts); + } + function assertTSTypeAliasDeclaration(node, opts) { + assert("TSTypeAliasDeclaration", node, opts); + } + function assertTSInstantiationExpression(node, opts) { + assert("TSInstantiationExpression", node, opts); + } + function assertTSAsExpression(node, opts) { + assert("TSAsExpression", node, opts); + } + function assertTSSatisfiesExpression(node, opts) { + assert("TSSatisfiesExpression", node, opts); + } + function assertTSTypeAssertion(node, opts) { + assert("TSTypeAssertion", node, opts); + } + function assertTSEnumDeclaration(node, opts) { + assert("TSEnumDeclaration", node, opts); + } + function assertTSEnumMember(node, opts) { + assert("TSEnumMember", node, opts); + } + function assertTSModuleDeclaration(node, opts) { + assert("TSModuleDeclaration", node, opts); + } + function assertTSModuleBlock(node, opts) { + assert("TSModuleBlock", node, opts); + } + function assertTSImportType(node, opts) { + assert("TSImportType", node, opts); + } + function assertTSImportEqualsDeclaration(node, opts) { + assert("TSImportEqualsDeclaration", node, opts); + } + function assertTSExternalModuleReference(node, opts) { + assert("TSExternalModuleReference", node, opts); + } + function assertTSNonNullExpression(node, opts) { + assert("TSNonNullExpression", node, opts); + } + function assertTSExportAssignment(node, opts) { + assert("TSExportAssignment", node, opts); + } + function assertTSNamespaceExportDeclaration(node, opts) { + assert("TSNamespaceExportDeclaration", node, opts); + } + function assertTSTypeAnnotation(node, opts) { + assert("TSTypeAnnotation", node, opts); + } + function assertTSTypeParameterInstantiation(node, opts) { + assert("TSTypeParameterInstantiation", node, opts); + } + function assertTSTypeParameterDeclaration(node, opts) { + assert("TSTypeParameterDeclaration", node, opts); + } + function assertTSTypeParameter(node, opts) { + assert("TSTypeParameter", node, opts); + } + function assertStandardized(node, opts) { + assert("Standardized", node, opts); + } + function assertExpression(node, opts) { + assert("Expression", node, opts); + } + function assertBinary(node, opts) { + assert("Binary", node, opts); + } + function assertScopable(node, opts) { + assert("Scopable", node, opts); + } + function assertBlockParent(node, opts) { + assert("BlockParent", node, opts); + } + function assertBlock(node, opts) { + assert("Block", node, opts); + } + function assertStatement(node, opts) { + assert("Statement", node, opts); + } + function assertTerminatorless(node, opts) { + assert("Terminatorless", node, opts); + } + function assertCompletionStatement(node, opts) { + assert("CompletionStatement", node, opts); + } + function assertConditional(node, opts) { + assert("Conditional", node, opts); + } + function assertLoop(node, opts) { + assert("Loop", node, opts); + } + function assertWhile(node, opts) { + assert("While", node, opts); + } + function assertExpressionWrapper(node, opts) { + assert("ExpressionWrapper", node, opts); + } + function assertFor(node, opts) { + assert("For", node, opts); + } + function assertForXStatement(node, opts) { + assert("ForXStatement", node, opts); + } + function assertFunction(node, opts) { + assert("Function", node, opts); + } + function assertFunctionParent(node, opts) { + assert("FunctionParent", node, opts); + } + function assertPureish(node, opts) { + assert("Pureish", node, opts); + } + function assertDeclaration(node, opts) { + assert("Declaration", node, opts); + } + function assertPatternLike(node, opts) { + assert("PatternLike", node, opts); + } + function assertLVal(node, opts) { + assert("LVal", node, opts); + } + function assertTSEntityName(node, opts) { + assert("TSEntityName", node, opts); + } + function assertLiteral(node, opts) { + assert("Literal", node, opts); + } + function assertImmutable(node, opts) { + assert("Immutable", node, opts); + } + function assertUserWhitespacable(node, opts) { + assert("UserWhitespacable", node, opts); + } + function assertMethod(node, opts) { + assert("Method", node, opts); + } + function assertObjectMember(node, opts) { + assert("ObjectMember", node, opts); + } + function assertProperty(node, opts) { + assert("Property", node, opts); + } + function assertUnaryLike(node, opts) { + assert("UnaryLike", node, opts); + } + function assertPattern(node, opts) { + assert("Pattern", node, opts); + } + function assertClass(node, opts) { + assert("Class", node, opts); + } + function assertImportOrExportDeclaration(node, opts) { + assert("ImportOrExportDeclaration", node, opts); + } + function assertExportDeclaration(node, opts) { + assert("ExportDeclaration", node, opts); + } + function assertModuleSpecifier(node, opts) { + assert("ModuleSpecifier", node, opts); + } + function assertAccessor(node, opts) { + assert("Accessor", node, opts); + } + function assertPrivate(node, opts) { + assert("Private", node, opts); + } + function assertFlow(node, opts) { + assert("Flow", node, opts); + } + function assertFlowType(node, opts) { + assert("FlowType", node, opts); + } + function assertFlowBaseAnnotation(node, opts) { + assert("FlowBaseAnnotation", node, opts); + } + function assertFlowDeclaration(node, opts) { + assert("FlowDeclaration", node, opts); + } + function assertFlowPredicate(node, opts) { + assert("FlowPredicate", node, opts); + } + function assertEnumBody(node, opts) { + assert("EnumBody", node, opts); + } + function assertEnumMember(node, opts) { + assert("EnumMember", node, opts); + } + function assertJSX(node, opts) { + assert("JSX", node, opts); + } + function assertMiscellaneous(node, opts) { + assert("Miscellaneous", node, opts); + } + function assertTypeScript(node, opts) { + assert("TypeScript", node, opts); + } + function assertTSTypeElement(node, opts) { + assert("TSTypeElement", node, opts); + } + function assertTSType(node, opts) { + assert("TSType", node, opts); + } + function assertTSBaseType(node, opts) { + assert("TSBaseType", node, opts); + } + function assertNumberLiteral(node, opts) { + (0, _deprecationWarning.default)("assertNumberLiteral", "assertNumericLiteral"); + assert("NumberLiteral", node, opts); + } + function assertRegexLiteral(node, opts) { + (0, _deprecationWarning.default)("assertRegexLiteral", "assertRegExpLiteral"); + assert("RegexLiteral", node, opts); + } + function assertRestProperty(node, opts) { + (0, _deprecationWarning.default)("assertRestProperty", "assertRestElement"); + assert("RestProperty", node, opts); + } + function assertSpreadProperty(node, opts) { + (0, _deprecationWarning.default)("assertSpreadProperty", "assertSpreadElement"); + assert("SpreadProperty", node, opts); + } + function assertModuleDeclaration(node, opts) { + (0, _deprecationWarning.default)("assertModuleDeclaration", "assertImportOrExportDeclaration"); + assert("ModuleDeclaration", node, opts); + } + + + return generated$1; +} + +var createTypeAnnotationBasedOnTypeof = {}; + +var hasRequiredCreateTypeAnnotationBasedOnTypeof; + +function requireCreateTypeAnnotationBasedOnTypeof () { + if (hasRequiredCreateTypeAnnotationBasedOnTypeof) return createTypeAnnotationBasedOnTypeof; + hasRequiredCreateTypeAnnotationBasedOnTypeof = 1; + + Object.defineProperty(createTypeAnnotationBasedOnTypeof, "__esModule", { + value: true + }); + createTypeAnnotationBasedOnTypeof.default = void 0; + var _index = requireGenerated$2(); + createTypeAnnotationBasedOnTypeof.default = createTypeAnnotationBasedOnTypeof$1; + function createTypeAnnotationBasedOnTypeof$1(type) { + switch (type) { + case "string": + return (0, _index.stringTypeAnnotation)(); + case "number": + return (0, _index.numberTypeAnnotation)(); + case "undefined": + return (0, _index.voidTypeAnnotation)(); + case "boolean": + return (0, _index.booleanTypeAnnotation)(); + case "function": + return (0, _index.genericTypeAnnotation)((0, _index.identifier)("Function")); + case "object": + return (0, _index.genericTypeAnnotation)((0, _index.identifier)("Object")); + case "symbol": + return (0, _index.genericTypeAnnotation)((0, _index.identifier)("Symbol")); + case "bigint": + return (0, _index.anyTypeAnnotation)(); + } + throw new Error("Invalid typeof value: " + type); + } + + + return createTypeAnnotationBasedOnTypeof; +} + +var createFlowUnionType = {}; + +var removeTypeDuplicates$1 = {}; + +var hasRequiredRemoveTypeDuplicates$1; + +function requireRemoveTypeDuplicates$1 () { + if (hasRequiredRemoveTypeDuplicates$1) return removeTypeDuplicates$1; + hasRequiredRemoveTypeDuplicates$1 = 1; + + Object.defineProperty(removeTypeDuplicates$1, "__esModule", { + value: true + }); + removeTypeDuplicates$1.default = removeTypeDuplicates; + var _index = requireGenerated$3(); + function getQualifiedName(node) { + return (0, _index.isIdentifier)(node) ? node.name : `${node.id.name}.${getQualifiedName(node.qualification)}`; + } + function removeTypeDuplicates(nodesIn) { + const nodes = Array.from(nodesIn); + const generics = new Map(); + const bases = new Map(); + const typeGroups = new Set(); + const types = []; + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + if (!node) continue; + if (types.includes(node)) { + continue; + } + if ((0, _index.isAnyTypeAnnotation)(node)) { + return [node]; + } + if ((0, _index.isFlowBaseAnnotation)(node)) { + bases.set(node.type, node); + continue; + } + if ((0, _index.isUnionTypeAnnotation)(node)) { + if (!typeGroups.has(node.types)) { + nodes.push(...node.types); + typeGroups.add(node.types); + } + continue; + } + if ((0, _index.isGenericTypeAnnotation)(node)) { + const name = getQualifiedName(node.id); + if (generics.has(name)) { + let existing = generics.get(name); + if (existing.typeParameters) { + if (node.typeParameters) { + existing.typeParameters.params.push(...node.typeParameters.params); + existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params); + } + } else { + existing = node.typeParameters; + } + } else { + generics.set(name, node); + } + continue; + } + types.push(node); + } + for (const [, baseType] of bases) { + types.push(baseType); + } + for (const [, genericName] of generics) { + types.push(genericName); + } + return types; + } + + + return removeTypeDuplicates$1; +} + +var hasRequiredCreateFlowUnionType; + +function requireCreateFlowUnionType () { + if (hasRequiredCreateFlowUnionType) return createFlowUnionType; + hasRequiredCreateFlowUnionType = 1; + + Object.defineProperty(createFlowUnionType, "__esModule", { + value: true + }); + createFlowUnionType.default = createFlowUnionType$1; + var _index = requireGenerated$2(); + var _removeTypeDuplicates = requireRemoveTypeDuplicates$1(); + function createFlowUnionType$1(types) { + const flattened = (0, _removeTypeDuplicates.default)(types); + if (flattened.length === 1) { + return flattened[0]; + } else { + return (0, _index.unionTypeAnnotation)(flattened); + } + } + + + return createFlowUnionType; +} + +var createTSUnionType = {}; + +var removeTypeDuplicates = {}; + +var hasRequiredRemoveTypeDuplicates; + +function requireRemoveTypeDuplicates () { + if (hasRequiredRemoveTypeDuplicates) return removeTypeDuplicates; + hasRequiredRemoveTypeDuplicates = 1; + + Object.defineProperty(removeTypeDuplicates, "__esModule", { + value: true + }); + removeTypeDuplicates.default = removeTypeDuplicates$1; + var _index = requireGenerated$3(); + function getQualifiedName(node) { + return (0, _index.isIdentifier)(node) ? node.name : `${node.right.name}.${getQualifiedName(node.left)}`; + } + function removeTypeDuplicates$1(nodesIn) { + const nodes = Array.from(nodesIn); + const generics = new Map(); + const bases = new Map(); + const typeGroups = new Set(); + const types = []; + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + if (!node) continue; + if (types.includes(node)) { + continue; + } + if ((0, _index.isTSAnyKeyword)(node)) { + return [node]; + } + if ((0, _index.isTSBaseType)(node)) { + bases.set(node.type, node); + continue; + } + if ((0, _index.isTSUnionType)(node)) { + if (!typeGroups.has(node.types)) { + nodes.push(...node.types); + typeGroups.add(node.types); + } + continue; + } + if ((0, _index.isTSTypeReference)(node) && node.typeParameters) { + const name = getQualifiedName(node.typeName); + if (generics.has(name)) { + let existing = generics.get(name); + if (existing.typeParameters) { + if (node.typeParameters) { + existing.typeParameters.params.push(...node.typeParameters.params); + existing.typeParameters.params = removeTypeDuplicates$1(existing.typeParameters.params); + } + } else { + existing = node.typeParameters; + } + } else { + generics.set(name, node); + } + continue; + } + types.push(node); + } + for (const [, baseType] of bases) { + types.push(baseType); + } + for (const [, genericName] of generics) { + types.push(genericName); + } + return types; + } + + + return removeTypeDuplicates; +} + +var hasRequiredCreateTSUnionType; + +function requireCreateTSUnionType () { + if (hasRequiredCreateTSUnionType) return createTSUnionType; + hasRequiredCreateTSUnionType = 1; + + Object.defineProperty(createTSUnionType, "__esModule", { + value: true + }); + createTSUnionType.default = createTSUnionType$1; + var _index = requireGenerated$2(); + var _removeTypeDuplicates = requireRemoveTypeDuplicates(); + var _index2 = requireGenerated$3(); + function createTSUnionType$1(typeAnnotations) { + const types = typeAnnotations.map(type => { + return (0, _index2.isTSTypeAnnotation)(type) ? type.typeAnnotation : type; + }); + const flattened = (0, _removeTypeDuplicates.default)(types); + if (flattened.length === 1) { + return flattened[0]; + } else { + return (0, _index.tsUnionType)(flattened); + } + } + + + return createTSUnionType; +} + +var uppercase = {}; + +var hasRequiredUppercase; + +function requireUppercase () { + if (hasRequiredUppercase) return uppercase; + hasRequiredUppercase = 1; + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "AnyTypeAnnotation", { + enumerable: true, + get: function () { + return _index.anyTypeAnnotation; + } + }); + Object.defineProperty(exports, "ArgumentPlaceholder", { + enumerable: true, + get: function () { + return _index.argumentPlaceholder; + } + }); + Object.defineProperty(exports, "ArrayExpression", { + enumerable: true, + get: function () { + return _index.arrayExpression; + } + }); + Object.defineProperty(exports, "ArrayPattern", { + enumerable: true, + get: function () { + return _index.arrayPattern; + } + }); + Object.defineProperty(exports, "ArrayTypeAnnotation", { + enumerable: true, + get: function () { + return _index.arrayTypeAnnotation; + } + }); + Object.defineProperty(exports, "ArrowFunctionExpression", { + enumerable: true, + get: function () { + return _index.arrowFunctionExpression; + } + }); + Object.defineProperty(exports, "AssignmentExpression", { + enumerable: true, + get: function () { + return _index.assignmentExpression; + } + }); + Object.defineProperty(exports, "AssignmentPattern", { + enumerable: true, + get: function () { + return _index.assignmentPattern; + } + }); + Object.defineProperty(exports, "AwaitExpression", { + enumerable: true, + get: function () { + return _index.awaitExpression; + } + }); + Object.defineProperty(exports, "BigIntLiteral", { + enumerable: true, + get: function () { + return _index.bigIntLiteral; + } + }); + Object.defineProperty(exports, "BinaryExpression", { + enumerable: true, + get: function () { + return _index.binaryExpression; + } + }); + Object.defineProperty(exports, "BindExpression", { + enumerable: true, + get: function () { + return _index.bindExpression; + } + }); + Object.defineProperty(exports, "BlockStatement", { + enumerable: true, + get: function () { + return _index.blockStatement; + } + }); + Object.defineProperty(exports, "BooleanLiteral", { + enumerable: true, + get: function () { + return _index.booleanLiteral; + } + }); + Object.defineProperty(exports, "BooleanLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _index.booleanLiteralTypeAnnotation; + } + }); + Object.defineProperty(exports, "BooleanTypeAnnotation", { + enumerable: true, + get: function () { + return _index.booleanTypeAnnotation; + } + }); + Object.defineProperty(exports, "BreakStatement", { + enumerable: true, + get: function () { + return _index.breakStatement; + } + }); + Object.defineProperty(exports, "CallExpression", { + enumerable: true, + get: function () { + return _index.callExpression; + } + }); + Object.defineProperty(exports, "CatchClause", { + enumerable: true, + get: function () { + return _index.catchClause; + } + }); + Object.defineProperty(exports, "ClassAccessorProperty", { + enumerable: true, + get: function () { + return _index.classAccessorProperty; + } + }); + Object.defineProperty(exports, "ClassBody", { + enumerable: true, + get: function () { + return _index.classBody; + } + }); + Object.defineProperty(exports, "ClassDeclaration", { + enumerable: true, + get: function () { + return _index.classDeclaration; + } + }); + Object.defineProperty(exports, "ClassExpression", { + enumerable: true, + get: function () { + return _index.classExpression; + } + }); + Object.defineProperty(exports, "ClassImplements", { + enumerable: true, + get: function () { + return _index.classImplements; + } + }); + Object.defineProperty(exports, "ClassMethod", { + enumerable: true, + get: function () { + return _index.classMethod; + } + }); + Object.defineProperty(exports, "ClassPrivateMethod", { + enumerable: true, + get: function () { + return _index.classPrivateMethod; + } + }); + Object.defineProperty(exports, "ClassPrivateProperty", { + enumerable: true, + get: function () { + return _index.classPrivateProperty; + } + }); + Object.defineProperty(exports, "ClassProperty", { + enumerable: true, + get: function () { + return _index.classProperty; + } + }); + Object.defineProperty(exports, "ConditionalExpression", { + enumerable: true, + get: function () { + return _index.conditionalExpression; + } + }); + Object.defineProperty(exports, "ContinueStatement", { + enumerable: true, + get: function () { + return _index.continueStatement; + } + }); + Object.defineProperty(exports, "DebuggerStatement", { + enumerable: true, + get: function () { + return _index.debuggerStatement; + } + }); + Object.defineProperty(exports, "DecimalLiteral", { + enumerable: true, + get: function () { + return _index.decimalLiteral; + } + }); + Object.defineProperty(exports, "DeclareClass", { + enumerable: true, + get: function () { + return _index.declareClass; + } + }); + Object.defineProperty(exports, "DeclareExportAllDeclaration", { + enumerable: true, + get: function () { + return _index.declareExportAllDeclaration; + } + }); + Object.defineProperty(exports, "DeclareExportDeclaration", { + enumerable: true, + get: function () { + return _index.declareExportDeclaration; + } + }); + Object.defineProperty(exports, "DeclareFunction", { + enumerable: true, + get: function () { + return _index.declareFunction; + } + }); + Object.defineProperty(exports, "DeclareInterface", { + enumerable: true, + get: function () { + return _index.declareInterface; + } + }); + Object.defineProperty(exports, "DeclareModule", { + enumerable: true, + get: function () { + return _index.declareModule; + } + }); + Object.defineProperty(exports, "DeclareModuleExports", { + enumerable: true, + get: function () { + return _index.declareModuleExports; + } + }); + Object.defineProperty(exports, "DeclareOpaqueType", { + enumerable: true, + get: function () { + return _index.declareOpaqueType; + } + }); + Object.defineProperty(exports, "DeclareTypeAlias", { + enumerable: true, + get: function () { + return _index.declareTypeAlias; + } + }); + Object.defineProperty(exports, "DeclareVariable", { + enumerable: true, + get: function () { + return _index.declareVariable; + } + }); + Object.defineProperty(exports, "DeclaredPredicate", { + enumerable: true, + get: function () { + return _index.declaredPredicate; + } + }); + Object.defineProperty(exports, "Decorator", { + enumerable: true, + get: function () { + return _index.decorator; + } + }); + Object.defineProperty(exports, "Directive", { + enumerable: true, + get: function () { + return _index.directive; + } + }); + Object.defineProperty(exports, "DirectiveLiteral", { + enumerable: true, + get: function () { + return _index.directiveLiteral; + } + }); + Object.defineProperty(exports, "DoExpression", { + enumerable: true, + get: function () { + return _index.doExpression; + } + }); + Object.defineProperty(exports, "DoWhileStatement", { + enumerable: true, + get: function () { + return _index.doWhileStatement; + } + }); + Object.defineProperty(exports, "EmptyStatement", { + enumerable: true, + get: function () { + return _index.emptyStatement; + } + }); + Object.defineProperty(exports, "EmptyTypeAnnotation", { + enumerable: true, + get: function () { + return _index.emptyTypeAnnotation; + } + }); + Object.defineProperty(exports, "EnumBooleanBody", { + enumerable: true, + get: function () { + return _index.enumBooleanBody; + } + }); + Object.defineProperty(exports, "EnumBooleanMember", { + enumerable: true, + get: function () { + return _index.enumBooleanMember; + } + }); + Object.defineProperty(exports, "EnumDeclaration", { + enumerable: true, + get: function () { + return _index.enumDeclaration; + } + }); + Object.defineProperty(exports, "EnumDefaultedMember", { + enumerable: true, + get: function () { + return _index.enumDefaultedMember; + } + }); + Object.defineProperty(exports, "EnumNumberBody", { + enumerable: true, + get: function () { + return _index.enumNumberBody; + } + }); + Object.defineProperty(exports, "EnumNumberMember", { + enumerable: true, + get: function () { + return _index.enumNumberMember; + } + }); + Object.defineProperty(exports, "EnumStringBody", { + enumerable: true, + get: function () { + return _index.enumStringBody; + } + }); + Object.defineProperty(exports, "EnumStringMember", { + enumerable: true, + get: function () { + return _index.enumStringMember; + } + }); + Object.defineProperty(exports, "EnumSymbolBody", { + enumerable: true, + get: function () { + return _index.enumSymbolBody; + } + }); + Object.defineProperty(exports, "ExistsTypeAnnotation", { + enumerable: true, + get: function () { + return _index.existsTypeAnnotation; + } + }); + Object.defineProperty(exports, "ExportAllDeclaration", { + enumerable: true, + get: function () { + return _index.exportAllDeclaration; + } + }); + Object.defineProperty(exports, "ExportDefaultDeclaration", { + enumerable: true, + get: function () { + return _index.exportDefaultDeclaration; + } + }); + Object.defineProperty(exports, "ExportDefaultSpecifier", { + enumerable: true, + get: function () { + return _index.exportDefaultSpecifier; + } + }); + Object.defineProperty(exports, "ExportNamedDeclaration", { + enumerable: true, + get: function () { + return _index.exportNamedDeclaration; + } + }); + Object.defineProperty(exports, "ExportNamespaceSpecifier", { + enumerable: true, + get: function () { + return _index.exportNamespaceSpecifier; + } + }); + Object.defineProperty(exports, "ExportSpecifier", { + enumerable: true, + get: function () { + return _index.exportSpecifier; + } + }); + Object.defineProperty(exports, "ExpressionStatement", { + enumerable: true, + get: function () { + return _index.expressionStatement; + } + }); + Object.defineProperty(exports, "File", { + enumerable: true, + get: function () { + return _index.file; + } + }); + Object.defineProperty(exports, "ForInStatement", { + enumerable: true, + get: function () { + return _index.forInStatement; + } + }); + Object.defineProperty(exports, "ForOfStatement", { + enumerable: true, + get: function () { + return _index.forOfStatement; + } + }); + Object.defineProperty(exports, "ForStatement", { + enumerable: true, + get: function () { + return _index.forStatement; + } + }); + Object.defineProperty(exports, "FunctionDeclaration", { + enumerable: true, + get: function () { + return _index.functionDeclaration; + } + }); + Object.defineProperty(exports, "FunctionExpression", { + enumerable: true, + get: function () { + return _index.functionExpression; + } + }); + Object.defineProperty(exports, "FunctionTypeAnnotation", { + enumerable: true, + get: function () { + return _index.functionTypeAnnotation; + } + }); + Object.defineProperty(exports, "FunctionTypeParam", { + enumerable: true, + get: function () { + return _index.functionTypeParam; + } + }); + Object.defineProperty(exports, "GenericTypeAnnotation", { + enumerable: true, + get: function () { + return _index.genericTypeAnnotation; + } + }); + Object.defineProperty(exports, "Identifier", { + enumerable: true, + get: function () { + return _index.identifier; + } + }); + Object.defineProperty(exports, "IfStatement", { + enumerable: true, + get: function () { + return _index.ifStatement; + } + }); + Object.defineProperty(exports, "Import", { + enumerable: true, + get: function () { + return _index.import; + } + }); + Object.defineProperty(exports, "ImportAttribute", { + enumerable: true, + get: function () { + return _index.importAttribute; + } + }); + Object.defineProperty(exports, "ImportDeclaration", { + enumerable: true, + get: function () { + return _index.importDeclaration; + } + }); + Object.defineProperty(exports, "ImportDefaultSpecifier", { + enumerable: true, + get: function () { + return _index.importDefaultSpecifier; + } + }); + Object.defineProperty(exports, "ImportExpression", { + enumerable: true, + get: function () { + return _index.importExpression; + } + }); + Object.defineProperty(exports, "ImportNamespaceSpecifier", { + enumerable: true, + get: function () { + return _index.importNamespaceSpecifier; + } + }); + Object.defineProperty(exports, "ImportSpecifier", { + enumerable: true, + get: function () { + return _index.importSpecifier; + } + }); + Object.defineProperty(exports, "IndexedAccessType", { + enumerable: true, + get: function () { + return _index.indexedAccessType; + } + }); + Object.defineProperty(exports, "InferredPredicate", { + enumerable: true, + get: function () { + return _index.inferredPredicate; + } + }); + Object.defineProperty(exports, "InterfaceDeclaration", { + enumerable: true, + get: function () { + return _index.interfaceDeclaration; + } + }); + Object.defineProperty(exports, "InterfaceExtends", { + enumerable: true, + get: function () { + return _index.interfaceExtends; + } + }); + Object.defineProperty(exports, "InterfaceTypeAnnotation", { + enumerable: true, + get: function () { + return _index.interfaceTypeAnnotation; + } + }); + Object.defineProperty(exports, "InterpreterDirective", { + enumerable: true, + get: function () { + return _index.interpreterDirective; + } + }); + Object.defineProperty(exports, "IntersectionTypeAnnotation", { + enumerable: true, + get: function () { + return _index.intersectionTypeAnnotation; + } + }); + Object.defineProperty(exports, "JSXAttribute", { + enumerable: true, + get: function () { + return _index.jsxAttribute; + } + }); + Object.defineProperty(exports, "JSXClosingElement", { + enumerable: true, + get: function () { + return _index.jsxClosingElement; + } + }); + Object.defineProperty(exports, "JSXClosingFragment", { + enumerable: true, + get: function () { + return _index.jsxClosingFragment; + } + }); + Object.defineProperty(exports, "JSXElement", { + enumerable: true, + get: function () { + return _index.jsxElement; + } + }); + Object.defineProperty(exports, "JSXEmptyExpression", { + enumerable: true, + get: function () { + return _index.jsxEmptyExpression; + } + }); + Object.defineProperty(exports, "JSXExpressionContainer", { + enumerable: true, + get: function () { + return _index.jsxExpressionContainer; + } + }); + Object.defineProperty(exports, "JSXFragment", { + enumerable: true, + get: function () { + return _index.jsxFragment; + } + }); + Object.defineProperty(exports, "JSXIdentifier", { + enumerable: true, + get: function () { + return _index.jsxIdentifier; + } + }); + Object.defineProperty(exports, "JSXMemberExpression", { + enumerable: true, + get: function () { + return _index.jsxMemberExpression; + } + }); + Object.defineProperty(exports, "JSXNamespacedName", { + enumerable: true, + get: function () { + return _index.jsxNamespacedName; + } + }); + Object.defineProperty(exports, "JSXOpeningElement", { + enumerable: true, + get: function () { + return _index.jsxOpeningElement; + } + }); + Object.defineProperty(exports, "JSXOpeningFragment", { + enumerable: true, + get: function () { + return _index.jsxOpeningFragment; + } + }); + Object.defineProperty(exports, "JSXSpreadAttribute", { + enumerable: true, + get: function () { + return _index.jsxSpreadAttribute; + } + }); + Object.defineProperty(exports, "JSXSpreadChild", { + enumerable: true, + get: function () { + return _index.jsxSpreadChild; + } + }); + Object.defineProperty(exports, "JSXText", { + enumerable: true, + get: function () { + return _index.jsxText; + } + }); + Object.defineProperty(exports, "LabeledStatement", { + enumerable: true, + get: function () { + return _index.labeledStatement; + } + }); + Object.defineProperty(exports, "LogicalExpression", { + enumerable: true, + get: function () { + return _index.logicalExpression; + } + }); + Object.defineProperty(exports, "MemberExpression", { + enumerable: true, + get: function () { + return _index.memberExpression; + } + }); + Object.defineProperty(exports, "MetaProperty", { + enumerable: true, + get: function () { + return _index.metaProperty; + } + }); + Object.defineProperty(exports, "MixedTypeAnnotation", { + enumerable: true, + get: function () { + return _index.mixedTypeAnnotation; + } + }); + Object.defineProperty(exports, "ModuleExpression", { + enumerable: true, + get: function () { + return _index.moduleExpression; + } + }); + Object.defineProperty(exports, "NewExpression", { + enumerable: true, + get: function () { + return _index.newExpression; + } + }); + Object.defineProperty(exports, "Noop", { + enumerable: true, + get: function () { + return _index.noop; + } + }); + Object.defineProperty(exports, "NullLiteral", { + enumerable: true, + get: function () { + return _index.nullLiteral; + } + }); + Object.defineProperty(exports, "NullLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _index.nullLiteralTypeAnnotation; + } + }); + Object.defineProperty(exports, "NullableTypeAnnotation", { + enumerable: true, + get: function () { + return _index.nullableTypeAnnotation; + } + }); + Object.defineProperty(exports, "NumberLiteral", { + enumerable: true, + get: function () { + return _index.numberLiteral; + } + }); + Object.defineProperty(exports, "NumberLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _index.numberLiteralTypeAnnotation; + } + }); + Object.defineProperty(exports, "NumberTypeAnnotation", { + enumerable: true, + get: function () { + return _index.numberTypeAnnotation; + } + }); + Object.defineProperty(exports, "NumericLiteral", { + enumerable: true, + get: function () { + return _index.numericLiteral; + } + }); + Object.defineProperty(exports, "ObjectExpression", { + enumerable: true, + get: function () { + return _index.objectExpression; + } + }); + Object.defineProperty(exports, "ObjectMethod", { + enumerable: true, + get: function () { + return _index.objectMethod; + } + }); + Object.defineProperty(exports, "ObjectPattern", { + enumerable: true, + get: function () { + return _index.objectPattern; + } + }); + Object.defineProperty(exports, "ObjectProperty", { + enumerable: true, + get: function () { + return _index.objectProperty; + } + }); + Object.defineProperty(exports, "ObjectTypeAnnotation", { + enumerable: true, + get: function () { + return _index.objectTypeAnnotation; + } + }); + Object.defineProperty(exports, "ObjectTypeCallProperty", { + enumerable: true, + get: function () { + return _index.objectTypeCallProperty; + } + }); + Object.defineProperty(exports, "ObjectTypeIndexer", { + enumerable: true, + get: function () { + return _index.objectTypeIndexer; + } + }); + Object.defineProperty(exports, "ObjectTypeInternalSlot", { + enumerable: true, + get: function () { + return _index.objectTypeInternalSlot; + } + }); + Object.defineProperty(exports, "ObjectTypeProperty", { + enumerable: true, + get: function () { + return _index.objectTypeProperty; + } + }); + Object.defineProperty(exports, "ObjectTypeSpreadProperty", { + enumerable: true, + get: function () { + return _index.objectTypeSpreadProperty; + } + }); + Object.defineProperty(exports, "OpaqueType", { + enumerable: true, + get: function () { + return _index.opaqueType; + } + }); + Object.defineProperty(exports, "OptionalCallExpression", { + enumerable: true, + get: function () { + return _index.optionalCallExpression; + } + }); + Object.defineProperty(exports, "OptionalIndexedAccessType", { + enumerable: true, + get: function () { + return _index.optionalIndexedAccessType; + } + }); + Object.defineProperty(exports, "OptionalMemberExpression", { + enumerable: true, + get: function () { + return _index.optionalMemberExpression; + } + }); + Object.defineProperty(exports, "ParenthesizedExpression", { + enumerable: true, + get: function () { + return _index.parenthesizedExpression; + } + }); + Object.defineProperty(exports, "PipelineBareFunction", { + enumerable: true, + get: function () { + return _index.pipelineBareFunction; + } + }); + Object.defineProperty(exports, "PipelinePrimaryTopicReference", { + enumerable: true, + get: function () { + return _index.pipelinePrimaryTopicReference; + } + }); + Object.defineProperty(exports, "PipelineTopicExpression", { + enumerable: true, + get: function () { + return _index.pipelineTopicExpression; + } + }); + Object.defineProperty(exports, "Placeholder", { + enumerable: true, + get: function () { + return _index.placeholder; + } + }); + Object.defineProperty(exports, "PrivateName", { + enumerable: true, + get: function () { + return _index.privateName; + } + }); + Object.defineProperty(exports, "Program", { + enumerable: true, + get: function () { + return _index.program; + } + }); + Object.defineProperty(exports, "QualifiedTypeIdentifier", { + enumerable: true, + get: function () { + return _index.qualifiedTypeIdentifier; + } + }); + Object.defineProperty(exports, "RecordExpression", { + enumerable: true, + get: function () { + return _index.recordExpression; + } + }); + Object.defineProperty(exports, "RegExpLiteral", { + enumerable: true, + get: function () { + return _index.regExpLiteral; + } + }); + Object.defineProperty(exports, "RegexLiteral", { + enumerable: true, + get: function () { + return _index.regexLiteral; + } + }); + Object.defineProperty(exports, "RestElement", { + enumerable: true, + get: function () { + return _index.restElement; + } + }); + Object.defineProperty(exports, "RestProperty", { + enumerable: true, + get: function () { + return _index.restProperty; + } + }); + Object.defineProperty(exports, "ReturnStatement", { + enumerable: true, + get: function () { + return _index.returnStatement; + } + }); + Object.defineProperty(exports, "SequenceExpression", { + enumerable: true, + get: function () { + return _index.sequenceExpression; + } + }); + Object.defineProperty(exports, "SpreadElement", { + enumerable: true, + get: function () { + return _index.spreadElement; + } + }); + Object.defineProperty(exports, "SpreadProperty", { + enumerable: true, + get: function () { + return _index.spreadProperty; + } + }); + Object.defineProperty(exports, "StaticBlock", { + enumerable: true, + get: function () { + return _index.staticBlock; + } + }); + Object.defineProperty(exports, "StringLiteral", { + enumerable: true, + get: function () { + return _index.stringLiteral; + } + }); + Object.defineProperty(exports, "StringLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _index.stringLiteralTypeAnnotation; + } + }); + Object.defineProperty(exports, "StringTypeAnnotation", { + enumerable: true, + get: function () { + return _index.stringTypeAnnotation; + } + }); + Object.defineProperty(exports, "Super", { + enumerable: true, + get: function () { + return _index.super; + } + }); + Object.defineProperty(exports, "SwitchCase", { + enumerable: true, + get: function () { + return _index.switchCase; + } + }); + Object.defineProperty(exports, "SwitchStatement", { + enumerable: true, + get: function () { + return _index.switchStatement; + } + }); + Object.defineProperty(exports, "SymbolTypeAnnotation", { + enumerable: true, + get: function () { + return _index.symbolTypeAnnotation; + } + }); + Object.defineProperty(exports, "TSAnyKeyword", { + enumerable: true, + get: function () { + return _index.tsAnyKeyword; + } + }); + Object.defineProperty(exports, "TSArrayType", { + enumerable: true, + get: function () { + return _index.tsArrayType; + } + }); + Object.defineProperty(exports, "TSAsExpression", { + enumerable: true, + get: function () { + return _index.tsAsExpression; + } + }); + Object.defineProperty(exports, "TSBigIntKeyword", { + enumerable: true, + get: function () { + return _index.tsBigIntKeyword; + } + }); + Object.defineProperty(exports, "TSBooleanKeyword", { + enumerable: true, + get: function () { + return _index.tsBooleanKeyword; + } + }); + Object.defineProperty(exports, "TSCallSignatureDeclaration", { + enumerable: true, + get: function () { + return _index.tsCallSignatureDeclaration; + } + }); + Object.defineProperty(exports, "TSConditionalType", { + enumerable: true, + get: function () { + return _index.tsConditionalType; + } + }); + Object.defineProperty(exports, "TSConstructSignatureDeclaration", { + enumerable: true, + get: function () { + return _index.tsConstructSignatureDeclaration; + } + }); + Object.defineProperty(exports, "TSConstructorType", { + enumerable: true, + get: function () { + return _index.tsConstructorType; + } + }); + Object.defineProperty(exports, "TSDeclareFunction", { + enumerable: true, + get: function () { + return _index.tsDeclareFunction; + } + }); + Object.defineProperty(exports, "TSDeclareMethod", { + enumerable: true, + get: function () { + return _index.tsDeclareMethod; + } + }); + Object.defineProperty(exports, "TSEnumDeclaration", { + enumerable: true, + get: function () { + return _index.tsEnumDeclaration; + } + }); + Object.defineProperty(exports, "TSEnumMember", { + enumerable: true, + get: function () { + return _index.tsEnumMember; + } + }); + Object.defineProperty(exports, "TSExportAssignment", { + enumerable: true, + get: function () { + return _index.tsExportAssignment; + } + }); + Object.defineProperty(exports, "TSExpressionWithTypeArguments", { + enumerable: true, + get: function () { + return _index.tsExpressionWithTypeArguments; + } + }); + Object.defineProperty(exports, "TSExternalModuleReference", { + enumerable: true, + get: function () { + return _index.tsExternalModuleReference; + } + }); + Object.defineProperty(exports, "TSFunctionType", { + enumerable: true, + get: function () { + return _index.tsFunctionType; + } + }); + Object.defineProperty(exports, "TSImportEqualsDeclaration", { + enumerable: true, + get: function () { + return _index.tsImportEqualsDeclaration; + } + }); + Object.defineProperty(exports, "TSImportType", { + enumerable: true, + get: function () { + return _index.tsImportType; + } + }); + Object.defineProperty(exports, "TSIndexSignature", { + enumerable: true, + get: function () { + return _index.tsIndexSignature; + } + }); + Object.defineProperty(exports, "TSIndexedAccessType", { + enumerable: true, + get: function () { + return _index.tsIndexedAccessType; + } + }); + Object.defineProperty(exports, "TSInferType", { + enumerable: true, + get: function () { + return _index.tsInferType; + } + }); + Object.defineProperty(exports, "TSInstantiationExpression", { + enumerable: true, + get: function () { + return _index.tsInstantiationExpression; + } + }); + Object.defineProperty(exports, "TSInterfaceBody", { + enumerable: true, + get: function () { + return _index.tsInterfaceBody; + } + }); + Object.defineProperty(exports, "TSInterfaceDeclaration", { + enumerable: true, + get: function () { + return _index.tsInterfaceDeclaration; + } + }); + Object.defineProperty(exports, "TSIntersectionType", { + enumerable: true, + get: function () { + return _index.tsIntersectionType; + } + }); + Object.defineProperty(exports, "TSIntrinsicKeyword", { + enumerable: true, + get: function () { + return _index.tsIntrinsicKeyword; + } + }); + Object.defineProperty(exports, "TSLiteralType", { + enumerable: true, + get: function () { + return _index.tsLiteralType; + } + }); + Object.defineProperty(exports, "TSMappedType", { + enumerable: true, + get: function () { + return _index.tsMappedType; + } + }); + Object.defineProperty(exports, "TSMethodSignature", { + enumerable: true, + get: function () { + return _index.tsMethodSignature; + } + }); + Object.defineProperty(exports, "TSModuleBlock", { + enumerable: true, + get: function () { + return _index.tsModuleBlock; + } + }); + Object.defineProperty(exports, "TSModuleDeclaration", { + enumerable: true, + get: function () { + return _index.tsModuleDeclaration; + } + }); + Object.defineProperty(exports, "TSNamedTupleMember", { + enumerable: true, + get: function () { + return _index.tsNamedTupleMember; + } + }); + Object.defineProperty(exports, "TSNamespaceExportDeclaration", { + enumerable: true, + get: function () { + return _index.tsNamespaceExportDeclaration; + } + }); + Object.defineProperty(exports, "TSNeverKeyword", { + enumerable: true, + get: function () { + return _index.tsNeverKeyword; + } + }); + Object.defineProperty(exports, "TSNonNullExpression", { + enumerable: true, + get: function () { + return _index.tsNonNullExpression; + } + }); + Object.defineProperty(exports, "TSNullKeyword", { + enumerable: true, + get: function () { + return _index.tsNullKeyword; + } + }); + Object.defineProperty(exports, "TSNumberKeyword", { + enumerable: true, + get: function () { + return _index.tsNumberKeyword; + } + }); + Object.defineProperty(exports, "TSObjectKeyword", { + enumerable: true, + get: function () { + return _index.tsObjectKeyword; + } + }); + Object.defineProperty(exports, "TSOptionalType", { + enumerable: true, + get: function () { + return _index.tsOptionalType; + } + }); + Object.defineProperty(exports, "TSParameterProperty", { + enumerable: true, + get: function () { + return _index.tsParameterProperty; + } + }); + Object.defineProperty(exports, "TSParenthesizedType", { + enumerable: true, + get: function () { + return _index.tsParenthesizedType; + } + }); + Object.defineProperty(exports, "TSPropertySignature", { + enumerable: true, + get: function () { + return _index.tsPropertySignature; + } + }); + Object.defineProperty(exports, "TSQualifiedName", { + enumerable: true, + get: function () { + return _index.tsQualifiedName; + } + }); + Object.defineProperty(exports, "TSRestType", { + enumerable: true, + get: function () { + return _index.tsRestType; + } + }); + Object.defineProperty(exports, "TSSatisfiesExpression", { + enumerable: true, + get: function () { + return _index.tsSatisfiesExpression; + } + }); + Object.defineProperty(exports, "TSStringKeyword", { + enumerable: true, + get: function () { + return _index.tsStringKeyword; + } + }); + Object.defineProperty(exports, "TSSymbolKeyword", { + enumerable: true, + get: function () { + return _index.tsSymbolKeyword; + } + }); + Object.defineProperty(exports, "TSThisType", { + enumerable: true, + get: function () { + return _index.tsThisType; + } + }); + Object.defineProperty(exports, "TSTupleType", { + enumerable: true, + get: function () { + return _index.tsTupleType; + } + }); + Object.defineProperty(exports, "TSTypeAliasDeclaration", { + enumerable: true, + get: function () { + return _index.tsTypeAliasDeclaration; + } + }); + Object.defineProperty(exports, "TSTypeAnnotation", { + enumerable: true, + get: function () { + return _index.tsTypeAnnotation; + } + }); + Object.defineProperty(exports, "TSTypeAssertion", { + enumerable: true, + get: function () { + return _index.tsTypeAssertion; + } + }); + Object.defineProperty(exports, "TSTypeLiteral", { + enumerable: true, + get: function () { + return _index.tsTypeLiteral; + } + }); + Object.defineProperty(exports, "TSTypeOperator", { + enumerable: true, + get: function () { + return _index.tsTypeOperator; + } + }); + Object.defineProperty(exports, "TSTypeParameter", { + enumerable: true, + get: function () { + return _index.tsTypeParameter; + } + }); + Object.defineProperty(exports, "TSTypeParameterDeclaration", { + enumerable: true, + get: function () { + return _index.tsTypeParameterDeclaration; + } + }); + Object.defineProperty(exports, "TSTypeParameterInstantiation", { + enumerable: true, + get: function () { + return _index.tsTypeParameterInstantiation; + } + }); + Object.defineProperty(exports, "TSTypePredicate", { + enumerable: true, + get: function () { + return _index.tsTypePredicate; + } + }); + Object.defineProperty(exports, "TSTypeQuery", { + enumerable: true, + get: function () { + return _index.tsTypeQuery; + } + }); + Object.defineProperty(exports, "TSTypeReference", { + enumerable: true, + get: function () { + return _index.tsTypeReference; + } + }); + Object.defineProperty(exports, "TSUndefinedKeyword", { + enumerable: true, + get: function () { + return _index.tsUndefinedKeyword; + } + }); + Object.defineProperty(exports, "TSUnionType", { + enumerable: true, + get: function () { + return _index.tsUnionType; + } + }); + Object.defineProperty(exports, "TSUnknownKeyword", { + enumerable: true, + get: function () { + return _index.tsUnknownKeyword; + } + }); + Object.defineProperty(exports, "TSVoidKeyword", { + enumerable: true, + get: function () { + return _index.tsVoidKeyword; + } + }); + Object.defineProperty(exports, "TaggedTemplateExpression", { + enumerable: true, + get: function () { + return _index.taggedTemplateExpression; + } + }); + Object.defineProperty(exports, "TemplateElement", { + enumerable: true, + get: function () { + return _index.templateElement; + } + }); + Object.defineProperty(exports, "TemplateLiteral", { + enumerable: true, + get: function () { + return _index.templateLiteral; + } + }); + Object.defineProperty(exports, "ThisExpression", { + enumerable: true, + get: function () { + return _index.thisExpression; + } + }); + Object.defineProperty(exports, "ThisTypeAnnotation", { + enumerable: true, + get: function () { + return _index.thisTypeAnnotation; + } + }); + Object.defineProperty(exports, "ThrowStatement", { + enumerable: true, + get: function () { + return _index.throwStatement; + } + }); + Object.defineProperty(exports, "TopicReference", { + enumerable: true, + get: function () { + return _index.topicReference; + } + }); + Object.defineProperty(exports, "TryStatement", { + enumerable: true, + get: function () { + return _index.tryStatement; + } + }); + Object.defineProperty(exports, "TupleExpression", { + enumerable: true, + get: function () { + return _index.tupleExpression; + } + }); + Object.defineProperty(exports, "TupleTypeAnnotation", { + enumerable: true, + get: function () { + return _index.tupleTypeAnnotation; + } + }); + Object.defineProperty(exports, "TypeAlias", { + enumerable: true, + get: function () { + return _index.typeAlias; + } + }); + Object.defineProperty(exports, "TypeAnnotation", { + enumerable: true, + get: function () { + return _index.typeAnnotation; + } + }); + Object.defineProperty(exports, "TypeCastExpression", { + enumerable: true, + get: function () { + return _index.typeCastExpression; + } + }); + Object.defineProperty(exports, "TypeParameter", { + enumerable: true, + get: function () { + return _index.typeParameter; + } + }); + Object.defineProperty(exports, "TypeParameterDeclaration", { + enumerable: true, + get: function () { + return _index.typeParameterDeclaration; + } + }); + Object.defineProperty(exports, "TypeParameterInstantiation", { + enumerable: true, + get: function () { + return _index.typeParameterInstantiation; + } + }); + Object.defineProperty(exports, "TypeofTypeAnnotation", { + enumerable: true, + get: function () { + return _index.typeofTypeAnnotation; + } + }); + Object.defineProperty(exports, "UnaryExpression", { + enumerable: true, + get: function () { + return _index.unaryExpression; + } + }); + Object.defineProperty(exports, "UnionTypeAnnotation", { + enumerable: true, + get: function () { + return _index.unionTypeAnnotation; + } + }); + Object.defineProperty(exports, "UpdateExpression", { + enumerable: true, + get: function () { + return _index.updateExpression; + } + }); + Object.defineProperty(exports, "V8IntrinsicIdentifier", { + enumerable: true, + get: function () { + return _index.v8IntrinsicIdentifier; + } + }); + Object.defineProperty(exports, "VariableDeclaration", { + enumerable: true, + get: function () { + return _index.variableDeclaration; + } + }); + Object.defineProperty(exports, "VariableDeclarator", { + enumerable: true, + get: function () { + return _index.variableDeclarator; + } + }); + Object.defineProperty(exports, "Variance", { + enumerable: true, + get: function () { + return _index.variance; + } + }); + Object.defineProperty(exports, "VoidTypeAnnotation", { + enumerable: true, + get: function () { + return _index.voidTypeAnnotation; + } + }); + Object.defineProperty(exports, "WhileStatement", { + enumerable: true, + get: function () { + return _index.whileStatement; + } + }); + Object.defineProperty(exports, "WithStatement", { + enumerable: true, + get: function () { + return _index.withStatement; + } + }); + Object.defineProperty(exports, "YieldExpression", { + enumerable: true, + get: function () { + return _index.yieldExpression; + } + }); + var _index = requireGenerated$2(); + + +} (uppercase)); + return uppercase; +} + +var productions = {}; + +var hasRequiredProductions; + +function requireProductions () { + if (hasRequiredProductions) return productions; + hasRequiredProductions = 1; + + Object.defineProperty(productions, "__esModule", { + value: true + }); + productions.buildUndefinedNode = buildUndefinedNode; + var _index = requireGenerated$2(); + function buildUndefinedNode() { + return (0, _index.unaryExpression)("void", (0, _index.numericLiteral)(0), true); + } + + + return productions; +} + +var cloneNode = {}; + +var hasRequiredCloneNode; + +function requireCloneNode () { + if (hasRequiredCloneNode) return cloneNode; + hasRequiredCloneNode = 1; + + Object.defineProperty(cloneNode, "__esModule", { + value: true + }); + cloneNode.default = cloneNode$1; + var _index = requireDefinitions(); + var _index2 = requireGenerated$3(); + const { + hasOwn + } = { + hasOwn: Function.call.bind(Object.prototype.hasOwnProperty) + }; + function cloneIfNode(obj, deep, withoutLoc, commentsCache) { + if (obj && typeof obj.type === "string") { + return cloneNodeInternal(obj, deep, withoutLoc, commentsCache); + } + return obj; + } + function cloneIfNodeOrArray(obj, deep, withoutLoc, commentsCache) { + if (Array.isArray(obj)) { + return obj.map(node => cloneIfNode(node, deep, withoutLoc, commentsCache)); + } + return cloneIfNode(obj, deep, withoutLoc, commentsCache); + } + function cloneNode$1(node, deep = true, withoutLoc = false) { + return cloneNodeInternal(node, deep, withoutLoc, new Map()); + } + function cloneNodeInternal(node, deep = true, withoutLoc = false, commentsCache) { + if (!node) return node; + const { + type + } = node; + const newNode = { + type: node.type + }; + if ((0, _index2.isIdentifier)(node)) { + newNode.name = node.name; + if (hasOwn(node, "optional") && typeof node.optional === "boolean") { + newNode.optional = node.optional; + } + if (hasOwn(node, "typeAnnotation")) { + newNode.typeAnnotation = deep ? cloneIfNodeOrArray(node.typeAnnotation, true, withoutLoc, commentsCache) : node.typeAnnotation; + } + if (hasOwn(node, "decorators")) { + newNode.decorators = deep ? cloneIfNodeOrArray(node.decorators, true, withoutLoc, commentsCache) : node.decorators; + } + } else if (!hasOwn(_index.NODE_FIELDS, type)) { + throw new Error(`Unknown node type: "${type}"`); + } else { + for (const field of Object.keys(_index.NODE_FIELDS[type])) { + if (hasOwn(node, field)) { + if (deep) { + newNode[field] = (0, _index2.isFile)(node) && field === "comments" ? maybeCloneComments(node.comments, deep, withoutLoc, commentsCache) : cloneIfNodeOrArray(node[field], true, withoutLoc, commentsCache); + } else { + newNode[field] = node[field]; + } + } + } + } + if (hasOwn(node, "loc")) { + if (withoutLoc) { + newNode.loc = null; + } else { + newNode.loc = node.loc; + } + } + if (hasOwn(node, "leadingComments")) { + newNode.leadingComments = maybeCloneComments(node.leadingComments, deep, withoutLoc, commentsCache); + } + if (hasOwn(node, "innerComments")) { + newNode.innerComments = maybeCloneComments(node.innerComments, deep, withoutLoc, commentsCache); + } + if (hasOwn(node, "trailingComments")) { + newNode.trailingComments = maybeCloneComments(node.trailingComments, deep, withoutLoc, commentsCache); + } + if (hasOwn(node, "extra")) { + newNode.extra = Object.assign({}, node.extra); + } + return newNode; + } + function maybeCloneComments(comments, deep, withoutLoc, commentsCache) { + if (!comments || !deep) { + return comments; + } + return comments.map(comment => { + const cache = commentsCache.get(comment); + if (cache) return cache; + const { + type, + value, + loc + } = comment; + const ret = { + type, + value, + loc + }; + if (withoutLoc) { + ret.loc = null; + } + commentsCache.set(comment, ret); + return ret; + }); + } + + + return cloneNode; +} + +var clone = {}; + +var hasRequiredClone; + +function requireClone () { + if (hasRequiredClone) return clone; + hasRequiredClone = 1; + + Object.defineProperty(clone, "__esModule", { + value: true + }); + clone.default = clone$1; + var _cloneNode = requireCloneNode(); + function clone$1(node) { + return (0, _cloneNode.default)(node, false); + } + + + return clone; +} + +var cloneDeep = {}; + +var hasRequiredCloneDeep; + +function requireCloneDeep () { + if (hasRequiredCloneDeep) return cloneDeep; + hasRequiredCloneDeep = 1; + + Object.defineProperty(cloneDeep, "__esModule", { + value: true + }); + cloneDeep.default = cloneDeep$1; + var _cloneNode = requireCloneNode(); + function cloneDeep$1(node) { + return (0, _cloneNode.default)(node); + } + + + return cloneDeep; +} + +var cloneDeepWithoutLoc = {}; + +var hasRequiredCloneDeepWithoutLoc; + +function requireCloneDeepWithoutLoc () { + if (hasRequiredCloneDeepWithoutLoc) return cloneDeepWithoutLoc; + hasRequiredCloneDeepWithoutLoc = 1; + + Object.defineProperty(cloneDeepWithoutLoc, "__esModule", { + value: true + }); + cloneDeepWithoutLoc.default = cloneDeepWithoutLoc$1; + var _cloneNode = requireCloneNode(); + function cloneDeepWithoutLoc$1(node) { + return (0, _cloneNode.default)(node, true, true); + } + + + return cloneDeepWithoutLoc; +} + +var cloneWithoutLoc = {}; + +var hasRequiredCloneWithoutLoc; + +function requireCloneWithoutLoc () { + if (hasRequiredCloneWithoutLoc) return cloneWithoutLoc; + hasRequiredCloneWithoutLoc = 1; + + Object.defineProperty(cloneWithoutLoc, "__esModule", { + value: true + }); + cloneWithoutLoc.default = cloneWithoutLoc$1; + var _cloneNode = requireCloneNode(); + function cloneWithoutLoc$1(node) { + return (0, _cloneNode.default)(node, false, true); + } + + + return cloneWithoutLoc; +} + +var addComment = {}; + +var addComments = {}; + +var hasRequiredAddComments; + +function requireAddComments () { + if (hasRequiredAddComments) return addComments; + hasRequiredAddComments = 1; + + Object.defineProperty(addComments, "__esModule", { + value: true + }); + addComments.default = addComments$1; + function addComments$1(node, type, comments) { + if (!comments || !node) return node; + const key = `${type}Comments`; + if (node[key]) { + if (type === "leading") { + node[key] = comments.concat(node[key]); + } else { + node[key].push(...comments); + } + } else { + node[key] = comments; + } + return node; + } + + + return addComments; +} + +var hasRequiredAddComment; + +function requireAddComment () { + if (hasRequiredAddComment) return addComment; + hasRequiredAddComment = 1; + + Object.defineProperty(addComment, "__esModule", { + value: true + }); + addComment.default = addComment$1; + var _addComments = requireAddComments(); + function addComment$1(node, type, content, line) { + return (0, _addComments.default)(node, type, [{ + type: line ? "CommentLine" : "CommentBlock", + value: content + }]); + } + + + return addComment; +} + +var inheritInnerComments = {}; + +var inherit = {}; + +var hasRequiredInherit; + +function requireInherit () { + if (hasRequiredInherit) return inherit; + hasRequiredInherit = 1; + + Object.defineProperty(inherit, "__esModule", { + value: true + }); + inherit.default = inherit$1; + function inherit$1(key, child, parent) { + if (child && parent) { + child[key] = Array.from(new Set([].concat(child[key], parent[key]).filter(Boolean))); + } + } + + + return inherit; +} + +var hasRequiredInheritInnerComments; + +function requireInheritInnerComments () { + if (hasRequiredInheritInnerComments) return inheritInnerComments; + hasRequiredInheritInnerComments = 1; + + Object.defineProperty(inheritInnerComments, "__esModule", { + value: true + }); + inheritInnerComments.default = inheritInnerComments$1; + var _inherit = requireInherit(); + function inheritInnerComments$1(child, parent) { + (0, _inherit.default)("innerComments", child, parent); + } + + + return inheritInnerComments; +} + +var inheritLeadingComments = {}; + +var hasRequiredInheritLeadingComments; + +function requireInheritLeadingComments () { + if (hasRequiredInheritLeadingComments) return inheritLeadingComments; + hasRequiredInheritLeadingComments = 1; + + Object.defineProperty(inheritLeadingComments, "__esModule", { + value: true + }); + inheritLeadingComments.default = inheritLeadingComments$1; + var _inherit = requireInherit(); + function inheritLeadingComments$1(child, parent) { + (0, _inherit.default)("leadingComments", child, parent); + } + + + return inheritLeadingComments; +} + +var inheritsComments = {}; + +var inheritTrailingComments = {}; + +var hasRequiredInheritTrailingComments; + +function requireInheritTrailingComments () { + if (hasRequiredInheritTrailingComments) return inheritTrailingComments; + hasRequiredInheritTrailingComments = 1; + + Object.defineProperty(inheritTrailingComments, "__esModule", { + value: true + }); + inheritTrailingComments.default = inheritTrailingComments$1; + var _inherit = requireInherit(); + function inheritTrailingComments$1(child, parent) { + (0, _inherit.default)("trailingComments", child, parent); + } + + + return inheritTrailingComments; +} + +var hasRequiredInheritsComments; + +function requireInheritsComments () { + if (hasRequiredInheritsComments) return inheritsComments; + hasRequiredInheritsComments = 1; + + Object.defineProperty(inheritsComments, "__esModule", { + value: true + }); + inheritsComments.default = inheritsComments$1; + var _inheritTrailingComments = requireInheritTrailingComments(); + var _inheritLeadingComments = requireInheritLeadingComments(); + var _inheritInnerComments = requireInheritInnerComments(); + function inheritsComments$1(child, parent) { + (0, _inheritTrailingComments.default)(child, parent); + (0, _inheritLeadingComments.default)(child, parent); + (0, _inheritInnerComments.default)(child, parent); + return child; + } + + + return inheritsComments; +} + +var removeComments = {}; + +var hasRequiredRemoveComments; + +function requireRemoveComments () { + if (hasRequiredRemoveComments) return removeComments; + hasRequiredRemoveComments = 1; + + Object.defineProperty(removeComments, "__esModule", { + value: true + }); + removeComments.default = removeComments$1; + var _index = requireConstants(); + function removeComments$1(node) { + _index.COMMENT_KEYS.forEach(key => { + node[key] = null; + }); + return node; + } + + + return removeComments; +} + +var generated = {}; + +var hasRequiredGenerated; + +function requireGenerated () { + if (hasRequiredGenerated) return generated; + hasRequiredGenerated = 1; + + Object.defineProperty(generated, "__esModule", { + value: true + }); + generated.WHILE_TYPES = generated.USERWHITESPACABLE_TYPES = generated.UNARYLIKE_TYPES = generated.TYPESCRIPT_TYPES = generated.TSTYPE_TYPES = generated.TSTYPEELEMENT_TYPES = generated.TSENTITYNAME_TYPES = generated.TSBASETYPE_TYPES = generated.TERMINATORLESS_TYPES = generated.STATEMENT_TYPES = generated.STANDARDIZED_TYPES = generated.SCOPABLE_TYPES = generated.PUREISH_TYPES = generated.PROPERTY_TYPES = generated.PRIVATE_TYPES = generated.PATTERN_TYPES = generated.PATTERNLIKE_TYPES = generated.OBJECTMEMBER_TYPES = generated.MODULESPECIFIER_TYPES = generated.MODULEDECLARATION_TYPES = generated.MISCELLANEOUS_TYPES = generated.METHOD_TYPES = generated.LVAL_TYPES = generated.LOOP_TYPES = generated.LITERAL_TYPES = generated.JSX_TYPES = generated.IMPORTOREXPORTDECLARATION_TYPES = generated.IMMUTABLE_TYPES = generated.FUNCTION_TYPES = generated.FUNCTIONPARENT_TYPES = generated.FOR_TYPES = generated.FORXSTATEMENT_TYPES = generated.FLOW_TYPES = generated.FLOWTYPE_TYPES = generated.FLOWPREDICATE_TYPES = generated.FLOWDECLARATION_TYPES = generated.FLOWBASEANNOTATION_TYPES = generated.EXPRESSION_TYPES = generated.EXPRESSIONWRAPPER_TYPES = generated.EXPORTDECLARATION_TYPES = generated.ENUMMEMBER_TYPES = generated.ENUMBODY_TYPES = generated.DECLARATION_TYPES = generated.CONDITIONAL_TYPES = generated.COMPLETIONSTATEMENT_TYPES = generated.CLASS_TYPES = generated.BLOCK_TYPES = generated.BLOCKPARENT_TYPES = generated.BINARY_TYPES = generated.ACCESSOR_TYPES = void 0; + var _index = requireDefinitions(); + generated.STANDARDIZED_TYPES = _index.FLIPPED_ALIAS_KEYS["Standardized"]; + generated.EXPRESSION_TYPES = _index.FLIPPED_ALIAS_KEYS["Expression"]; + generated.BINARY_TYPES = _index.FLIPPED_ALIAS_KEYS["Binary"]; + generated.SCOPABLE_TYPES = _index.FLIPPED_ALIAS_KEYS["Scopable"]; + generated.BLOCKPARENT_TYPES = _index.FLIPPED_ALIAS_KEYS["BlockParent"]; + generated.BLOCK_TYPES = _index.FLIPPED_ALIAS_KEYS["Block"]; + generated.STATEMENT_TYPES = _index.FLIPPED_ALIAS_KEYS["Statement"]; + generated.TERMINATORLESS_TYPES = _index.FLIPPED_ALIAS_KEYS["Terminatorless"]; + generated.COMPLETIONSTATEMENT_TYPES = _index.FLIPPED_ALIAS_KEYS["CompletionStatement"]; + generated.CONDITIONAL_TYPES = _index.FLIPPED_ALIAS_KEYS["Conditional"]; + generated.LOOP_TYPES = _index.FLIPPED_ALIAS_KEYS["Loop"]; + generated.WHILE_TYPES = _index.FLIPPED_ALIAS_KEYS["While"]; + generated.EXPRESSIONWRAPPER_TYPES = _index.FLIPPED_ALIAS_KEYS["ExpressionWrapper"]; + generated.FOR_TYPES = _index.FLIPPED_ALIAS_KEYS["For"]; + generated.FORXSTATEMENT_TYPES = _index.FLIPPED_ALIAS_KEYS["ForXStatement"]; + generated.FUNCTION_TYPES = _index.FLIPPED_ALIAS_KEYS["Function"]; + generated.FUNCTIONPARENT_TYPES = _index.FLIPPED_ALIAS_KEYS["FunctionParent"]; + generated.PUREISH_TYPES = _index.FLIPPED_ALIAS_KEYS["Pureish"]; + generated.DECLARATION_TYPES = _index.FLIPPED_ALIAS_KEYS["Declaration"]; + generated.PATTERNLIKE_TYPES = _index.FLIPPED_ALIAS_KEYS["PatternLike"]; + generated.LVAL_TYPES = _index.FLIPPED_ALIAS_KEYS["LVal"]; + generated.TSENTITYNAME_TYPES = _index.FLIPPED_ALIAS_KEYS["TSEntityName"]; + generated.LITERAL_TYPES = _index.FLIPPED_ALIAS_KEYS["Literal"]; + generated.IMMUTABLE_TYPES = _index.FLIPPED_ALIAS_KEYS["Immutable"]; + generated.USERWHITESPACABLE_TYPES = _index.FLIPPED_ALIAS_KEYS["UserWhitespacable"]; + generated.METHOD_TYPES = _index.FLIPPED_ALIAS_KEYS["Method"]; + generated.OBJECTMEMBER_TYPES = _index.FLIPPED_ALIAS_KEYS["ObjectMember"]; + generated.PROPERTY_TYPES = _index.FLIPPED_ALIAS_KEYS["Property"]; + generated.UNARYLIKE_TYPES = _index.FLIPPED_ALIAS_KEYS["UnaryLike"]; + generated.PATTERN_TYPES = _index.FLIPPED_ALIAS_KEYS["Pattern"]; + generated.CLASS_TYPES = _index.FLIPPED_ALIAS_KEYS["Class"]; + const IMPORTOREXPORTDECLARATION_TYPES = generated.IMPORTOREXPORTDECLARATION_TYPES = _index.FLIPPED_ALIAS_KEYS["ImportOrExportDeclaration"]; + generated.EXPORTDECLARATION_TYPES = _index.FLIPPED_ALIAS_KEYS["ExportDeclaration"]; + generated.MODULESPECIFIER_TYPES = _index.FLIPPED_ALIAS_KEYS["ModuleSpecifier"]; + generated.ACCESSOR_TYPES = _index.FLIPPED_ALIAS_KEYS["Accessor"]; + generated.PRIVATE_TYPES = _index.FLIPPED_ALIAS_KEYS["Private"]; + generated.FLOW_TYPES = _index.FLIPPED_ALIAS_KEYS["Flow"]; + generated.FLOWTYPE_TYPES = _index.FLIPPED_ALIAS_KEYS["FlowType"]; + generated.FLOWBASEANNOTATION_TYPES = _index.FLIPPED_ALIAS_KEYS["FlowBaseAnnotation"]; + generated.FLOWDECLARATION_TYPES = _index.FLIPPED_ALIAS_KEYS["FlowDeclaration"]; + generated.FLOWPREDICATE_TYPES = _index.FLIPPED_ALIAS_KEYS["FlowPredicate"]; + generated.ENUMBODY_TYPES = _index.FLIPPED_ALIAS_KEYS["EnumBody"]; + generated.ENUMMEMBER_TYPES = _index.FLIPPED_ALIAS_KEYS["EnumMember"]; + generated.JSX_TYPES = _index.FLIPPED_ALIAS_KEYS["JSX"]; + generated.MISCELLANEOUS_TYPES = _index.FLIPPED_ALIAS_KEYS["Miscellaneous"]; + generated.TYPESCRIPT_TYPES = _index.FLIPPED_ALIAS_KEYS["TypeScript"]; + generated.TSTYPEELEMENT_TYPES = _index.FLIPPED_ALIAS_KEYS["TSTypeElement"]; + generated.TSTYPE_TYPES = _index.FLIPPED_ALIAS_KEYS["TSType"]; + generated.TSBASETYPE_TYPES = _index.FLIPPED_ALIAS_KEYS["TSBaseType"]; + generated.MODULEDECLARATION_TYPES = IMPORTOREXPORTDECLARATION_TYPES; + + + return generated; +} + +var ensureBlock = {}; + +var toBlock = {}; + +var hasRequiredToBlock; + +function requireToBlock () { + if (hasRequiredToBlock) return toBlock; + hasRequiredToBlock = 1; + + Object.defineProperty(toBlock, "__esModule", { + value: true + }); + toBlock.default = toBlock$1; + var _index = requireGenerated$3(); + var _index2 = requireGenerated$2(); + function toBlock$1(node, parent) { + if ((0, _index.isBlockStatement)(node)) { + return node; + } + let blockNodes = []; + if ((0, _index.isEmptyStatement)(node)) { + blockNodes = []; + } else { + if (!(0, _index.isStatement)(node)) { + if ((0, _index.isFunction)(parent)) { + node = (0, _index2.returnStatement)(node); + } else { + node = (0, _index2.expressionStatement)(node); + } + } + blockNodes = [node]; + } + return (0, _index2.blockStatement)(blockNodes); + } + + + return toBlock; +} + +var hasRequiredEnsureBlock; + +function requireEnsureBlock () { + if (hasRequiredEnsureBlock) return ensureBlock; + hasRequiredEnsureBlock = 1; + + Object.defineProperty(ensureBlock, "__esModule", { + value: true + }); + ensureBlock.default = ensureBlock$1; + var _toBlock = requireToBlock(); + function ensureBlock$1(node, key = "body") { + const result = (0, _toBlock.default)(node[key], node); + node[key] = result; + return result; + } + + + return ensureBlock; +} + +var toBindingIdentifierName = {}; + +var toIdentifier = {}; + +var hasRequiredToIdentifier; + +function requireToIdentifier () { + if (hasRequiredToIdentifier) return toIdentifier; + hasRequiredToIdentifier = 1; + + Object.defineProperty(toIdentifier, "__esModule", { + value: true + }); + toIdentifier.default = toIdentifier$1; + var _isValidIdentifier = requireIsValidIdentifier(); + var _helperValidatorIdentifier = requireLib$3(); + function toIdentifier$1(input) { + input = input + ""; + let name = ""; + for (const c of input) { + name += (0, _helperValidatorIdentifier.isIdentifierChar)(c.codePointAt(0)) ? c : "-"; + } + name = name.replace(/^[-0-9]+/, ""); + name = name.replace(/[-\s]+(.)?/g, function (match, c) { + return c ? c.toUpperCase() : ""; + }); + if (!(0, _isValidIdentifier.default)(name)) { + name = `_${name}`; + } + return name || "_"; + } + + + return toIdentifier; +} + +var hasRequiredToBindingIdentifierName; + +function requireToBindingIdentifierName () { + if (hasRequiredToBindingIdentifierName) return toBindingIdentifierName; + hasRequiredToBindingIdentifierName = 1; + + Object.defineProperty(toBindingIdentifierName, "__esModule", { + value: true + }); + toBindingIdentifierName.default = toBindingIdentifierName$1; + var _toIdentifier = requireToIdentifier(); + function toBindingIdentifierName$1(name) { + name = (0, _toIdentifier.default)(name); + if (name === "eval" || name === "arguments") name = "_" + name; + return name; + } + + + return toBindingIdentifierName; +} + +var toComputedKey = {}; + +var hasRequiredToComputedKey; + +function requireToComputedKey () { + if (hasRequiredToComputedKey) return toComputedKey; + hasRequiredToComputedKey = 1; + + Object.defineProperty(toComputedKey, "__esModule", { + value: true + }); + toComputedKey.default = toComputedKey$1; + var _index = requireGenerated$3(); + var _index2 = requireGenerated$2(); + function toComputedKey$1(node, key = node.key || node.property) { + if (!node.computed && (0, _index.isIdentifier)(key)) key = (0, _index2.stringLiteral)(key.name); + return key; + } + + + return toComputedKey; +} + +var toExpression = {}; + +var hasRequiredToExpression; + +function requireToExpression () { + if (hasRequiredToExpression) return toExpression; + hasRequiredToExpression = 1; + + Object.defineProperty(toExpression, "__esModule", { + value: true + }); + toExpression.default = void 0; + var _index = requireGenerated$3(); + toExpression.default = toExpression$1; + function toExpression$1(node) { + if ((0, _index.isExpressionStatement)(node)) { + node = node.expression; + } + if ((0, _index.isExpression)(node)) { + return node; + } + if ((0, _index.isClass)(node)) { + node.type = "ClassExpression"; + } else if ((0, _index.isFunction)(node)) { + node.type = "FunctionExpression"; + } + if (!(0, _index.isExpression)(node)) { + throw new Error(`cannot turn ${node.type} to an expression`); + } + return node; + } + + + return toExpression; +} + +var toKeyAlias = {}; + +var removePropertiesDeep = {}; + +var traverseFast = {}; + +var hasRequiredTraverseFast; + +function requireTraverseFast () { + if (hasRequiredTraverseFast) return traverseFast; + hasRequiredTraverseFast = 1; + + Object.defineProperty(traverseFast, "__esModule", { + value: true + }); + traverseFast.default = traverseFast$1; + var _index = requireDefinitions(); + function traverseFast$1(node, enter, opts) { + if (!node) return; + const keys = _index.VISITOR_KEYS[node.type]; + if (!keys) return; + opts = opts || {}; + enter(node, opts); + for (const key of keys) { + const subNode = node[key]; + if (Array.isArray(subNode)) { + for (const node of subNode) { + traverseFast$1(node, enter, opts); + } + } else { + traverseFast$1(subNode, enter, opts); + } + } + } + + + return traverseFast; +} + +var removeProperties = {}; + +var hasRequiredRemoveProperties; + +function requireRemoveProperties () { + if (hasRequiredRemoveProperties) return removeProperties; + hasRequiredRemoveProperties = 1; + + Object.defineProperty(removeProperties, "__esModule", { + value: true + }); + removeProperties.default = removeProperties$1; + var _index = requireConstants(); + const CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"]; + const CLEAR_KEYS_PLUS_COMMENTS = [..._index.COMMENT_KEYS, "comments", ...CLEAR_KEYS]; + function removeProperties$1(node, opts = {}) { + const map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; + for (const key of map) { + if (node[key] != null) node[key] = undefined; + } + for (const key of Object.keys(node)) { + if (key[0] === "_" && node[key] != null) node[key] = undefined; + } + const symbols = Object.getOwnPropertySymbols(node); + for (const sym of symbols) { + node[sym] = null; + } + } + + + return removeProperties; +} + +var hasRequiredRemovePropertiesDeep; + +function requireRemovePropertiesDeep () { + if (hasRequiredRemovePropertiesDeep) return removePropertiesDeep; + hasRequiredRemovePropertiesDeep = 1; + + Object.defineProperty(removePropertiesDeep, "__esModule", { + value: true + }); + removePropertiesDeep.default = removePropertiesDeep$1; + var _traverseFast = requireTraverseFast(); + var _removeProperties = requireRemoveProperties(); + function removePropertiesDeep$1(tree, opts) { + (0, _traverseFast.default)(tree, _removeProperties.default, opts); + return tree; + } + + + return removePropertiesDeep; +} + +var hasRequiredToKeyAlias; + +function requireToKeyAlias () { + if (hasRequiredToKeyAlias) return toKeyAlias; + hasRequiredToKeyAlias = 1; + + Object.defineProperty(toKeyAlias, "__esModule", { + value: true + }); + toKeyAlias.default = toKeyAlias$1; + var _index = requireGenerated$3(); + var _cloneNode = requireCloneNode(); + var _removePropertiesDeep = requireRemovePropertiesDeep(); + function toKeyAlias$1(node, key = node.key) { + let alias; + if (node.kind === "method") { + return toKeyAlias$1.increment() + ""; + } else if ((0, _index.isIdentifier)(key)) { + alias = key.name; + } else if ((0, _index.isStringLiteral)(key)) { + alias = JSON.stringify(key.value); + } else { + alias = JSON.stringify((0, _removePropertiesDeep.default)((0, _cloneNode.default)(key))); + } + if (node.computed) { + alias = `[${alias}]`; + } + if (node.static) { + alias = `static:${alias}`; + } + return alias; + } + toKeyAlias$1.uid = 0; + toKeyAlias$1.increment = function () { + if (toKeyAlias$1.uid >= Number.MAX_SAFE_INTEGER) { + return toKeyAlias$1.uid = 0; + } else { + return toKeyAlias$1.uid++; + } + }; + + + return toKeyAlias; +} + +var toStatement = {}; + +var hasRequiredToStatement; + +function requireToStatement () { + if (hasRequiredToStatement) return toStatement; + hasRequiredToStatement = 1; + + Object.defineProperty(toStatement, "__esModule", { + value: true + }); + toStatement.default = void 0; + var _index = requireGenerated$3(); + var _index2 = requireGenerated$2(); + toStatement.default = toStatement$1; + function toStatement$1(node, ignore) { + if ((0, _index.isStatement)(node)) { + return node; + } + let mustHaveId = false; + let newType; + if ((0, _index.isClass)(node)) { + mustHaveId = true; + newType = "ClassDeclaration"; + } else if ((0, _index.isFunction)(node)) { + mustHaveId = true; + newType = "FunctionDeclaration"; + } else if ((0, _index.isAssignmentExpression)(node)) { + return (0, _index2.expressionStatement)(node); + } + if (mustHaveId && !node.id) { + newType = false; + } + if (!newType) { + if (ignore) { + return false; + } else { + throw new Error(`cannot turn ${node.type} to a statement`); + } + } + node.type = newType; + return node; + } + + + return toStatement; +} + +var valueToNode = {}; + +var hasRequiredValueToNode; + +function requireValueToNode () { + if (hasRequiredValueToNode) return valueToNode; + hasRequiredValueToNode = 1; + + Object.defineProperty(valueToNode, "__esModule", { + value: true + }); + valueToNode.default = void 0; + var _isValidIdentifier = requireIsValidIdentifier(); + var _index = requireGenerated$2(); + valueToNode.default = valueToNode$1; + const objectToString = Function.call.bind(Object.prototype.toString); + function isRegExp(value) { + return objectToString(value) === "[object RegExp]"; + } + function isPlainObject(value) { + if (typeof value !== "object" || value === null || Object.prototype.toString.call(value) !== "[object Object]") { + return false; + } + const proto = Object.getPrototypeOf(value); + return proto === null || Object.getPrototypeOf(proto) === null; + } + function valueToNode$1(value) { + if (value === undefined) { + return (0, _index.identifier)("undefined"); + } + if (value === true || value === false) { + return (0, _index.booleanLiteral)(value); + } + if (value === null) { + return (0, _index.nullLiteral)(); + } + if (typeof value === "string") { + return (0, _index.stringLiteral)(value); + } + if (typeof value === "number") { + let result; + if (Number.isFinite(value)) { + result = (0, _index.numericLiteral)(Math.abs(value)); + } else { + let numerator; + if (Number.isNaN(value)) { + numerator = (0, _index.numericLiteral)(0); + } else { + numerator = (0, _index.numericLiteral)(1); + } + result = (0, _index.binaryExpression)("/", numerator, (0, _index.numericLiteral)(0)); + } + if (value < 0 || Object.is(value, -0)) { + result = (0, _index.unaryExpression)("-", result); + } + return result; + } + if (isRegExp(value)) { + const pattern = value.source; + const flags = /\/([a-z]*)$/.exec(value.toString())[1]; + return (0, _index.regExpLiteral)(pattern, flags); + } + if (Array.isArray(value)) { + return (0, _index.arrayExpression)(value.map(valueToNode$1)); + } + if (isPlainObject(value)) { + const props = []; + for (const key of Object.keys(value)) { + let nodeKey; + if ((0, _isValidIdentifier.default)(key)) { + nodeKey = (0, _index.identifier)(key); + } else { + nodeKey = (0, _index.stringLiteral)(key); + } + props.push((0, _index.objectProperty)(nodeKey, valueToNode$1(value[key]))); + } + return (0, _index.objectExpression)(props); + } + throw new Error("don't know how to turn this value into a node"); + } + + + return valueToNode; +} + +var appendToMemberExpression = {}; + +var hasRequiredAppendToMemberExpression; + +function requireAppendToMemberExpression () { + if (hasRequiredAppendToMemberExpression) return appendToMemberExpression; + hasRequiredAppendToMemberExpression = 1; + + Object.defineProperty(appendToMemberExpression, "__esModule", { + value: true + }); + appendToMemberExpression.default = appendToMemberExpression$1; + var _index = requireGenerated$2(); + function appendToMemberExpression$1(member, append, computed = false) { + member.object = (0, _index.memberExpression)(member.object, member.property, member.computed); + member.property = append; + member.computed = !!computed; + return member; + } + + + return appendToMemberExpression; +} + +var inherits = {}; + +var hasRequiredInherits; + +function requireInherits () { + if (hasRequiredInherits) return inherits; + hasRequiredInherits = 1; + + Object.defineProperty(inherits, "__esModule", { + value: true + }); + inherits.default = inherits$1; + var _index = requireConstants(); + var _inheritsComments = requireInheritsComments(); + function inherits$1(child, parent) { + if (!child || !parent) return child; + for (const key of _index.INHERIT_KEYS.optional) { + if (child[key] == null) { + child[key] = parent[key]; + } + } + for (const key of Object.keys(parent)) { + if (key[0] === "_" && key !== "__clone") { + child[key] = parent[key]; + } + } + for (const key of _index.INHERIT_KEYS.force) { + child[key] = parent[key]; + } + (0, _inheritsComments.default)(child, parent); + return child; + } + + + return inherits; +} + +var prependToMemberExpression = {}; + +var hasRequiredPrependToMemberExpression; + +function requirePrependToMemberExpression () { + if (hasRequiredPrependToMemberExpression) return prependToMemberExpression; + hasRequiredPrependToMemberExpression = 1; + + Object.defineProperty(prependToMemberExpression, "__esModule", { + value: true + }); + prependToMemberExpression.default = prependToMemberExpression$1; + var _index = requireGenerated$2(); + var _index2 = requireLib$1(); + function prependToMemberExpression$1(member, prepend) { + if ((0, _index2.isSuper)(member.object)) { + throw new Error("Cannot prepend node to super property access (`super.foo`)."); + } + member.object = (0, _index.memberExpression)(prepend, member.object); + return member; + } + + + return prependToMemberExpression; +} + +var getAssignmentIdentifiers = {}; + +var hasRequiredGetAssignmentIdentifiers; + +function requireGetAssignmentIdentifiers () { + if (hasRequiredGetAssignmentIdentifiers) return getAssignmentIdentifiers; + hasRequiredGetAssignmentIdentifiers = 1; + + Object.defineProperty(getAssignmentIdentifiers, "__esModule", { + value: true + }); + getAssignmentIdentifiers.default = getAssignmentIdentifiers$1; + function getAssignmentIdentifiers$1(node) { + const search = [].concat(node); + const ids = Object.create(null); + while (search.length) { + const id = search.pop(); + if (!id) continue; + switch (id.type) { + case "ArrayPattern": + search.push(...id.elements); + break; + case "AssignmentExpression": + case "AssignmentPattern": + case "ForInStatement": + case "ForOfStatement": + search.push(id.left); + break; + case "ObjectPattern": + search.push(...id.properties); + break; + case "ObjectProperty": + search.push(id.value); + break; + case "RestElement": + case "UpdateExpression": + search.push(id.argument); + break; + case "UnaryExpression": + if (id.operator === "delete") { + search.push(id.argument); + } + break; + case "Identifier": + ids[id.name] = id; + break; + } + } + return ids; + } + + + return getAssignmentIdentifiers; +} + +var getBindingIdentifiers = {}; + +var hasRequiredGetBindingIdentifiers; + +function requireGetBindingIdentifiers () { + if (hasRequiredGetBindingIdentifiers) return getBindingIdentifiers; + hasRequiredGetBindingIdentifiers = 1; + + Object.defineProperty(getBindingIdentifiers, "__esModule", { + value: true + }); + getBindingIdentifiers.default = getBindingIdentifiers$1; + var _index = requireGenerated$3(); + function getBindingIdentifiers$1(node, duplicates, outerOnly, newBindingsOnly) { + const search = [].concat(node); + const ids = Object.create(null); + while (search.length) { + const id = search.shift(); + if (!id) continue; + if (newBindingsOnly && ((0, _index.isAssignmentExpression)(id) || (0, _index.isUnaryExpression)(id) || (0, _index.isUpdateExpression)(id))) { + continue; + } + if ((0, _index.isIdentifier)(id)) { + if (duplicates) { + const _ids = ids[id.name] = ids[id.name] || []; + _ids.push(id); + } else { + ids[id.name] = id; + } + continue; + } + if ((0, _index.isExportDeclaration)(id) && !(0, _index.isExportAllDeclaration)(id)) { + if ((0, _index.isDeclaration)(id.declaration)) { + search.push(id.declaration); + } + continue; + } + if (outerOnly) { + if ((0, _index.isFunctionDeclaration)(id)) { + search.push(id.id); + continue; + } + if ((0, _index.isFunctionExpression)(id)) { + continue; + } + } + const keys = getBindingIdentifiers$1.keys[id.type]; + if (keys) { + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const nodes = id[key]; + if (nodes) { + if (Array.isArray(nodes)) { + search.push(...nodes); + } else { + search.push(nodes); + } + } + } + } + } + return ids; + } + const keys = { + DeclareClass: ["id"], + DeclareFunction: ["id"], + DeclareModule: ["id"], + DeclareVariable: ["id"], + DeclareInterface: ["id"], + DeclareTypeAlias: ["id"], + DeclareOpaqueType: ["id"], + InterfaceDeclaration: ["id"], + TypeAlias: ["id"], + OpaqueType: ["id"], + CatchClause: ["param"], + LabeledStatement: ["label"], + UnaryExpression: ["argument"], + AssignmentExpression: ["left"], + ImportSpecifier: ["local"], + ImportNamespaceSpecifier: ["local"], + ImportDefaultSpecifier: ["local"], + ImportDeclaration: ["specifiers"], + ExportSpecifier: ["exported"], + ExportNamespaceSpecifier: ["exported"], + ExportDefaultSpecifier: ["exported"], + FunctionDeclaration: ["id", "params"], + FunctionExpression: ["id", "params"], + ArrowFunctionExpression: ["params"], + ObjectMethod: ["params"], + ClassMethod: ["params"], + ClassPrivateMethod: ["params"], + ForInStatement: ["left"], + ForOfStatement: ["left"], + ClassDeclaration: ["id"], + ClassExpression: ["id"], + RestElement: ["argument"], + UpdateExpression: ["argument"], + ObjectProperty: ["value"], + AssignmentPattern: ["left"], + ArrayPattern: ["elements"], + ObjectPattern: ["properties"], + VariableDeclaration: ["declarations"], + VariableDeclarator: ["id"] + }; + getBindingIdentifiers$1.keys = keys; + + + return getBindingIdentifiers; +} + +var getOuterBindingIdentifiers = {}; + +var hasRequiredGetOuterBindingIdentifiers; + +function requireGetOuterBindingIdentifiers () { + if (hasRequiredGetOuterBindingIdentifiers) return getOuterBindingIdentifiers; + hasRequiredGetOuterBindingIdentifiers = 1; + + Object.defineProperty(getOuterBindingIdentifiers, "__esModule", { + value: true + }); + getOuterBindingIdentifiers.default = void 0; + var _getBindingIdentifiers = requireGetBindingIdentifiers(); + getOuterBindingIdentifiers.default = getOuterBindingIdentifiers$1; + function getOuterBindingIdentifiers$1(node, duplicates) { + return (0, _getBindingIdentifiers.default)(node, duplicates, true); + } + + + return getOuterBindingIdentifiers; +} + +var getFunctionName$3 = {}; + +var hasRequiredGetFunctionName; + +function requireGetFunctionName () { + if (hasRequiredGetFunctionName) return getFunctionName$3; + hasRequiredGetFunctionName = 1; + + Object.defineProperty(getFunctionName$3, "__esModule", { + value: true + }); + getFunctionName$3.default = getFunctionName; + var _index = requireGenerated$3(); + function getNameFromLiteralId(id) { + if ((0, _index.isNullLiteral)(id)) { + return "null"; + } + if ((0, _index.isRegExpLiteral)(id)) { + return `/${id.pattern}/${id.flags}`; + } + if ((0, _index.isTemplateLiteral)(id)) { + return id.quasis.map(quasi => quasi.value.raw).join(""); + } + if (id.value !== undefined) { + return String(id.value); + } + return null; + } + function getObjectMemberKey(node) { + if (!node.computed || (0, _index.isLiteral)(node.key)) { + return node.key; + } + } + function getFunctionName(node, parent) { + if ("id" in node && node.id) { + return { + name: node.id.name, + originalNode: node.id + }; + } + let prefix = ""; + let id; + if ((0, _index.isObjectProperty)(parent, { + value: node + })) { + id = getObjectMemberKey(parent); + } else if ((0, _index.isObjectMethod)(node) || (0, _index.isClassMethod)(node)) { + id = getObjectMemberKey(node); + if (node.kind === "get") prefix = "get ";else if (node.kind === "set") prefix = "set "; + } else if ((0, _index.isVariableDeclarator)(parent, { + init: node + })) { + id = parent.id; + } else if ((0, _index.isAssignmentExpression)(parent, { + operator: "=", + right: node + })) { + id = parent.left; + } + if (!id) return null; + const name = (0, _index.isLiteral)(id) ? getNameFromLiteralId(id) : (0, _index.isIdentifier)(id) ? id.name : (0, _index.isPrivateName)(id) ? id.id.name : null; + if (name == null) return null; + return { + name: prefix + name, + originalNode: id + }; + } + + + return getFunctionName$3; +} + +var traverse = {}; + +var hasRequiredTraverse; + +function requireTraverse () { + if (hasRequiredTraverse) return traverse; + hasRequiredTraverse = 1; + + Object.defineProperty(traverse, "__esModule", { + value: true + }); + traverse.default = traverse$1; + var _index = requireDefinitions(); + function traverse$1(node, handlers, state) { + if (typeof handlers === "function") { + handlers = { + enter: handlers + }; + } + const { + enter, + exit + } = handlers; + traverseSimpleImpl(node, enter, exit, state, []); + } + function traverseSimpleImpl(node, enter, exit, state, ancestors) { + const keys = _index.VISITOR_KEYS[node.type]; + if (!keys) return; + if (enter) enter(node, ancestors, state); + for (const key of keys) { + const subNode = node[key]; + if (Array.isArray(subNode)) { + for (let i = 0; i < subNode.length; i++) { + const child = subNode[i]; + if (!child) continue; + ancestors.push({ + node, + key, + index: i + }); + traverseSimpleImpl(child, enter, exit, state, ancestors); + ancestors.pop(); + } + } else if (subNode) { + ancestors.push({ + node, + key + }); + traverseSimpleImpl(subNode, enter, exit, state, ancestors); + ancestors.pop(); + } + } + if (exit) exit(node, ancestors, state); + } + + + return traverse; +} + +var isBinding = {}; + +var hasRequiredIsBinding; + +function requireIsBinding () { + if (hasRequiredIsBinding) return isBinding; + hasRequiredIsBinding = 1; + + Object.defineProperty(isBinding, "__esModule", { + value: true + }); + isBinding.default = isBinding$1; + var _getBindingIdentifiers = requireGetBindingIdentifiers(); + function isBinding$1(node, parent, grandparent) { + if (grandparent && node.type === "Identifier" && parent.type === "ObjectProperty" && grandparent.type === "ObjectExpression") { + return false; + } + const keys = _getBindingIdentifiers.default.keys[parent.type]; + if (keys) { + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const val = parent[key]; + if (Array.isArray(val)) { + if (val.includes(node)) return true; + } else { + if (val === node) return true; + } + } + } + return false; + } + + + return isBinding; +} + +var isBlockScoped = {}; + +var isLet = {}; + +var hasRequiredIsLet; + +function requireIsLet () { + if (hasRequiredIsLet) return isLet; + hasRequiredIsLet = 1; + + Object.defineProperty(isLet, "__esModule", { + value: true + }); + isLet.default = isLet$1; + var _index = requireGenerated$3(); + var _index2 = requireConstants(); + function isLet$1(node) { + return (0, _index.isVariableDeclaration)(node) && (node.kind !== "var" || node[_index2.BLOCK_SCOPED_SYMBOL]); + } + + + return isLet; +} + +var hasRequiredIsBlockScoped; + +function requireIsBlockScoped () { + if (hasRequiredIsBlockScoped) return isBlockScoped; + hasRequiredIsBlockScoped = 1; + + Object.defineProperty(isBlockScoped, "__esModule", { + value: true + }); + isBlockScoped.default = isBlockScoped$1; + var _index = requireGenerated$3(); + var _isLet = requireIsLet(); + function isBlockScoped$1(node) { + return (0, _index.isFunctionDeclaration)(node) || (0, _index.isClassDeclaration)(node) || (0, _isLet.default)(node); + } + + + return isBlockScoped; +} + +var isImmutable = {}; + +var hasRequiredIsImmutable; + +function requireIsImmutable () { + if (hasRequiredIsImmutable) return isImmutable; + hasRequiredIsImmutable = 1; + + Object.defineProperty(isImmutable, "__esModule", { + value: true + }); + isImmutable.default = isImmutable$1; + var _isType = requireIsType(); + var _index = requireGenerated$3(); + function isImmutable$1(node) { + if ((0, _isType.default)(node.type, "Immutable")) return true; + if ((0, _index.isIdentifier)(node)) { + if (node.name === "undefined") { + return true; + } else { + return false; + } + } + return false; + } + + + return isImmutable; +} + +var isNodesEquivalent = {}; + +var hasRequiredIsNodesEquivalent; + +function requireIsNodesEquivalent () { + if (hasRequiredIsNodesEquivalent) return isNodesEquivalent; + hasRequiredIsNodesEquivalent = 1; + + Object.defineProperty(isNodesEquivalent, "__esModule", { + value: true + }); + isNodesEquivalent.default = isNodesEquivalent$1; + var _index = requireDefinitions(); + function isNodesEquivalent$1(a, b) { + if (typeof a !== "object" || typeof b !== "object" || a == null || b == null) { + return a === b; + } + if (a.type !== b.type) { + return false; + } + const fields = Object.keys(_index.NODE_FIELDS[a.type] || a.type); + const visitorKeys = _index.VISITOR_KEYS[a.type]; + for (const field of fields) { + const val_a = a[field]; + const val_b = b[field]; + if (typeof val_a !== typeof val_b) { + return false; + } + if (val_a == null && val_b == null) { + continue; + } else if (val_a == null || val_b == null) { + return false; + } + if (Array.isArray(val_a)) { + if (!Array.isArray(val_b)) { + return false; + } + if (val_a.length !== val_b.length) { + return false; + } + for (let i = 0; i < val_a.length; i++) { + if (!isNodesEquivalent$1(val_a[i], val_b[i])) { + return false; + } + } + continue; + } + if (typeof val_a === "object" && !(visitorKeys != null && visitorKeys.includes(field))) { + for (const key of Object.keys(val_a)) { + if (val_a[key] !== val_b[key]) { + return false; + } + } + continue; + } + if (!isNodesEquivalent$1(val_a, val_b)) { + return false; + } + } + return true; + } + + + return isNodesEquivalent; +} + +var isReferenced = {}; + +var hasRequiredIsReferenced; + +function requireIsReferenced () { + if (hasRequiredIsReferenced) return isReferenced; + hasRequiredIsReferenced = 1; + + Object.defineProperty(isReferenced, "__esModule", { + value: true + }); + isReferenced.default = isReferenced$1; + function isReferenced$1(node, parent, grandparent) { + switch (parent.type) { + case "MemberExpression": + case "OptionalMemberExpression": + if (parent.property === node) { + return !!parent.computed; + } + return parent.object === node; + case "JSXMemberExpression": + return parent.object === node; + case "VariableDeclarator": + return parent.init === node; + case "ArrowFunctionExpression": + return parent.body === node; + case "PrivateName": + return false; + case "ClassMethod": + case "ClassPrivateMethod": + case "ObjectMethod": + if (parent.key === node) { + return !!parent.computed; + } + return false; + case "ObjectProperty": + if (parent.key === node) { + return !!parent.computed; + } + return !grandparent || grandparent.type !== "ObjectPattern"; + case "ClassProperty": + case "ClassAccessorProperty": + if (parent.key === node) { + return !!parent.computed; + } + return true; + case "ClassPrivateProperty": + return parent.key !== node; + case "ClassDeclaration": + case "ClassExpression": + return parent.superClass === node; + case "AssignmentExpression": + return parent.right === node; + case "AssignmentPattern": + return parent.right === node; + case "LabeledStatement": + return false; + case "CatchClause": + return false; + case "RestElement": + return false; + case "BreakStatement": + case "ContinueStatement": + return false; + case "FunctionDeclaration": + case "FunctionExpression": + return false; + case "ExportNamespaceSpecifier": + case "ExportDefaultSpecifier": + return false; + case "ExportSpecifier": + if (grandparent != null && grandparent.source) { + return false; + } + return parent.local === node; + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "ImportSpecifier": + return false; + case "ImportAttribute": + return false; + case "JSXAttribute": + return false; + case "ObjectPattern": + case "ArrayPattern": + return false; + case "MetaProperty": + return false; + case "ObjectTypeProperty": + return parent.key !== node; + case "TSEnumMember": + return parent.id !== node; + case "TSPropertySignature": + if (parent.key === node) { + return !!parent.computed; + } + return true; + } + return true; + } + + + return isReferenced; +} + +var isScope = {}; + +var hasRequiredIsScope; + +function requireIsScope () { + if (hasRequiredIsScope) return isScope; + hasRequiredIsScope = 1; + + Object.defineProperty(isScope, "__esModule", { + value: true + }); + isScope.default = isScope$1; + var _index = requireGenerated$3(); + function isScope$1(node, parent) { + if ((0, _index.isBlockStatement)(node) && ((0, _index.isFunction)(parent) || (0, _index.isCatchClause)(parent))) { + return false; + } + if ((0, _index.isPattern)(node) && ((0, _index.isFunction)(parent) || (0, _index.isCatchClause)(parent))) { + return true; + } + return (0, _index.isScopable)(node); + } + + + return isScope; +} + +var isSpecifierDefault = {}; + +var hasRequiredIsSpecifierDefault; + +function requireIsSpecifierDefault () { + if (hasRequiredIsSpecifierDefault) return isSpecifierDefault; + hasRequiredIsSpecifierDefault = 1; + + Object.defineProperty(isSpecifierDefault, "__esModule", { + value: true + }); + isSpecifierDefault.default = isSpecifierDefault$1; + var _index = requireGenerated$3(); + function isSpecifierDefault$1(specifier) { + return (0, _index.isImportDefaultSpecifier)(specifier) || (0, _index.isIdentifier)(specifier.imported || specifier.exported, { + name: "default" + }); + } + + + return isSpecifierDefault; +} + +var isValidES3Identifier = {}; + +var hasRequiredIsValidES3Identifier; + +function requireIsValidES3Identifier () { + if (hasRequiredIsValidES3Identifier) return isValidES3Identifier; + hasRequiredIsValidES3Identifier = 1; + + Object.defineProperty(isValidES3Identifier, "__esModule", { + value: true + }); + isValidES3Identifier.default = isValidES3Identifier$1; + var _isValidIdentifier = requireIsValidIdentifier(); + const RESERVED_WORDS_ES3_ONLY = new Set(["abstract", "boolean", "byte", "char", "double", "enum", "final", "float", "goto", "implements", "int", "interface", "long", "native", "package", "private", "protected", "public", "short", "static", "synchronized", "throws", "transient", "volatile"]); + function isValidES3Identifier$1(name) { + return (0, _isValidIdentifier.default)(name) && !RESERVED_WORDS_ES3_ONLY.has(name); + } + + + return isValidES3Identifier; +} + +var isVar = {}; + +var hasRequiredIsVar; + +function requireIsVar () { + if (hasRequiredIsVar) return isVar; + hasRequiredIsVar = 1; + + Object.defineProperty(isVar, "__esModule", { + value: true + }); + isVar.default = isVar$1; + var _index = requireGenerated$3(); + var _index2 = requireConstants(); + function isVar$1(node) { + return (0, _index.isVariableDeclaration)(node, { + kind: "var" + }) && !node[_index2.BLOCK_SCOPED_SYMBOL]; + } + + + return isVar; +} + +var toSequenceExpression = {}; + +var gatherSequenceExpressions = {}; + +var hasRequiredGatherSequenceExpressions; + +function requireGatherSequenceExpressions () { + if (hasRequiredGatherSequenceExpressions) return gatherSequenceExpressions; + hasRequiredGatherSequenceExpressions = 1; + + Object.defineProperty(gatherSequenceExpressions, "__esModule", { + value: true + }); + gatherSequenceExpressions.default = gatherSequenceExpressions$1; + var _getBindingIdentifiers = requireGetBindingIdentifiers(); + var _index = requireGenerated$3(); + var _index2 = requireGenerated$2(); + var _productions = requireProductions(); + var _cloneNode = requireCloneNode(); + function gatherSequenceExpressions$1(nodes, declars) { + const exprs = []; + let ensureLastUndefined = true; + for (const node of nodes) { + if (!(0, _index.isEmptyStatement)(node)) { + ensureLastUndefined = false; + } + if ((0, _index.isExpression)(node)) { + exprs.push(node); + } else if ((0, _index.isExpressionStatement)(node)) { + exprs.push(node.expression); + } else if ((0, _index.isVariableDeclaration)(node)) { + if (node.kind !== "var") return; + for (const declar of node.declarations) { + const bindings = (0, _getBindingIdentifiers.default)(declar); + for (const key of Object.keys(bindings)) { + declars.push({ + kind: node.kind, + id: (0, _cloneNode.default)(bindings[key]) + }); + } + if (declar.init) { + exprs.push((0, _index2.assignmentExpression)("=", declar.id, declar.init)); + } + } + ensureLastUndefined = true; + } else if ((0, _index.isIfStatement)(node)) { + const consequent = node.consequent ? gatherSequenceExpressions$1([node.consequent], declars) : (0, _productions.buildUndefinedNode)(); + const alternate = node.alternate ? gatherSequenceExpressions$1([node.alternate], declars) : (0, _productions.buildUndefinedNode)(); + if (!consequent || !alternate) return; + exprs.push((0, _index2.conditionalExpression)(node.test, consequent, alternate)); + } else if ((0, _index.isBlockStatement)(node)) { + const body = gatherSequenceExpressions$1(node.body, declars); + if (!body) return; + exprs.push(body); + } else if ((0, _index.isEmptyStatement)(node)) { + if (nodes.indexOf(node) === 0) { + ensureLastUndefined = true; + } + } else { + return; + } + } + if (ensureLastUndefined) { + exprs.push((0, _productions.buildUndefinedNode)()); + } + if (exprs.length === 1) { + return exprs[0]; + } else { + return (0, _index2.sequenceExpression)(exprs); + } + } + + + return gatherSequenceExpressions; +} + +var hasRequiredToSequenceExpression; + +function requireToSequenceExpression () { + if (hasRequiredToSequenceExpression) return toSequenceExpression; + hasRequiredToSequenceExpression = 1; + + Object.defineProperty(toSequenceExpression, "__esModule", { + value: true + }); + toSequenceExpression.default = toSequenceExpression$1; + var _gatherSequenceExpressions = requireGatherSequenceExpressions(); + function toSequenceExpression$1(nodes, scope) { + if (!(nodes != null && nodes.length)) return; + const declars = []; + const result = (0, _gatherSequenceExpressions.default)(nodes, declars); + if (!result) return; + for (const declar of declars) { + scope.push(declar); + } + return result; + } + + + return toSequenceExpression; +} + +var hasRequiredLib$1; + +function requireLib$1 () { + if (hasRequiredLib$1) return lib$3; + hasRequiredLib$1 = 1; + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + var _exportNames = { + react: true, + assertNode: true, + createTypeAnnotationBasedOnTypeof: true, + createUnionTypeAnnotation: true, + createFlowUnionType: true, + createTSUnionType: true, + cloneNode: true, + clone: true, + cloneDeep: true, + cloneDeepWithoutLoc: true, + cloneWithoutLoc: true, + addComment: true, + addComments: true, + inheritInnerComments: true, + inheritLeadingComments: true, + inheritsComments: true, + inheritTrailingComments: true, + removeComments: true, + ensureBlock: true, + toBindingIdentifierName: true, + toBlock: true, + toComputedKey: true, + toExpression: true, + toIdentifier: true, + toKeyAlias: true, + toStatement: true, + valueToNode: true, + appendToMemberExpression: true, + inherits: true, + prependToMemberExpression: true, + removeProperties: true, + removePropertiesDeep: true, + removeTypeDuplicates: true, + getAssignmentIdentifiers: true, + getBindingIdentifiers: true, + getOuterBindingIdentifiers: true, + getFunctionName: true, + traverse: true, + traverseFast: true, + shallowEqual: true, + is: true, + isBinding: true, + isBlockScoped: true, + isImmutable: true, + isLet: true, + isNode: true, + isNodesEquivalent: true, + isPlaceholderType: true, + isReferenced: true, + isScope: true, + isSpecifierDefault: true, + isType: true, + isValidES3Identifier: true, + isValidIdentifier: true, + isVar: true, + matchesPattern: true, + validate: true, + buildMatchMemberExpression: true, + __internal__deprecationWarning: true + }; + Object.defineProperty(exports, "__internal__deprecationWarning", { + enumerable: true, + get: function () { + return _deprecationWarning.default; + } + }); + Object.defineProperty(exports, "addComment", { + enumerable: true, + get: function () { + return _addComment.default; + } + }); + Object.defineProperty(exports, "addComments", { + enumerable: true, + get: function () { + return _addComments.default; + } + }); + Object.defineProperty(exports, "appendToMemberExpression", { + enumerable: true, + get: function () { + return _appendToMemberExpression.default; + } + }); + Object.defineProperty(exports, "assertNode", { + enumerable: true, + get: function () { + return _assertNode.default; + } + }); + Object.defineProperty(exports, "buildMatchMemberExpression", { + enumerable: true, + get: function () { + return _buildMatchMemberExpression.default; + } + }); + Object.defineProperty(exports, "clone", { + enumerable: true, + get: function () { + return _clone.default; + } + }); + Object.defineProperty(exports, "cloneDeep", { + enumerable: true, + get: function () { + return _cloneDeep.default; + } + }); + Object.defineProperty(exports, "cloneDeepWithoutLoc", { + enumerable: true, + get: function () { + return _cloneDeepWithoutLoc.default; + } + }); + Object.defineProperty(exports, "cloneNode", { + enumerable: true, + get: function () { + return _cloneNode.default; + } + }); + Object.defineProperty(exports, "cloneWithoutLoc", { + enumerable: true, + get: function () { + return _cloneWithoutLoc.default; + } + }); + Object.defineProperty(exports, "createFlowUnionType", { + enumerable: true, + get: function () { + return _createFlowUnionType.default; + } + }); + Object.defineProperty(exports, "createTSUnionType", { + enumerable: true, + get: function () { + return _createTSUnionType.default; + } + }); + Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", { + enumerable: true, + get: function () { + return _createTypeAnnotationBasedOnTypeof.default; + } + }); + Object.defineProperty(exports, "createUnionTypeAnnotation", { + enumerable: true, + get: function () { + return _createFlowUnionType.default; + } + }); + Object.defineProperty(exports, "ensureBlock", { + enumerable: true, + get: function () { + return _ensureBlock.default; + } + }); + Object.defineProperty(exports, "getAssignmentIdentifiers", { + enumerable: true, + get: function () { + return _getAssignmentIdentifiers.default; + } + }); + Object.defineProperty(exports, "getBindingIdentifiers", { + enumerable: true, + get: function () { + return _getBindingIdentifiers.default; + } + }); + Object.defineProperty(exports, "getFunctionName", { + enumerable: true, + get: function () { + return _getFunctionName.default; + } + }); + Object.defineProperty(exports, "getOuterBindingIdentifiers", { + enumerable: true, + get: function () { + return _getOuterBindingIdentifiers.default; + } + }); + Object.defineProperty(exports, "inheritInnerComments", { + enumerable: true, + get: function () { + return _inheritInnerComments.default; + } + }); + Object.defineProperty(exports, "inheritLeadingComments", { + enumerable: true, + get: function () { + return _inheritLeadingComments.default; + } + }); + Object.defineProperty(exports, "inheritTrailingComments", { + enumerable: true, + get: function () { + return _inheritTrailingComments.default; + } + }); + Object.defineProperty(exports, "inherits", { + enumerable: true, + get: function () { + return _inherits.default; + } + }); + Object.defineProperty(exports, "inheritsComments", { + enumerable: true, + get: function () { + return _inheritsComments.default; + } + }); + Object.defineProperty(exports, "is", { + enumerable: true, + get: function () { + return _is.default; + } + }); + Object.defineProperty(exports, "isBinding", { + enumerable: true, + get: function () { + return _isBinding.default; + } + }); + Object.defineProperty(exports, "isBlockScoped", { + enumerable: true, + get: function () { + return _isBlockScoped.default; + } + }); + Object.defineProperty(exports, "isImmutable", { + enumerable: true, + get: function () { + return _isImmutable.default; + } + }); + Object.defineProperty(exports, "isLet", { + enumerable: true, + get: function () { + return _isLet.default; + } + }); + Object.defineProperty(exports, "isNode", { + enumerable: true, + get: function () { + return _isNode.default; + } + }); + Object.defineProperty(exports, "isNodesEquivalent", { + enumerable: true, + get: function () { + return _isNodesEquivalent.default; + } + }); + Object.defineProperty(exports, "isPlaceholderType", { + enumerable: true, + get: function () { + return _isPlaceholderType.default; + } + }); + Object.defineProperty(exports, "isReferenced", { + enumerable: true, + get: function () { + return _isReferenced.default; + } + }); + Object.defineProperty(exports, "isScope", { + enumerable: true, + get: function () { + return _isScope.default; + } + }); + Object.defineProperty(exports, "isSpecifierDefault", { + enumerable: true, + get: function () { + return _isSpecifierDefault.default; + } + }); + Object.defineProperty(exports, "isType", { + enumerable: true, + get: function () { + return _isType.default; + } + }); + Object.defineProperty(exports, "isValidES3Identifier", { + enumerable: true, + get: function () { + return _isValidES3Identifier.default; + } + }); + Object.defineProperty(exports, "isValidIdentifier", { + enumerable: true, + get: function () { + return _isValidIdentifier.default; + } + }); + Object.defineProperty(exports, "isVar", { + enumerable: true, + get: function () { + return _isVar.default; + } + }); + Object.defineProperty(exports, "matchesPattern", { + enumerable: true, + get: function () { + return _matchesPattern.default; + } + }); + Object.defineProperty(exports, "prependToMemberExpression", { + enumerable: true, + get: function () { + return _prependToMemberExpression.default; + } + }); + exports.react = void 0; + Object.defineProperty(exports, "removeComments", { + enumerable: true, + get: function () { + return _removeComments.default; + } + }); + Object.defineProperty(exports, "removeProperties", { + enumerable: true, + get: function () { + return _removeProperties.default; + } + }); + Object.defineProperty(exports, "removePropertiesDeep", { + enumerable: true, + get: function () { + return _removePropertiesDeep.default; + } + }); + Object.defineProperty(exports, "removeTypeDuplicates", { + enumerable: true, + get: function () { + return _removeTypeDuplicates.default; + } + }); + Object.defineProperty(exports, "shallowEqual", { + enumerable: true, + get: function () { + return _shallowEqual.default; + } + }); + Object.defineProperty(exports, "toBindingIdentifierName", { + enumerable: true, + get: function () { + return _toBindingIdentifierName.default; + } + }); + Object.defineProperty(exports, "toBlock", { + enumerable: true, + get: function () { + return _toBlock.default; + } + }); + Object.defineProperty(exports, "toComputedKey", { + enumerable: true, + get: function () { + return _toComputedKey.default; + } + }); + Object.defineProperty(exports, "toExpression", { + enumerable: true, + get: function () { + return _toExpression.default; + } + }); + Object.defineProperty(exports, "toIdentifier", { + enumerable: true, + get: function () { + return _toIdentifier.default; + } + }); + Object.defineProperty(exports, "toKeyAlias", { + enumerable: true, + get: function () { + return _toKeyAlias.default; + } + }); + Object.defineProperty(exports, "toStatement", { + enumerable: true, + get: function () { + return _toStatement.default; + } + }); + Object.defineProperty(exports, "traverse", { + enumerable: true, + get: function () { + return _traverse.default; + } + }); + Object.defineProperty(exports, "traverseFast", { + enumerable: true, + get: function () { + return _traverseFast.default; + } + }); + Object.defineProperty(exports, "validate", { + enumerable: true, + get: function () { + return _validate.default; + } + }); + Object.defineProperty(exports, "valueToNode", { + enumerable: true, + get: function () { + return _valueToNode.default; + } + }); + var _isReactComponent = requireIsReactComponent(); + var _isCompatTag = requireIsCompatTag(); + var _buildChildren = requireBuildChildren(); + var _assertNode = requireAssertNode(); + var _index = requireGenerated$1(); + Object.keys(_index).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index[key]; + } + }); + }); + var _createTypeAnnotationBasedOnTypeof = requireCreateTypeAnnotationBasedOnTypeof(); + var _createFlowUnionType = requireCreateFlowUnionType(); + var _createTSUnionType = requireCreateTSUnionType(); + var _index2 = requireGenerated$2(); + Object.keys(_index2).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index2[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index2[key]; + } + }); + }); + var _uppercase = requireUppercase(); + Object.keys(_uppercase).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _uppercase[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _uppercase[key]; + } + }); + }); + var _productions = requireProductions(); + Object.keys(_productions).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _productions[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _productions[key]; + } + }); + }); + var _cloneNode = requireCloneNode(); + var _clone = requireClone(); + var _cloneDeep = requireCloneDeep(); + var _cloneDeepWithoutLoc = requireCloneDeepWithoutLoc(); + var _cloneWithoutLoc = requireCloneWithoutLoc(); + var _addComment = requireAddComment(); + var _addComments = requireAddComments(); + var _inheritInnerComments = requireInheritInnerComments(); + var _inheritLeadingComments = requireInheritLeadingComments(); + var _inheritsComments = requireInheritsComments(); + var _inheritTrailingComments = requireInheritTrailingComments(); + var _removeComments = requireRemoveComments(); + var _index3 = requireGenerated(); + Object.keys(_index3).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index3[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index3[key]; + } + }); + }); + var _index4 = requireConstants(); + Object.keys(_index4).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index4[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index4[key]; + } + }); + }); + var _ensureBlock = requireEnsureBlock(); + var _toBindingIdentifierName = requireToBindingIdentifierName(); + var _toBlock = requireToBlock(); + var _toComputedKey = requireToComputedKey(); + var _toExpression = requireToExpression(); + var _toIdentifier = requireToIdentifier(); + var _toKeyAlias = requireToKeyAlias(); + var _toStatement = requireToStatement(); + var _valueToNode = requireValueToNode(); + var _index5 = requireDefinitions(); + Object.keys(_index5).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index5[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index5[key]; + } + }); + }); + var _appendToMemberExpression = requireAppendToMemberExpression(); + var _inherits = requireInherits(); + var _prependToMemberExpression = requirePrependToMemberExpression(); + var _removeProperties = requireRemoveProperties(); + var _removePropertiesDeep = requireRemovePropertiesDeep(); + var _removeTypeDuplicates = requireRemoveTypeDuplicates$1(); + var _getAssignmentIdentifiers = requireGetAssignmentIdentifiers(); + var _getBindingIdentifiers = requireGetBindingIdentifiers(); + var _getOuterBindingIdentifiers = requireGetOuterBindingIdentifiers(); + var _getFunctionName = requireGetFunctionName(); + var _traverse = requireTraverse(); + Object.keys(_traverse).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _traverse[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _traverse[key]; + } + }); + }); + var _traverseFast = requireTraverseFast(); + var _shallowEqual = requireShallowEqual(); + var _is = requireIs(); + var _isBinding = requireIsBinding(); + var _isBlockScoped = requireIsBlockScoped(); + var _isImmutable = requireIsImmutable(); + var _isLet = requireIsLet(); + var _isNode = requireIsNode(); + var _isNodesEquivalent = requireIsNodesEquivalent(); + var _isPlaceholderType = requireIsPlaceholderType(); + var _isReferenced = requireIsReferenced(); + var _isScope = requireIsScope(); + var _isSpecifierDefault = requireIsSpecifierDefault(); + var _isType = requireIsType(); + var _isValidES3Identifier = requireIsValidES3Identifier(); + var _isValidIdentifier = requireIsValidIdentifier(); + var _isVar = requireIsVar(); + var _matchesPattern = requireMatchesPattern(); + var _validate = requireValidate(); + var _buildMatchMemberExpression = requireBuildMatchMemberExpression(); + var _index6 = requireGenerated$3(); + Object.keys(_index6).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index6[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _index6[key]; + } + }); + }); + var _deprecationWarning = requireDeprecationWarning(); + exports.react = { + isReactComponent: _isReactComponent.default, + isCompatTag: _isCompatTag.default, + buildChildren: _buildChildren.default + }; + { + exports.toSequenceExpression = requireToSequenceExpression().default; + } + if (process.env.BABEL_TYPES_8_BREAKING) { + console.warn("BABEL_TYPES_8_BREAKING is not supported anymore. Use the latest Babel 8.0.0 pre-release instead!"); + } + + +} (lib$3)); + return lib$3; +} + +var libExports$1 = requireLib$1(); + +var lib = {}; + +var picocolorsExports = {}; +var picocolors = { + get exports(){ return picocolorsExports; }, + set exports(v){ picocolorsExports = v; }, +}; + +var hasRequiredPicocolors; + +function requirePicocolors () { + if (hasRequiredPicocolors) return picocolorsExports; + hasRequiredPicocolors = 1; + let p = process || {}, argv = p.argv || [], env = p.env || {}; + let isColorSupported = + !(!!env.NO_COLOR || argv.includes("--no-color")) && + (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI); + + let formatter = (open, close, replace = open) => + input => { + let string = "" + input, index = string.indexOf(close, open.length); + return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close + }; + + let replaceClose = (string, close, replace, index) => { + let result = "", cursor = 0; + do { + result += string.substring(cursor, index) + replace; + cursor = index + close.length; + index = string.indexOf(close, cursor); + } while (~index) + return result + string.substring(cursor) + }; + + let createColors = (enabled = isColorSupported) => { + let f = enabled ? formatter : () => String; + return { + isColorSupported: enabled, + reset: f("\x1b[0m", "\x1b[0m"), + bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), + dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), + italic: f("\x1b[3m", "\x1b[23m"), + underline: f("\x1b[4m", "\x1b[24m"), + inverse: f("\x1b[7m", "\x1b[27m"), + hidden: f("\x1b[8m", "\x1b[28m"), + strikethrough: f("\x1b[9m", "\x1b[29m"), + + black: f("\x1b[30m", "\x1b[39m"), + red: f("\x1b[31m", "\x1b[39m"), + green: f("\x1b[32m", "\x1b[39m"), + yellow: f("\x1b[33m", "\x1b[39m"), + blue: f("\x1b[34m", "\x1b[39m"), + magenta: f("\x1b[35m", "\x1b[39m"), + cyan: f("\x1b[36m", "\x1b[39m"), + white: f("\x1b[37m", "\x1b[39m"), + gray: f("\x1b[90m", "\x1b[39m"), + + bgBlack: f("\x1b[40m", "\x1b[49m"), + bgRed: f("\x1b[41m", "\x1b[49m"), + bgGreen: f("\x1b[42m", "\x1b[49m"), + bgYellow: f("\x1b[43m", "\x1b[49m"), + bgBlue: f("\x1b[44m", "\x1b[49m"), + bgMagenta: f("\x1b[45m", "\x1b[49m"), + bgCyan: f("\x1b[46m", "\x1b[49m"), + bgWhite: f("\x1b[47m", "\x1b[49m"), + + blackBright: f("\x1b[90m", "\x1b[39m"), + redBright: f("\x1b[91m", "\x1b[39m"), + greenBright: f("\x1b[92m", "\x1b[39m"), + yellowBright: f("\x1b[93m", "\x1b[39m"), + blueBright: f("\x1b[94m", "\x1b[39m"), + magentaBright: f("\x1b[95m", "\x1b[39m"), + cyanBright: f("\x1b[96m", "\x1b[39m"), + whiteBright: f("\x1b[97m", "\x1b[39m"), + + bgBlackBright: f("\x1b[100m", "\x1b[49m"), + bgRedBright: f("\x1b[101m", "\x1b[49m"), + bgGreenBright: f("\x1b[102m", "\x1b[49m"), + bgYellowBright: f("\x1b[103m", "\x1b[49m"), + bgBlueBright: f("\x1b[104m", "\x1b[49m"), + bgMagentaBright: f("\x1b[105m", "\x1b[49m"), + bgCyanBright: f("\x1b[106m", "\x1b[49m"), + bgWhiteBright: f("\x1b[107m", "\x1b[49m"), + } + }; + + picocolors.exports = createColors(); + picocolorsExports.createColors = createColors; + return picocolorsExports; +} + +var jsTokens = {}; + +var hasRequiredJsTokens; + +function requireJsTokens () { + if (hasRequiredJsTokens) return jsTokens; + hasRequiredJsTokens = 1; + // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell + // License: MIT. (See LICENSE.) + + Object.defineProperty(jsTokens, "__esModule", { + value: true + }); + + // This regex comes from regex.coffee, and is inserted here by generate-index.js + // (run `npm run build`). + jsTokens.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; + + jsTokens.matchToToken = function(match) { + var token = {type: "invalid", value: match[0], closed: undefined}; + if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]); + else if (match[ 5]) token.type = "comment"; + else if (match[ 6]) token.type = "comment", token.closed = !!match[7]; + else if (match[ 8]) token.type = "regex"; + else if (match[ 9]) token.type = "number"; + else if (match[10]) token.type = "name"; + else if (match[11]) token.type = "punctuator"; + else if (match[12]) token.type = "whitespace"; + return token + }; + return jsTokens; +} + +var hasRequiredLib; + +function requireLib () { + if (hasRequiredLib) return lib; + hasRequiredLib = 1; + + Object.defineProperty(lib, '__esModule', { value: true }); + + var picocolors = requirePicocolors(); + var jsTokens = requireJsTokens(); + var helperValidatorIdentifier = requireLib$3(); + + function isColorSupported() { + return (typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported + ); + } + const compose = (f, g) => v => f(g(v)); + function buildDefs(colors) { + return { + keyword: colors.cyan, + capitalized: colors.yellow, + jsxIdentifier: colors.yellow, + punctuator: colors.yellow, + number: colors.magenta, + string: colors.green, + regex: colors.magenta, + comment: colors.gray, + invalid: compose(compose(colors.white, colors.bgRed), colors.bold), + gutter: colors.gray, + marker: compose(colors.red, colors.bold), + message: compose(colors.red, colors.bold), + reset: colors.reset + }; + } + const defsOn = buildDefs(picocolors.createColors(true)); + const defsOff = buildDefs(picocolors.createColors(false)); + function getDefs(enabled) { + return enabled ? defsOn : defsOff; + } + + const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]); + const NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/; + const BRACKET = /^[()[\]{}]$/; + let tokenize; + { + const JSX_TAG = /^[a-z][\w-]*$/i; + const getTokenType = function (token, offset, text) { + if (token.type === "name") { + if (helperValidatorIdentifier.isKeyword(token.value) || helperValidatorIdentifier.isStrictReservedWord(token.value, true) || sometimesKeywords.has(token.value)) { + return "keyword"; + } + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === " defs[type](str)).join("\n"); + } else { + highlighted += value; + } + } + return highlighted; + } + + let deprecationWarningShown = false; + const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + function getMarkerLines(loc, source, opts) { + const startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + const endLoc = Object.assign({}, startLoc, loc.end); + const { + linesAbove = 2, + linesBelow = 3 + } = opts || {}; + const startLine = startLoc.line; + const startColumn = startLoc.column; + const endLine = endLoc.line; + const endColumn = endLoc.column; + let start = Math.max(startLine - (linesAbove + 1), 0); + let end = Math.min(source.length, endLine + linesBelow); + if (startLine === -1) { + start = 0; + } + if (endLine === -1) { + end = source.length; + } + const lineDiff = endLine - startLine; + const markerLines = {}; + if (lineDiff) { + for (let i = 0; i <= lineDiff; i++) { + const lineNumber = i + startLine; + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + const sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + const sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, sourceLength]; + } + } + } else { + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } + } + return { + start, + end, + markerLines + }; + } + function codeFrameColumns(rawLines, loc, opts = {}) { + const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode; + const defs = getDefs(shouldHighlight); + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end).length; + const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines; + let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number}`.slice(-numberMaxWidth); + const gutter = ` ${paddedNumber} |`; + const hasMarker = markerLines[number]; + const lastMarkerLine = !markerLines[number + 1]; + if (hasMarker) { + let markerLine = ""; + if (Array.isArray(hasMarker)) { + const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + const numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join(""); + if (lastMarkerLine && opts.message) { + markerLine += " " + defs.message(opts.message); + } + } + return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join(""); + } else { + return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`; + } + }).join("\n"); + if (opts.message && !hasColumns) { + frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; + } + if (shouldHighlight) { + return defs.reset(frame); + } else { + return frame; + } + } + function index (rawLines, lineNumber, colNumber, opts = {}) { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + const deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + colNumber = Math.max(colNumber, 0); + const location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); + } + + lib.codeFrameColumns = codeFrameColumns; + lib.default = index; + lib.highlight = highlight; + + return lib; +} + +var libExports = requireLib(); + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + + +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +var _OkImpl_val, _ErrImpl_val; +function Ok(val) { + return new OkImpl(val); +} +class OkImpl { + constructor(val) { + _OkImpl_val.set(this, void 0); + __classPrivateFieldSet(this, _OkImpl_val, val, "f"); + } + map(fn) { + return new OkImpl(fn(__classPrivateFieldGet(this, _OkImpl_val, "f"))); + } + mapErr(_fn) { + return this; + } + mapOr(_fallback, fn) { + return fn(__classPrivateFieldGet(this, _OkImpl_val, "f")); + } + mapOrElse(_fallback, fn) { + return fn(__classPrivateFieldGet(this, _OkImpl_val, "f")); + } + andThen(fn) { + return fn(__classPrivateFieldGet(this, _OkImpl_val, "f")); + } + and(res) { + return res; + } + or(_res) { + return this; + } + orElse(_fn) { + return this; + } + isOk() { + return true; + } + isErr() { + return false; + } + expect(_msg) { + return __classPrivateFieldGet(this, _OkImpl_val, "f"); + } + expectErr(msg) { + throw new Error(`${msg}: ${__classPrivateFieldGet(this, _OkImpl_val, "f")}`); + } + unwrap() { + return __classPrivateFieldGet(this, _OkImpl_val, "f"); + } + unwrapOr(_fallback) { + return __classPrivateFieldGet(this, _OkImpl_val, "f"); + } + unwrapOrElse(_fallback) { + return __classPrivateFieldGet(this, _OkImpl_val, "f"); + } + unwrapErr() { + if (__classPrivateFieldGet(this, _OkImpl_val, "f") instanceof Error) { + throw __classPrivateFieldGet(this, _OkImpl_val, "f"); + } + throw new Error(`Can't unwrap \`Ok\` to \`Err\`: ${__classPrivateFieldGet(this, _OkImpl_val, "f")}`); + } +} +_OkImpl_val = new WeakMap(); +function Err(val) { + return new ErrImpl(val); +} +class ErrImpl { + constructor(val) { + _ErrImpl_val.set(this, void 0); + __classPrivateFieldSet(this, _ErrImpl_val, val, "f"); + } + map(_fn) { + return this; + } + mapErr(fn) { + return new ErrImpl(fn(__classPrivateFieldGet(this, _ErrImpl_val, "f"))); + } + mapOr(fallback, _fn) { + return fallback; + } + mapOrElse(fallback, _fn) { + return fallback(); + } + andThen(_fn) { + return this; + } + and(_res) { + return this; + } + or(res) { + return res; + } + orElse(fn) { + return fn(__classPrivateFieldGet(this, _ErrImpl_val, "f")); + } + isOk() { + return false; + } + isErr() { + return true; + } + expect(msg) { + throw new Error(`${msg}: ${__classPrivateFieldGet(this, _ErrImpl_val, "f")}`); + } + expectErr(_msg) { + return __classPrivateFieldGet(this, _ErrImpl_val, "f"); + } + unwrap() { + if (__classPrivateFieldGet(this, _ErrImpl_val, "f") instanceof Error) { + throw __classPrivateFieldGet(this, _ErrImpl_val, "f"); + } + throw new Error(`Can't unwrap \`Err\` to \`Ok\`: ${__classPrivateFieldGet(this, _ErrImpl_val, "f")}`); + } + unwrapOr(fallback) { + return fallback; + } + unwrapOrElse(fallback) { + return fallback(__classPrivateFieldGet(this, _ErrImpl_val, "f")); + } + unwrapErr() { + return __classPrivateFieldGet(this, _ErrImpl_val, "f"); + } +} +_ErrImpl_val = new WeakMap(); + +function assertExhaustive$1(_, errorMsg) { + throw new Error(errorMsg); +} +function retainWhere(array, predicate) { + let writeIndex = 0; + for (let readIndex = 0; readIndex < array.length; readIndex++) { + const item = array[readIndex]; + if (predicate(item, readIndex) === true) { + array[writeIndex++] = item; + } + } + array.length = writeIndex; +} +function retainWhere_Set(items, predicate) { + for (const item of items) { + if (!predicate(item)) { + items.delete(item); + } + } +} +function getOrInsertWith(m, key, makeDefault) { + if (m.has(key)) { + return m.get(key); + } + else { + const defaultValue = makeDefault(); + m.set(key, defaultValue); + return defaultValue; + } +} +function getOrInsertDefault(m, key, defaultValue) { + if (m.has(key)) { + return m.get(key); + } + else { + m.set(key, defaultValue); + return defaultValue; + } +} +function Set_equal(a, b) { + if (a.size !== b.size) { + return false; + } + for (const item of a) { + if (!b.has(item)) { + return false; + } + } + return true; +} +function Set_union(a, b) { + const union = new Set(a); + for (const item of b) { + union.add(item); + } + return union; +} +function Set_intersect(sets) { + if (sets.length === 0 || sets.some(s => s.size === 0)) { + return new Set(); + } + else if (sets.length === 1) { + return new Set(sets[0]); + } + const result = new Set(); + const first = sets[0]; + outer: for (const e of first) { + for (let i = 1; i < sets.length; i++) { + if (!sets[i].has(e)) { + continue outer; + } + } + result.add(e); + } + return result; +} +function Set_isSuperset(a, b) { + for (const v of b) { + if (!a.has(v)) { + return false; + } + } + return true; +} +function Iterable_some(iter, pred) { + for (const item of iter) { + if (pred(item)) { + return true; + } + } + return false; +} +function Set_filter(source, fn) { + const result = new Set(); + for (const entry of source) { + if (fn(entry)) { + result.add(entry); + } + } + return result; +} +function hasNode(input) { + return input.node != null; +} +function hasOwnProperty$1(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +const CODEFRAME_LINES_ABOVE = 2; +const CODEFRAME_LINES_BELOW = 3; +const CODEFRAME_MAX_LINES = 10; +const CODEFRAME_ABBREVIATED_SOURCE_LINES = 5; +var ErrorSeverity; +(function (ErrorSeverity) { + ErrorSeverity["Error"] = "Error"; + ErrorSeverity["Warning"] = "Warning"; + ErrorSeverity["Hint"] = "Hint"; + ErrorSeverity["Off"] = "Off"; +})(ErrorSeverity || (ErrorSeverity = {})); +var CompilerSuggestionOperation; +(function (CompilerSuggestionOperation) { + CompilerSuggestionOperation[CompilerSuggestionOperation["InsertBefore"] = 0] = "InsertBefore"; + CompilerSuggestionOperation[CompilerSuggestionOperation["InsertAfter"] = 1] = "InsertAfter"; + CompilerSuggestionOperation[CompilerSuggestionOperation["Remove"] = 2] = "Remove"; + CompilerSuggestionOperation[CompilerSuggestionOperation["Replace"] = 3] = "Replace"; +})(CompilerSuggestionOperation || (CompilerSuggestionOperation = {})); +class CompilerDiagnostic { + constructor(options) { + this.options = options; + } + static create(options) { + return new CompilerDiagnostic(Object.assign(Object.assign({}, options), { details: [] })); + } + get reason() { + return this.options.reason; + } + get description() { + return this.options.description; + } + get severity() { + return getRuleForCategory(this.category).severity; + } + get suggestions() { + return this.options.suggestions; + } + get category() { + return this.options.category; + } + withDetails(...details) { + this.options.details.push(...details); + return this; + } + primaryLocation() { + const firstErrorDetail = this.options.details.filter(d => d.kind === 'error')[0]; + return firstErrorDetail != null && firstErrorDetail.kind === 'error' + ? firstErrorDetail.loc + : null; + } + printErrorMessage(source, options) { + var _a, _b; + const buffer = [printErrorSummary(this.category, this.reason)]; + if (this.description != null) { + buffer.push('\n\n', `${this.description}.`); + } + for (const detail of this.options.details) { + switch (detail.kind) { + case 'error': { + const loc = detail.loc; + if (loc == null || typeof loc === 'symbol') { + continue; + } + let codeFrame; + try { + codeFrame = printCodeFrame(source, loc, (_a = detail.message) !== null && _a !== void 0 ? _a : ''); + } + catch (e) { + codeFrame = (_b = detail.message) !== null && _b !== void 0 ? _b : ''; + } + buffer.push('\n\n'); + if (loc.filename != null) { + const line = loc.start.line; + const column = options.eslint + ? loc.start.column + 1 + : loc.start.column; + buffer.push(`${loc.filename}:${line}:${column}\n`); + } + buffer.push(codeFrame); + break; + } + case 'hint': { + buffer.push('\n\n'); + buffer.push(detail.message); + break; + } + default: { + assertExhaustive$1(detail, `Unexpected detail kind ${detail.kind}`); + } + } + } + return buffer.join(''); + } + toString() { + const buffer = [printErrorSummary(this.category, this.reason)]; + if (this.description != null) { + buffer.push(`. ${this.description}.`); + } + const loc = this.primaryLocation(); + if (loc != null && typeof loc !== 'symbol') { + buffer.push(` (${loc.start.line}:${loc.start.column})`); + } + return buffer.join(''); + } +} +class CompilerErrorDetail { + constructor(options) { + this.options = options; + } + get reason() { + return this.options.reason; + } + get description() { + return this.options.description; + } + get severity() { + return getRuleForCategory(this.category).severity; + } + get loc() { + return this.options.loc; + } + get suggestions() { + return this.options.suggestions; + } + get category() { + return this.options.category; + } + primaryLocation() { + return this.loc; + } + printErrorMessage(source, options) { + const buffer = [printErrorSummary(this.category, this.reason)]; + if (this.description != null) { + buffer.push(`\n\n${this.description}.`); + } + const loc = this.loc; + if (loc != null && typeof loc !== 'symbol') { + let codeFrame; + try { + codeFrame = printCodeFrame(source, loc, this.reason); + } + catch (e) { + codeFrame = ''; + } + buffer.push(`\n\n`); + if (loc.filename != null) { + const line = loc.start.line; + const column = options.eslint ? loc.start.column + 1 : loc.start.column; + buffer.push(`${loc.filename}:${line}:${column}\n`); + } + buffer.push(codeFrame); + buffer.push('\n\n'); + } + return buffer.join(''); + } + toString() { + const buffer = [printErrorSummary(this.category, this.reason)]; + if (this.description != null) { + buffer.push(`. ${this.description}.`); + } + const loc = this.loc; + if (loc != null && typeof loc !== 'symbol') { + buffer.push(` (${loc.start.line}:${loc.start.column})`); + } + return buffer.join(''); + } +} +class CompilerError extends Error { + static invariant(condition, options) { + var _a, _b; + if (!condition) { + const errors = new CompilerError(); + errors.pushDiagnostic(CompilerDiagnostic.create({ + reason: options.reason, + description: (_a = options.description) !== null && _a !== void 0 ? _a : null, + category: ErrorCategory.Invariant, + }).withDetails({ + kind: 'error', + loc: options.loc, + message: (_b = options.message) !== null && _b !== void 0 ? _b : options.reason, + })); + throw errors; + } + } + static throwDiagnostic(options) { + const errors = new CompilerError(); + errors.pushDiagnostic(new CompilerDiagnostic(options)); + throw errors; + } + static throwTodo(options) { + const errors = new CompilerError(); + errors.pushErrorDetail(new CompilerErrorDetail(Object.assign(Object.assign({}, options), { category: ErrorCategory.Todo }))); + throw errors; + } + static throwInvalidJS(options) { + const errors = new CompilerError(); + errors.pushErrorDetail(new CompilerErrorDetail(Object.assign(Object.assign({}, options), { category: ErrorCategory.Syntax }))); + throw errors; + } + static throwInvalidReact(options) { + const errors = new CompilerError(); + errors.pushErrorDetail(new CompilerErrorDetail(options)); + throw errors; + } + static throwInvalidConfig(options) { + const errors = new CompilerError(); + errors.pushErrorDetail(new CompilerErrorDetail(Object.assign(Object.assign({}, options), { category: ErrorCategory.Config }))); + throw errors; + } + static throw(options) { + const errors = new CompilerError(); + errors.pushErrorDetail(new CompilerErrorDetail(options)); + throw errors; + } + constructor(...args) { + super(...args); + this.details = []; + this.disabledDetails = []; + this.printedMessage = null; + this.name = 'ReactCompilerError'; + this.details = []; + this.disabledDetails = []; + } + get message() { + var _a; + return (_a = this.printedMessage) !== null && _a !== void 0 ? _a : this.toString(); + } + set message(_message) { } + toString() { + if (this.printedMessage) { + return this.printedMessage; + } + if (Array.isArray(this.details)) { + return this.details.map(detail => detail.toString()).join('\n\n'); + } + return this.name; + } + withPrintedMessage(source, options) { + this.printedMessage = this.printErrorMessage(source, options); + return this; + } + printErrorMessage(source, options) { + if (options.eslint && this.details.length === 1) { + return this.details[0].printErrorMessage(source, options); + } + return (`Found ${this.details.length} error${this.details.length === 1 ? '' : 's'}:\n\n` + + this.details + .map(detail => detail.printErrorMessage(source, options).trim()) + .join('\n\n')); + } + merge(other) { + this.details.push(...other.details); + this.disabledDetails.push(...other.disabledDetails); + } + pushDiagnostic(diagnostic) { + if (diagnostic.severity === ErrorSeverity.Off) { + this.disabledDetails.push(diagnostic); + } + else { + this.details.push(diagnostic); + } + } + push(options) { + var _a; + const detail = new CompilerErrorDetail({ + category: options.category, + reason: options.reason, + description: (_a = options.description) !== null && _a !== void 0 ? _a : null, + suggestions: options.suggestions, + loc: typeof options.loc === 'symbol' ? null : options.loc, + }); + return this.pushErrorDetail(detail); + } + pushErrorDetail(detail) { + if (detail.severity === ErrorSeverity.Off) { + this.disabledDetails.push(detail); + } + else { + this.details.push(detail); + } + return detail; + } + hasAnyErrors() { + return this.details.length > 0; + } + asResult() { + return this.hasAnyErrors() ? Err(this) : Ok(undefined); + } + hasErrors() { + for (const detail of this.details) { + if (detail.severity === ErrorSeverity.Error) { + return true; + } + } + return false; + } + hasWarning() { + let res = false; + for (const detail of this.details) { + if (detail.severity === ErrorSeverity.Error) { + return false; + } + if (detail.severity === ErrorSeverity.Warning) { + res = true; + } + } + return res; + } + hasHints() { + let res = false; + for (const detail of this.details) { + if (detail.severity === ErrorSeverity.Error) { + return false; + } + if (detail.severity === ErrorSeverity.Warning) { + return false; + } + if (detail.severity === ErrorSeverity.Hint) { + res = true; + } + } + return res; + } +} +function printCodeFrame(source, loc, message) { + const printed = libExports.codeFrameColumns(source, { + start: { + line: loc.start.line, + column: loc.start.column + 1, + }, + end: { + line: loc.end.line, + column: loc.end.column + 1, + }, + }, { + message, + linesAbove: CODEFRAME_LINES_ABOVE, + linesBelow: CODEFRAME_LINES_BELOW, + }); + const lines = printed.split(/\r?\n/); + if (loc.end.line - loc.start.line < CODEFRAME_MAX_LINES) { + return printed; + } + const pipeIndex = lines[0].indexOf('|'); + return [ + ...lines.slice(0, CODEFRAME_LINES_ABOVE + CODEFRAME_ABBREVIATED_SOURCE_LINES), + ' '.repeat(pipeIndex) + '…', + ...lines.slice(-(CODEFRAME_LINES_BELOW + CODEFRAME_ABBREVIATED_SOURCE_LINES)), + ].join('\n'); +} +function printErrorSummary(category, message) { + let heading; + switch (category) { + case ErrorCategory.CapitalizedCalls: + case ErrorCategory.Config: + case ErrorCategory.EffectDerivationsOfState: + case ErrorCategory.EffectSetState: + case ErrorCategory.ErrorBoundaries: + case ErrorCategory.FBT: + case ErrorCategory.Gating: + case ErrorCategory.Globals: + case ErrorCategory.Hooks: + case ErrorCategory.Immutability: + case ErrorCategory.Purity: + case ErrorCategory.Refs: + case ErrorCategory.RenderSetState: + case ErrorCategory.StaticComponents: + case ErrorCategory.Suppression: + case ErrorCategory.Syntax: + case ErrorCategory.UseMemo: + case ErrorCategory.VoidUseMemo: + case ErrorCategory.MemoDependencies: + case ErrorCategory.EffectExhaustiveDependencies: { + heading = 'Error'; + break; + } + case ErrorCategory.EffectDependencies: + case ErrorCategory.IncompatibleLibrary: + case ErrorCategory.PreserveManualMemo: + case ErrorCategory.UnsupportedSyntax: { + heading = 'Compilation Skipped'; + break; + } + case ErrorCategory.Invariant: { + heading = 'Invariant'; + break; + } + case ErrorCategory.Todo: { + heading = 'Todo'; + break; + } + default: { + assertExhaustive$1(category, `Unhandled category '${category}'`); + } + } + return `${heading}: ${message}`; +} +var ErrorCategory; +(function (ErrorCategory) { + ErrorCategory["Hooks"] = "Hooks"; + ErrorCategory["CapitalizedCalls"] = "CapitalizedCalls"; + ErrorCategory["StaticComponents"] = "StaticComponents"; + ErrorCategory["UseMemo"] = "UseMemo"; + ErrorCategory["VoidUseMemo"] = "VoidUseMemo"; + ErrorCategory["PreserveManualMemo"] = "PreserveManualMemo"; + ErrorCategory["MemoDependencies"] = "MemoDependencies"; + ErrorCategory["IncompatibleLibrary"] = "IncompatibleLibrary"; + ErrorCategory["Immutability"] = "Immutability"; + ErrorCategory["Globals"] = "Globals"; + ErrorCategory["Refs"] = "Refs"; + ErrorCategory["EffectDependencies"] = "EffectDependencies"; + ErrorCategory["EffectExhaustiveDependencies"] = "EffectExhaustiveDependencies"; + ErrorCategory["EffectSetState"] = "EffectSetState"; + ErrorCategory["EffectDerivationsOfState"] = "EffectDerivationsOfState"; + ErrorCategory["ErrorBoundaries"] = "ErrorBoundaries"; + ErrorCategory["Purity"] = "Purity"; + ErrorCategory["RenderSetState"] = "RenderSetState"; + ErrorCategory["Invariant"] = "Invariant"; + ErrorCategory["Todo"] = "Todo"; + ErrorCategory["Syntax"] = "Syntax"; + ErrorCategory["UnsupportedSyntax"] = "UnsupportedSyntax"; + ErrorCategory["Config"] = "Config"; + ErrorCategory["Gating"] = "Gating"; + ErrorCategory["Suppression"] = "Suppression"; + ErrorCategory["FBT"] = "FBT"; +})(ErrorCategory || (ErrorCategory = {})); +var LintRulePreset; +(function (LintRulePreset) { + LintRulePreset["Recommended"] = "recommended"; + LintRulePreset["RecommendedLatest"] = "recommended-latest"; + LintRulePreset["Off"] = "off"; +})(LintRulePreset || (LintRulePreset = {})); +const RULE_NAME_PATTERN = /^[a-z]+(-[a-z]+)*$/; +function getRuleForCategory(category) { + const rule = getRuleForCategoryImpl(category); + invariant(RULE_NAME_PATTERN.test(rule.name), `Invalid rule name, got '${rule.name}' but rules must match ${RULE_NAME_PATTERN.toString()}`); + return rule; +} +function getRuleForCategoryImpl(category) { + switch (category) { + case ErrorCategory.CapitalizedCalls: { + return { + category, + severity: ErrorSeverity.Error, + name: 'capitalized-calls', + description: 'Validates against calling capitalized functions/methods instead of using JSX', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.Config: { + return { + category, + severity: ErrorSeverity.Error, + name: 'config', + description: 'Validates the compiler configuration options', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.EffectDependencies: { + return { + category, + severity: ErrorSeverity.Error, + name: 'memoized-effect-dependencies', + description: 'Validates that effect dependencies are memoized', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.EffectExhaustiveDependencies: { + return { + category, + severity: ErrorSeverity.Error, + name: 'exhaustive-effect-dependencies', + description: 'Validates that effect dependencies are exhaustive and without extraneous values', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.EffectDerivationsOfState: { + return { + category, + severity: ErrorSeverity.Error, + name: 'no-deriving-state-in-effects', + description: 'Validates against deriving values from state in an effect', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.EffectSetState: { + return { + category, + severity: ErrorSeverity.Error, + name: 'set-state-in-effect', + description: 'Validates against calling setState synchronously in an effect. ' + + 'This can indicate non-local derived data, a derived event pattern, or ' + + 'improper external data synchronization.', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.ErrorBoundaries: { + return { + category, + severity: ErrorSeverity.Error, + name: 'error-boundaries', + description: 'Validates usage of error boundaries instead of try/catch for errors in child components', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.FBT: { + return { + category, + severity: ErrorSeverity.Error, + name: 'fbt', + description: 'Validates usage of fbt', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.Gating: { + return { + category, + severity: ErrorSeverity.Error, + name: 'gating', + description: 'Validates configuration of [gating mode](https://react.dev/reference/react-compiler/gating)', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Globals: { + return { + category, + severity: ErrorSeverity.Error, + name: 'globals', + description: 'Validates against assignment/mutation of globals during render, part of ensuring that ' + + '[side effects must render outside of render](https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render)', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Hooks: { + return { + category, + severity: ErrorSeverity.Error, + name: 'hooks', + description: 'Validates the rules of hooks', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.Immutability: { + return { + category, + severity: ErrorSeverity.Error, + name: 'immutability', + description: 'Validates against mutating props, state, and other values that [are immutable](https://react.dev/reference/rules/components-and-hooks-must-be-pure#props-and-state-are-immutable)', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Invariant: { + return { + category, + severity: ErrorSeverity.Error, + name: 'invariant', + description: 'Internal invariants', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.PreserveManualMemo: { + return { + category, + severity: ErrorSeverity.Error, + name: 'preserve-manual-memoization', + description: 'Validates that existing manual memoized is preserved by the compiler. ' + + 'React Compiler will only compile components and hooks if its inference ' + + '[matches or exceeds the existing manual memoization](https://react.dev/learn/react-compiler/introduction#what-should-i-do-about-usememo-usecallback-and-reactmemo)', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Purity: { + return { + category, + severity: ErrorSeverity.Error, + name: 'purity', + description: 'Validates that [components/hooks are pure](https://react.dev/reference/rules/components-and-hooks-must-be-pure) by checking that they do not call known-impure functions', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Refs: { + return { + category, + severity: ErrorSeverity.Error, + name: 'refs', + description: 'Validates correct usage of refs, not reading/writing during render. See the "pitfalls" section in [`useRef()` usage](https://react.dev/reference/react/useRef#usage)', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.RenderSetState: { + return { + category, + severity: ErrorSeverity.Error, + name: 'set-state-in-render', + description: 'Validates against setting state during render, which can trigger additional renders and potential infinite render loops', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.StaticComponents: { + return { + category, + severity: ErrorSeverity.Error, + name: 'static-components', + description: 'Validates that components are static, not recreated every render. Components that are recreated dynamically can reset state and trigger excessive re-rendering', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.Suppression: { + return { + category, + severity: ErrorSeverity.Error, + name: 'rule-suppression', + description: 'Validates against suppression of other rules', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.Syntax: { + return { + category, + severity: ErrorSeverity.Error, + name: 'syntax', + description: 'Validates against invalid syntax', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.Todo: { + return { + category, + severity: ErrorSeverity.Hint, + name: 'todo', + description: 'Unimplemented features', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.UnsupportedSyntax: { + return { + category, + severity: ErrorSeverity.Warning, + name: 'unsupported-syntax', + description: 'Validates against syntax that we do not plan to support in React Compiler', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.UseMemo: { + return { + category, + severity: ErrorSeverity.Error, + name: 'use-memo', + description: 'Validates usage of the useMemo() hook against common mistakes. See [`useMemo()` docs](https://react.dev/reference/react/useMemo) for more information.', + preset: LintRulePreset.Recommended, + }; + } + case ErrorCategory.VoidUseMemo: { + return { + category, + severity: ErrorSeverity.Error, + name: 'void-use-memo', + description: 'Validates that useMemos always return a value and that the result of the useMemo is used by the component/hook. See [`useMemo()` docs](https://react.dev/reference/react/useMemo) for more information.', + preset: LintRulePreset.RecommendedLatest, + }; + } + case ErrorCategory.MemoDependencies: { + return { + category, + severity: ErrorSeverity.Error, + name: 'memo-dependencies', + description: 'Validates that useMemo() and useCallback() specify comprehensive dependencies without extraneous values. See [`useMemo()` docs](https://react.dev/reference/react/useMemo) for more information.', + preset: LintRulePreset.Off, + }; + } + case ErrorCategory.IncompatibleLibrary: { + return { + category, + severity: ErrorSeverity.Warning, + name: 'incompatible-library', + description: 'Validates against usage of libraries which are incompatible with memoization (manual or automatic)', + preset: LintRulePreset.Recommended, + }; + } + default: { + assertExhaustive$1(category, `Unsupported category ${category}`); + } + } +} +const LintRules = Object.keys(ErrorCategory).map(category => getRuleForCategory(category)); + +function makeTypeId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected instruction id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +let typeCounter = 0; +function makeType() { + return { + kind: 'Type', + id: makeTypeId(typeCounter++), + }; +} +function typeEquals(tA, tB) { + if (tA.kind !== tB.kind) + return false; + return (typeVarEquals(tA, tB) || + funcTypeEquals(tA, tB) || + objectTypeEquals(tA, tB) || + primitiveTypeEquals(tA, tB) || + polyTypeEquals(tA, tB) || + phiTypeEquals(tA, tB) || + propTypeEquals(tA, tB) || + objectMethodTypeEquals(tA, tB)); +} +function typeVarEquals(tA, tB) { + if (tA.kind === 'Type' && tB.kind === 'Type') { + return tA.id === tB.id; + } + return false; +} +function typeKindCheck(tA, tb, type) { + return tA.kind === type && tb.kind === type; +} +function objectMethodTypeEquals(tA, tB) { + return typeKindCheck(tA, tB, 'ObjectMethod'); +} +function propTypeEquals(tA, tB) { + if (tA.kind === 'Property' && tB.kind === 'Property') { + if (!typeEquals(tA.objectType, tB.objectType)) { + return false; + } + return (tA.propertyName === tB.propertyName && tA.objectName === tB.objectName); + } + return false; +} +function primitiveTypeEquals(tA, tB) { + return typeKindCheck(tA, tB, 'Primitive'); +} +function polyTypeEquals(tA, tB) { + return typeKindCheck(tA, tB, 'Poly'); +} +function objectTypeEquals(tA, tB) { + if (tA.kind === 'Object' && tB.kind == 'Object') { + return tA.shapeId === tB.shapeId; + } + return false; +} +function funcTypeEquals(tA, tB) { + if (tA.kind !== 'Function' || tB.kind !== 'Function') { + return false; + } + return typeEquals(tA.return, tB.return); +} +function phiTypeEquals(tA, tB) { + if (tA.kind === 'Phi' && tB.kind === 'Phi') { + if (tA.operands.length !== tB.operands.length) { + return false; + } + let operands = new Set(tA.operands); + for (let i = 0; i < tB.operands.length; i++) { + if (!operands.has(tB.operands[i])) { + return false; + } + } + } + return false; +} + +const RESERVED_WORDS = new Set([ + 'break', + 'case', + 'catch', + 'class', + 'const', + 'continue', + 'debugger', + 'default', + 'delete', + 'do', + 'else', + 'enum', + 'export', + 'extends', + 'false', + 'finally', + 'for', + 'function', + 'if', + 'import', + 'in', + 'instanceof', + 'new', + 'null', + 'return', + 'super', + 'switch', + 'this', + 'throw', + 'true', + 'try', + 'typeof', + 'var', + 'void', + 'while', + 'with', +]); +const STRICT_MODE_RESERVED_WORDS = new Set([ + 'let', + 'static', + 'implements', + 'interface', + 'package', + 'private', + 'protected', + 'public', +]); +const STRICT_MODE_RESTRICTED_WORDS = new Set(['eval', 'arguments']); +function isReservedWord(identifierName) { + return (RESERVED_WORDS.has(identifierName) || + STRICT_MODE_RESERVED_WORDS.has(identifierName) || + STRICT_MODE_RESTRICTED_WORDS.has(identifierName)); +} + +const GeneratedSource = Symbol(); +function isStatementBlockKind(kind) { + return kind === 'block' || kind === 'catch'; +} +var GotoVariant; +(function (GotoVariant) { + GotoVariant["Break"] = "Break"; + GotoVariant["Continue"] = "Continue"; + GotoVariant["Try"] = "Try"; +})(GotoVariant || (GotoVariant = {})); +var InstructionKind; +(function (InstructionKind) { + InstructionKind["Const"] = "Const"; + InstructionKind["Let"] = "Let"; + InstructionKind["Reassign"] = "Reassign"; + InstructionKind["Catch"] = "Catch"; + InstructionKind["HoistedConst"] = "HoistedConst"; + InstructionKind["HoistedLet"] = "HoistedLet"; + InstructionKind["HoistedFunction"] = "HoistedFunction"; + InstructionKind["Function"] = "Function"; +})(InstructionKind || (InstructionKind = {})); +function convertHoistedLValueKind(kind) { + switch (kind) { + case InstructionKind.HoistedLet: + return InstructionKind.Let; + case InstructionKind.HoistedConst: + return InstructionKind.Const; + case InstructionKind.HoistedFunction: + return InstructionKind.Function; + case InstructionKind.Let: + case InstructionKind.Const: + case InstructionKind.Function: + case InstructionKind.Reassign: + case InstructionKind.Catch: + return null; + default: + assertExhaustive$1(kind, 'Unexpected lvalue kind'); + } +} +function makeTemporaryIdentifier(id, loc) { + return { + id, + name: null, + declarationId: makeDeclarationId(id), + mutableRange: { start: makeInstructionId(0), end: makeInstructionId(0) }, + scope: null, + type: makeType(), + loc, + }; +} +function validateIdentifierName(name) { + if (isReservedWord(name)) { + const error = new CompilerError(); + error.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Syntax, + reason: 'Expected a non-reserved identifier name', + description: `\`${name}\` is a reserved word in JavaScript and cannot be used as an identifier name`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc: GeneratedSource, + message: 'reserved word', + })); + return Err(error); + } + else if (!libExports$1.isValidIdentifier(name)) { + const error = new CompilerError(); + error.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Syntax, + reason: `Expected a valid identifier name`, + description: `\`${name}\` is not a valid JavaScript identifier`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc: GeneratedSource, + message: 'reserved word', + })); + } + return Ok({ + kind: 'named', + value: name, + }); +} +function makeIdentifierName(name) { + return validateIdentifierName(name).unwrap(); +} +function promoteTemporary(identifier) { + CompilerError.invariant(identifier.name === null, { + reason: `Expected a temporary (unnamed) identifier`, + description: `Identifier already has a name, \`${identifier.name}\``, + loc: GeneratedSource, + }); + identifier.name = { + kind: 'promoted', + value: `#t${identifier.declarationId}`, + }; +} +function isPromotedTemporary(name) { + return name.startsWith('#t'); +} +function promoteTemporaryJsxTag(identifier) { + CompilerError.invariant(identifier.name === null, { + reason: `Expected a temporary (unnamed) identifier`, + description: `Identifier already has a name, \`${identifier.name}\``, + loc: GeneratedSource, + }); + identifier.name = { + kind: 'promoted', + value: `#T${identifier.declarationId}`, + }; +} +function isPromotedJsxTemporary(name) { + return name.startsWith('#T'); +} +var ValueReason; +(function (ValueReason) { + ValueReason["Global"] = "global"; + ValueReason["JsxCaptured"] = "jsx-captured"; + ValueReason["HookCaptured"] = "hook-captured"; + ValueReason["HookReturn"] = "hook-return"; + ValueReason["Effect"] = "effect"; + ValueReason["KnownReturnSignature"] = "known-return-signature"; + ValueReason["Context"] = "context"; + ValueReason["State"] = "state"; + ValueReason["ReducerState"] = "reducer-state"; + ValueReason["ReactiveFunctionArgument"] = "reactive-function-argument"; + ValueReason["Other"] = "other"; +})(ValueReason || (ValueReason = {})); +var ValueKind; +(function (ValueKind) { + ValueKind["MaybeFrozen"] = "maybefrozen"; + ValueKind["Frozen"] = "frozen"; + ValueKind["Primitive"] = "primitive"; + ValueKind["Global"] = "global"; + ValueKind["Mutable"] = "mutable"; + ValueKind["Context"] = "context"; +})(ValueKind || (ValueKind = {})); +const ValueKindSchema = v4.z.enum([ + ValueKind.MaybeFrozen, + ValueKind.Frozen, + ValueKind.Primitive, + ValueKind.Global, + ValueKind.Mutable, + ValueKind.Context, +]); +const ValueReasonSchema = v4.z.enum([ + ValueReason.Context, + ValueReason.Effect, + ValueReason.Global, + ValueReason.HookCaptured, + ValueReason.HookReturn, + ValueReason.JsxCaptured, + ValueReason.KnownReturnSignature, + ValueReason.Other, + ValueReason.ReactiveFunctionArgument, + ValueReason.ReducerState, + ValueReason.State, +]); +var Effect; +(function (Effect) { + Effect["Unknown"] = ""; + Effect["Freeze"] = "freeze"; + Effect["Read"] = "read"; + Effect["Capture"] = "capture"; + Effect["ConditionallyMutateIterator"] = "mutate-iterator?"; + Effect["ConditionallyMutate"] = "mutate?"; + Effect["Mutate"] = "mutate"; + Effect["Store"] = "store"; +})(Effect || (Effect = {})); +const EffectSchema = v4.z.enum([ + Effect.Read, + Effect.Mutate, + Effect.ConditionallyMutate, + Effect.ConditionallyMutateIterator, + Effect.Capture, + Effect.Store, + Effect.Freeze, +]); +function isMutableEffect(effect, location) { + switch (effect) { + case Effect.Capture: + case Effect.Store: + case Effect.ConditionallyMutate: + case Effect.ConditionallyMutateIterator: + case Effect.Mutate: { + return true; + } + case Effect.Unknown: { + CompilerError.invariant(false, { + reason: 'Unexpected unknown effect', + loc: location, + }); + } + case Effect.Read: + case Effect.Freeze: { + return false; + } + default: { + assertExhaustive$1(effect, `Unexpected effect \`${effect}\``); + } + } +} +function makePropertyLiteral(value) { + return value; +} +function areEqualPaths(a, b) { + return (a.length === b.length && + a.every((item, ix) => item.property === b[ix].property && item.optional === b[ix].optional)); +} +function isSubPath(subpath, path) { + return (subpath.length <= path.length && + subpath.every((item, ix) => item.property === path[ix].property && + item.optional === path[ix].optional)); +} +function isSubPathIgnoringOptionals(subpath, path) { + return (subpath.length <= path.length && + subpath.every((item, ix) => item.property === path[ix].property)); +} +function getPlaceScope(id, place) { + const scope = place.identifier.scope; + if (scope !== null && isScopeActive(scope, id)) { + return scope; + } + return null; +} +function isScopeActive(scope, id) { + return id >= scope.range.start && id < scope.range.end; +} +function makeBlockId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected block id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function makeScopeId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected block id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function makeIdentifierId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected identifier id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function makeDeclarationId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected declaration id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function makeInstructionId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected instruction id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function isObjectMethodType(id) { + return id.type.kind == 'ObjectMethod'; +} +function isPrimitiveType(id) { + return id.type.kind === 'Primitive'; +} +function isPlainObjectType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInObject'; +} +function isArrayType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInArray'; +} +function isMapType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInMap'; +} +function isSetType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInSet'; +} +function isPropsType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInProps'; +} +function isRefValueType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInRefValue'; +} +function isUseRefType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInUseRefId'; +} +function isUseStateType(id) { + return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInUseState'; +} +function isJsxType(type) { + return type.kind === 'Object' && type.shapeId === 'BuiltInJsx'; +} +function isRefOrRefValue(id) { + return isUseRefType(id) || isRefValueType(id); +} +function isRefOrRefLikeMutableType(type) { + return (type.kind === 'Object' && + (type.shapeId === 'BuiltInUseRefId' || + type.shapeId == 'ReanimatedSharedValueId')); +} +function isSetStateType(id) { + return id.type.kind === 'Function' && id.type.shapeId === 'BuiltInSetState'; +} +function isUseActionStateType(id) { + return (id.type.kind === 'Object' && id.type.shapeId === 'BuiltInUseActionState'); +} +function isStartTransitionType(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInStartTransition'); +} +function isUseOptimisticType(id) { + return (id.type.kind === 'Object' && id.type.shapeId === 'BuiltInUseOptimistic'); +} +function isSetOptimisticType(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInSetOptimistic'); +} +function isSetActionStateType(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInSetActionState'); +} +function isUseReducerType(id) { + return id.type.kind === 'Function' && id.type.shapeId === 'BuiltInUseReducer'; +} +function isDispatcherType(id) { + return id.type.kind === 'Function' && id.type.shapeId === 'BuiltInDispatch'; +} +function isEffectEventFunctionType(id) { + return (id.type.kind === 'Function' && + id.type.shapeId === 'BuiltInEffectEventFunction'); +} +function isStableType(id) { + return (isSetStateType(id) || + isSetActionStateType(id) || + isDispatcherType(id) || + isUseRefType(id) || + isStartTransitionType(id) || + isSetOptimisticType(id)); +} +function isStableTypeContainer(id) { + const type_ = id.type; + if (type_.kind !== 'Object') { + return false; + } + return (isUseStateType(id) || + isUseActionStateType(id) || + isUseReducerType(id) || + isUseOptimisticType(id) || + type_.shapeId === 'BuiltInUseTransition'); +} +function evaluatesToStableTypeOrContainer(env, { value }) { + if (value.kind === 'CallExpression' || value.kind === 'MethodCall') { + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + const calleeHookKind = getHookKind(env, callee.identifier); + switch (calleeHookKind) { + case 'useState': + case 'useReducer': + case 'useActionState': + case 'useRef': + case 'useTransition': + case 'useOptimistic': + return true; + } + } + return false; +} +function isUseEffectHookType(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInUseEffectHook'); +} +function isUseLayoutEffectHookType(id) { + return (id.type.kind === 'Function' && + id.type.shapeId === 'BuiltInUseLayoutEffectHook'); +} +function isUseInsertionEffectHookType(id) { + return (id.type.kind === 'Function' && + id.type.shapeId === 'BuiltInUseInsertionEffectHook'); +} +function isUseEffectEventType(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInUseEffectEvent'); +} +function getHookKind(env, id) { + return getHookKindForType(env, id.type); +} +function isUseOperator(id) { + return (id.type.kind === 'Function' && id.type.shapeId === 'BuiltInUseOperator'); +} +function getHookKindForType(env, type) { + var _a; + if (type.kind === 'Function') { + const signature = env.getFunctionSignature(type); + return (_a = signature === null || signature === void 0 ? void 0 : signature.hookKind) !== null && _a !== void 0 ? _a : null; + } + return null; +} + +function printReactiveScopeSummary(scope) { + const items = []; + items.push('scope'); + items.push(`@${scope.id}`); + items.push(`[${scope.range.start}:${scope.range.end}]`); + items.push(`dependencies=[${Array.from(scope.dependencies) + .map(dep => printDependency(dep)) + .join(', ')}]`); + items.push(`declarations=[${Array.from(scope.declarations) + .map(([, decl]) => printIdentifier(Object.assign(Object.assign({}, decl.identifier), { scope: decl.scope }))) + .join(', ')}]`); + items.push(`reassignments=[${Array.from(scope.reassignments).map(reassign => printIdentifier(reassign))}]`); + if (scope.earlyReturnValue !== null) { + items.push(`earlyReturn={id: ${printIdentifier(scope.earlyReturnValue.value)}, label: ${scope.earlyReturnValue.label}}}`); + } + return items.join(' '); +} +function printDependency(dependency) { + const identifier = printIdentifier(dependency.identifier) + + printType(dependency.identifier.type); + return `${identifier}${dependency.path.map(token => `${token.optional ? '?.' : '.'}${token.property}`).join('')}_${printSourceLocation(dependency.loc)}`; +} + +function printFunction(fn) { + const output = []; + let definition = ''; + if (fn.id !== null) { + definition += fn.id; + } + else { + definition += '<>'; + } + if (fn.nameHint != null) { + definition += ` ${fn.nameHint}`; + } + if (fn.params.length !== 0) { + definition += + '(' + + fn.params + .map(param => { + if (param.kind === 'Identifier') { + return printPlace(param); + } + else { + return `...${printPlace(param.place)}`; + } + }) + .join(', ') + + ')'; + } + else { + definition += '()'; + } + definition += `: ${printPlace(fn.returns)}`; + output.push(definition); + output.push(...fn.directives); + output.push(printHIR(fn.body)); + return output.join('\n'); +} +function printHIR(ir, options = null) { + var _a; + let output = []; + let indent = ' '.repeat((_a = options === null || options === void 0 ? void 0 : options.indent) !== null && _a !== void 0 ? _a : 0); + const push = (text, indent = ' ') => { + output.push(`${indent}${text}`); + }; + for (const [blockId, block] of ir.blocks) { + output.push(`bb${blockId} (${block.kind}):`); + if (block.preds.size > 0) { + const preds = ['predecessor blocks:']; + for (const pred of block.preds) { + preds.push(`bb${pred}`); + } + push(preds.join(' ')); + } + for (const phi of block.phis) { + push(printPhi(phi)); + } + for (const instr of block.instructions) { + push(printInstruction(instr)); + } + const terminal = printTerminal(block.terminal); + if (Array.isArray(terminal)) { + terminal.forEach(line => push(line)); + } + else { + push(terminal); + } + } + return output.map(line => indent + line).join('\n'); +} +function printInstruction(instr) { + const id = `[${instr.id}]`; + let value = printInstructionValue(instr.value); + if (instr.effects != null) { + value += `\n ${instr.effects.map(printAliasingEffect).join('\n ')}`; + } + if (instr.lvalue !== null) { + return `${id} ${printPlace(instr.lvalue)} = ${value}`; + } + else { + return `${id} ${value}`; + } +} +function printPhi(phi) { + const items = []; + items.push(printPlace(phi.place)); + items.push(printMutableRange(phi.place.identifier)); + items.push(printType(phi.place.identifier.type)); + items.push(': phi('); + const phis = []; + for (const [blockId, place] of phi.operands) { + phis.push(`bb${blockId}: ${printPlace(place)}`); + } + items.push(phis.join(', ')); + items.push(')'); + return items.join(''); +} +function printTerminal(terminal) { + let value; + switch (terminal.kind) { + case 'if': { + value = `[${terminal.id}] If (${printPlace(terminal.test)}) then:bb${terminal.consequent} else:bb${terminal.alternate}${terminal.fallthrough ? ` fallthrough=bb${terminal.fallthrough}` : ''}`; + break; + } + case 'branch': { + value = `[${terminal.id}] Branch (${printPlace(terminal.test)}) then:bb${terminal.consequent} else:bb${terminal.alternate} fallthrough:bb${terminal.fallthrough}`; + break; + } + case 'logical': { + value = `[${terminal.id}] Logical ${terminal.operator} test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'ternary': { + value = `[${terminal.id}] Ternary test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'optional': { + value = `[${terminal.id}] Optional (optional=${terminal.optional}) test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'throw': { + value = `[${terminal.id}] Throw ${printPlace(terminal.value)}`; + break; + } + case 'return': { + value = `[${terminal.id}] Return ${terminal.returnVariant}${terminal.value != null ? ' ' + printPlace(terminal.value) : ''}`; + if (terminal.effects != null) { + value += `\n ${terminal.effects.map(printAliasingEffect).join('\n ')}`; + } + break; + } + case 'goto': { + value = `[${terminal.id}] Goto${terminal.variant === GotoVariant.Continue ? '(Continue)' : ''} bb${terminal.block}`; + break; + } + case 'switch': { + const output = []; + output.push(`[${terminal.id}] Switch (${printPlace(terminal.test)})`); + terminal.cases.forEach(case_ => { + if (case_.test !== null) { + output.push(` Case ${printPlace(case_.test)}: bb${case_.block}`); + } + else { + output.push(` Default: bb${case_.block}`); + } + }); + if (terminal.fallthrough) { + output.push(` Fallthrough: bb${terminal.fallthrough}`); + } + value = output; + break; + } + case 'do-while': { + value = `[${terminal.id}] DoWhile loop=${`bb${terminal.loop}`} test=bb${terminal.test} fallthrough=${`bb${terminal.fallthrough}`}`; + break; + } + case 'while': { + value = `[${terminal.id}] While test=bb${terminal.test} loop=${terminal.loop !== null ? `bb${terminal.loop}` : ''} fallthrough=${terminal.fallthrough ? `bb${terminal.fallthrough}` : ''}`; + break; + } + case 'for': { + value = `[${terminal.id}] For init=bb${terminal.init} test=bb${terminal.test} loop=bb${terminal.loop} update=bb${terminal.update} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'for-of': { + value = `[${terminal.id}] ForOf init=bb${terminal.init} test=bb${terminal.test} loop=bb${terminal.loop} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'for-in': { + value = `[${terminal.id}] ForIn init=bb${terminal.init} loop=bb${terminal.loop} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'label': { + value = `[${terminal.id}] Label block=bb${terminal.block} fallthrough=${terminal.fallthrough ? `bb${terminal.fallthrough}` : ''}`; + break; + } + case 'sequence': { + value = `[${terminal.id}] Sequence block=bb${terminal.block} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'unreachable': { + value = `[${terminal.id}] Unreachable`; + break; + } + case 'unsupported': { + value = `[${terminal.id}] Unsupported`; + break; + } + case 'maybe-throw': { + const handlerStr = terminal.handler !== null ? `bb${terminal.handler}` : '(none)'; + value = `[${terminal.id}] MaybeThrow continuation=bb${terminal.continuation} handler=${handlerStr}`; + if (terminal.effects != null) { + value += `\n ${terminal.effects.map(printAliasingEffect).join('\n ')}`; + } + break; + } + case 'scope': { + value = `[${terminal.id}] Scope ${printReactiveScopeSummary(terminal.scope)} block=bb${terminal.block} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'pruned-scope': { + value = `[${terminal.id}] Scope ${printReactiveScopeSummary(terminal.scope)} block=bb${terminal.block} fallthrough=bb${terminal.fallthrough}`; + break; + } + case 'try': { + value = `[${terminal.id}] Try block=bb${terminal.block} handler=bb${terminal.handler}${terminal.handlerBinding !== null + ? ` handlerBinding=(${printPlace(terminal.handlerBinding)})` + : ''} fallthrough=${terminal.fallthrough != null ? `bb${terminal.fallthrough}` : ''}`; + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal}\``); + } + } + return value; +} +function printHole() { + return ''; +} +function printObjectPropertyKey(key) { + switch (key.kind) { + case 'identifier': + return key.name; + case 'string': + return `"${key.name}"`; + case 'computed': { + return `[${printPlace(key.name)}]`; + } + case 'number': { + return String(key.name); + } + } +} +function printInstructionValue(instrValue) { + var _a, _b, _c, _d, _e; + let value = ''; + switch (instrValue.kind) { + case 'ArrayExpression': { + value = `Array [${instrValue.elements + .map(element => { + if (element.kind === 'Identifier') { + return printPlace(element); + } + else if (element.kind === 'Hole') { + return printHole(); + } + else { + return `...${printPlace(element.place)}`; + } + }) + .join(', ')}]`; + break; + } + case 'ObjectExpression': { + const properties = []; + if (instrValue.properties !== null) { + for (const property of instrValue.properties) { + if (property.kind === 'ObjectProperty') { + properties.push(`${printObjectPropertyKey(property.key)}: ${printPlace(property.place)}`); + } + else { + properties.push(`...${printPlace(property.place)}`); + } + } + } + value = `Object { ${properties.join(', ')} }`; + break; + } + case 'UnaryExpression': { + value = `Unary ${printPlace(instrValue.value)}`; + break; + } + case 'BinaryExpression': { + value = `Binary ${printPlace(instrValue.left)} ${instrValue.operator} ${printPlace(instrValue.right)}`; + break; + } + case 'NewExpression': { + value = `New ${printPlace(instrValue.callee)}(${instrValue.args + .map(arg => printPattern(arg)) + .join(', ')})`; + break; + } + case 'CallExpression': { + value = `Call ${printPlace(instrValue.callee)}(${instrValue.args + .map(arg => printPattern(arg)) + .join(', ')})`; + break; + } + case 'MethodCall': { + value = `MethodCall ${printPlace(instrValue.receiver)}.${printPlace(instrValue.property)}(${instrValue.args.map(arg => printPattern(arg)).join(', ')})`; + break; + } + case 'JSXText': { + value = `JSXText ${JSON.stringify(instrValue.value)}`; + break; + } + case 'Primitive': { + if (instrValue.value === undefined) { + value = ''; + } + else { + value = JSON.stringify(instrValue.value); + } + break; + } + case 'TypeCastExpression': { + value = `TypeCast ${printPlace(instrValue.value)}: ${printType(instrValue.type)}`; + break; + } + case 'JsxExpression': { + const propItems = []; + for (const attribute of instrValue.props) { + if (attribute.kind === 'JsxAttribute') { + propItems.push(`${attribute.name}={${attribute.place !== null ? printPlace(attribute.place) : ''}}`); + } + else { + propItems.push(`...${printPlace(attribute.argument)}`); + } + } + const tag = instrValue.tag.kind === 'Identifier' + ? printPlace(instrValue.tag) + : instrValue.tag.name; + const props = propItems.length !== 0 ? ' ' + propItems.join(' ') : ''; + if (instrValue.children !== null) { + const children = instrValue.children.map(child => { + return `{${printPlace(child)}}`; + }); + value = `JSX <${tag}${props}${props.length > 0 ? ' ' : ''}>${children.join('')}`; + } + else { + value = `JSX <${tag}${props}${props.length > 0 ? ' ' : ''}/>`; + } + break; + } + case 'JsxFragment': { + value = `JsxFragment [${instrValue.children + .map(child => printPlace(child)) + .join(', ')}]`; + break; + } + case 'UnsupportedNode': { + value = `UnsupportedNode ${instrValue.node.type}`; + break; + } + case 'LoadLocal': { + value = `LoadLocal ${printPlace(instrValue.place)}`; + break; + } + case 'DeclareLocal': { + value = `DeclareLocal ${instrValue.lvalue.kind} ${printPlace(instrValue.lvalue.place)}`; + break; + } + case 'DeclareContext': { + value = `DeclareContext ${instrValue.lvalue.kind} ${printPlace(instrValue.lvalue.place)}`; + break; + } + case 'StoreLocal': { + value = `StoreLocal ${instrValue.lvalue.kind} ${printPlace(instrValue.lvalue.place)} = ${printPlace(instrValue.value)}`; + break; + } + case 'LoadContext': { + value = `LoadContext ${printPlace(instrValue.place)}`; + break; + } + case 'StoreContext': { + value = `StoreContext ${instrValue.lvalue.kind} ${printPlace(instrValue.lvalue.place)} = ${printPlace(instrValue.value)}`; + break; + } + case 'Destructure': { + value = `Destructure ${instrValue.lvalue.kind} ${printPattern(instrValue.lvalue.pattern)} = ${printPlace(instrValue.value)}`; + break; + } + case 'PropertyLoad': { + value = `PropertyLoad ${printPlace(instrValue.object)}.${instrValue.property}`; + break; + } + case 'PropertyStore': { + value = `PropertyStore ${printPlace(instrValue.object)}.${instrValue.property} = ${printPlace(instrValue.value)}`; + break; + } + case 'PropertyDelete': { + value = `PropertyDelete ${printPlace(instrValue.object)}.${instrValue.property}`; + break; + } + case 'ComputedLoad': { + value = `ComputedLoad ${printPlace(instrValue.object)}[${printPlace(instrValue.property)}]`; + break; + } + case 'ComputedStore': { + value = `ComputedStore ${printPlace(instrValue.object)}[${printPlace(instrValue.property)}] = ${printPlace(instrValue.value)}`; + break; + } + case 'ComputedDelete': { + value = `ComputedDelete ${printPlace(instrValue.object)}[${printPlace(instrValue.property)}]`; + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + const kind = instrValue.kind === 'FunctionExpression' ? 'Function' : 'ObjectMethod'; + const name = getFunctionName$2(instrValue, ''); + const fn = printFunction(instrValue.loweredFunc.func) + .split('\n') + .map(line => ` ${line}`) + .join('\n'); + const context = instrValue.loweredFunc.func.context + .map(dep => printPlace(dep)) + .join(','); + const aliasingEffects = (_c = (_b = (_a = instrValue.loweredFunc.func.aliasingEffects) === null || _a === void 0 ? void 0 : _a.map(printAliasingEffect)) === null || _b === void 0 ? void 0 : _b.join(', ')) !== null && _c !== void 0 ? _c : ''; + value = `${kind} ${name} @context[${context}] @aliasingEffects=[${aliasingEffects}]\n${fn}`; + break; + } + case 'TaggedTemplateExpression': { + value = `${printPlace(instrValue.tag)}\`${instrValue.value.raw}\``; + break; + } + case 'LogicalExpression': { + value = `Logical ${printInstructionValue(instrValue.left)} ${instrValue.operator} ${printInstructionValue(instrValue.right)}`; + break; + } + case 'SequenceExpression': { + value = [ + `Sequence`, + ...instrValue.instructions.map(instr => ` ${printInstruction(instr)}`), + ` ${printInstructionValue(instrValue.value)}`, + ].join('\n'); + break; + } + case 'ConditionalExpression': { + value = `Ternary ${printInstructionValue(instrValue.test)} ? ${printInstructionValue(instrValue.consequent)} : ${printInstructionValue(instrValue.alternate)}`; + break; + } + case 'TemplateLiteral': { + value = '`'; + CompilerError.invariant(instrValue.subexprs.length === instrValue.quasis.length - 1, { + reason: 'Bad assumption about quasi length.', + loc: instrValue.loc, + }); + for (let i = 0; i < instrValue.subexprs.length; i++) { + value += instrValue.quasis[i].raw; + value += `\${${printPlace(instrValue.subexprs[i])}}`; + } + value += instrValue.quasis.at(-1).raw + '`'; + break; + } + case 'LoadGlobal': { + switch (instrValue.binding.kind) { + case 'Global': { + value = `LoadGlobal(global) ${instrValue.binding.name}`; + break; + } + case 'ModuleLocal': { + value = `LoadGlobal(module) ${instrValue.binding.name}`; + break; + } + case 'ImportDefault': { + value = `LoadGlobal import ${instrValue.binding.name} from '${instrValue.binding.module}'`; + break; + } + case 'ImportNamespace': { + value = `LoadGlobal import * as ${instrValue.binding.name} from '${instrValue.binding.module}'`; + break; + } + case 'ImportSpecifier': { + if (instrValue.binding.imported !== instrValue.binding.name) { + value = `LoadGlobal import { ${instrValue.binding.imported} as ${instrValue.binding.name} } from '${instrValue.binding.module}'`; + } + else { + value = `LoadGlobal import { ${instrValue.binding.name} } from '${instrValue.binding.module}'`; + } + break; + } + default: { + assertExhaustive$1(instrValue.binding, `Unexpected binding kind \`${instrValue.binding.kind}\``); + } + } + break; + } + case 'StoreGlobal': { + value = `StoreGlobal ${instrValue.name} = ${printPlace(instrValue.value)}`; + break; + } + case 'OptionalExpression': { + value = `OptionalExpression ${printInstructionValue(instrValue.value)}`; + break; + } + case 'RegExpLiteral': { + value = `RegExp /${instrValue.pattern}/${instrValue.flags}`; + break; + } + case 'MetaProperty': { + value = `MetaProperty ${instrValue.meta}.${instrValue.property}`; + break; + } + case 'Await': { + value = `Await ${printPlace(instrValue.value)}`; + break; + } + case 'GetIterator': { + value = `GetIterator collection=${printPlace(instrValue.collection)}`; + break; + } + case 'IteratorNext': { + value = `IteratorNext iterator=${printPlace(instrValue.iterator)} collection=${printPlace(instrValue.collection)}`; + break; + } + case 'NextPropertyOf': { + value = `NextPropertyOf ${printPlace(instrValue.value)}`; + break; + } + case 'Debugger': { + value = `Debugger`; + break; + } + case 'PostfixUpdate': { + value = `PostfixUpdate ${printPlace(instrValue.lvalue)} = ${printPlace(instrValue.value)} ${instrValue.operation}`; + break; + } + case 'PrefixUpdate': { + value = `PrefixUpdate ${printPlace(instrValue.lvalue)} = ${instrValue.operation} ${printPlace(instrValue.value)}`; + break; + } + case 'StartMemoize': { + value = `StartMemoize deps=${(_e = (_d = instrValue.deps) === null || _d === void 0 ? void 0 : _d.map(dep => printManualMemoDependency$1(dep, false))) !== null && _e !== void 0 ? _e : '(none)'}`; + break; + } + case 'FinishMemoize': { + value = `FinishMemoize decl=${printPlace(instrValue.decl)}${instrValue.pruned ? ' pruned' : ''}`; + break; + } + default: { + assertExhaustive$1(instrValue, `Unexpected instruction kind '${instrValue.kind}'`); + } + } + return value; +} +function isMutable$1(range) { + return range.end > range.start + 1; +} +function printMutableRange(identifier) { + var _b, _c; + const range = (_c = (_b = identifier.scope) === null || _b === void 0 ? void 0 : _b.range) !== null && _c !== void 0 ? _c : identifier.mutableRange; + return isMutable$1(range) ? `[${range.start}:${range.end}]` : ''; +} +function printPattern(pattern) { + switch (pattern.kind) { + case 'ArrayPattern': { + return ('[ ' + + pattern.items + .map(item => { + if (item.kind === 'Hole') { + return ''; + } + return printPattern(item); + }) + .join(', ') + + ' ]'); + } + case 'ObjectPattern': { + return ('{ ' + + pattern.properties + .map(item => { + switch (item.kind) { + case 'ObjectProperty': { + return `${printObjectPropertyKey(item.key)}: ${printPattern(item.place)}`; + } + case 'Spread': { + return printPattern(item); + } + default: { + assertExhaustive$1(item, 'Unexpected object property kind'); + } + } + }) + .join(', ') + + ' }'); + } + case 'Spread': { + return `...${printPlace(pattern.place)}`; + } + case 'Identifier': { + return printPlace(pattern); + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } +} +function printPlace(place) { + const items = [ + place.effect, + ' ', + printIdentifier(place.identifier), + printMutableRange(place.identifier), + printType(place.identifier.type), + place.reactive ? '{reactive}' : null, + ]; + return items.filter(x => x != null).join(''); +} +function printIdentifier(id) { + return `${printName(id.name)}\$${id.id}${printScope(id.scope)}`; +} +function printName(name) { + if (name === null) { + return ''; + } + return name.value; +} +function printScope(scope) { + return `${scope !== null ? `_@${scope.id}` : ''}`; +} +function printManualMemoDependency$1(val, nameOnly) { + var _a; + let rootStr; + if (val.root.kind === 'Global') { + rootStr = val.root.identifierName; + } + else { + CompilerError.invariant(((_a = val.root.value.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named', { + reason: 'DepsValidation: expected named local variable in depslist', + loc: val.root.value.loc, + }); + rootStr = nameOnly + ? val.root.value.identifier.name.value + : printIdentifier(val.root.value.identifier); + } + return `${rootStr}${val.path.map(v => `${v.optional ? '?.' : '.'}${v.property}`).join('')}`; +} +function printType(type) { + if (type.kind === 'Type') + return ''; + if (type.kind === 'Object' && type.shapeId != null) { + return `:T${type.kind}<${type.shapeId}>`; + } + else if (type.kind === 'Function' && type.shapeId != null) { + const returnType = printType(type.return); + return `:T${type.kind}<${type.shapeId}>()${returnType !== '' ? `: ${returnType}` : ''}`; + } + else { + return `:T${type.kind}`; + } +} +function printSourceLocation(loc) { + if (typeof loc === 'symbol') { + return 'generated'; + } + else { + return `${loc.start.line}:${loc.start.column}:${loc.end.line}:${loc.end.column}`; + } +} +function getFunctionName$2(instrValue, defaultValue) { + var _a; + switch (instrValue.kind) { + case 'FunctionExpression': + return (_a = instrValue.name) !== null && _a !== void 0 ? _a : defaultValue; + case 'ObjectMethod': + return defaultValue; + } +} +function printAliasingEffect(effect) { + var _a; + switch (effect.kind) { + case 'Assign': { + return `Assign ${printPlaceForAliasEffect(effect.into)} = ${printPlaceForAliasEffect(effect.from)}`; + } + case 'Alias': { + return `Alias ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; + } + case 'MaybeAlias': { + return `MaybeAlias ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; + } + case 'Capture': { + return `Capture ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; + } + case 'ImmutableCapture': { + return `ImmutableCapture ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`; + } + case 'Create': { + return `Create ${printPlaceForAliasEffect(effect.into)} = ${effect.value}`; + } + case 'CreateFrom': { + return `Create ${printPlaceForAliasEffect(effect.into)} = kindOf(${printPlaceForAliasEffect(effect.from)})`; + } + case 'CreateFunction': { + return `Function ${printPlaceForAliasEffect(effect.into)} = Function captures=[${effect.captures.map(printPlaceForAliasEffect).join(', ')}]`; + } + case 'Apply': { + const receiverCallee = effect.receiver.identifier.id === effect.function.identifier.id + ? printPlaceForAliasEffect(effect.receiver) + : `${printPlaceForAliasEffect(effect.receiver)}.${printPlaceForAliasEffect(effect.function)}`; + const args = effect.args + .map(arg => { + if (arg.kind === 'Identifier') { + return printPlaceForAliasEffect(arg); + } + else if (arg.kind === 'Hole') { + return ' '; + } + return `...${printPlaceForAliasEffect(arg.place)}`; + }) + .join(', '); + let signature = ''; + if (effect.signature != null) { + if (effect.signature.aliasing != null) { + signature = printAliasingSignature(effect.signature.aliasing); + } + else { + signature = JSON.stringify(effect.signature, null, 2); + } + } + return `Apply ${printPlaceForAliasEffect(effect.into)} = ${receiverCallee}(${args})${signature != '' ? '\n ' : ''}${signature}`; + } + case 'Freeze': { + return `Freeze ${printPlaceForAliasEffect(effect.value)} ${effect.reason}`; + } + case 'Mutate': + case 'MutateConditionally': + case 'MutateTransitive': + case 'MutateTransitiveConditionally': { + return `${effect.kind} ${printPlaceForAliasEffect(effect.value)}${effect.kind === 'Mutate' && ((_a = effect.reason) === null || _a === void 0 ? void 0 : _a.kind) === 'AssignCurrentProperty' ? ' (assign `.current`)' : ''}`; + } + case 'MutateFrozen': { + return `MutateFrozen ${printPlaceForAliasEffect(effect.place)} reason=${JSON.stringify(effect.error.reason)}`; + } + case 'MutateGlobal': { + return `MutateGlobal ${printPlaceForAliasEffect(effect.place)} reason=${JSON.stringify(effect.error.reason)}`; + } + case 'Impure': { + return `Impure ${printPlaceForAliasEffect(effect.place)} reason=${JSON.stringify(effect.error.reason)}`; + } + case 'Render': { + return `Render ${printPlaceForAliasEffect(effect.place)}`; + } + default: { + assertExhaustive$1(effect, `Unexpected kind '${effect.kind}'`); + } + } +} +function printPlaceForAliasEffect(place) { + return printIdentifier(place.identifier); +} +function printAliasingSignature(signature) { + const tokens = ['function ']; + if (signature.temporaries.length !== 0) { + tokens.push('<'); + tokens.push(signature.temporaries.map(temp => `$${temp.identifier.id}`).join(', ')); + tokens.push('>'); + } + tokens.push('('); + tokens.push('this=$' + String(signature.receiver)); + for (const param of signature.params) { + tokens.push(', $' + String(param)); + } + if (signature.rest != null) { + tokens.push(`, ...$${String(signature.rest)}`); + } + tokens.push('): '); + tokens.push('$' + String(signature.returns) + ':'); + for (const effect of signature.effects) { + tokens.push('\n ' + printAliasingEffect(effect)); + } + return tokens.join(''); +} + +var _ScopeBlockTraversal_activeScopes; +function* eachInstructionLValue(instr) { + if (instr.lvalue !== null) { + yield instr.lvalue; + } + yield* eachInstructionValueLValue(instr.value); +} +function* eachInstructionLValueWithKind(instr) { + switch (instr.value.kind) { + case 'DeclareContext': + case 'StoreContext': + case 'DeclareLocal': + case 'StoreLocal': { + yield [instr.value.lvalue.place, instr.value.lvalue.kind]; + break; + } + case 'Destructure': { + const kind = instr.value.lvalue.kind; + for (const place of eachPatternOperand(instr.value.lvalue.pattern)) { + yield [place, kind]; + } + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + yield [instr.value.lvalue, InstructionKind.Reassign]; + break; + } + } +} +function* eachInstructionValueLValue(value) { + switch (value.kind) { + case 'DeclareContext': + case 'StoreContext': + case 'DeclareLocal': + case 'StoreLocal': { + yield value.lvalue.place; + break; + } + case 'Destructure': { + yield* eachPatternOperand(value.lvalue.pattern); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + yield value.lvalue; + break; + } + } +} +function* eachInstructionOperand(instr) { + yield* eachInstructionValueOperand(instr.value); +} +function* eachInstructionValueOperand(instrValue) { + switch (instrValue.kind) { + case 'NewExpression': + case 'CallExpression': { + yield instrValue.callee; + yield* eachCallArgument(instrValue.args); + break; + } + case 'BinaryExpression': { + yield instrValue.left; + yield instrValue.right; + break; + } + case 'MethodCall': { + yield instrValue.receiver; + yield instrValue.property; + yield* eachCallArgument(instrValue.args); + break; + } + case 'DeclareContext': + case 'DeclareLocal': { + break; + } + case 'LoadLocal': + case 'LoadContext': { + yield instrValue.place; + break; + } + case 'StoreLocal': { + yield instrValue.value; + break; + } + case 'StoreContext': { + yield instrValue.lvalue.place; + yield instrValue.value; + break; + } + case 'StoreGlobal': { + yield instrValue.value; + break; + } + case 'Destructure': { + yield instrValue.value; + break; + } + case 'PropertyLoad': { + yield instrValue.object; + break; + } + case 'PropertyDelete': { + yield instrValue.object; + break; + } + case 'PropertyStore': { + yield instrValue.object; + yield instrValue.value; + break; + } + case 'ComputedLoad': { + yield instrValue.object; + yield instrValue.property; + break; + } + case 'ComputedDelete': { + yield instrValue.object; + yield instrValue.property; + break; + } + case 'ComputedStore': { + yield instrValue.object; + yield instrValue.property; + yield instrValue.value; + break; + } + case 'UnaryExpression': { + yield instrValue.value; + break; + } + case 'JsxExpression': { + if (instrValue.tag.kind === 'Identifier') { + yield instrValue.tag; + } + for (const attribute of instrValue.props) { + switch (attribute.kind) { + case 'JsxAttribute': { + yield attribute.place; + break; + } + case 'JsxSpreadAttribute': { + yield attribute.argument; + break; + } + default: { + assertExhaustive$1(attribute, `Unexpected attribute kind \`${attribute.kind}\``); + } + } + } + if (instrValue.children) { + yield* instrValue.children; + } + break; + } + case 'JsxFragment': { + yield* instrValue.children; + break; + } + case 'ObjectExpression': { + for (const property of instrValue.properties) { + if (property.kind === 'ObjectProperty' && + property.key.kind === 'computed') { + yield property.key.name; + } + yield property.place; + } + break; + } + case 'ArrayExpression': { + for (const element of instrValue.elements) { + if (element.kind === 'Identifier') { + yield element; + } + else if (element.kind === 'Spread') { + yield element.place; + } + } + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + yield* instrValue.loweredFunc.func.context; + break; + } + case 'TaggedTemplateExpression': { + yield instrValue.tag; + break; + } + case 'TypeCastExpression': { + yield instrValue.value; + break; + } + case 'TemplateLiteral': { + yield* instrValue.subexprs; + break; + } + case 'Await': { + yield instrValue.value; + break; + } + case 'GetIterator': { + yield instrValue.collection; + break; + } + case 'IteratorNext': { + yield instrValue.iterator; + yield instrValue.collection; + break; + } + case 'NextPropertyOf': { + yield instrValue.value; + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + yield instrValue.value; + break; + } + case 'StartMemoize': { + if (instrValue.deps != null) { + for (const dep of instrValue.deps) { + if (dep.root.kind === 'NamedLocal') { + yield dep.root.value; + } + } + } + break; + } + case 'FinishMemoize': { + yield instrValue.decl; + break; + } + case 'Debugger': + case 'RegExpLiteral': + case 'MetaProperty': + case 'LoadGlobal': + case 'UnsupportedNode': + case 'Primitive': + case 'JSXText': { + break; + } + default: { + assertExhaustive$1(instrValue, `Unexpected instruction kind \`${instrValue.kind}\``); + } + } +} +function* eachCallArgument(args) { + for (const arg of args) { + if (arg.kind === 'Identifier') { + yield arg; + } + else { + yield arg.place; + } + } +} +function doesPatternContainSpreadElement(pattern) { + switch (pattern.kind) { + case 'ArrayPattern': { + for (const item of pattern.items) { + if (item.kind === 'Spread') { + return true; + } + } + break; + } + case 'ObjectPattern': { + for (const property of pattern.properties) { + if (property.kind === 'Spread') { + return true; + } + } + break; + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } + return false; +} +function* eachPatternOperand(pattern) { + switch (pattern.kind) { + case 'ArrayPattern': { + for (const item of pattern.items) { + if (item.kind === 'Identifier') { + yield item; + } + else if (item.kind === 'Spread') { + yield item.place; + } + else if (item.kind === 'Hole') { + continue; + } + else { + assertExhaustive$1(item, `Unexpected item kind \`${item.kind}\``); + } + } + break; + } + case 'ObjectPattern': { + for (const property of pattern.properties) { + if (property.kind === 'ObjectProperty') { + yield property.place; + } + else if (property.kind === 'Spread') { + yield property.place; + } + else { + assertExhaustive$1(property, `Unexpected item kind \`${property.kind}\``); + } + } + break; + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } +} +function* eachPatternItem(pattern) { + switch (pattern.kind) { + case 'ArrayPattern': { + for (const item of pattern.items) { + if (item.kind === 'Identifier') { + yield item; + } + else if (item.kind === 'Spread') { + yield item; + } + else if (item.kind === 'Hole') { + continue; + } + else { + assertExhaustive$1(item, `Unexpected item kind \`${item.kind}\``); + } + } + break; + } + case 'ObjectPattern': { + for (const property of pattern.properties) { + if (property.kind === 'ObjectProperty') { + yield property.place; + } + else if (property.kind === 'Spread') { + yield property; + } + else { + assertExhaustive$1(property, `Unexpected item kind \`${property.kind}\``); + } + } + break; + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } +} +function mapInstructionLValues(instr, fn) { + switch (instr.value.kind) { + case 'DeclareLocal': + case 'StoreLocal': { + const lvalue = instr.value.lvalue; + lvalue.place = fn(lvalue.place); + break; + } + case 'Destructure': { + mapPatternOperands(instr.value.lvalue.pattern, fn); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + instr.value.lvalue = fn(instr.value.lvalue); + break; + } + } + if (instr.lvalue !== null) { + instr.lvalue = fn(instr.lvalue); + } +} +function mapInstructionOperands(instr, fn) { + mapInstructionValueOperands(instr.value, fn); +} +function mapInstructionValueOperands(instrValue, fn) { + switch (instrValue.kind) { + case 'BinaryExpression': { + instrValue.left = fn(instrValue.left); + instrValue.right = fn(instrValue.right); + break; + } + case 'PropertyLoad': { + instrValue.object = fn(instrValue.object); + break; + } + case 'PropertyDelete': { + instrValue.object = fn(instrValue.object); + break; + } + case 'PropertyStore': { + instrValue.object = fn(instrValue.object); + instrValue.value = fn(instrValue.value); + break; + } + case 'ComputedLoad': { + instrValue.object = fn(instrValue.object); + instrValue.property = fn(instrValue.property); + break; + } + case 'ComputedDelete': { + instrValue.object = fn(instrValue.object); + instrValue.property = fn(instrValue.property); + break; + } + case 'ComputedStore': { + instrValue.object = fn(instrValue.object); + instrValue.property = fn(instrValue.property); + instrValue.value = fn(instrValue.value); + break; + } + case 'DeclareContext': + case 'DeclareLocal': { + break; + } + case 'LoadLocal': + case 'LoadContext': { + instrValue.place = fn(instrValue.place); + break; + } + case 'StoreLocal': { + instrValue.value = fn(instrValue.value); + break; + } + case 'StoreContext': { + instrValue.lvalue.place = fn(instrValue.lvalue.place); + instrValue.value = fn(instrValue.value); + break; + } + case 'StoreGlobal': { + instrValue.value = fn(instrValue.value); + break; + } + case 'Destructure': { + instrValue.value = fn(instrValue.value); + break; + } + case 'NewExpression': + case 'CallExpression': { + instrValue.callee = fn(instrValue.callee); + instrValue.args = mapCallArguments(instrValue.args, fn); + break; + } + case 'MethodCall': { + instrValue.receiver = fn(instrValue.receiver); + instrValue.property = fn(instrValue.property); + instrValue.args = mapCallArguments(instrValue.args, fn); + break; + } + case 'UnaryExpression': { + instrValue.value = fn(instrValue.value); + break; + } + case 'JsxExpression': { + if (instrValue.tag.kind === 'Identifier') { + instrValue.tag = fn(instrValue.tag); + } + for (const attribute of instrValue.props) { + switch (attribute.kind) { + case 'JsxAttribute': { + attribute.place = fn(attribute.place); + break; + } + case 'JsxSpreadAttribute': { + attribute.argument = fn(attribute.argument); + break; + } + default: { + assertExhaustive$1(attribute, `Unexpected attribute kind \`${attribute.kind}\``); + } + } + } + if (instrValue.children) { + instrValue.children = instrValue.children.map(p => fn(p)); + } + break; + } + case 'ObjectExpression': { + for (const property of instrValue.properties) { + if (property.kind === 'ObjectProperty' && + property.key.kind === 'computed') { + property.key.name = fn(property.key.name); + } + property.place = fn(property.place); + } + break; + } + case 'ArrayExpression': { + instrValue.elements = instrValue.elements.map(element => { + if (element.kind === 'Identifier') { + return fn(element); + } + else if (element.kind === 'Spread') { + element.place = fn(element.place); + return element; + } + else { + return element; + } + }); + break; + } + case 'JsxFragment': { + instrValue.children = instrValue.children.map(e => fn(e)); + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + instrValue.loweredFunc.func.context = + instrValue.loweredFunc.func.context.map(d => fn(d)); + break; + } + case 'TaggedTemplateExpression': { + instrValue.tag = fn(instrValue.tag); + break; + } + case 'TypeCastExpression': { + instrValue.value = fn(instrValue.value); + break; + } + case 'TemplateLiteral': { + instrValue.subexprs = instrValue.subexprs.map(fn); + break; + } + case 'Await': { + instrValue.value = fn(instrValue.value); + break; + } + case 'GetIterator': { + instrValue.collection = fn(instrValue.collection); + break; + } + case 'IteratorNext': { + instrValue.iterator = fn(instrValue.iterator); + instrValue.collection = fn(instrValue.collection); + break; + } + case 'NextPropertyOf': { + instrValue.value = fn(instrValue.value); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + instrValue.value = fn(instrValue.value); + break; + } + case 'StartMemoize': { + if (instrValue.deps != null) { + for (const dep of instrValue.deps) { + if (dep.root.kind === 'NamedLocal') { + dep.root.value = fn(dep.root.value); + } + } + } + break; + } + case 'FinishMemoize': { + instrValue.decl = fn(instrValue.decl); + break; + } + case 'Debugger': + case 'RegExpLiteral': + case 'MetaProperty': + case 'LoadGlobal': + case 'UnsupportedNode': + case 'Primitive': + case 'JSXText': { + break; + } + default: { + assertExhaustive$1(instrValue, 'Unexpected instruction kind'); + } + } +} +function mapCallArguments(args, fn) { + return args.map(arg => { + if (arg.kind === 'Identifier') { + return fn(arg); + } + else { + arg.place = fn(arg.place); + return arg; + } + }); +} +function mapPatternOperands(pattern, fn) { + switch (pattern.kind) { + case 'ArrayPattern': { + pattern.items = pattern.items.map(item => { + if (item.kind === 'Identifier') { + return fn(item); + } + else if (item.kind === 'Spread') { + item.place = fn(item.place); + return item; + } + else { + return item; + } + }); + break; + } + case 'ObjectPattern': { + for (const property of pattern.properties) { + property.place = fn(property.place); + } + break; + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } +} +function mapTerminalSuccessors(terminal, fn) { + switch (terminal.kind) { + case 'goto': { + const target = fn(terminal.block); + return { + kind: 'goto', + block: target, + variant: terminal.variant, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'if': { + const consequent = fn(terminal.consequent); + const alternate = fn(terminal.alternate); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'if', + test: terminal.test, + consequent, + alternate, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'branch': { + const consequent = fn(terminal.consequent); + const alternate = fn(terminal.alternate); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'branch', + test: terminal.test, + consequent, + alternate, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'switch': { + const cases = terminal.cases.map(case_ => { + const target = fn(case_.block); + return { + test: case_.test, + block: target, + }; + }); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'switch', + test: terminal.test, + cases, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'logical': { + const test = fn(terminal.test); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'logical', + test, + fallthrough, + operator: terminal.operator, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'ternary': { + const test = fn(terminal.test); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'ternary', + test, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'optional': { + const test = fn(terminal.test); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'optional', + optional: terminal.optional, + test, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'return': { + return { + kind: 'return', + returnVariant: terminal.returnVariant, + loc: terminal.loc, + value: terminal.value, + id: makeInstructionId(0), + effects: terminal.effects, + }; + } + case 'throw': { + return terminal; + } + case 'do-while': { + const loop = fn(terminal.loop); + const test = fn(terminal.test); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'do-while', + loc: terminal.loc, + test, + loop, + fallthrough, + id: makeInstructionId(0), + }; + } + case 'while': { + const test = fn(terminal.test); + const loop = fn(terminal.loop); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'while', + loc: terminal.loc, + test, + loop, + fallthrough, + id: makeInstructionId(0), + }; + } + case 'for': { + const init = fn(terminal.init); + const test = fn(terminal.test); + const update = terminal.update !== null ? fn(terminal.update) : null; + const loop = fn(terminal.loop); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'for', + loc: terminal.loc, + init, + test, + update, + loop, + fallthrough, + id: makeInstructionId(0), + }; + } + case 'for-of': { + const init = fn(terminal.init); + const loop = fn(terminal.loop); + const test = fn(terminal.test); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'for-of', + loc: terminal.loc, + init, + test, + loop, + fallthrough, + id: makeInstructionId(0), + }; + } + case 'for-in': { + const init = fn(terminal.init); + const loop = fn(terminal.loop); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'for-in', + loc: terminal.loc, + init, + loop, + fallthrough, + id: makeInstructionId(0), + }; + } + case 'label': { + const block = fn(terminal.block); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'label', + block, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'sequence': { + const block = fn(terminal.block); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'sequence', + block, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'maybe-throw': { + const continuation = fn(terminal.continuation); + const handler = terminal.handler !== null ? fn(terminal.handler) : null; + return { + kind: 'maybe-throw', + continuation, + handler, + id: makeInstructionId(0), + loc: terminal.loc, + effects: terminal.effects, + }; + } + case 'try': { + const block = fn(terminal.block); + const handler = fn(terminal.handler); + const fallthrough = fn(terminal.fallthrough); + return { + kind: 'try', + block, + handlerBinding: terminal.handlerBinding, + handler, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'scope': + case 'pruned-scope': { + const block = fn(terminal.block); + const fallthrough = fn(terminal.fallthrough); + return { + kind: terminal.kind, + scope: terminal.scope, + block, + fallthrough, + id: makeInstructionId(0), + loc: terminal.loc, + }; + } + case 'unreachable': + case 'unsupported': { + return terminal; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +function terminalHasFallthrough(terminal) { + switch (terminal.kind) { + case 'maybe-throw': + case 'goto': + case 'return': + case 'throw': + case 'unreachable': + case 'unsupported': { + return false; + } + case 'branch': + case 'try': + case 'do-while': + case 'for-of': + case 'for-in': + case 'for': + case 'if': + case 'label': + case 'logical': + case 'optional': + case 'sequence': + case 'switch': + case 'ternary': + case 'while': + case 'scope': + case 'pruned-scope': { + return true; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +function terminalFallthrough(terminal) { + if (terminalHasFallthrough(terminal)) { + return terminal.fallthrough; + } + else { + return null; + } +} +function* eachTerminalSuccessor(terminal) { + switch (terminal.kind) { + case 'goto': { + yield terminal.block; + break; + } + case 'if': { + yield terminal.consequent; + yield terminal.alternate; + break; + } + case 'branch': { + yield terminal.consequent; + yield terminal.alternate; + break; + } + case 'switch': { + for (const case_ of terminal.cases) { + yield case_.block; + } + break; + } + case 'optional': + case 'ternary': + case 'logical': { + yield terminal.test; + break; + } + case 'return': { + break; + } + case 'throw': { + break; + } + case 'do-while': { + yield terminal.loop; + break; + } + case 'while': { + yield terminal.test; + break; + } + case 'for': { + yield terminal.init; + break; + } + case 'for-of': { + yield terminal.init; + break; + } + case 'for-in': { + yield terminal.init; + break; + } + case 'label': { + yield terminal.block; + break; + } + case 'sequence': { + yield terminal.block; + break; + } + case 'maybe-throw': { + yield terminal.continuation; + if (terminal.handler !== null) { + yield terminal.handler; + } + break; + } + case 'try': { + yield terminal.block; + break; + } + case 'scope': + case 'pruned-scope': { + yield terminal.block; + break; + } + case 'unreachable': + case 'unsupported': + break; + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +function mapTerminalOperands(terminal, fn) { + switch (terminal.kind) { + case 'if': { + terminal.test = fn(terminal.test); + break; + } + case 'branch': { + terminal.test = fn(terminal.test); + break; + } + case 'switch': { + terminal.test = fn(terminal.test); + for (const case_ of terminal.cases) { + if (case_.test === null) { + continue; + } + case_.test = fn(case_.test); + } + break; + } + case 'return': + case 'throw': { + terminal.value = fn(terminal.value); + break; + } + case 'try': { + if (terminal.handlerBinding !== null) { + terminal.handlerBinding = fn(terminal.handlerBinding); + } + else { + terminal.handlerBinding = null; + } + break; + } + case 'maybe-throw': + case 'sequence': + case 'label': + case 'optional': + case 'ternary': + case 'logical': + case 'do-while': + case 'while': + case 'for': + case 'for-of': + case 'for-in': + case 'goto': + case 'unreachable': + case 'unsupported': + case 'scope': + case 'pruned-scope': { + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +function* eachTerminalOperand(terminal) { + switch (terminal.kind) { + case 'if': { + yield terminal.test; + break; + } + case 'branch': { + yield terminal.test; + break; + } + case 'switch': { + yield terminal.test; + for (const case_ of terminal.cases) { + if (case_.test === null) { + continue; + } + yield case_.test; + } + break; + } + case 'return': + case 'throw': { + yield terminal.value; + break; + } + case 'try': { + if (terminal.handlerBinding !== null) { + yield terminal.handlerBinding; + } + break; + } + case 'maybe-throw': + case 'sequence': + case 'label': + case 'optional': + case 'ternary': + case 'logical': + case 'do-while': + case 'while': + case 'for': + case 'for-of': + case 'for-in': + case 'goto': + case 'unreachable': + case 'unsupported': + case 'scope': + case 'pruned-scope': { + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +class ScopeBlockTraversal { + constructor() { + _ScopeBlockTraversal_activeScopes.set(this, []); + this.blockInfos = new Map(); + } + recordScopes(block) { + var _a, _b; + const blockInfo = this.blockInfos.get(block.id); + if ((blockInfo === null || blockInfo === void 0 ? void 0 : blockInfo.kind) === 'begin') { + __classPrivateFieldGet(this, _ScopeBlockTraversal_activeScopes, "f").push(blockInfo.scope.id); + } + else if ((blockInfo === null || blockInfo === void 0 ? void 0 : blockInfo.kind) === 'end') { + const top = __classPrivateFieldGet(this, _ScopeBlockTraversal_activeScopes, "f").at(-1); + CompilerError.invariant(blockInfo.scope.id === top, { + reason: 'Expected traversed block fallthrough to match top-most active scope', + loc: (_b = (_a = block.instructions[0]) === null || _a === void 0 ? void 0 : _a.loc) !== null && _b !== void 0 ? _b : block.terminal.loc, + }); + __classPrivateFieldGet(this, _ScopeBlockTraversal_activeScopes, "f").pop(); + } + if (block.terminal.kind === 'scope' || + block.terminal.kind === 'pruned-scope') { + CompilerError.invariant(!this.blockInfos.has(block.terminal.block) && + !this.blockInfos.has(block.terminal.fallthrough), { + reason: 'Expected unique scope blocks and fallthroughs', + loc: block.terminal.loc, + }); + this.blockInfos.set(block.terminal.block, { + kind: 'begin', + scope: block.terminal.scope, + pruned: block.terminal.kind === 'pruned-scope', + fallthrough: block.terminal.fallthrough, + }); + this.blockInfos.set(block.terminal.fallthrough, { + kind: 'end', + scope: block.terminal.scope, + pruned: block.terminal.kind === 'pruned-scope', + }); + } + } + isScopeActive(scopeId) { + return __classPrivateFieldGet(this, _ScopeBlockTraversal_activeScopes, "f").indexOf(scopeId) !== -1; + } + get currentScope() { + var _a; + return (_a = __classPrivateFieldGet(this, _ScopeBlockTraversal_activeScopes, "f").at(-1)) !== null && _a !== void 0 ? _a : null; + } +} +_ScopeBlockTraversal_activeScopes = new WeakMap(); + +function assertConsistentIdentifiers(fn) { + const identifiers = new Map(); + const assignments = new Set(); + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + validate(identifiers, phi.place.identifier); + for (const [, operand] of phi.operands) { + validate(identifiers, operand.identifier); + } + } + for (const instr of block.instructions) { + CompilerError.invariant(instr.lvalue.identifier.name === null, { + reason: `Expected all lvalues to be temporaries`, + description: `Found named lvalue \`${instr.lvalue.identifier.name}\``, + loc: instr.lvalue.loc, + }); + CompilerError.invariant(!assignments.has(instr.lvalue.identifier.id), { + reason: `Expected lvalues to be assigned exactly once`, + description: `Found duplicate assignment of '${printPlace(instr.lvalue)}'`, + loc: instr.lvalue.loc, + }); + assignments.add(instr.lvalue.identifier.id); + for (const operand of eachInstructionLValue(instr)) { + validate(identifiers, operand.identifier, operand.loc); + } + for (const operand of eachInstructionValueOperand(instr.value)) { + validate(identifiers, operand.identifier, operand.loc); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + validate(identifiers, operand.identifier, operand.loc); + } + } +} +function validate(identifiers, identifier, loc = null) { + const previous = identifiers.get(identifier.id); + if (previous === undefined) { + identifiers.set(identifier.id, identifier); + } + else { + CompilerError.invariant(identifier === previous, { + reason: `Duplicate identifier object`, + description: `Found duplicate identifier object for id ${identifier.id}`, + loc: loc !== null && loc !== void 0 ? loc : GeneratedSource, + }); + } +} + +function assertTerminalSuccessorsExist(fn) { + for (const [, block] of fn.body.blocks) { + mapTerminalSuccessors(block.terminal, successor => { + var _a; + CompilerError.invariant(fn.body.blocks.has(successor), { + reason: `Terminal successor references unknown block`, + description: `Block bb${successor} does not exist for terminal '${printTerminal(block.terminal)}'`, + loc: (_a = block.terminal.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + return successor; + }); + } +} +function assertTerminalPredsExist(fn) { + for (const [, block] of fn.body.blocks) { + for (const pred of block.preds) { + const predBlock = fn.body.blocks.get(pred); + CompilerError.invariant(predBlock != null, { + reason: 'Expected predecessor block to exist', + description: `Block ${block.id} references non-existent ${pred}`, + loc: GeneratedSource, + }); + CompilerError.invariant([...eachTerminalSuccessor(predBlock.terminal)].includes(block.id), { + reason: 'Terminal successor does not reference correct predecessor', + description: `Block bb${block.id} has bb${predBlock.id} as a predecessor, but bb${predBlock.id}'s successors do not include bb${block.id}`, + loc: GeneratedSource, + }); + } + } +} + +function getScopes(fn) { + const scopes = new Set(); + function visitPlace(place) { + const scope = place.identifier.scope; + if (scope != null) { + if (scope.range.start !== scope.range.end) { + scopes.add(scope); + } + } + } + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + for (const operand of eachInstructionLValue(instr)) { + visitPlace(operand); + } + for (const operand of eachInstructionOperand(instr)) { + visitPlace(operand); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + visitPlace(operand); + } + } + return scopes; +} +function rangePreOrderComparator(a, b) { + const startDiff = a.start - b.start; + if (startDiff !== 0) + return startDiff; + return b.end - a.end; +} +function recursivelyTraverseItems(items, getRange, context, enter, exit) { + items.sort((a, b) => rangePreOrderComparator(getRange(a), getRange(b))); + let activeItems = []; + const ranges = items.map(getRange); + for (let i = 0; i < items.length; i++) { + const curr = items[i]; + const currRange = ranges[i]; + for (let i = activeItems.length - 1; i >= 0; i--) { + const maybeParent = activeItems[i]; + const maybeParentRange = getRange(maybeParent); + const disjoint = currRange.start >= maybeParentRange.end; + const nested = currRange.end <= maybeParentRange.end; + CompilerError.invariant(disjoint || nested, { + reason: 'Invalid nesting in program blocks or scopes', + description: `Items overlap but are not nested: ${maybeParentRange.start}:${maybeParentRange.end}(${currRange.start}:${currRange.end})`, + loc: GeneratedSource, + }); + if (disjoint) { + exit(maybeParent, context); + activeItems.length = i; + } + else { + break; + } + } + enter(curr, context); + activeItems.push(curr); + } + let curr = activeItems.pop(); + while (curr != null) { + exit(curr, context); + curr = activeItems.pop(); + } +} +const no_op = () => { }; +function assertValidBlockNesting(fn) { + var _a, _b; + const scopes = getScopes(fn); + const blocks = [...scopes].map(scope => (Object.assign({ kind: 'Scope', id: scope.id }, scope.range))); + for (const [, block] of fn.body.blocks) { + const fallthroughId = terminalFallthrough(block.terminal); + if (fallthroughId != null) { + const fallthrough = fn.body.blocks.get(fallthroughId); + const end = (_b = (_a = fallthrough.instructions[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : fallthrough.terminal.id; + blocks.push({ + kind: 'ProgramBlockSubtree', + id: block.id, + start: block.terminal.id, + end, + }); + } + } + recursivelyTraverseItems(blocks, block => block, null, no_op, no_op); +} + +function assertValidMutableRanges(fn) { + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + visit$1(phi.place, `phi for block bb${block.id}`); + for (const [pred, operand] of phi.operands) { + visit$1(operand, `phi predecessor bb${pred} for block bb${block.id}`); + } + } + for (const instr of block.instructions) { + for (const operand of eachInstructionLValue(instr)) { + visit$1(operand, `instruction [${instr.id}]`); + } + for (const operand of eachInstructionOperand(instr)) { + visit$1(operand, `instruction [${instr.id}]`); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + visit$1(operand, `terminal [${block.terminal.id}]`); + } + } +} +function visit$1(place, description) { + validateMutableRange(place, place.identifier.mutableRange, description); + if (place.identifier.scope !== null) { + validateMutableRange(place, place.identifier.scope.range, description); + } +} +function validateMutableRange(place, range, description) { + CompilerError.invariant((range.start === 0 && range.end === 0) || range.end > range.start, { + reason: `Invalid mutable range: [${range.start}:${range.end}]`, + description: `${printPlace(place)} in ${description}`, + loc: place.loc, + }); +} + +var _HIRBuilder_instances, _HIRBuilder_completed, _HIRBuilder_current, _HIRBuilder_entry, _HIRBuilder_scopes, _HIRBuilder_context, _HIRBuilder_bindings, _HIRBuilder_env, _HIRBuilder_exceptionHandlerStack, _HIRBuilder_resolveBabelBinding; +function newBlock(id, kind) { + return { id, kind, instructions: [] }; +} +class HIRBuilder { + get nextIdentifierId() { + return __classPrivateFieldGet(this, _HIRBuilder_env, "f").nextIdentifierId; + } + get context() { + return __classPrivateFieldGet(this, _HIRBuilder_context, "f"); + } + get bindings() { + return __classPrivateFieldGet(this, _HIRBuilder_bindings, "f"); + } + get environment() { + return __classPrivateFieldGet(this, _HIRBuilder_env, "f"); + } + constructor(env, options) { + var _a, _b, _c; + _HIRBuilder_instances.add(this); + _HIRBuilder_completed.set(this, new Map()); + _HIRBuilder_current.set(this, void 0); + _HIRBuilder_entry.set(this, void 0); + _HIRBuilder_scopes.set(this, []); + _HIRBuilder_context.set(this, void 0); + _HIRBuilder_bindings.set(this, void 0); + _HIRBuilder_env.set(this, void 0); + _HIRBuilder_exceptionHandlerStack.set(this, []); + this.fbtDepth = 0; + __classPrivateFieldSet(this, _HIRBuilder_env, env, "f"); + __classPrivateFieldSet(this, _HIRBuilder_bindings, (_a = options === null || options === void 0 ? void 0 : options.bindings) !== null && _a !== void 0 ? _a : new Map(), "f"); + __classPrivateFieldSet(this, _HIRBuilder_context, (_b = options === null || options === void 0 ? void 0 : options.context) !== null && _b !== void 0 ? _b : new Map(), "f"); + __classPrivateFieldSet(this, _HIRBuilder_entry, makeBlockId(env.nextBlockId), "f"); + __classPrivateFieldSet(this, _HIRBuilder_current, newBlock(__classPrivateFieldGet(this, _HIRBuilder_entry, "f"), (_c = options === null || options === void 0 ? void 0 : options.entryBlockKind) !== null && _c !== void 0 ? _c : 'block'), "f"); + } + recordError(error) { + __classPrivateFieldGet(this, _HIRBuilder_env, "f").recordError(error); + } + currentBlockKind() { + return __classPrivateFieldGet(this, _HIRBuilder_current, "f").kind; + } + push(instruction) { + __classPrivateFieldGet(this, _HIRBuilder_current, "f").instructions.push(instruction); + const exceptionHandler = __classPrivateFieldGet(this, _HIRBuilder_exceptionHandlerStack, "f").at(-1); + if (exceptionHandler !== undefined) { + const continuationBlock = this.reserve(this.currentBlockKind()); + this.terminateWithContinuation({ + kind: 'maybe-throw', + continuation: continuationBlock.id, + handler: exceptionHandler, + id: makeInstructionId(0), + loc: instruction.loc, + effects: null, + }, continuationBlock); + } + } + enterTryCatch(handler, fn) { + __classPrivateFieldGet(this, _HIRBuilder_exceptionHandlerStack, "f").push(handler); + fn(); + __classPrivateFieldGet(this, _HIRBuilder_exceptionHandlerStack, "f").pop(); + } + resolveThrowHandler() { + const handler = __classPrivateFieldGet(this, _HIRBuilder_exceptionHandlerStack, "f").at(-1); + return handler !== null && handler !== void 0 ? handler : null; + } + makeTemporary(loc) { + const id = this.nextIdentifierId; + return makeTemporaryIdentifier(id, loc); + } + resolveIdentifier(path) { + const originalName = path.node.name; + const babelBinding = __classPrivateFieldGet(this, _HIRBuilder_instances, "m", _HIRBuilder_resolveBabelBinding).call(this, path); + if (babelBinding == null) { + return { kind: 'Global', name: originalName }; + } + const outerBinding = __classPrivateFieldGet(this, _HIRBuilder_env, "f").parentFunction.scope.parent.getBinding(originalName); + if (babelBinding === outerBinding) { + const path = babelBinding.path; + if (path.isImportDefaultSpecifier()) { + const importDeclaration = path.parentPath; + return { + kind: 'ImportDefault', + name: originalName, + module: importDeclaration.node.source.value, + }; + } + else if (path.isImportSpecifier()) { + const importDeclaration = path.parentPath; + return { + kind: 'ImportSpecifier', + name: originalName, + module: importDeclaration.node.source.value, + imported: path.node.imported.type === 'Identifier' + ? path.node.imported.name + : path.node.imported.value, + }; + } + else if (path.isImportNamespaceSpecifier()) { + const importDeclaration = path.parentPath; + return { + kind: 'ImportNamespace', + name: originalName, + module: importDeclaration.node.source.value, + }; + } + else { + return { + kind: 'ModuleLocal', + name: originalName, + }; + } + } + const resolvedBinding = this.resolveBinding(babelBinding.identifier); + if (resolvedBinding.name && resolvedBinding.name.value !== originalName) { + babelBinding.scope.rename(originalName, resolvedBinding.name.value); + } + return { + kind: 'Identifier', + identifier: resolvedBinding, + bindingKind: babelBinding.kind, + }; + } + isContextIdentifier(path) { + const binding = __classPrivateFieldGet(this, _HIRBuilder_instances, "m", _HIRBuilder_resolveBabelBinding).call(this, path); + if (binding) { + const outerBinding = __classPrivateFieldGet(this, _HIRBuilder_env, "f").parentFunction.scope.parent.getBinding(path.node.name); + if (binding === outerBinding) { + return false; + } + return __classPrivateFieldGet(this, _HIRBuilder_env, "f").isContextIdentifier(binding.identifier); + } + else { + return false; + } + } + resolveBinding(node) { + var _a, _b, _c; + if (node.name === 'fbt') { + this.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Support local variables named `fbt`', + description: 'Local variables named `fbt` may conflict with the fbt plugin and are not yet supported', + loc: (_a = node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + suggestions: null, + })); + } + if (node.name === 'this') { + this.recordError(new CompilerErrorDetail({ + category: ErrorCategory.UnsupportedSyntax, + reason: '`this` is not supported syntax', + description: 'React Compiler does not support compiling functions that use `this`', + loc: (_b = node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + suggestions: null, + })); + } + const originalName = node.name; + let name = originalName; + let index = 0; + while (true) { + const mapping = __classPrivateFieldGet(this, _HIRBuilder_bindings, "f").get(name); + if (mapping === undefined) { + const id = this.nextIdentifierId; + const identifier = { + id, + declarationId: makeDeclarationId(id), + name: makeIdentifierName(name), + mutableRange: { + start: makeInstructionId(0), + end: makeInstructionId(0), + }, + scope: null, + type: makeType(), + loc: (_c = node.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + }; + __classPrivateFieldGet(this, _HIRBuilder_env, "f").programContext.addNewReference(name); + __classPrivateFieldGet(this, _HIRBuilder_bindings, "f").set(name, { node, identifier }); + return identifier; + } + else if (mapping.node === node) { + return mapping.identifier; + } + else { + name = `${originalName}_${index++}`; + } + } + } + build() { + var _a, _b; + let ir = { + blocks: __classPrivateFieldGet(this, _HIRBuilder_completed, "f"), + entry: __classPrivateFieldGet(this, _HIRBuilder_entry, "f"), + }; + const rpoBlocks = getReversePostorderedBlocks(ir); + for (const [id, block] of ir.blocks) { + if (!rpoBlocks.has(id) && + block.instructions.some(instr => instr.value.kind === 'FunctionExpression')) { + this.recordError(new CompilerErrorDetail({ + reason: `Support functions with unreachable code that may contain hoisted declarations`, + loc: (_b = (_a = block.instructions[0]) === null || _a === void 0 ? void 0 : _a.loc) !== null && _b !== void 0 ? _b : block.terminal.loc, + description: null, + suggestions: null, + category: ErrorCategory.Todo, + })); + } + } + ir.blocks = rpoBlocks; + removeUnreachableForUpdates(ir); + removeDeadDoWhileStatements(ir); + removeUnnecessaryTryCatch(ir); + markInstructionIds(ir); + markPredecessors(ir); + return ir; + } + terminate(terminal, nextBlockKind) { + const { id: blockId, kind, instructions } = __classPrivateFieldGet(this, _HIRBuilder_current, "f"); + __classPrivateFieldGet(this, _HIRBuilder_completed, "f").set(blockId, { + kind, + id: blockId, + instructions, + terminal, + preds: new Set(), + phis: new Set(), + }); + if (nextBlockKind) { + const nextId = __classPrivateFieldGet(this, _HIRBuilder_env, "f").nextBlockId; + __classPrivateFieldSet(this, _HIRBuilder_current, newBlock(nextId, nextBlockKind), "f"); + } + return blockId; + } + terminateWithContinuation(terminal, continuation) { + const { id: blockId, kind, instructions } = __classPrivateFieldGet(this, _HIRBuilder_current, "f"); + __classPrivateFieldGet(this, _HIRBuilder_completed, "f").set(blockId, { + kind: kind, + id: blockId, + instructions, + terminal: terminal, + preds: new Set(), + phis: new Set(), + }); + __classPrivateFieldSet(this, _HIRBuilder_current, continuation, "f"); + } + reserve(kind) { + return newBlock(makeBlockId(__classPrivateFieldGet(this, _HIRBuilder_env, "f").nextBlockId), kind); + } + complete(block, terminal) { + const { id: blockId, kind, instructions } = block; + __classPrivateFieldGet(this, _HIRBuilder_completed, "f").set(blockId, { + kind, + id: blockId, + instructions, + terminal, + preds: new Set(), + phis: new Set(), + }); + } + enterReserved(wip, fn) { + const current = __classPrivateFieldGet(this, _HIRBuilder_current, "f"); + __classPrivateFieldSet(this, _HIRBuilder_current, wip, "f"); + const terminal = fn(); + const { id: blockId, kind, instructions } = __classPrivateFieldGet(this, _HIRBuilder_current, "f"); + __classPrivateFieldGet(this, _HIRBuilder_completed, "f").set(blockId, { + kind, + id: blockId, + instructions, + terminal, + preds: new Set(), + phis: new Set(), + }); + __classPrivateFieldSet(this, _HIRBuilder_current, current, "f"); + } + enter(nextBlockKind, fn) { + const wip = this.reserve(nextBlockKind); + this.enterReserved(wip, () => { + return fn(wip.id); + }); + return wip.id; + } + label(label, breakBlock, fn) { + __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").push({ + kind: 'label', + breakBlock, + label, + }); + const value = fn(); + const last = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").pop(); + CompilerError.invariant(last != null && + last.kind === 'label' && + last.label === label && + last.breakBlock === breakBlock, { + reason: 'Mismatched label', + loc: GeneratedSource, + }); + return value; + } + switch(label, breakBlock, fn) { + __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").push({ + kind: 'switch', + breakBlock, + label, + }); + const value = fn(); + const last = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").pop(); + CompilerError.invariant(last != null && + last.kind === 'switch' && + last.label === label && + last.breakBlock === breakBlock, { + reason: 'Mismatched label', + loc: GeneratedSource, + }); + return value; + } + loop(label, continueBlock, breakBlock, fn) { + __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").push({ + kind: 'loop', + label, + continueBlock, + breakBlock, + }); + const value = fn(); + const last = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").pop(); + CompilerError.invariant(last != null && + last.kind === 'loop' && + last.label === label && + last.continueBlock === continueBlock && + last.breakBlock === breakBlock, { + reason: 'Mismatched loops', + loc: GeneratedSource, + }); + return value; + } + lookupBreak(label) { + for (let ii = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").length - 1; ii >= 0; ii--) { + const scope = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f")[ii]; + if ((label === null && + (scope.kind === 'loop' || scope.kind === 'switch')) || + label === scope.label) { + return scope.breakBlock; + } + } + CompilerError.invariant(false, { + reason: 'Expected a loop or switch to be in scope', + loc: GeneratedSource, + }); + } + lookupContinue(label) { + for (let ii = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f").length - 1; ii >= 0; ii--) { + const scope = __classPrivateFieldGet(this, _HIRBuilder_scopes, "f")[ii]; + if (scope.kind === 'loop') { + if (label === null || label === scope.label) { + return scope.continueBlock; + } + } + else if (label !== null && scope.label === label) { + CompilerError.invariant(false, { + reason: 'Continue may only refer to a labeled loop', + loc: GeneratedSource, + }); + } + } + CompilerError.invariant(false, { + reason: 'Expected a loop to be in scope', + loc: GeneratedSource, + }); + } +} +_HIRBuilder_completed = new WeakMap(), _HIRBuilder_current = new WeakMap(), _HIRBuilder_entry = new WeakMap(), _HIRBuilder_scopes = new WeakMap(), _HIRBuilder_context = new WeakMap(), _HIRBuilder_bindings = new WeakMap(), _HIRBuilder_env = new WeakMap(), _HIRBuilder_exceptionHandlerStack = new WeakMap(), _HIRBuilder_instances = new WeakSet(), _HIRBuilder_resolveBabelBinding = function _HIRBuilder_resolveBabelBinding(path) { + const originalName = path.node.name; + const binding = path.scope.getBinding(originalName); + if (binding == null) { + return null; + } + return binding; +}; +function removeUnreachableForUpdates(fn) { + for (const [, block] of fn.blocks) { + if (block.terminal.kind === 'for' && + block.terminal.update !== null && + !fn.blocks.has(block.terminal.update)) { + block.terminal.update = null; + } + } +} +function removeDeadDoWhileStatements(func) { + const visited = new Set(); + for (const [_, block] of func.blocks) { + visited.add(block.id); + } + for (const [_, block] of func.blocks) { + if (block.terminal.kind === 'do-while') { + if (!visited.has(block.terminal.test)) { + block.terminal = { + kind: 'goto', + block: block.terminal.loop, + variant: GotoVariant.Break, + id: block.terminal.id, + loc: block.terminal.loc, + }; + } + } + } +} +function reversePostorderBlocks(func) { + const rpoBlocks = getReversePostorderedBlocks(func); + func.blocks = rpoBlocks; +} +function getReversePostorderedBlocks(func) { + const visited = new Set(); + const used = new Set(); + const usedFallthroughs = new Set(); + const postorder = []; + function visit(blockId, isUsed) { + const wasUsed = used.has(blockId); + const wasVisited = visited.has(blockId); + visited.add(blockId); + if (isUsed) { + used.add(blockId); + } + if (wasVisited && (wasUsed || !isUsed)) { + return; + } + const block = func.blocks.get(blockId); + CompilerError.invariant(block != null, { + reason: '[HIRBuilder] Unexpected null block', + description: `expected block ${blockId} to exist`, + loc: GeneratedSource, + }); + const successors = [...eachTerminalSuccessor(block.terminal)].reverse(); + const fallthrough = terminalFallthrough(block.terminal); + if (fallthrough != null) { + if (isUsed) { + usedFallthroughs.add(fallthrough); + } + visit(fallthrough, false); + } + for (const successor of successors) { + visit(successor, isUsed); + } + if (!wasVisited) { + postorder.push(blockId); + } + } + visit(func.entry, true); + const blocks = new Map(); + for (const blockId of postorder.reverse()) { + const block = func.blocks.get(blockId); + if (used.has(blockId)) { + blocks.set(blockId, func.blocks.get(blockId)); + } + else if (usedFallthroughs.has(blockId)) { + blocks.set(blockId, Object.assign(Object.assign({}, block), { instructions: [], terminal: { + kind: 'unreachable', + id: block.terminal.id, + loc: block.terminal.loc, + } })); + } + } + return blocks; +} +function markInstructionIds(func) { + let id = 0; + const visited = new Set(); + for (const [_, block] of func.blocks) { + for (const instr of block.instructions) { + CompilerError.invariant(!visited.has(instr), { + reason: `${printInstruction(instr)} already visited!`, + loc: instr.loc, + }); + visited.add(instr); + instr.id = makeInstructionId(++id); + } + block.terminal.id = makeInstructionId(++id); + } +} +function markPredecessors(func) { + for (const [, block] of func.blocks) { + block.preds.clear(); + } + const visited = new Set(); + function visit(blockId, prevBlock) { + const block = func.blocks.get(blockId); + if (block == null) { + return; + } + CompilerError.invariant(block != null, { + reason: 'unexpected missing block', + description: `block ${blockId}`, + loc: GeneratedSource, + }); + if (prevBlock) { + block.preds.add(prevBlock.id); + } + if (visited.has(blockId)) { + return; + } + visited.add(blockId); + const { terminal } = block; + for (const successor of eachTerminalSuccessor(terminal)) { + visit(successor, block); + } + } + visit(func.entry, null); +} +function removeUnnecessaryTryCatch(fn) { + for (const [, block] of fn.blocks) { + if (block.terminal.kind === 'try' && + !fn.blocks.has(block.terminal.handler)) { + const handlerId = block.terminal.handler; + const fallthroughId = block.terminal.fallthrough; + const fallthrough = fn.blocks.get(fallthroughId); + block.terminal = { + kind: 'goto', + block: block.terminal.block, + id: makeInstructionId(0), + loc: block.terminal.loc, + variant: GotoVariant.Break, + }; + if (fallthrough != null) { + if (fallthrough.preds.size === 1 && fallthrough.preds.has(handlerId)) { + fn.blocks.delete(fallthroughId); + } + else { + fallthrough.preds.delete(handlerId); + } + } + } + } +} +function createTemporaryPlace(env, loc) { + return { + kind: 'Identifier', + identifier: makeTemporaryIdentifier(env.nextIdentifierId, loc), + reactive: false, + effect: Effect.Unknown, + loc: GeneratedSource, + }; +} +function clonePlaceToTemporary(env, place) { + const temp = createTemporaryPlace(env, place.loc); + temp.effect = place.effect; + temp.identifier.type = place.identifier.type; + temp.reactive = place.reactive; + return temp; +} +function fixScopeAndIdentifierRanges(func) { + var _a, _b; + for (const [, block] of func.blocks) { + const terminal = block.terminal; + if (terminal.kind === 'scope' || terminal.kind === 'pruned-scope') { + const fallthroughBlock = func.blocks.get(terminal.fallthrough); + const firstId = (_b = (_a = fallthroughBlock.instructions[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : fallthroughBlock.terminal.id; + terminal.scope.range.start = terminal.id; + terminal.scope.range.end = firstId; + } + } +} + +const PRIMITIVE_TYPE = { + kind: 'Primitive', +}; +let nextAnonId = 0; +function createAnonId() { + return ``; +} +function addFunction(registry, properties, fn, id = null, isConstructor = false) { + const shapeId = id !== null && id !== void 0 ? id : createAnonId(); + const aliasing = fn.aliasing != null + ? parseAliasingSignatureConfig(fn.aliasing, '', GeneratedSource) + : null; + addShape(registry, shapeId, properties, Object.assign(Object.assign({}, fn), { aliasing, hookKind: null })); + return { + kind: 'Function', + return: fn.returnType, + shapeId, + isConstructor, + }; +} +function addHook(registry, fn, id = null) { + const shapeId = id !== null && id !== void 0 ? id : createAnonId(); + const aliasing = fn.aliasing != null + ? parseAliasingSignatureConfig(fn.aliasing, '', GeneratedSource) + : null; + addShape(registry, shapeId, [], Object.assign(Object.assign({}, fn), { aliasing })); + return { + kind: 'Function', + return: fn.returnType, + shapeId, + isConstructor: false, + }; +} +function parseAliasingSignatureConfig(typeConfig, moduleName, loc) { + const lifetimes = new Map(); + function define(temp) { + CompilerError.invariant(!lifetimes.has(temp), { + reason: `Invalid type configuration for module`, + description: `Expected aliasing signature to have unique names for receiver, params, rest, returns, and temporaries in module '${moduleName}'`, + loc, + }); + const place = signatureArgument(lifetimes.size); + lifetimes.set(temp, place); + return place; + } + function lookup(temp) { + const place = lifetimes.get(temp); + CompilerError.invariant(place != null, { + reason: `Invalid type configuration for module`, + description: `Expected aliasing signature effects to reference known names from receiver/params/rest/returns/temporaries, but '${temp}' is not a known name in '${moduleName}'`, + loc, + }); + return place; + } + const receiver = define(typeConfig.receiver); + const params = typeConfig.params.map(define); + const rest = typeConfig.rest != null ? define(typeConfig.rest) : null; + const returns = define(typeConfig.returns); + const temporaries = typeConfig.temporaries.map(define); + const effects = typeConfig.effects.map((effect) => { + switch (effect.kind) { + case 'ImmutableCapture': + case 'CreateFrom': + case 'Capture': + case 'Alias': + case 'Assign': { + const from = lookup(effect.from); + const into = lookup(effect.into); + return { + kind: effect.kind, + from, + into, + }; + } + case 'Mutate': + case 'MutateTransitiveConditionally': { + const value = lookup(effect.value); + return { kind: effect.kind, value }; + } + case 'Create': { + const into = lookup(effect.into); + return { + kind: 'Create', + into, + reason: effect.reason, + value: effect.value, + }; + } + case 'Freeze': { + const value = lookup(effect.value); + return { + kind: 'Freeze', + value, + reason: effect.reason, + }; + } + case 'Impure': { + const place = lookup(effect.place); + return { + kind: 'Impure', + place, + error: CompilerError.throwTodo({ + reason: 'Support impure effect declarations', + loc: GeneratedSource, + }), + }; + } + case 'Apply': { + const receiver = lookup(effect.receiver); + const fn = lookup(effect.function); + const args = effect.args.map(arg => { + if (typeof arg === 'string') { + return lookup(arg); + } + else if (arg.kind === 'Spread') { + return { kind: 'Spread', place: lookup(arg.place) }; + } + else { + return arg; + } + }); + const into = lookup(effect.into); + return { + kind: 'Apply', + receiver, + function: fn, + mutatesFunction: effect.mutatesFunction, + args, + into, + loc, + signature: null, + }; + } + default: { + assertExhaustive$1(effect, `Unexpected effect kind '${effect.kind}'`); + } + } + }); + return { + receiver: receiver.identifier.id, + params: params.map(p => p.identifier.id), + rest: rest != null ? rest.identifier.id : null, + returns: returns.identifier.id, + temporaries, + effects, + }; +} +function addObject(registry, id, properties) { + const shapeId = id !== null && id !== void 0 ? id : createAnonId(); + addShape(registry, shapeId, properties, null); + return { + kind: 'Object', + shapeId, + }; +} +function addShape(registry, id, properties, functionType) { + const shape = { + properties: new Map(properties), + functionType, + }; + CompilerError.invariant(!registry.has(id), { + reason: `[ObjectShape] Could not add shape to registry: name ${id} already exists.`, + loc: GeneratedSource, + }); + registry.set(id, shape); + return shape; +} +const BuiltInPropsId = 'BuiltInProps'; +const BuiltInArrayId = 'BuiltInArray'; +const BuiltInSetId = 'BuiltInSet'; +const BuiltInMapId = 'BuiltInMap'; +const BuiltInWeakSetId = 'BuiltInWeakSet'; +const BuiltInWeakMapId = 'BuiltInWeakMap'; +const BuiltInFunctionId = 'BuiltInFunction'; +const BuiltInJsxId = 'BuiltInJsx'; +const BuiltInObjectId = 'BuiltInObject'; +const BuiltInUseStateId = 'BuiltInUseState'; +const BuiltInSetStateId = 'BuiltInSetState'; +const BuiltInUseActionStateId = 'BuiltInUseActionState'; +const BuiltInSetActionStateId = 'BuiltInSetActionState'; +const BuiltInUseRefId = 'BuiltInUseRefId'; +const BuiltInRefValueId = 'BuiltInRefValue'; +const BuiltInMixedReadonlyId = 'BuiltInMixedReadonly'; +const BuiltInUseEffectHookId = 'BuiltInUseEffectHook'; +const BuiltInUseLayoutEffectHookId = 'BuiltInUseLayoutEffectHook'; +const BuiltInUseInsertionEffectHookId = 'BuiltInUseInsertionEffectHook'; +const BuiltInUseOperatorId = 'BuiltInUseOperator'; +const BuiltInUseReducerId = 'BuiltInUseReducer'; +const BuiltInDispatchId = 'BuiltInDispatch'; +const BuiltInUseContextHookId = 'BuiltInUseContextHook'; +const BuiltInUseTransitionId = 'BuiltInUseTransition'; +const BuiltInUseOptimisticId = 'BuiltInUseOptimistic'; +const BuiltInSetOptimisticId = 'BuiltInSetOptimistic'; +const BuiltInStartTransitionId = 'BuiltInStartTransition'; +const BuiltInUseEffectEventId = 'BuiltInUseEffectEvent'; +const BuiltInEffectEventId = 'BuiltInEffectEventFunction'; +const ReanimatedSharedValueId = 'ReanimatedSharedValueId'; +const BUILTIN_SHAPES = new Map(); +addObject(BUILTIN_SHAPES, BuiltInPropsId, [ + ['ref', { kind: 'Object', shapeId: BuiltInUseRefId }], +]); +addObject(BUILTIN_SHAPES, BuiltInArrayId, [ + [ + 'indexOf', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'includes', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'pop', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'at', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'concat', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Capture, + returnType: { + kind: 'Object', + shapeId: BuiltInArrayId, + }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + ['length', PRIMITIVE_TYPE], + [ + 'push', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Capture, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + aliasing: { + receiver: '@receiver', + params: [], + rest: '@rest', + returns: '@returns', + temporaries: [], + effects: [ + { kind: 'Mutate', value: '@receiver' }, + { + kind: 'Capture', + from: '@rest', + into: '@receiver', + }, + { + kind: 'Create', + into: '@returns', + value: ValueKind.Primitive, + reason: ValueReason.KnownReturnSignature, + }, + ], + }, + }), + ], + [ + 'slice', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { + kind: 'Object', + shapeId: BuiltInArrayId, + }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'map', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + aliasing: { + receiver: '@receiver', + params: ['@callback'], + rest: null, + returns: '@returns', + temporaries: [ + '@item', + '@callbackReturn', + '@thisArg', + ], + effects: [ + { + kind: 'Create', + into: '@returns', + value: ValueKind.Mutable, + reason: ValueReason.KnownReturnSignature, + }, + { + kind: 'CreateFrom', + from: '@receiver', + into: '@item', + }, + { + kind: 'Create', + into: '@thisArg', + value: ValueKind.Primitive, + reason: ValueReason.KnownReturnSignature, + }, + { + kind: 'Apply', + receiver: '@thisArg', + args: ['@item', { kind: 'Hole' }, '@receiver'], + function: '@callback', + into: '@callbackReturn', + mutatesFunction: false, + }, + { + kind: 'Capture', + from: '@callbackReturn', + into: '@returns', + }, + ], + }, + }), + ], + [ + 'flatMap', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'filter', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'every', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'some', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'find', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'findIndex', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'join', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInObjectId, [ + [ + 'toString', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInSetId, [ + [ + 'add', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInSetId }, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Mutable, + aliasing: { + receiver: '@receiver', + params: [], + rest: '@rest', + returns: '@returns', + temporaries: [], + effects: [ + { + kind: 'Assign', + from: '@receiver', + into: '@returns', + }, + { + kind: 'Mutate', + value: '@receiver', + }, + { + kind: 'Capture', + from: '@rest', + into: '@receiver', + }, + ], + }, + }), + ], + [ + 'clear', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'delete', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'has', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + ['size', PRIMITIVE_TYPE], + [ + 'difference', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInSetId }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'union', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInSetId }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'symmetricalDifference', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInSetId }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'isSubsetOf', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'isSupersetOf', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'forEach', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'entries', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'keys', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'values', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInMapId, [ + [ + 'clear', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'delete', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'get', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'has', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'set', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture, Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInMapId }, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Mutable, + }), + ], + ['size', PRIMITIVE_TYPE], + [ + 'forEach', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'entries', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'keys', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'values', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInWeakSetId, [ + [ + 'add', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInWeakSetId }, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'delete', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'has', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInWeakMapId, [ + [ + 'delete', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'get', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'has', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'set', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Capture, Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInWeakMapId }, + calleeEffect: Effect.Store, + returnValueKind: ValueKind.Mutable, + }), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseStateId, [ + ['0', { kind: 'Poly' }], + [ + '1', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }, BuiltInSetStateId), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseTransitionId, [ + ['0', { kind: 'Primitive' }], + [ + '1', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: null, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }, BuiltInStartTransitionId), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseOptimisticId, [ + ['0', { kind: 'Poly' }], + [ + '1', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }, BuiltInSetOptimisticId), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseActionStateId, [ + ['0', { kind: 'Poly' }], + [ + '1', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }, BuiltInSetActionStateId), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseReducerId, [ + ['0', { kind: 'Poly' }], + [ + '1', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }, BuiltInDispatchId), + ], +]); +addObject(BUILTIN_SHAPES, BuiltInUseRefId, [ + ['current', { kind: 'Object', shapeId: BuiltInRefValueId }], +]); +addObject(BUILTIN_SHAPES, BuiltInRefValueId, [ + ['*', { kind: 'Object', shapeId: BuiltInRefValueId }], +]); +addObject(BUILTIN_SHAPES, ReanimatedSharedValueId, []); +addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, +}, BuiltInEffectEventId); +addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [ + [ + 'toString', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'indexOf', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'includes', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'at', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInMixedReadonlyId }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'map', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + }), + ], + [ + 'flatMap', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + }), + ], + [ + 'filter', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Mutable, + noAlias: true, + }), + ], + [ + 'concat', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Capture, + returnType: { + kind: 'Object', + shapeId: BuiltInArrayId, + }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'slice', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { + kind: 'Object', + shapeId: BuiltInArrayId, + }, + calleeEffect: Effect.Capture, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'every', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'some', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'find', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Object', shapeId: BuiltInMixedReadonlyId }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Frozen, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'findIndex', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.ConditionallyMutate, + returnValueKind: ValueKind.Primitive, + noAlias: true, + mutableOnlyIfOperandsAreMutable: true, + }), + ], + [ + 'join', + addFunction(BUILTIN_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: PRIMITIVE_TYPE, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + ['*', { kind: 'Object', shapeId: BuiltInMixedReadonlyId }], +]); +addObject(BUILTIN_SHAPES, BuiltInJsxId, []); +addObject(BUILTIN_SHAPES, BuiltInFunctionId, []); +const DefaultMutatingHook = addHook(BUILTIN_SHAPES, { + positionalParams: [], + restParam: Effect.ConditionallyMutate, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'Custom', + returnValueKind: ValueKind.Mutable, +}, 'DefaultMutatingHook'); +const DefaultNonmutatingHook = addHook(BUILTIN_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'Custom', + returnValueKind: ValueKind.Frozen, + aliasing: { + receiver: '@receiver', + params: [], + rest: '@rest', + returns: '@returns', + temporaries: [], + effects: [ + { + kind: 'Freeze', + value: '@rest', + reason: ValueReason.HookCaptured, + }, + { + kind: 'Create', + into: '@returns', + value: ValueKind.Frozen, + reason: ValueReason.HookReturn, + }, + { + kind: 'Alias', + from: '@rest', + into: '@returns', + }, + ], + }, +}, 'DefaultNonmutatingHook'); +function signatureArgument(id) { + const place = { + kind: 'Identifier', + effect: Effect.Unknown, + loc: GeneratedSource, + reactive: false, + identifier: { + declarationId: makeDeclarationId(id), + id: makeIdentifierId(id), + loc: GeneratedSource, + mutableRange: { start: makeInstructionId(0), end: makeInstructionId(0) }, + name: null, + scope: null, + type: makeType(), + }, + }; + return place; +} + +function lower(func, env, bindings = null, capturedRefs = new Map()) { + var _a, _b, _c; + const builder = new HIRBuilder(env, { + bindings, + context: capturedRefs, + }); + const context = []; + for (const [ref, loc] of capturedRefs !== null && capturedRefs !== void 0 ? capturedRefs : []) { + context.push({ + kind: 'Identifier', + identifier: builder.resolveBinding(ref), + effect: Effect.Unknown, + reactive: false, + loc, + }); + } + let id = null; + if (func.isFunctionDeclaration() || func.isFunctionExpression()) { + const idNode = func.get('id'); + if (hasNode(idNode)) { + id = idNode.node.name; + } + } + const params = []; + func.get('params').forEach(param => { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (param.isIdentifier()) { + const binding = builder.resolveIdentifier(param); + if (binding.kind !== 'Identifier') { + builder.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Invariant, + reason: 'Could not find binding', + description: `[BuildHIR] Could not find binding for param \`${param.node.name}\``, + }).withDetails({ + kind: 'error', + loc: (_a = param.node.loc) !== null && _a !== void 0 ? _a : null, + message: 'Could not find binding', + })); + return; + } + const place = { + kind: 'Identifier', + identifier: binding.identifier, + effect: Effect.Unknown, + reactive: false, + loc: (_b = param.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + params.push(place); + } + else if (param.isObjectPattern() || + param.isArrayPattern() || + param.isAssignmentPattern()) { + const place = { + kind: 'Identifier', + identifier: builder.makeTemporary((_c = param.node.loc) !== null && _c !== void 0 ? _c : GeneratedSource), + effect: Effect.Unknown, + reactive: false, + loc: (_d = param.node.loc) !== null && _d !== void 0 ? _d : GeneratedSource, + }; + promoteTemporary(place.identifier); + params.push(place); + lowerAssignment(builder, (_e = param.node.loc) !== null && _e !== void 0 ? _e : GeneratedSource, InstructionKind.Let, param, place, 'Assignment'); + } + else if (param.isRestElement()) { + const place = { + kind: 'Identifier', + identifier: builder.makeTemporary((_f = param.node.loc) !== null && _f !== void 0 ? _f : GeneratedSource), + effect: Effect.Unknown, + reactive: false, + loc: (_g = param.node.loc) !== null && _g !== void 0 ? _g : GeneratedSource, + }; + params.push({ + kind: 'Spread', + place, + }); + lowerAssignment(builder, (_h = param.node.loc) !== null && _h !== void 0 ? _h : GeneratedSource, InstructionKind.Let, param.get('argument'), place, 'Assignment'); + } + else { + builder.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Todo, + reason: `Handle ${param.node.type} parameters`, + description: `[BuildHIR] Add support for ${param.node.type} parameters`, + }).withDetails({ + kind: 'error', + loc: (_j = param.node.loc) !== null && _j !== void 0 ? _j : null, + message: 'Unsupported parameter type', + })); + } + }); + let directives = []; + const body = func.get('body'); + if (body.isExpression()) { + const fallthrough = builder.reserve('block'); + const terminal = { + kind: 'return', + returnVariant: 'Implicit', + loc: GeneratedSource, + value: lowerExpressionToTemporary(builder, body), + id: makeInstructionId(0), + effects: null, + }; + builder.terminateWithContinuation(terminal, fallthrough); + } + else if (body.isBlockStatement()) { + lowerStatement(builder, body); + directives = body.get('directives').map(d => d.node.value.value); + } + else { + builder.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Syntax, + reason: `Unexpected function body kind`, + description: `Expected function body to be an expression or a block statement, got \`${body.type}\``, + }).withDetails({ + kind: 'error', + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : null, + message: 'Expected a block statement or expression', + })); + } + let validatedId = null; + if (id != null) { + const idResult = validateIdentifierName(id); + if (idResult.isErr()) { + for (const detail of idResult.unwrapErr().details) { + builder.recordError(detail); + } + } + else { + validatedId = idResult.unwrap().value; + } + } + builder.terminate({ + kind: 'return', + returnVariant: 'Void', + loc: GeneratedSource, + value: lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc: GeneratedSource, + }), + id: makeInstructionId(0), + effects: null, + }, null); + const hirBody = builder.build(); + return { + id: validatedId, + nameHint: null, + params, + fnType: bindings == null ? env.fnType : 'Other', + returnTypeAnnotation: null, + returns: createTemporaryPlace(env, (_b = func.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource), + body: hirBody, + context, + generator: func.node.generator === true, + async: func.node.async === true, + loc: (_c = func.node.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + env, + aliasingEffects: null, + directives, + }; +} +function lowerStatement(builder, stmtPath, label = null) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38; + const stmtNode = stmtPath.node; + switch (stmtNode.type) { + case 'ThrowStatement': { + const stmt = stmtPath; + const value = lowerExpressionToTemporary(builder, stmt.get('argument')); + const handler = builder.resolveThrowHandler(); + if (handler != null) { + builder.recordError(new CompilerErrorDetail({ + reason: '(BuildHIR::lowerStatement) Support ThrowStatement inside of try/catch', + category: ErrorCategory.Todo, + loc: (_a = stmt.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + } + const terminal = { + kind: 'throw', + value, + id: makeInstructionId(0), + loc: (_b = stmt.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + builder.terminate(terminal, 'block'); + return; + } + case 'ReturnStatement': { + const stmt = stmtPath; + const argument = stmt.get('argument'); + let value; + if (argument.node === null) { + value = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc: GeneratedSource, + }); + } + else { + value = lowerExpressionToTemporary(builder, argument); + } + const terminal = { + kind: 'return', + returnVariant: 'Explicit', + loc: (_c = stmt.node.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + value, + id: makeInstructionId(0), + effects: null, + }; + builder.terminate(terminal, 'block'); + return; + } + case 'IfStatement': { + const stmt = stmtPath; + const continuationBlock = builder.reserve('block'); + const consequentBlock = builder.enter('block', _blockId => { + var _a; + const consequent = stmt.get('consequent'); + lowerStatement(builder, consequent); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_a = consequent.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + let alternateBlock; + const alternate = stmt.get('alternate'); + if (hasNode(alternate)) { + alternateBlock = builder.enter('block', _blockId => { + var _a, _b; + lowerStatement(builder, alternate); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_b = (_a = alternate.node) === null || _a === void 0 ? void 0 : _a.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + }); + } + else { + alternateBlock = continuationBlock.id; + } + const test = lowerExpressionToTemporary(builder, stmt.get('test')); + const terminal = { + kind: 'if', + test, + consequent: consequentBlock, + alternate: alternateBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_d = stmt.node.loc) !== null && _d !== void 0 ? _d : GeneratedSource, + }; + builder.terminateWithContinuation(terminal, continuationBlock); + return; + } + case 'BlockStatement': { + const stmt = stmtPath; + const statements = stmt.get('body'); + const hoistableIdentifiers = new Set(); + for (const [, binding] of Object.entries(stmt.scope.bindings)) { + if (binding.kind !== 'param') { + hoistableIdentifiers.add(binding.identifier); + } + } + for (const s of statements) { + const willHoist = new Set(); + let fnDepth = s.isFunctionDeclaration() ? 1 : 0; + const withFunctionContext = { + enter: () => { + fnDepth++; + }, + exit: () => { + fnDepth--; + }, + }; + s.traverse({ + FunctionExpression: withFunctionContext, + FunctionDeclaration: withFunctionContext, + ArrowFunctionExpression: withFunctionContext, + ObjectMethod: withFunctionContext, + Identifier(id) { + const id2 = id; + if (!id2.isReferencedIdentifier() && + id.parent.type !== 'AssignmentExpression') { + return; + } + const binding = id.scope.getBinding(id.node.name); + if (binding != null && + hoistableIdentifiers.has(binding.identifier) && + (fnDepth > 0 || binding.kind === 'hoisted')) { + willHoist.add(id); + } + }, + }); + s.traverse({ + Identifier(path) { + if (hoistableIdentifiers.has(path.node)) { + hoistableIdentifiers.delete(path.node); + } + }, + }); + for (const id of willHoist) { + const binding = stmt.scope.getBinding(id.node.name); + CompilerError.invariant(binding != null, { + reason: 'Expected to find binding for hoisted identifier', + description: `Could not find a binding for ${id.node.name}`, + loc: (_e = id.node.loc) !== null && _e !== void 0 ? _e : GeneratedSource, + }); + if (builder.environment.isHoistedIdentifier(binding.identifier)) { + continue; + } + let kind; + if (binding.kind === 'const' || binding.kind === 'var') { + kind = InstructionKind.HoistedConst; + } + else if (binding.kind === 'let') { + kind = InstructionKind.HoistedLet; + } + else if (binding.path.isFunctionDeclaration()) { + kind = InstructionKind.HoistedFunction; + } + else if (!binding.path.isVariableDeclarator()) { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Unsupported declaration type for hoisting', + description: `variable "${binding.identifier.name}" declared with ${binding.path.type}`, + suggestions: null, + loc: (_f = id.parentPath.node.loc) !== null && _f !== void 0 ? _f : GeneratedSource, + })); + continue; + } + else { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Handle non-const declarations for hoisting', + description: `variable "${binding.identifier.name}" declared with ${binding.kind}`, + suggestions: null, + loc: (_g = id.parentPath.node.loc) !== null && _g !== void 0 ? _g : GeneratedSource, + })); + continue; + } + const identifier = builder.resolveIdentifier(id); + CompilerError.invariant(identifier.kind === 'Identifier', { + reason: 'Expected hoisted binding to be a local identifier, not a global', + loc: (_h = id.node.loc) !== null && _h !== void 0 ? _h : GeneratedSource, + }); + const place = { + effect: Effect.Unknown, + identifier: identifier.identifier, + kind: 'Identifier', + reactive: false, + loc: (_j = id.node.loc) !== null && _j !== void 0 ? _j : GeneratedSource, + }; + lowerValueToTemporary(builder, { + kind: 'DeclareContext', + lvalue: { + kind, + place, + }, + loc: (_k = id.node.loc) !== null && _k !== void 0 ? _k : GeneratedSource, + }); + builder.environment.addHoistedIdentifier(binding.identifier); + } + lowerStatement(builder, s); + } + return; + } + case 'BreakStatement': { + const stmt = stmtPath; + const block = builder.lookupBreak((_m = (_l = stmt.node.label) === null || _l === void 0 ? void 0 : _l.name) !== null && _m !== void 0 ? _m : null); + builder.terminate({ + kind: 'goto', + block, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_o = stmt.node.loc) !== null && _o !== void 0 ? _o : GeneratedSource, + }, 'block'); + return; + } + case 'ContinueStatement': { + const stmt = stmtPath; + const block = builder.lookupContinue((_q = (_p = stmt.node.label) === null || _p === void 0 ? void 0 : _p.name) !== null && _q !== void 0 ? _q : null); + builder.terminate({ + kind: 'goto', + block, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_r = stmt.node.loc) !== null && _r !== void 0 ? _r : GeneratedSource, + }, 'block'); + return; + } + case 'ForStatement': { + const stmt = stmtPath; + const testBlock = builder.reserve('loop'); + const continuationBlock = builder.reserve('block'); + const initBlock = builder.enter('loop', _blockId => { + var _a, _b, _c, _d, _e, _f; + const init = stmt.get('init'); + if (init.node == null) { + lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc: (_a = stmt.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + return { + kind: 'goto', + block: testBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_b = stmt.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + } + if (!init.isVariableDeclaration()) { + builder.recordError(new CompilerErrorDetail({ + reason: '(BuildHIR::lowerStatement) Handle non-variable initialization in ForStatement', + category: ErrorCategory.Todo, + loc: (_c = stmt.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + if (init.isExpression()) { + lowerExpressionToTemporary(builder, init); + } + return { + kind: 'goto', + block: testBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_e = (_d = init.node) === null || _d === void 0 ? void 0 : _d.loc) !== null && _e !== void 0 ? _e : GeneratedSource, + }; + } + lowerStatement(builder, init); + return { + kind: 'goto', + block: testBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_f = init.node.loc) !== null && _f !== void 0 ? _f : GeneratedSource, + }; + }); + let updateBlock = null; + const update = stmt.get('update'); + if (hasNode(update)) { + updateBlock = builder.enter('loop', _blockId => { + var _a, _b; + lowerExpressionToTemporary(builder, update); + return { + kind: 'goto', + block: testBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_b = (_a = update.node) === null || _a === void 0 ? void 0 : _a.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + }); + } + const bodyBlock = builder.enter('block', _blockId => { + return builder.loop(label, updateBlock !== null && updateBlock !== void 0 ? updateBlock : testBlock.id, continuationBlock.id, () => { + var _a; + const body = stmt.get('body'); + lowerStatement(builder, body); + return { + kind: 'goto', + block: updateBlock !== null && updateBlock !== void 0 ? updateBlock : testBlock.id, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + builder.terminateWithContinuation({ + kind: 'for', + loc: (_s = stmtNode.loc) !== null && _s !== void 0 ? _s : GeneratedSource, + init: initBlock, + test: testBlock.id, + update: updateBlock, + loop: bodyBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + }, testBlock); + const test = stmt.get('test'); + if (test.node == null) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerStatement) Handle empty test in ForStatement`, + category: ErrorCategory.Todo, + loc: (_t = stmt.node.loc) !== null && _t !== void 0 ? _t : null, + suggestions: null, + })); + builder.terminateWithContinuation({ + kind: 'branch', + test: lowerValueToTemporary(builder, { + kind: 'Primitive', + value: true, + loc: (_u = stmt.node.loc) !== null && _u !== void 0 ? _u : GeneratedSource, + }), + consequent: bodyBlock, + alternate: continuationBlock.id, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_v = stmt.node.loc) !== null && _v !== void 0 ? _v : GeneratedSource, + }, continuationBlock); + } + else { + builder.terminateWithContinuation({ + kind: 'branch', + test: lowerExpressionToTemporary(builder, test), + consequent: bodyBlock, + alternate: continuationBlock.id, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_w = stmt.node.loc) !== null && _w !== void 0 ? _w : GeneratedSource, + }, continuationBlock); + } + return; + } + case 'WhileStatement': { + const stmt = stmtPath; + const conditionalBlock = builder.reserve('loop'); + const continuationBlock = builder.reserve('block'); + const loopBlock = builder.enter('block', _blockId => { + return builder.loop(label, conditionalBlock.id, continuationBlock.id, () => { + var _a; + const body = stmt.get('body'); + lowerStatement(builder, body); + return { + kind: 'goto', + block: conditionalBlock.id, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + const loc = (_x = stmt.node.loc) !== null && _x !== void 0 ? _x : GeneratedSource; + builder.terminateWithContinuation({ + kind: 'while', + loc, + test: conditionalBlock.id, + loop: loopBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + }, conditionalBlock); + const test = lowerExpressionToTemporary(builder, stmt.get('test')); + const terminal = { + kind: 'branch', + test, + consequent: loopBlock, + alternate: continuationBlock.id, + fallthrough: conditionalBlock.id, + id: makeInstructionId(0), + loc: (_y = stmt.node.loc) !== null && _y !== void 0 ? _y : GeneratedSource, + }; + builder.terminateWithContinuation(terminal, continuationBlock); + return; + } + case 'LabeledStatement': { + const stmt = stmtPath; + const label = stmt.node.label.name; + const body = stmt.get('body'); + switch (body.node.type) { + case 'ForInStatement': + case 'ForOfStatement': + case 'ForStatement': + case 'WhileStatement': + case 'DoWhileStatement': { + lowerStatement(builder, stmt.get('body'), label); + break; + } + default: { + const continuationBlock = builder.reserve('block'); + const block = builder.enter('block', () => { + var _a; + const body = stmt.get('body'); + builder.label(label, continuationBlock.id, () => { + lowerStatement(builder, body); + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + builder.terminateWithContinuation({ + kind: 'label', + block, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_z = stmt.node.loc) !== null && _z !== void 0 ? _z : GeneratedSource, + }, continuationBlock); + } + } + return; + } + case 'SwitchStatement': { + const stmt = stmtPath; + const continuationBlock = builder.reserve('block'); + let fallthrough = continuationBlock.id; + const cases = []; + let hasDefault = false; + for (let ii = stmt.get('cases').length - 1; ii >= 0; ii--) { + const case_ = stmt.get('cases')[ii]; + const testExpr = case_.get('test'); + if (testExpr.node == null) { + if (hasDefault) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected at most one \`default\` branch in a switch statement, this code should have failed to parse`, + category: ErrorCategory.Syntax, + loc: (_0 = case_.node.loc) !== null && _0 !== void 0 ? _0 : null, + suggestions: null, + })); + break; + } + hasDefault = true; + } + const block = builder.enter('block', _blockId => { + return builder.switch(label, continuationBlock.id, () => { + var _a; + case_ + .get('consequent') + .forEach(consequent => lowerStatement(builder, consequent)); + return { + kind: 'goto', + block: fallthrough, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_a = case_.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + let test = null; + if (hasNode(testExpr)) { + test = lowerReorderableExpression(builder, testExpr); + } + cases.push({ + test, + block, + }); + fallthrough = block; + } + cases.reverse(); + if (!hasDefault) { + cases.push({ test: null, block: continuationBlock.id }); + } + const test = lowerExpressionToTemporary(builder, stmt.get('discriminant')); + builder.terminateWithContinuation({ + kind: 'switch', + test, + cases, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_1 = stmt.node.loc) !== null && _1 !== void 0 ? _1 : GeneratedSource, + }, continuationBlock); + return; + } + case 'VariableDeclaration': { + const stmt = stmtPath; + const nodeKind = stmt.node.kind; + if (nodeKind === 'var') { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerStatement) Handle ${nodeKind} kinds in VariableDeclaration`, + category: ErrorCategory.Todo, + loc: (_2 = stmt.node.loc) !== null && _2 !== void 0 ? _2 : null, + suggestions: null, + })); + } + const kind = nodeKind === 'let' || nodeKind === 'var' + ? InstructionKind.Let + : InstructionKind.Const; + for (const declaration of stmt.get('declarations')) { + const id = declaration.get('id'); + const init = declaration.get('init'); + if (hasNode(init)) { + const value = lowerExpressionToTemporary(builder, init); + lowerAssignment(builder, (_3 = stmt.node.loc) !== null && _3 !== void 0 ? _3 : GeneratedSource, kind, id, value, id.isObjectPattern() || id.isArrayPattern() + ? 'Destructure' + : 'Assignment'); + } + else if (id.isIdentifier()) { + const binding = builder.resolveIdentifier(id); + if (binding.kind !== 'Identifier') { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Could not find binding for declaration.`, + category: ErrorCategory.Invariant, + loc: (_4 = id.node.loc) !== null && _4 !== void 0 ? _4 : null, + suggestions: null, + })); + } + else { + const place = { + effect: Effect.Unknown, + identifier: binding.identifier, + kind: 'Identifier', + reactive: false, + loc: (_5 = id.node.loc) !== null && _5 !== void 0 ? _5 : GeneratedSource, + }; + if (builder.isContextIdentifier(id)) { + if (kind === InstructionKind.Const) { + const declRangeStart = declaration.parentPath.node.start; + builder.recordError(new CompilerErrorDetail({ + reason: `Expect \`const\` declaration not to be reassigned`, + category: ErrorCategory.Syntax, + loc: (_6 = id.node.loc) !== null && _6 !== void 0 ? _6 : null, + suggestions: [ + { + description: 'Change to a `let` declaration', + op: CompilerSuggestionOperation.Replace, + range: [declRangeStart, declRangeStart + 5], + text: 'let', + }, + ], + })); + } + lowerValueToTemporary(builder, { + kind: 'DeclareContext', + lvalue: { + kind: InstructionKind.Let, + place, + }, + loc: (_7 = id.node.loc) !== null && _7 !== void 0 ? _7 : GeneratedSource, + }); + } + else { + const typeAnnotation = id.get('typeAnnotation'); + let type; + if (typeAnnotation.isTSTypeAnnotation()) { + const typePath = typeAnnotation.get('typeAnnotation'); + type = typePath.node; + } + else if (typeAnnotation.isTypeAnnotation()) { + const typePath = typeAnnotation.get('typeAnnotation'); + type = typePath.node; + } + else { + type = null; + } + lowerValueToTemporary(builder, { + kind: 'DeclareLocal', + lvalue: { + kind, + place, + }, + type, + loc: (_8 = id.node.loc) !== null && _8 !== void 0 ? _8 : GeneratedSource, + }); + } + } + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected variable declaration to be an identifier if no initializer was provided`, + description: `Got a \`${id.type}\``, + category: ErrorCategory.Syntax, + loc: (_9 = stmt.node.loc) !== null && _9 !== void 0 ? _9 : null, + suggestions: null, + })); + } + } + return; + } + case 'ExpressionStatement': { + const stmt = stmtPath; + const expression = stmt.get('expression'); + lowerExpressionToTemporary(builder, expression); + return; + } + case 'DoWhileStatement': { + const stmt = stmtPath; + const conditionalBlock = builder.reserve('loop'); + const continuationBlock = builder.reserve('block'); + const loopBlock = builder.enter('block', _loopBlockId => { + return builder.loop(label, conditionalBlock.id, continuationBlock.id, () => { + var _a; + const body = stmt.get('body'); + lowerStatement(builder, body); + return { + kind: 'goto', + block: conditionalBlock.id, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + const loc = (_10 = stmt.node.loc) !== null && _10 !== void 0 ? _10 : GeneratedSource; + builder.terminateWithContinuation({ + kind: 'do-while', + loc, + test: conditionalBlock.id, + loop: loopBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + }, conditionalBlock); + const test = lowerExpressionToTemporary(builder, stmt.get('test')); + const terminal = { + kind: 'branch', + test, + consequent: loopBlock, + alternate: continuationBlock.id, + fallthrough: conditionalBlock.id, + id: makeInstructionId(0), + loc, + }; + builder.terminateWithContinuation(terminal, continuationBlock); + return; + } + case 'FunctionDeclaration': { + const stmt = stmtPath; + stmt.skip(); + CompilerError.invariant(stmt.get('id').type === 'Identifier', { + reason: 'function declarations must have a name', + loc: (_11 = stmt.node.loc) !== null && _11 !== void 0 ? _11 : GeneratedSource, + }); + const id = stmt.get('id'); + const fn = lowerValueToTemporary(builder, lowerFunctionToValue(builder, stmt)); + lowerAssignment(builder, (_12 = stmt.node.loc) !== null && _12 !== void 0 ? _12 : GeneratedSource, InstructionKind.Function, id, fn, 'Assignment'); + return; + } + case 'ForOfStatement': { + const stmt = stmtPath; + const continuationBlock = builder.reserve('block'); + const initBlock = builder.reserve('loop'); + const testBlock = builder.reserve('loop'); + if (stmt.node.await) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerStatement) Handle for-await loops`, + category: ErrorCategory.Todo, + loc: (_13 = stmt.node.loc) !== null && _13 !== void 0 ? _13 : null, + suggestions: null, + })); + return; + } + const loopBlock = builder.enter('block', _blockId => { + return builder.loop(label, initBlock.id, continuationBlock.id, () => { + var _a; + const body = stmt.get('body'); + lowerStatement(builder, body); + return { + kind: 'goto', + block: initBlock.id, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + const loc = (_14 = stmt.node.loc) !== null && _14 !== void 0 ? _14 : GeneratedSource; + const value = lowerExpressionToTemporary(builder, stmt.get('right')); + builder.terminateWithContinuation({ + kind: 'for-of', + loc, + init: initBlock.id, + test: testBlock.id, + loop: loopBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + }, initBlock); + const iterator = lowerValueToTemporary(builder, { + kind: 'GetIterator', + loc: value.loc, + collection: Object.assign({}, value), + }); + builder.terminateWithContinuation({ + id: makeInstructionId(0), + kind: 'goto', + block: testBlock.id, + variant: GotoVariant.Break, + loc: (_15 = stmt.node.loc) !== null && _15 !== void 0 ? _15 : GeneratedSource, + }, testBlock); + const left = stmt.get('left'); + const leftLoc = (_16 = left.node.loc) !== null && _16 !== void 0 ? _16 : GeneratedSource; + let test; + const advanceIterator = lowerValueToTemporary(builder, { + kind: 'IteratorNext', + loc: leftLoc, + iterator: Object.assign({}, iterator), + collection: Object.assign({}, value), + }); + if (left.isVariableDeclaration()) { + const declarations = left.get('declarations'); + CompilerError.invariant(declarations.length === 1, { + reason: `Expected only one declaration in the init of a ForOfStatement, got ${declarations.length}`, + loc: (_17 = left.node.loc) !== null && _17 !== void 0 ? _17 : GeneratedSource, + }); + const id = declarations[0].get('id'); + const assign = lowerAssignment(builder, leftLoc, InstructionKind.Let, id, advanceIterator, 'Assignment'); + test = lowerValueToTemporary(builder, assign); + } + else { + CompilerError.invariant(left.isLVal(), { + reason: 'Expected ForOf init to be a variable declaration or lval', + loc: leftLoc, + }); + const assign = lowerAssignment(builder, leftLoc, InstructionKind.Reassign, left, advanceIterator, 'Assignment'); + test = lowerValueToTemporary(builder, assign); + } + builder.terminateWithContinuation({ + id: makeInstructionId(0), + kind: 'branch', + test, + consequent: loopBlock, + alternate: continuationBlock.id, + loc: (_18 = stmt.node.loc) !== null && _18 !== void 0 ? _18 : GeneratedSource, + fallthrough: continuationBlock.id, + }, continuationBlock); + return; + } + case 'ForInStatement': { + const stmt = stmtPath; + const continuationBlock = builder.reserve('block'); + const initBlock = builder.reserve('loop'); + const loopBlock = builder.enter('block', _blockId => { + return builder.loop(label, initBlock.id, continuationBlock.id, () => { + var _a; + const body = stmt.get('body'); + lowerStatement(builder, body); + return { + kind: 'goto', + block: initBlock.id, + variant: GotoVariant.Continue, + id: makeInstructionId(0), + loc: (_a = body.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + }); + const loc = (_19 = stmt.node.loc) !== null && _19 !== void 0 ? _19 : GeneratedSource; + const value = lowerExpressionToTemporary(builder, stmt.get('right')); + builder.terminateWithContinuation({ + kind: 'for-in', + loc, + init: initBlock.id, + loop: loopBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + }, initBlock); + const left = stmt.get('left'); + const leftLoc = (_20 = left.node.loc) !== null && _20 !== void 0 ? _20 : GeneratedSource; + let test; + const nextPropertyTemp = lowerValueToTemporary(builder, { + kind: 'NextPropertyOf', + loc: leftLoc, + value, + }); + if (left.isVariableDeclaration()) { + const declarations = left.get('declarations'); + CompilerError.invariant(declarations.length === 1, { + reason: `Expected only one declaration in the init of a ForInStatement, got ${declarations.length}`, + loc: (_21 = left.node.loc) !== null && _21 !== void 0 ? _21 : GeneratedSource, + }); + const id = declarations[0].get('id'); + const assign = lowerAssignment(builder, leftLoc, InstructionKind.Let, id, nextPropertyTemp, 'Assignment'); + test = lowerValueToTemporary(builder, assign); + } + else { + CompilerError.invariant(left.isLVal(), { + reason: 'Expected ForIn init to be a variable declaration or lval', + loc: leftLoc, + }); + const assign = lowerAssignment(builder, leftLoc, InstructionKind.Reassign, left, nextPropertyTemp, 'Assignment'); + test = lowerValueToTemporary(builder, assign); + } + builder.terminateWithContinuation({ + id: makeInstructionId(0), + kind: 'branch', + test, + consequent: loopBlock, + alternate: continuationBlock.id, + fallthrough: continuationBlock.id, + loc: (_22 = stmt.node.loc) !== null && _22 !== void 0 ? _22 : GeneratedSource, + }, continuationBlock); + return; + } + case 'DebuggerStatement': { + const stmt = stmtPath; + const loc = (_23 = stmt.node.loc) !== null && _23 !== void 0 ? _23 : GeneratedSource; + builder.push({ + id: makeInstructionId(0), + lvalue: buildTemporaryPlace(builder, loc), + value: { + kind: 'Debugger', + loc, + }, + effects: null, + loc, + }); + return; + } + case 'EmptyStatement': { + return; + } + case 'TryStatement': { + const stmt = stmtPath; + const continuationBlock = builder.reserve('block'); + const handlerPath = stmt.get('handler'); + if (!hasNode(handlerPath)) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerStatement) Handle TryStatement without a catch clause`, + category: ErrorCategory.Todo, + loc: (_24 = stmt.node.loc) !== null && _24 !== void 0 ? _24 : null, + suggestions: null, + })); + return; + } + if (hasNode(stmt.get('finalizer'))) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerStatement) Handle TryStatement with a finalizer ('finally') clause`, + category: ErrorCategory.Todo, + loc: (_25 = stmt.node.loc) !== null && _25 !== void 0 ? _25 : null, + suggestions: null, + })); + } + const handlerBindingPath = handlerPath.get('param'); + let handlerBinding = null; + if (hasNode(handlerBindingPath)) { + const place = { + kind: 'Identifier', + identifier: builder.makeTemporary((_26 = handlerBindingPath.node.loc) !== null && _26 !== void 0 ? _26 : GeneratedSource), + effect: Effect.Unknown, + reactive: false, + loc: (_27 = handlerBindingPath.node.loc) !== null && _27 !== void 0 ? _27 : GeneratedSource, + }; + promoteTemporary(place.identifier); + lowerValueToTemporary(builder, { + kind: 'DeclareLocal', + lvalue: { + kind: InstructionKind.Catch, + place: Object.assign({}, place), + }, + type: null, + loc: (_28 = handlerBindingPath.node.loc) !== null && _28 !== void 0 ? _28 : GeneratedSource, + }); + handlerBinding = { + path: handlerBindingPath, + place, + }; + } + const handler = builder.enter('catch', _blockId => { + var _a, _b; + if (handlerBinding !== null) { + lowerAssignment(builder, (_a = handlerBinding.path.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, InstructionKind.Catch, handlerBinding.path, Object.assign({}, handlerBinding.place), 'Assignment'); + } + lowerStatement(builder, handlerPath.get('body')); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_b = handlerPath.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }; + }); + const block = builder.enter('block', _blockId => { + var _a; + const block = stmt.get('block'); + builder.enterTryCatch(handler, () => { + lowerStatement(builder, block); + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Try, + id: makeInstructionId(0), + loc: (_a = block.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + builder.terminateWithContinuation({ + kind: 'try', + block, + handlerBinding: handlerBinding !== null ? Object.assign({}, handlerBinding.place) : null, + handler, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: (_29 = stmt.node.loc) !== null && _29 !== void 0 ? _29 : GeneratedSource, + }, continuationBlock); + return; + } + case 'WithStatement': { + builder.recordError(new CompilerErrorDetail({ + reason: `JavaScript 'with' syntax is not supported`, + description: `'with' syntax is considered deprecated and removed from JavaScript standards, consider alternatives`, + category: ErrorCategory.UnsupportedSyntax, + loc: (_30 = stmtPath.node.loc) !== null && _30 !== void 0 ? _30 : null, + suggestions: null, + })); + lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + loc: (_31 = stmtPath.node.loc) !== null && _31 !== void 0 ? _31 : GeneratedSource, + node: stmtPath.node, + }); + return; + } + case 'ClassDeclaration': { + builder.recordError(new CompilerErrorDetail({ + reason: 'Inline `class` declarations are not supported', + description: `Move class declarations outside of components/hooks`, + category: ErrorCategory.UnsupportedSyntax, + loc: (_32 = stmtPath.node.loc) !== null && _32 !== void 0 ? _32 : null, + suggestions: null, + })); + lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + loc: (_33 = stmtPath.node.loc) !== null && _33 !== void 0 ? _33 : GeneratedSource, + node: stmtPath.node, + }); + return; + } + case 'EnumDeclaration': + case 'TSEnumDeclaration': { + lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + loc: (_34 = stmtPath.node.loc) !== null && _34 !== void 0 ? _34 : GeneratedSource, + node: stmtPath.node, + }); + return; + } + case 'ExportAllDeclaration': + case 'ExportDefaultDeclaration': + case 'ExportNamedDeclaration': + case 'ImportDeclaration': + case 'TSExportAssignment': + case 'TSImportEqualsDeclaration': { + builder.recordError(new CompilerErrorDetail({ + reason: 'JavaScript `import` and `export` statements may only appear at the top level of a module', + category: ErrorCategory.Syntax, + loc: (_35 = stmtPath.node.loc) !== null && _35 !== void 0 ? _35 : null, + suggestions: null, + })); + lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + loc: (_36 = stmtPath.node.loc) !== null && _36 !== void 0 ? _36 : GeneratedSource, + node: stmtPath.node, + }); + return; + } + case 'TSNamespaceExportDeclaration': { + builder.recordError(new CompilerErrorDetail({ + reason: 'TypeScript `namespace` statements may only appear at the top level of a module', + category: ErrorCategory.Syntax, + loc: (_37 = stmtPath.node.loc) !== null && _37 !== void 0 ? _37 : null, + suggestions: null, + })); + lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + loc: (_38 = stmtPath.node.loc) !== null && _38 !== void 0 ? _38 : GeneratedSource, + node: stmtPath.node, + }); + return; + } + case 'DeclareClass': + case 'DeclareExportAllDeclaration': + case 'DeclareExportDeclaration': + case 'DeclareFunction': + case 'DeclareInterface': + case 'DeclareModule': + case 'DeclareModuleExports': + case 'DeclareOpaqueType': + case 'DeclareTypeAlias': + case 'DeclareVariable': + case 'InterfaceDeclaration': + case 'OpaqueType': + case 'TSDeclareFunction': + case 'TSInterfaceDeclaration': + case 'TSModuleDeclaration': + case 'TSTypeAliasDeclaration': + case 'TypeAlias': { + return; + } + default: { + return assertExhaustive$1(stmtNode, `Unsupported statement kind '${stmtNode.type}'`); + } + } +} +function lowerObjectMethod(builder, property) { + var _a; + const loc = (_a = property.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const loweredFunc = lowerFunction(builder, property); + return { + kind: 'ObjectMethod', + loc, + loweredFunc, + }; +} +function lowerObjectPropertyKey(builder, property) { + var _a; + const key = property.get('key'); + if (key.isStringLiteral()) { + return { + kind: 'string', + name: key.node.value, + }; + } + else if (property.node.computed && key.isExpression()) { + const place = lowerExpressionToTemporary(builder, key); + return { + kind: 'computed', + name: place, + }; + } + else if (key.isIdentifier()) { + return { + kind: 'identifier', + name: key.node.name, + }; + } + else if (key.isNumericLiteral()) { + return { + kind: 'identifier', + name: String(key.node.value), + }; + } + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Expected Identifier, got ${key.type} key in ObjectExpression`, + category: ErrorCategory.Todo, + loc: (_a = key.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + return null; +} +function lowerExpression(builder, exprPath) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23; + const exprNode = exprPath.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + switch (exprNode.type) { + case 'Identifier': { + const expr = exprPath; + const place = lowerIdentifier(builder, expr); + return { + kind: getLoadKind(builder, expr), + place, + loc: exprLoc, + }; + } + case 'NullLiteral': { + return { + kind: 'Primitive', + value: null, + loc: exprLoc, + }; + } + case 'BooleanLiteral': + case 'NumericLiteral': + case 'StringLiteral': { + const expr = exprPath; + const value = expr.node.value; + return { + kind: 'Primitive', + value, + loc: exprLoc, + }; + } + case 'ObjectExpression': { + const expr = exprPath; + const propertyPaths = expr.get('properties'); + const properties = []; + for (const propertyPath of propertyPaths) { + if (propertyPath.isObjectProperty()) { + const loweredKey = lowerObjectPropertyKey(builder, propertyPath); + if (!loweredKey) { + continue; + } + const valuePath = propertyPath.get('value'); + if (!valuePath.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${valuePath.type} values in ObjectExpression`, + category: ErrorCategory.Todo, + loc: (_b = valuePath.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + continue; + } + const value = lowerExpressionToTemporary(builder, valuePath); + properties.push({ + kind: 'ObjectProperty', + type: 'property', + place: value, + key: loweredKey, + }); + } + else if (propertyPath.isSpreadElement()) { + const place = lowerExpressionToTemporary(builder, propertyPath.get('argument')); + properties.push({ + kind: 'Spread', + place, + }); + } + else if (propertyPath.isObjectMethod()) { + if (propertyPath.node.kind !== 'method') { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${propertyPath.node.kind} functions in ObjectExpression`, + category: ErrorCategory.Todo, + loc: (_c = propertyPath.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + continue; + } + const method = lowerObjectMethod(builder, propertyPath); + const place = lowerValueToTemporary(builder, method); + const loweredKey = lowerObjectPropertyKey(builder, propertyPath); + if (!loweredKey) { + continue; + } + properties.push({ + kind: 'ObjectProperty', + type: 'method', + place, + key: loweredKey, + }); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${propertyPath.type} properties in ObjectExpression`, + category: ErrorCategory.Todo, + loc: (_d = propertyPath.node.loc) !== null && _d !== void 0 ? _d : null, + suggestions: null, + })); + continue; + } + } + return { + kind: 'ObjectExpression', + properties, + loc: exprLoc, + }; + } + case 'ArrayExpression': { + const expr = exprPath; + let elements = []; + for (const element of expr.get('elements')) { + if (element.node == null) { + elements.push({ + kind: 'Hole', + }); + continue; + } + else if (element.isExpression()) { + elements.push(lowerExpressionToTemporary(builder, element)); + } + else if (element.isSpreadElement()) { + const place = lowerExpressionToTemporary(builder, element.get('argument')); + elements.push({ kind: 'Spread', place }); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${element.type} elements in ArrayExpression`, + category: ErrorCategory.Todo, + loc: (_e = element.node.loc) !== null && _e !== void 0 ? _e : null, + suggestions: null, + })); + continue; + } + } + return { + kind: 'ArrayExpression', + elements, + loc: exprLoc, + }; + } + case 'NewExpression': { + const expr = exprPath; + const calleePath = expr.get('callee'); + if (!calleePath.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected an expression as the \`new\` expression receiver (v8 intrinsics are not supported)`, + description: `Got a \`${calleePath.node.type}\``, + category: ErrorCategory.Syntax, + loc: (_f = calleePath.node.loc) !== null && _f !== void 0 ? _f : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const callee = lowerExpressionToTemporary(builder, calleePath); + const args = lowerArguments(builder, expr.get('arguments')); + return { + kind: 'NewExpression', + callee, + args, + loc: exprLoc, + }; + } + case 'OptionalCallExpression': { + const expr = exprPath; + return lowerOptionalCallExpression(builder, expr, null); + } + case 'CallExpression': { + const expr = exprPath; + const calleePath = expr.get('callee'); + if (!calleePath.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected Expression, got ${calleePath.type} in CallExpression (v8 intrinsics not supported). This error is likely caused by a bug in React Compiler. Please file an issue`, + category: ErrorCategory.Todo, + loc: (_g = calleePath.node.loc) !== null && _g !== void 0 ? _g : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + if (calleePath.isMemberExpression()) { + const memberExpr = lowerMemberExpression(builder, calleePath); + const propertyPlace = lowerValueToTemporary(builder, memberExpr.value); + const args = lowerArguments(builder, expr.get('arguments')); + return { + kind: 'MethodCall', + receiver: memberExpr.object, + property: Object.assign({}, propertyPlace), + args, + loc: exprLoc, + }; + } + else { + const callee = lowerExpressionToTemporary(builder, calleePath); + const args = lowerArguments(builder, expr.get('arguments')); + return { + kind: 'CallExpression', + callee, + args, + loc: exprLoc, + }; + } + } + case 'BinaryExpression': { + const expr = exprPath; + const leftPath = expr.get('left'); + if (!leftPath.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Expected Expression, got ${leftPath.type} lval in BinaryExpression`, + category: ErrorCategory.Todo, + loc: (_h = leftPath.node.loc) !== null && _h !== void 0 ? _h : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const left = lowerExpressionToTemporary(builder, leftPath); + const right = lowerExpressionToTemporary(builder, expr.get('right')); + const operator = expr.node.operator; + if (operator === '|>') { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Pipe operator not supported`, + category: ErrorCategory.Todo, + loc: (_j = leftPath.node.loc) !== null && _j !== void 0 ? _j : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + return { + kind: 'BinaryExpression', + operator, + left, + right, + loc: exprLoc, + }; + } + case 'SequenceExpression': { + const expr = exprPath; + const exprLoc = (_k = expr.node.loc) !== null && _k !== void 0 ? _k : GeneratedSource; + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const place = buildTemporaryPlace(builder, exprLoc); + const sequenceBlock = builder.enter('sequence', _ => { + var _a; + let last = null; + for (const item of expr.get('expressions')) { + last = lowerExpressionToTemporary(builder, item); + } + if (last === null) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected sequence expression to have at least one expression`, + category: ErrorCategory.Syntax, + loc: (_a = expr.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + } + else { + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: last, + type: null, + loc: exprLoc, + }); + } + return { + kind: 'goto', + id: makeInstructionId(0), + block: continuationBlock.id, + loc: exprLoc, + variant: GotoVariant.Break, + }; + }); + builder.terminateWithContinuation({ + kind: 'sequence', + block: sequenceBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: exprLoc, + }, continuationBlock); + return { kind: 'LoadLocal', place, loc: place.loc }; + } + case 'ConditionalExpression': { + const expr = exprPath; + const exprLoc = (_l = expr.node.loc) !== null && _l !== void 0 ? _l : GeneratedSource; + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const testBlock = builder.reserve('value'); + const place = buildTemporaryPlace(builder, exprLoc); + const consequentBlock = builder.enter('value', _blockId => { + var _a; + const consequentPath = expr.get('consequent'); + const consequent = lowerExpressionToTemporary(builder, consequentPath); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: consequent, + type: null, + loc: exprLoc, + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_a = consequentPath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + const alternateBlock = builder.enter('value', _blockId => { + var _a; + const alternatePath = expr.get('alternate'); + const alternate = lowerExpressionToTemporary(builder, alternatePath); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: alternate, + type: null, + loc: exprLoc, + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: (_a = alternatePath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }; + }); + builder.terminateWithContinuation({ + kind: 'ternary', + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + test: testBlock.id, + loc: exprLoc, + }, testBlock); + const testPlace = lowerExpressionToTemporary(builder, expr.get('test')); + builder.terminateWithContinuation({ + kind: 'branch', + test: Object.assign({}, testPlace), + consequent: consequentBlock, + alternate: alternateBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: exprLoc, + }, continuationBlock); + return { kind: 'LoadLocal', place, loc: place.loc }; + } + case 'LogicalExpression': { + const expr = exprPath; + const exprLoc = (_m = expr.node.loc) !== null && _m !== void 0 ? _m : GeneratedSource; + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const testBlock = builder.reserve('value'); + const place = buildTemporaryPlace(builder, exprLoc); + const leftPlace = buildTemporaryPlace(builder, (_o = expr.get('left').node.loc) !== null && _o !== void 0 ? _o : GeneratedSource); + const consequent = builder.enter('value', () => { + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, leftPlace), + type: null, + loc: leftPlace.loc, + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: leftPlace.loc, + }; + }); + const alternate = builder.enter('value', () => { + const right = lowerExpressionToTemporary(builder, expr.get('right')); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, right), + type: null, + loc: right.loc, + }); + return { + kind: 'goto', + block: continuationBlock.id, + variant: GotoVariant.Break, + id: makeInstructionId(0), + loc: right.loc, + }; + }); + builder.terminateWithContinuation({ + kind: 'logical', + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + test: testBlock.id, + operator: expr.node.operator, + loc: exprLoc, + }, testBlock); + const leftValue = lowerExpressionToTemporary(builder, expr.get('left')); + builder.push({ + id: makeInstructionId(0), + lvalue: Object.assign({}, leftPlace), + value: { + kind: 'LoadLocal', + place: leftValue, + loc: exprLoc, + }, + effects: null, + loc: exprLoc, + }); + builder.terminateWithContinuation({ + kind: 'branch', + test: Object.assign({}, leftPlace), + consequent, + alternate, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc: exprLoc, + }, continuationBlock); + return { kind: 'LoadLocal', place, loc: place.loc }; + } + case 'AssignmentExpression': { + const expr = exprPath; + const operator = expr.node.operator; + if (operator === '=') { + const left = expr.get('left'); + if (left.isLVal()) { + return lowerAssignment(builder, (_p = left.node.loc) !== null && _p !== void 0 ? _p : GeneratedSource, InstructionKind.Reassign, left, lowerExpressionToTemporary(builder, expr.get('right')), left.isArrayPattern() || left.isObjectPattern() + ? 'Destructure' + : 'Assignment'); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Unsupported syntax on the left side of an AssignmentExpression`, + description: `Expected an LVal, got: ${left.type}`, + category: ErrorCategory.Todo, + loc: (_q = left.node.loc) !== null && _q !== void 0 ? _q : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + } + const operators = { + '+=': '+', + '-=': '-', + '/=': '/', + '%=': '%', + '*=': '*', + '**=': '**', + '&=': '&', + '|=': '|', + '>>=': '>>', + '>>>=': '>>>', + '<<=': '<<', + '^=': '^', + }; + const binaryOperator = operators[operator]; + if (binaryOperator == null) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${operator} operators in AssignmentExpression`, + category: ErrorCategory.Todo, + loc: (_r = expr.node.loc) !== null && _r !== void 0 ? _r : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const left = expr.get('left'); + const leftNode = left.node; + switch (leftNode.type) { + case 'Identifier': { + const leftExpr = left; + const leftPlace = lowerExpressionToTemporary(builder, leftExpr); + const right = lowerExpressionToTemporary(builder, expr.get('right')); + const binaryPlace = lowerValueToTemporary(builder, { + kind: 'BinaryExpression', + operator: binaryOperator, + left: leftPlace, + right, + loc: exprLoc, + }); + const binding = builder.resolveIdentifier(leftExpr); + if (binding.kind === 'Identifier') { + const identifier = lowerIdentifier(builder, leftExpr); + const kind = getStoreKind(builder, leftExpr); + if (kind === 'StoreLocal') { + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { + place: Object.assign({}, identifier), + kind: InstructionKind.Reassign, + }, + value: Object.assign({}, binaryPlace), + type: null, + loc: exprLoc, + }); + return { kind: 'LoadLocal', place: identifier, loc: exprLoc }; + } + else { + lowerValueToTemporary(builder, { + kind: 'StoreContext', + lvalue: { + place: Object.assign({}, identifier), + kind: InstructionKind.Reassign, + }, + value: Object.assign({}, binaryPlace), + loc: exprLoc, + }); + return { kind: 'LoadContext', place: identifier, loc: exprLoc }; + } + } + else { + const temporary = lowerValueToTemporary(builder, { + kind: 'StoreGlobal', + name: leftExpr.node.name, + value: Object.assign({}, binaryPlace), + loc: exprLoc, + }); + return { kind: 'LoadLocal', place: temporary, loc: temporary.loc }; + } + } + case 'MemberExpression': { + const leftExpr = left; + const { object, property, value } = lowerMemberExpression(builder, leftExpr); + const previousValuePlace = lowerValueToTemporary(builder, value); + const newValuePlace = lowerValueToTemporary(builder, { + kind: 'BinaryExpression', + operator: binaryOperator, + left: Object.assign({}, previousValuePlace), + right: lowerExpressionToTemporary(builder, expr.get('right')), + loc: (_s = leftExpr.node.loc) !== null && _s !== void 0 ? _s : GeneratedSource, + }); + if (typeof property === 'string' || typeof property === 'number') { + return { + kind: 'PropertyStore', + object: Object.assign({}, object), + property: makePropertyLiteral(property), + value: Object.assign({}, newValuePlace), + loc: (_t = leftExpr.node.loc) !== null && _t !== void 0 ? _t : GeneratedSource, + }; + } + else { + return { + kind: 'ComputedStore', + object: Object.assign({}, object), + property: Object.assign({}, property), + value: Object.assign({}, newValuePlace), + loc: (_u = leftExpr.node.loc) !== null && _u !== void 0 ? _u : GeneratedSource, + }; + } + } + default: { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Expected Identifier or MemberExpression, got ${expr.type} lval in AssignmentExpression`, + category: ErrorCategory.Todo, + loc: (_v = expr.node.loc) !== null && _v !== void 0 ? _v : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + } + } + case 'OptionalMemberExpression': { + const expr = exprPath; + const { value } = lowerOptionalMemberExpression(builder, expr, null); + return { kind: 'LoadLocal', place: value, loc: value.loc }; + } + case 'MemberExpression': { + const expr = exprPath; + const { value } = lowerMemberExpression(builder, expr); + const place = lowerValueToTemporary(builder, value); + return { kind: 'LoadLocal', place, loc: place.loc }; + } + case 'JSXElement': { + const expr = exprPath; + const opening = expr.get('openingElement'); + const openingLoc = (_w = opening.node.loc) !== null && _w !== void 0 ? _w : GeneratedSource; + const tag = lowerJsxElementName(builder, opening.get('name')); + const props = []; + for (const attribute of opening.get('attributes')) { + if (attribute.isJSXSpreadAttribute()) { + const argument = lowerExpressionToTemporary(builder, attribute.get('argument')); + props.push({ kind: 'JsxSpreadAttribute', argument }); + continue; + } + if (!attribute.isJSXAttribute()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${attribute.type} attributes in JSXElement`, + category: ErrorCategory.Todo, + loc: (_x = attribute.node.loc) !== null && _x !== void 0 ? _x : null, + suggestions: null, + })); + continue; + } + const namePath = attribute.get('name'); + let propName; + if (namePath.isJSXIdentifier()) { + propName = namePath.node.name; + if (propName.indexOf(':') !== -1) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Unexpected colon in attribute name \`${propName}\``, + category: ErrorCategory.Todo, + loc: (_y = namePath.node.loc) !== null && _y !== void 0 ? _y : null, + suggestions: null, + })); + } + } + else { + CompilerError.invariant(namePath.isJSXNamespacedName(), { + reason: 'Refinement', + loc: (_z = namePath.node.loc) !== null && _z !== void 0 ? _z : GeneratedSource, + }); + const namespace = namePath.node.namespace.name; + const name = namePath.node.name.name; + propName = `${namespace}:${name}`; + } + const valueExpr = attribute.get('value'); + let value; + if (valueExpr.isJSXElement() || valueExpr.isStringLiteral()) { + value = lowerExpressionToTemporary(builder, valueExpr); + } + else if (valueExpr.type == null) { + value = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: true, + loc: (_0 = attribute.node.loc) !== null && _0 !== void 0 ? _0 : GeneratedSource, + }); + } + else { + if (!valueExpr.isJSXExpressionContainer()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${valueExpr.type} attribute values in JSXElement`, + category: ErrorCategory.Todo, + loc: (_2 = (_1 = valueExpr.node) === null || _1 === void 0 ? void 0 : _1.loc) !== null && _2 !== void 0 ? _2 : null, + suggestions: null, + })); + continue; + } + const expression = valueExpr.get('expression'); + if (!expression.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${expression.type} expressions in JSXExpressionContainer within JSXElement`, + category: ErrorCategory.Todo, + loc: (_3 = valueExpr.node.loc) !== null && _3 !== void 0 ? _3 : null, + suggestions: null, + })); + continue; + } + value = lowerExpressionToTemporary(builder, expression); + } + props.push({ kind: 'JsxAttribute', name: propName, place: value }); + } + const isFbt = tag.kind === 'BuiltinTag' && (tag.name === 'fbt' || tag.name === 'fbs'); + if (isFbt) { + const tagName = tag.name; + const openingIdentifier = opening.get('name'); + const tagIdentifier = openingIdentifier.isJSXIdentifier() + ? builder.resolveIdentifier(openingIdentifier) + : null; + if (tagIdentifier != null) { + CompilerError.invariant(tagIdentifier.kind !== 'Identifier', { + reason: `<${tagName}> tags should be module-level imports`, + loc: (_4 = openingIdentifier.node.loc) !== null && _4 !== void 0 ? _4 : GeneratedSource, + }); + } + const fbtLocations = { + enum: new Array(), + plural: new Array(), + pronoun: new Array(), + }; + expr.traverse({ + JSXClosingElement(path) { + path.skip(); + }, + JSXNamespacedName(path) { + var _a, _b, _c; + if (path.node.namespace.name === tagName) { + switch (path.node.name.name) { + case 'enum': + fbtLocations.enum.push((_a = path.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource); + break; + case 'plural': + fbtLocations.plural.push((_b = path.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource); + break; + case 'pronoun': + fbtLocations.pronoun.push((_c = path.node.loc) !== null && _c !== void 0 ? _c : GeneratedSource); + break; + } + } + }, + }); + for (const [name, locations] of Object.entries(fbtLocations)) { + if (locations.length > 1) { + builder.recordError(new CompilerDiagnostic({ + category: ErrorCategory.Todo, + reason: 'Support duplicate fbt tags', + description: `Support \`<${tagName}>\` tags with multiple \`<${tagName}:${name}>\` values`, + details: locations.map(loc => { + return { + kind: 'error', + message: `Multiple \`<${tagName}:${name}>\` tags found`, + loc, + }; + }), + })); + } + } + } + isFbt && builder.fbtDepth++; + const children = expr + .get('children') + .map(child => lowerJsxElement(builder, child)) + .filter(notNull); + isFbt && builder.fbtDepth--; + return { + kind: 'JsxExpression', + tag, + props, + children: children.length === 0 ? null : children, + loc: exprLoc, + openingLoc: openingLoc, + closingLoc: (_6 = (_5 = expr.get('closingElement').node) === null || _5 === void 0 ? void 0 : _5.loc) !== null && _6 !== void 0 ? _6 : GeneratedSource, + }; + } + case 'JSXFragment': { + const expr = exprPath; + const children = expr + .get('children') + .map(child => lowerJsxElement(builder, child)) + .filter(notNull); + return { + kind: 'JsxFragment', + children, + loc: exprLoc, + }; + } + case 'ArrowFunctionExpression': + case 'FunctionExpression': { + const expr = exprPath; + return lowerFunctionToValue(builder, expr); + } + case 'TaggedTemplateExpression': { + const expr = exprPath; + if (expr.get('quasi').get('expressions').length !== 0) { + builder.recordError(new CompilerErrorDetail({ + reason: '(BuildHIR::lowerExpression) Handle tagged template with interpolations', + category: ErrorCategory.Todo, + loc: (_7 = exprPath.node.loc) !== null && _7 !== void 0 ? _7 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + CompilerError.invariant(expr.get('quasi').get('quasis').length == 1, { + reason: "there should be only one quasi as we don't support interpolations yet", + loc: (_8 = expr.node.loc) !== null && _8 !== void 0 ? _8 : GeneratedSource, + }); + const value = expr.get('quasi').get('quasis').at(0).node.value; + if (value.raw !== value.cooked) { + builder.recordError(new CompilerErrorDetail({ + reason: '(BuildHIR::lowerExpression) Handle tagged template where cooked value is different from raw value', + category: ErrorCategory.Todo, + loc: (_9 = exprPath.node.loc) !== null && _9 !== void 0 ? _9 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + return { + kind: 'TaggedTemplateExpression', + tag: lowerExpressionToTemporary(builder, expr.get('tag')), + value, + loc: exprLoc, + }; + } + case 'TemplateLiteral': { + const expr = exprPath; + const subexprs = expr.get('expressions'); + const quasis = expr.get('quasis'); + if (subexprs.length !== quasis.length - 1) { + builder.recordError(new CompilerErrorDetail({ + reason: `Unexpected quasi and subexpression lengths in template literal`, + category: ErrorCategory.Syntax, + loc: (_10 = exprPath.node.loc) !== null && _10 !== void 0 ? _10 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + if (subexprs.some(e => !e.isExpression())) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle TSType in TemplateLiteral.`, + category: ErrorCategory.Todo, + loc: (_11 = exprPath.node.loc) !== null && _11 !== void 0 ? _11 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const subexprPlaces = subexprs.map(e => lowerExpressionToTemporary(builder, e)); + return { + kind: 'TemplateLiteral', + subexprs: subexprPlaces, + quasis: expr.get('quasis').map(q => q.node.value), + loc: exprLoc, + }; + } + case 'UnaryExpression': { + let expr = exprPath; + if (expr.node.operator === 'delete') { + const argument = expr.get('argument'); + if (argument.isMemberExpression()) { + const { object, property } = lowerMemberExpression(builder, argument); + if (typeof property === 'string' || typeof property === 'number') { + return { + kind: 'PropertyDelete', + object, + property: makePropertyLiteral(property), + loc: exprLoc, + }; + } + else { + return { + kind: 'ComputedDelete', + object, + property, + loc: exprLoc, + }; + } + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `Only object properties can be deleted`, + category: ErrorCategory.Syntax, + loc: (_12 = expr.node.loc) !== null && _12 !== void 0 ? _12 : null, + suggestions: [ + { + description: 'Remove this line', + range: [expr.node.start, expr.node.end], + op: CompilerSuggestionOperation.Remove, + }, + ], + })); + return { kind: 'UnsupportedNode', node: expr.node, loc: exprLoc }; + } + } + else if (expr.node.operator === 'throw') { + builder.recordError(new CompilerErrorDetail({ + reason: `Throw expressions are not supported`, + category: ErrorCategory.Syntax, + loc: (_13 = expr.node.loc) !== null && _13 !== void 0 ? _13 : null, + suggestions: [ + { + description: 'Remove this line', + range: [expr.node.start, expr.node.end], + op: CompilerSuggestionOperation.Remove, + }, + ], + })); + return { kind: 'UnsupportedNode', node: expr.node, loc: exprLoc }; + } + else { + return { + kind: 'UnaryExpression', + operator: expr.node.operator, + value: lowerExpressionToTemporary(builder, expr.get('argument')), + loc: exprLoc, + }; + } + } + case 'AwaitExpression': { + let expr = exprPath; + return { + kind: 'Await', + value: lowerExpressionToTemporary(builder, expr.get('argument')), + loc: exprLoc, + }; + } + case 'TypeCastExpression': { + let expr = exprPath; + const typeAnnotation = expr.get('typeAnnotation').get('typeAnnotation'); + return { + kind: 'TypeCastExpression', + value: lowerExpressionToTemporary(builder, expr.get('expression')), + typeAnnotation: typeAnnotation.node, + typeAnnotationKind: 'cast', + type: lowerType(typeAnnotation.node), + loc: exprLoc, + }; + } + case 'TSSatisfiesExpression': { + let expr = exprPath; + const typeAnnotation = expr.get('typeAnnotation'); + return { + kind: 'TypeCastExpression', + value: lowerExpressionToTemporary(builder, expr.get('expression')), + typeAnnotation: typeAnnotation.node, + typeAnnotationKind: 'satisfies', + type: lowerType(typeAnnotation.node), + loc: exprLoc, + }; + } + case 'TSAsExpression': { + let expr = exprPath; + const typeAnnotation = expr.get('typeAnnotation'); + return { + kind: 'TypeCastExpression', + value: lowerExpressionToTemporary(builder, expr.get('expression')), + typeAnnotation: typeAnnotation.node, + typeAnnotationKind: 'as', + type: lowerType(typeAnnotation.node), + loc: exprLoc, + }; + } + case 'UpdateExpression': { + let expr = exprPath; + const argument = expr.get('argument'); + if (argument.isMemberExpression()) { + const binaryOperator = expr.node.operator === '++' ? '+' : '-'; + const leftExpr = argument; + const { object, property, value } = lowerMemberExpression(builder, leftExpr); + const previousValuePlace = lowerValueToTemporary(builder, value); + const updatedValue = lowerValueToTemporary(builder, { + kind: 'BinaryExpression', + operator: binaryOperator, + left: Object.assign({}, previousValuePlace), + right: lowerValueToTemporary(builder, { + kind: 'Primitive', + value: 1, + loc: GeneratedSource, + }), + loc: (_14 = leftExpr.node.loc) !== null && _14 !== void 0 ? _14 : GeneratedSource, + }); + let newValuePlace; + if (typeof property === 'string' || typeof property === 'number') { + newValuePlace = lowerValueToTemporary(builder, { + kind: 'PropertyStore', + object: Object.assign({}, object), + property: makePropertyLiteral(property), + value: Object.assign({}, updatedValue), + loc: (_15 = leftExpr.node.loc) !== null && _15 !== void 0 ? _15 : GeneratedSource, + }); + } + else { + newValuePlace = lowerValueToTemporary(builder, { + kind: 'ComputedStore', + object: Object.assign({}, object), + property: Object.assign({}, property), + value: Object.assign({}, updatedValue), + loc: (_16 = leftExpr.node.loc) !== null && _16 !== void 0 ? _16 : GeneratedSource, + }); + } + return { + kind: 'LoadLocal', + place: expr.node.prefix + ? Object.assign({}, newValuePlace) : Object.assign({}, previousValuePlace), + loc: exprLoc, + }; + } + if (!argument.isIdentifier()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle UpdateExpression with ${argument.type} argument`, + category: ErrorCategory.Todo, + loc: (_17 = exprPath.node.loc) !== null && _17 !== void 0 ? _17 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + else if (builder.isContextIdentifier(argument)) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle UpdateExpression to variables captured within lambdas.`, + category: ErrorCategory.Todo, + loc: (_18 = exprPath.node.loc) !== null && _18 !== void 0 ? _18 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const lvalue = lowerIdentifierForAssignment(builder, (_19 = argument.node.loc) !== null && _19 !== void 0 ? _19 : GeneratedSource, InstructionKind.Reassign, argument); + if (lvalue === null) { + if (!builder.environment.hasErrors()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Found an invalid UpdateExpression without a previously reported error`, + category: ErrorCategory.Invariant, + loc: exprLoc, + suggestions: null, + })); + } + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + else if (lvalue.kind === 'Global') { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Support UpdateExpression where argument is a global`, + category: ErrorCategory.Todo, + loc: exprLoc, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + const value = lowerIdentifier(builder, argument); + if (expr.node.prefix) { + return { + kind: 'PrefixUpdate', + lvalue, + operation: expr.node.operator, + value, + loc: exprLoc, + }; + } + else { + return { + kind: 'PostfixUpdate', + lvalue, + operation: expr.node.operator, + value, + loc: exprLoc, + }; + } + } + case 'RegExpLiteral': { + let expr = exprPath; + return { + kind: 'RegExpLiteral', + pattern: expr.node.pattern, + flags: expr.node.flags, + loc: (_20 = expr.node.loc) !== null && _20 !== void 0 ? _20 : GeneratedSource, + }; + } + case 'TSInstantiationExpression': + case 'TSNonNullExpression': { + let expr = exprPath; + return lowerExpression(builder, expr.get('expression')); + } + case 'MetaProperty': { + let expr = exprPath; + if (expr.node.meta.name === 'import' && + expr.node.property.name === 'meta') { + return { + kind: 'MetaProperty', + meta: expr.node.meta.name, + property: expr.node.property.name, + loc: (_21 = expr.node.loc) !== null && _21 !== void 0 ? _21 : GeneratedSource, + }; + } + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle MetaProperty expressions other than import.meta`, + category: ErrorCategory.Todo, + loc: (_22 = exprPath.node.loc) !== null && _22 !== void 0 ? _22 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + default: { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${exprPath.type} expressions`, + category: ErrorCategory.Todo, + loc: (_23 = exprPath.node.loc) !== null && _23 !== void 0 ? _23 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }; + } + } +} +function lowerOptionalMemberExpression(builder, expr, parentAlternate) { + var _a; + const optional = expr.node.optional; + const loc = (_a = expr.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const place = buildTemporaryPlace(builder, loc); + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const consequent = builder.reserve('value'); + const alternate = parentAlternate !== null + ? parentAlternate + : builder.enter('value', () => { + const temp = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc, + }); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, temp), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + let object = null; + const testBlock = builder.enter('value', () => { + const objectPath = expr.get('object'); + if (objectPath.isOptionalMemberExpression()) { + const { value } = lowerOptionalMemberExpression(builder, objectPath, alternate); + object = value; + } + else if (objectPath.isOptionalCallExpression()) { + const value = lowerOptionalCallExpression(builder, objectPath, alternate); + object = lowerValueToTemporary(builder, value); + } + else { + object = lowerExpressionToTemporary(builder, objectPath); + } + return { + kind: 'branch', + test: Object.assign({}, object), + consequent: consequent.id, + alternate, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + CompilerError.invariant(object !== null, { + reason: 'Satisfy type checker', + loc: GeneratedSource, + }); + builder.enterReserved(consequent, () => { + const { value } = lowerMemberExpression(builder, expr, object); + const temp = lowerValueToTemporary(builder, value); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, temp), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + builder.terminateWithContinuation({ + kind: 'optional', + optional, + test: testBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }, continuationBlock); + return { object, value: place }; +} +function lowerOptionalCallExpression(builder, expr, parentAlternate) { + var _a; + const optional = expr.node.optional; + const calleePath = expr.get('callee'); + const loc = (_a = expr.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const place = buildTemporaryPlace(builder, loc); + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const consequent = builder.reserve('value'); + const alternate = parentAlternate !== null + ? parentAlternate + : builder.enter('value', () => { + const temp = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc, + }); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, temp), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + let callee; + const testBlock = builder.enter('value', () => { + if (calleePath.isOptionalCallExpression()) { + const value = lowerOptionalCallExpression(builder, calleePath, alternate); + const valuePlace = lowerValueToTemporary(builder, value); + callee = { + kind: 'CallExpression', + callee: valuePlace, + }; + } + else if (calleePath.isOptionalMemberExpression()) { + const { object, value } = lowerOptionalMemberExpression(builder, calleePath, alternate); + callee = { + kind: 'MethodCall', + receiver: object, + property: value, + }; + } + else if (calleePath.isMemberExpression()) { + const memberExpr = lowerMemberExpression(builder, calleePath); + const propertyPlace = lowerValueToTemporary(builder, memberExpr.value); + callee = { + kind: 'MethodCall', + receiver: memberExpr.object, + property: propertyPlace, + }; + } + else { + callee = { + kind: 'CallExpression', + callee: lowerExpressionToTemporary(builder, calleePath), + }; + } + const testPlace = callee.kind === 'CallExpression' ? callee.callee : callee.property; + return { + kind: 'branch', + test: Object.assign({}, testPlace), + consequent: consequent.id, + alternate, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + builder.enterReserved(consequent, () => { + const args = lowerArguments(builder, expr.get('arguments')); + const temp = buildTemporaryPlace(builder, loc); + if (callee.kind === 'CallExpression') { + builder.push({ + id: makeInstructionId(0), + lvalue: Object.assign({}, temp), + value: { + kind: 'CallExpression', + callee: Object.assign({}, callee.callee), + args, + loc, + }, + effects: null, + loc, + }); + } + else { + builder.push({ + id: makeInstructionId(0), + lvalue: Object.assign({}, temp), + value: { + kind: 'MethodCall', + receiver: Object.assign({}, callee.receiver), + property: Object.assign({}, callee.property), + args, + loc, + }, + effects: null, + loc, + }); + } + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, place) }, + value: Object.assign({}, temp), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + builder.terminateWithContinuation({ + kind: 'optional', + optional, + test: testBlock, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }, continuationBlock); + return { kind: 'LoadLocal', place, loc: place.loc }; +} +function lowerReorderableExpression(builder, expr) { + var _a; + if (!isReorderableExpression(builder, expr, true)) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::node.lowerReorderableExpression) Expression type \`${expr.type}\` cannot be safely reordered`, + category: ErrorCategory.Todo, + loc: (_a = expr.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + } + return lowerExpressionToTemporary(builder, expr); +} +function isReorderableExpression(builder, expr, allowLocalIdentifiers) { + switch (expr.node.type) { + case 'Identifier': { + const binding = builder.resolveIdentifier(expr); + if (binding.kind === 'Identifier') { + return allowLocalIdentifiers; + } + else { + return true; + } + } + case 'TSInstantiationExpression': { + const innerExpr = expr.get('expression'); + return isReorderableExpression(builder, innerExpr, allowLocalIdentifiers); + } + case 'RegExpLiteral': + case 'StringLiteral': + case 'NumericLiteral': + case 'NullLiteral': + case 'BooleanLiteral': + case 'BigIntLiteral': { + return true; + } + case 'UnaryExpression': { + const unary = expr; + switch (expr.node.operator) { + case '!': + case '+': + case '-': { + return isReorderableExpression(builder, unary.get('argument'), allowLocalIdentifiers); + } + default: { + return false; + } + } + } + case 'TSAsExpression': + case 'TSNonNullExpression': + case 'TypeCastExpression': { + return isReorderableExpression(builder, expr.get('expression'), allowLocalIdentifiers); + } + case 'LogicalExpression': { + const logical = expr; + return (isReorderableExpression(builder, logical.get('left'), allowLocalIdentifiers) && + isReorderableExpression(builder, logical.get('right'), allowLocalIdentifiers)); + } + case 'ConditionalExpression': { + const conditional = expr; + return (isReorderableExpression(builder, conditional.get('test'), allowLocalIdentifiers) && + isReorderableExpression(builder, conditional.get('consequent'), allowLocalIdentifiers) && + isReorderableExpression(builder, conditional.get('alternate'), allowLocalIdentifiers)); + } + case 'ArrayExpression': { + return expr + .get('elements') + .every(element => element.isExpression() && + isReorderableExpression(builder, element, allowLocalIdentifiers)); + } + case 'ObjectExpression': { + return expr + .get('properties') + .every(property => { + if (!property.isObjectProperty() || property.node.computed) { + return false; + } + const value = property.get('value'); + return (value.isExpression() && + isReorderableExpression(builder, value, allowLocalIdentifiers)); + }); + } + case 'MemberExpression': { + const test = expr; + let innerObject = test; + while (innerObject.isMemberExpression()) { + innerObject = innerObject.get('object'); + } + if (innerObject.isIdentifier() && + builder.resolveIdentifier(innerObject).kind !== 'Identifier') { + return true; + } + else { + return false; + } + } + case 'ArrowFunctionExpression': { + const fn = expr; + const body = fn.get('body'); + if (body.node.type === 'BlockStatement') { + return body.node.body.length === 0; + } + else { + invariant(body.isExpression(), 'Expected an expression'); + return isReorderableExpression(builder, body, false); + } + } + case 'CallExpression': { + const call = expr; + const callee = call.get('callee'); + return (callee.isExpression() && + isReorderableExpression(builder, callee, allowLocalIdentifiers) && + call + .get('arguments') + .every(arg => arg.isExpression() && + isReorderableExpression(builder, arg, allowLocalIdentifiers))); + } + case 'NewExpression': { + const newExpr = expr; + const callee = newExpr.get('callee'); + return (callee.isExpression() && + isReorderableExpression(builder, callee, allowLocalIdentifiers) && + newExpr + .get('arguments') + .every(arg => arg.isExpression() && + isReorderableExpression(builder, arg, allowLocalIdentifiers))); + } + default: { + return false; + } + } +} +function lowerArguments(builder, expr) { + var _a; + let args = []; + for (const argPath of expr) { + if (argPath.isSpreadElement()) { + args.push({ + kind: 'Spread', + place: lowerExpressionToTemporary(builder, argPath.get('argument')), + }); + } + else if (argPath.isExpression()) { + args.push(lowerExpressionToTemporary(builder, argPath)); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerExpression) Handle ${argPath.type} arguments in CallExpression`, + category: ErrorCategory.Todo, + loc: (_a = argPath.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + } + } + return args; +} +function lowerMemberExpression(builder, expr, loweredObject = null) { + var _a, _b, _c; + const exprNode = expr.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const objectNode = expr.get('object'); + const propertyNode = expr.get('property'); + const object = loweredObject !== null && loweredObject !== void 0 ? loweredObject : lowerExpressionToTemporary(builder, objectNode); + if (!expr.node.computed || expr.node.property.type === 'NumericLiteral') { + let property; + if (propertyNode.isIdentifier()) { + property = makePropertyLiteral(propertyNode.node.name); + } + else if (propertyNode.isNumericLiteral()) { + property = makePropertyLiteral(propertyNode.node.value); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerMemberExpression) Handle ${propertyNode.type} property`, + category: ErrorCategory.Todo, + loc: (_b = propertyNode.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + return { + object, + property: propertyNode.toString(), + value: { kind: 'UnsupportedNode', node: exprNode, loc: exprLoc }, + }; + } + const value = { + kind: 'PropertyLoad', + object: Object.assign({}, object), + property, + loc: exprLoc, + }; + return { object, property, value }; + } + else { + if (!propertyNode.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerMemberExpression) Expected Expression, got ${propertyNode.type} property`, + category: ErrorCategory.Todo, + loc: (_c = propertyNode.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + return { + object, + property: propertyNode.toString(), + value: { + kind: 'UnsupportedNode', + node: exprNode, + loc: exprLoc, + }, + }; + } + const property = lowerExpressionToTemporary(builder, propertyNode); + const value = { + kind: 'ComputedLoad', + object: Object.assign({}, object), + property: Object.assign({}, property), + loc: exprLoc, + }; + return { object, property, value }; + } +} +function lowerJsxElementName(builder, exprPath) { + var _a, _b, _c; + const exprNode = exprPath.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + if (exprPath.isJSXIdentifier()) { + const tag = exprPath.node.name; + if (tag.match(/^[A-Z]/)) { + const kind = getLoadKind(builder, exprPath); + return lowerValueToTemporary(builder, { + kind: kind, + place: lowerIdentifier(builder, exprPath), + loc: exprLoc, + }); + } + else { + return { + kind: 'BuiltinTag', + name: tag, + loc: exprLoc, + }; + } + } + else if (exprPath.isJSXMemberExpression()) { + return lowerJsxMemberExpression(builder, exprPath); + } + else if (exprPath.isJSXNamespacedName()) { + const namespace = exprPath.node.namespace.name; + const name = exprPath.node.name.name; + const tag = `${namespace}:${name}`; + if (namespace.indexOf(':') !== -1 || name.indexOf(':') !== -1) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected JSXNamespacedName to have no colons in the namespace or name`, + description: `Got \`${namespace}\` : \`${name}\``, + category: ErrorCategory.Syntax, + loc: (_b = exprPath.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + } + const place = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: tag, + loc: exprLoc, + }); + return place; + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerJsxElementName) Handle ${exprPath.type} tags`, + category: ErrorCategory.Todo, + loc: (_c = exprPath.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + return lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + node: exprNode, + loc: exprLoc, + }); + } +} +function lowerJsxMemberExpression(builder, exprPath) { + var _a, _b, _c; + const loc = (_a = exprPath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const object = exprPath.get('object'); + let objectPlace; + if (object.isJSXMemberExpression()) { + objectPlace = lowerJsxMemberExpression(builder, object); + } + else { + CompilerError.invariant(object.isJSXIdentifier(), { + reason: `TypeScript refinement fail: expected 'JsxIdentifier', got \`${object.node.type}\``, + loc: (_b = object.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + const kind = getLoadKind(builder, object); + objectPlace = lowerValueToTemporary(builder, { + kind: kind, + place: lowerIdentifier(builder, object), + loc: (_c = exprPath.node.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + }); + } + const property = exprPath.get('property').node.name; + return lowerValueToTemporary(builder, { + kind: 'PropertyLoad', + object: objectPlace, + property: makePropertyLiteral(property), + loc, + }); +} +function lowerJsxElement(builder, exprPath) { + var _a, _b, _c; + const exprNode = exprPath.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + if (exprPath.isJSXElement() || exprPath.isJSXFragment()) { + return lowerExpressionToTemporary(builder, exprPath); + } + else if (exprPath.isJSXExpressionContainer()) { + const expression = exprPath.get('expression'); + if (expression.isJSXEmptyExpression()) { + return null; + } + else { + CompilerError.invariant(expression.isExpression(), { + reason: `(BuildHIR::lowerJsxElement) Expected Expression but found ${expression.type}!`, + loc: (_b = expression.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + return lowerExpressionToTemporary(builder, expression); + } + } + else if (exprPath.isJSXText()) { + let text; + if (builder.fbtDepth > 0) { + text = exprPath.node.value; + } + else { + text = trimJsxText(exprPath.node.value); + } + if (text === null) { + return null; + } + const place = lowerValueToTemporary(builder, { + kind: 'JSXText', + value: text, + loc: exprLoc, + }); + return place; + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerJsxElement) Unhandled JsxElement, got: ${exprPath.type}`, + category: ErrorCategory.Todo, + loc: (_c = exprPath.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + const place = lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + node: exprNode, + loc: exprLoc, + }); + return place; + } +} +function trimJsxText(original) { + const lines = original.split(/\r\n|\n|\r/); + let lastNonEmptyLine = 0; + for (let i = 0; i < lines.length; i++) { + if (lines[i].match(/[^ \t]/)) { + lastNonEmptyLine = i; + } + } + let str = ''; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const isFirstLine = i === 0; + const isLastLine = i === lines.length - 1; + const isLastNonEmptyLine = i === lastNonEmptyLine; + let trimmedLine = line.replace(/\t/g, ' '); + if (!isFirstLine) { + trimmedLine = trimmedLine.replace(/^[ ]+/, ''); + } + if (!isLastLine) { + trimmedLine = trimmedLine.replace(/[ ]+$/, ''); + } + if (trimmedLine) { + if (!isLastNonEmptyLine) { + trimmedLine += ' '; + } + str += trimmedLine; + } + } + if (str.length !== 0) { + return str; + } + else { + return null; + } +} +function lowerFunctionToValue(builder, expr) { + var _a; + const exprNode = expr.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const loweredFunc = lowerFunction(builder, expr); + return { + kind: 'FunctionExpression', + name: loweredFunc.func.id, + nameHint: null, + type: expr.node.type, + loc: exprLoc, + loweredFunc, + }; +} +function lowerFunction(builder, expr) { + const componentScope = builder.environment.parentFunction.scope; + const capturedContext = gatherCapturedContext(expr, componentScope); + const loweredFunc = lower(expr, builder.environment, builder.bindings, new Map([...builder.context, ...capturedContext])); + return { + func: loweredFunc, + }; +} +function lowerExpressionToTemporary(builder, exprPath) { + const value = lowerExpression(builder, exprPath); + return lowerValueToTemporary(builder, value); +} +function lowerValueToTemporary(builder, value) { + if (value.kind === 'LoadLocal' && value.place.identifier.name === null) { + return value.place; + } + const place = buildTemporaryPlace(builder, value.loc); + builder.push({ + id: makeInstructionId(0), + lvalue: Object.assign({}, place), + value: value, + effects: null, + loc: value.loc, + }); + return place; +} +function lowerIdentifier(builder, exprPath) { + var _a, _b; + const exprNode = exprPath.node; + const exprLoc = (_a = exprNode.loc) !== null && _a !== void 0 ? _a : GeneratedSource; + const binding = builder.resolveIdentifier(exprPath); + switch (binding.kind) { + case 'Identifier': { + const place = { + kind: 'Identifier', + identifier: binding.identifier, + effect: Effect.Unknown, + reactive: false, + loc: exprLoc, + }; + return place; + } + default: { + if (binding.kind === 'Global' && binding.name === 'eval') { + builder.recordError(new CompilerErrorDetail({ + reason: `The 'eval' function is not supported`, + description: 'Eval is an anti-pattern in JavaScript, and the code executed cannot be evaluated by React Compiler', + category: ErrorCategory.UnsupportedSyntax, + loc: (_b = exprPath.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + } + return lowerValueToTemporary(builder, { + kind: 'LoadGlobal', + binding, + loc: exprLoc, + }); + } + } +} +function buildTemporaryPlace(builder, loc) { + const place = { + kind: 'Identifier', + identifier: builder.makeTemporary(loc), + effect: Effect.Unknown, + reactive: false, + loc, + }; + return place; +} +function getStoreKind(builder, identifier) { + const isContext = builder.isContextIdentifier(identifier); + return isContext ? 'StoreContext' : 'StoreLocal'; +} +function getLoadKind(builder, identifier) { + const isContext = builder.isContextIdentifier(identifier); + return isContext ? 'LoadContext' : 'LoadLocal'; +} +function lowerIdentifierForAssignment(builder, loc, kind, path) { + var _a, _b; + const binding = builder.resolveIdentifier(path); + if (binding.kind !== 'Identifier') { + if (kind === InstructionKind.Reassign) { + return { kind: 'Global', name: path.node.name }; + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Could not find binding for declaration.`, + category: ErrorCategory.Invariant, + loc: (_a = path.node.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + return null; + } + } + else if (binding.bindingKind === 'const' && + kind === InstructionKind.Reassign) { + builder.recordError(new CompilerErrorDetail({ + reason: `Cannot reassign a \`const\` variable`, + category: ErrorCategory.Syntax, + loc: (_b = path.node.loc) !== null && _b !== void 0 ? _b : null, + description: binding.identifier.name != null + ? `\`${binding.identifier.name.value}\` is declared as const` + : null, + })); + return null; + } + const place = { + kind: 'Identifier', + identifier: binding.identifier, + effect: Effect.Unknown, + reactive: false, + loc, + }; + return place; +} +function lowerAssignment(builder, loc, kind, lvaluePath, value, assignmentKind) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4; + const lvalueNode = lvaluePath.node; + switch (lvalueNode.type) { + case 'Identifier': { + const lvalue = lvaluePath; + const place = lowerIdentifierForAssignment(builder, loc, kind, lvalue); + if (place === null) { + return { + kind: 'UnsupportedNode', + loc: (_a = lvalue.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + node: lvalue.node, + }; + } + else if (place.kind === 'Global') { + const temporary = lowerValueToTemporary(builder, { + kind: 'StoreGlobal', + name: place.name, + value, + loc, + }); + return { kind: 'LoadLocal', place: temporary, loc: temporary.loc }; + } + const isHoistedIdentifier = builder.environment.isHoistedIdentifier(lvalue.node); + let temporary; + if (builder.isContextIdentifier(lvalue)) { + if (kind === InstructionKind.Const && !isHoistedIdentifier) { + builder.recordError(new CompilerErrorDetail({ + reason: `Expected \`const\` declaration not to be reassigned`, + category: ErrorCategory.Syntax, + loc: (_b = lvalue.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + } + if (kind !== InstructionKind.Const && + kind !== InstructionKind.Reassign && + kind !== InstructionKind.Let && + kind !== InstructionKind.Function) { + builder.recordError(new CompilerErrorDetail({ + reason: `Unexpected context variable kind`, + category: ErrorCategory.Syntax, + loc: (_c = lvalue.node.loc) !== null && _c !== void 0 ? _c : null, + suggestions: null, + })); + temporary = lowerValueToTemporary(builder, { + kind: 'UnsupportedNode', + node: lvalueNode, + loc: (_d = lvalueNode.loc) !== null && _d !== void 0 ? _d : GeneratedSource, + }); + } + else { + temporary = lowerValueToTemporary(builder, { + kind: 'StoreContext', + lvalue: { place: Object.assign({}, place), kind }, + value, + loc, + }); + } + } + else { + const typeAnnotation = lvalue.get('typeAnnotation'); + let type; + if (typeAnnotation.isTSTypeAnnotation()) { + const typePath = typeAnnotation.get('typeAnnotation'); + type = typePath.node; + } + else if (typeAnnotation.isTypeAnnotation()) { + const typePath = typeAnnotation.get('typeAnnotation'); + type = typePath.node; + } + else { + type = null; + } + temporary = lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { place: Object.assign({}, place), kind }, + value, + type, + loc, + }); + } + return { kind: 'LoadLocal', place: temporary, loc: temporary.loc }; + } + case 'MemberExpression': { + CompilerError.invariant(kind === InstructionKind.Reassign, { + reason: 'MemberExpression may only appear in an assignment expression', + loc: (_e = lvaluePath.node.loc) !== null && _e !== void 0 ? _e : GeneratedSource, + }); + const lvalue = lvaluePath; + const property = lvalue.get('property'); + const object = lowerExpressionToTemporary(builder, lvalue.get('object')); + if (!lvalue.node.computed || lvalue.get('property').isNumericLiteral()) { + let temporary; + if (property.isIdentifier()) { + temporary = lowerValueToTemporary(builder, { + kind: 'PropertyStore', + object, + property: makePropertyLiteral(property.node.name), + value, + loc, + }); + } + else if (property.isNumericLiteral()) { + temporary = lowerValueToTemporary(builder, { + kind: 'PropertyStore', + object, + property: makePropertyLiteral(property.node.value), + value, + loc, + }); + } + else { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle ${property.type} properties in MemberExpression`, + category: ErrorCategory.Todo, + loc: (_f = property.node.loc) !== null && _f !== void 0 ? _f : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: lvalueNode, loc }; + } + return { kind: 'LoadLocal', place: temporary, loc: temporary.loc }; + } + else { + if (!property.isExpression()) { + builder.recordError(new CompilerErrorDetail({ + reason: '(BuildHIR::lowerAssignment) Expected private name to appear as a non-computed property', + category: ErrorCategory.Todo, + loc: (_g = property.node.loc) !== null && _g !== void 0 ? _g : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: lvalueNode, loc }; + } + const propertyPlace = lowerExpressionToTemporary(builder, property); + const temporary = lowerValueToTemporary(builder, { + kind: 'ComputedStore', + object, + property: propertyPlace, + value, + loc, + }); + return { kind: 'LoadLocal', place: temporary, loc: temporary.loc }; + } + } + case 'ArrayPattern': { + const lvalue = lvaluePath; + const elements = lvalue.get('elements'); + const items = []; + const followups = []; + const forceTemporaries = kind === InstructionKind.Reassign && + (elements.some(element => !element.isIdentifier()) || + elements.some(element => element.isIdentifier() && + (getStoreKind(builder, element) !== 'StoreLocal' || + builder.resolveIdentifier(element).kind !== 'Identifier'))); + for (let i = 0; i < elements.length; i++) { + const element = elements[i]; + if (element.node == null) { + items.push({ + kind: 'Hole', + }); + continue; + } + if (element.isRestElement()) { + const argument = element.get('argument'); + if (argument.isIdentifier() && + !forceTemporaries && + (assignmentKind === 'Assignment' || + getStoreKind(builder, argument) === 'StoreLocal')) { + const identifier = lowerIdentifierForAssignment(builder, (_h = element.node.loc) !== null && _h !== void 0 ? _h : GeneratedSource, kind, argument); + if (identifier === null) { + continue; + } + else if (identifier.kind === 'Global') { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Expected reassignment of globals to enable forceTemporaries', + loc: (_j = element.node.loc) !== null && _j !== void 0 ? _j : GeneratedSource, + })); + continue; + } + items.push({ + kind: 'Spread', + place: identifier, + }); + } + else { + const temp = buildTemporaryPlace(builder, (_k = element.node.loc) !== null && _k !== void 0 ? _k : GeneratedSource); + promoteTemporary(temp.identifier); + items.push({ + kind: 'Spread', + place: Object.assign({}, temp), + }); + followups.push({ place: temp, path: argument }); + } + } + else if (element.isIdentifier() && + !forceTemporaries && + (assignmentKind === 'Assignment' || + getStoreKind(builder, element) === 'StoreLocal')) { + const identifier = lowerIdentifierForAssignment(builder, (_l = element.node.loc) !== null && _l !== void 0 ? _l : GeneratedSource, kind, element); + if (identifier === null) { + continue; + } + else if (identifier.kind === 'Global') { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Expected reassignment of globals to enable forceTemporaries', + loc: (_m = element.node.loc) !== null && _m !== void 0 ? _m : GeneratedSource, + })); + continue; + } + items.push(identifier); + } + else { + const temp = buildTemporaryPlace(builder, (_o = element.node.loc) !== null && _o !== void 0 ? _o : GeneratedSource); + promoteTemporary(temp.identifier); + items.push(Object.assign({}, temp)); + followups.push({ place: temp, path: element }); + } + } + const temporary = lowerValueToTemporary(builder, { + kind: 'Destructure', + lvalue: { + kind, + pattern: { + kind: 'ArrayPattern', + items, + loc: (_p = lvalue.node.loc) !== null && _p !== void 0 ? _p : GeneratedSource, + }, + }, + value, + loc, + }); + for (const { place, path } of followups) { + lowerAssignment(builder, (_q = path.node.loc) !== null && _q !== void 0 ? _q : loc, kind, path, place, assignmentKind); + } + return { kind: 'LoadLocal', place: temporary, loc: value.loc }; + } + case 'ObjectPattern': { + const lvalue = lvaluePath; + const propertiesPaths = lvalue.get('properties'); + const properties = []; + const followups = []; + const forceTemporaries = kind === InstructionKind.Reassign && + propertiesPaths.some(property => property.isRestElement() || + (property.isObjectProperty() && + (!property.get('value').isIdentifier() || + builder.resolveIdentifier(property.get('value')).kind !== 'Identifier'))); + for (let i = 0; i < propertiesPaths.length; i++) { + const property = propertiesPaths[i]; + if (property.isRestElement()) { + const argument = property.get('argument'); + if (!argument.isIdentifier()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle ${argument.node.type} rest element in ObjectPattern`, + category: ErrorCategory.Todo, + loc: (_r = argument.node.loc) !== null && _r !== void 0 ? _r : null, + suggestions: null, + })); + continue; + } + if (forceTemporaries || + getStoreKind(builder, argument) === 'StoreContext') { + const temp = buildTemporaryPlace(builder, (_s = property.node.loc) !== null && _s !== void 0 ? _s : GeneratedSource); + promoteTemporary(temp.identifier); + properties.push({ + kind: 'Spread', + place: Object.assign({}, temp), + }); + followups.push({ place: temp, path: argument }); + } + else { + const identifier = lowerIdentifierForAssignment(builder, (_t = property.node.loc) !== null && _t !== void 0 ? _t : GeneratedSource, kind, argument); + if (identifier === null) { + continue; + } + else if (identifier.kind === 'Global') { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Expected reassignment of globals to enable forceTemporaries', + loc: (_u = property.node.loc) !== null && _u !== void 0 ? _u : GeneratedSource, + })); + continue; + } + properties.push({ + kind: 'Spread', + place: identifier, + }); + } + } + else { + if (!property.isObjectProperty()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle ${property.type} properties in ObjectPattern`, + category: ErrorCategory.Todo, + loc: (_v = property.node.loc) !== null && _v !== void 0 ? _v : null, + suggestions: null, + })); + continue; + } + if (property.node.computed) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle computed properties in ObjectPattern`, + category: ErrorCategory.Todo, + loc: (_w = property.node.loc) !== null && _w !== void 0 ? _w : null, + suggestions: null, + })); + continue; + } + const loweredKey = lowerObjectPropertyKey(builder, property); + if (!loweredKey) { + continue; + } + const element = property.get('value'); + if (!element.isLVal()) { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Expected object property value to be an LVal, got: ${element.type}`, + category: ErrorCategory.Todo, + loc: (_x = element.node.loc) !== null && _x !== void 0 ? _x : null, + suggestions: null, + })); + continue; + } + if (element.isIdentifier() && + !forceTemporaries && + (assignmentKind === 'Assignment' || + getStoreKind(builder, element) === 'StoreLocal')) { + const identifier = lowerIdentifierForAssignment(builder, (_y = element.node.loc) !== null && _y !== void 0 ? _y : GeneratedSource, kind, element); + if (identifier === null) { + continue; + } + else if (identifier.kind === 'Global') { + builder.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Todo, + reason: 'Expected reassignment of globals to enable forceTemporaries', + loc: (_z = element.node.loc) !== null && _z !== void 0 ? _z : GeneratedSource, + })); + continue; + } + properties.push({ + kind: 'ObjectProperty', + type: 'property', + place: identifier, + key: loweredKey, + }); + } + else { + const temp = buildTemporaryPlace(builder, (_0 = element.node.loc) !== null && _0 !== void 0 ? _0 : GeneratedSource); + promoteTemporary(temp.identifier); + properties.push({ + kind: 'ObjectProperty', + type: 'property', + place: Object.assign({}, temp), + key: loweredKey, + }); + followups.push({ place: temp, path: element }); + } + } + } + const temporary = lowerValueToTemporary(builder, { + kind: 'Destructure', + lvalue: { + kind, + pattern: { + kind: 'ObjectPattern', + properties, + loc: (_1 = lvalue.node.loc) !== null && _1 !== void 0 ? _1 : GeneratedSource, + }, + }, + value, + loc, + }); + for (const { place, path } of followups) { + lowerAssignment(builder, (_2 = path.node.loc) !== null && _2 !== void 0 ? _2 : loc, kind, path, place, assignmentKind); + } + return { kind: 'LoadLocal', place: temporary, loc: value.loc }; + } + case 'AssignmentPattern': { + const lvalue = lvaluePath; + const loc = (_3 = lvalue.node.loc) !== null && _3 !== void 0 ? _3 : GeneratedSource; + const temp = buildTemporaryPlace(builder, loc); + const testBlock = builder.reserve('value'); + const continuationBlock = builder.reserve(builder.currentBlockKind()); + const consequent = builder.enter('value', () => { + const defaultValue = lowerReorderableExpression(builder, lvalue.get('right')); + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, temp) }, + value: Object.assign({}, defaultValue), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + const alternate = builder.enter('value', () => { + lowerValueToTemporary(builder, { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Const, place: Object.assign({}, temp) }, + value: Object.assign({}, value), + type: null, + loc, + }); + return { + kind: 'goto', + variant: GotoVariant.Break, + block: continuationBlock.id, + id: makeInstructionId(0), + loc, + }; + }); + builder.terminateWithContinuation({ + kind: 'ternary', + test: testBlock.id, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }, testBlock); + const undef = lowerValueToTemporary(builder, { + kind: 'Primitive', + value: undefined, + loc, + }); + const test = lowerValueToTemporary(builder, { + kind: 'BinaryExpression', + left: Object.assign({}, value), + operator: '===', + right: Object.assign({}, undef), + loc, + }); + builder.terminateWithContinuation({ + kind: 'branch', + test: Object.assign({}, test), + consequent, + alternate, + fallthrough: continuationBlock.id, + id: makeInstructionId(0), + loc, + }, continuationBlock); + return lowerAssignment(builder, loc, kind, lvalue.get('left'), temp, assignmentKind); + } + default: { + builder.recordError(new CompilerErrorDetail({ + reason: `(BuildHIR::lowerAssignment) Handle ${lvaluePath.type} assignments`, + category: ErrorCategory.Todo, + loc: (_4 = lvaluePath.node.loc) !== null && _4 !== void 0 ? _4 : null, + suggestions: null, + })); + return { kind: 'UnsupportedNode', node: lvalueNode, loc }; + } + } +} +function captureScopes({ from, to }) { + let scopes = new Set(); + while (from) { + scopes.add(from); + if (from === to) { + break; + } + from = from.parent; + } + return scopes; +} +function gatherCapturedContext(fn, componentScope) { + const capturedIds = new Map(); + const pureScopes = captureScopes({ + from: fn.scope.parent, + to: componentScope, + }); + function handleMaybeDependency(path) { + var _a, _b; + let baseIdentifier; + if (path.isJSXOpeningElement()) { + const name = path.get('name'); + if (!(name.isJSXMemberExpression() || name.isJSXIdentifier())) { + return; + } + let current = name; + while (current.isJSXMemberExpression()) { + current = current.get('object'); + } + invariant(current.isJSXIdentifier(), 'Invalid logic in gatherCapturedDeps'); + baseIdentifier = current; + } + else { + baseIdentifier = path; + } + path.skip(); + const binding = baseIdentifier.scope.getBinding(baseIdentifier.node.name); + if (binding !== undefined && + pureScopes.has(binding.scope) && + !capturedIds.has(binding.identifier)) { + capturedIds.set(binding.identifier, (_b = (_a = path.node.loc) !== null && _a !== void 0 ? _a : binding.identifier.loc) !== null && _b !== void 0 ? _b : GeneratedSource); + } + } + fn.traverse({ + TypeAnnotation(path) { + path.skip(); + }, + TSTypeAnnotation(path) { + path.skip(); + }, + TypeAlias(path) { + path.skip(); + }, + TSTypeAliasDeclaration(path) { + path.skip(); + }, + Expression(path) { + if (path.isAssignmentExpression()) { + const left = path.get('left'); + if (left.isIdentifier()) { + handleMaybeDependency(left); + } + return; + } + else if (path.isJSXElement()) { + handleMaybeDependency(path.get('openingElement')); + } + else if (path.isIdentifier()) { + handleMaybeDependency(path); + } + }, + }); + return capturedIds; +} +function notNull(value) { + return value !== null; +} +function lowerType(node) { + switch (node.type) { + case 'GenericTypeAnnotation': { + const id = node.id; + if (id.type === 'Identifier' && id.name === 'Array') { + return { kind: 'Object', shapeId: BuiltInArrayId }; + } + return makeType(); + } + case 'TSTypeReference': { + const typeName = node.typeName; + if (typeName.type === 'Identifier' && typeName.name === 'Array') { + return { kind: 'Object', shapeId: BuiltInArrayId }; + } + return makeType(); + } + case 'ArrayTypeAnnotation': + case 'TSArrayType': { + return { kind: 'Object', shapeId: BuiltInArrayId }; + } + case 'BooleanLiteralTypeAnnotation': + case 'BooleanTypeAnnotation': + case 'NullLiteralTypeAnnotation': + case 'NumberLiteralTypeAnnotation': + case 'NumberTypeAnnotation': + case 'StringLiteralTypeAnnotation': + case 'StringTypeAnnotation': + case 'TSBooleanKeyword': + case 'TSNullKeyword': + case 'TSNumberKeyword': + case 'TSStringKeyword': + case 'TSSymbolKeyword': + case 'TSUndefinedKeyword': + case 'TSVoidKeyword': + case 'VoidTypeAnnotation': { + return { kind: 'Primitive' }; + } + default: { + return makeType(); + } + } +} + +function buildReactiveScopeTerminalsHIR(fn) { + const queuedRewrites = []; + recursivelyTraverseItems([...getScopes(fn)], scope => scope.range, { + fallthroughs: new Map(), + rewrites: queuedRewrites, + env: fn.env, + }, pushStartScopeTerminal, pushEndScopeTerminal); + const rewrittenFinalBlocks = new Map(); + const nextBlocks = new Map(); + queuedRewrites.reverse(); + for (const [, block] of fn.body.blocks) { + const context = { + nextBlockId: block.id, + rewrites: [], + nextPreds: block.preds, + instrSliceIdx: 0, + source: block, + }; + for (let i = 0; i < block.instructions.length + 1; i++) { + const instrId = i < block.instructions.length + ? block.instructions[i].id + : block.terminal.id; + let rewrite = queuedRewrites.at(-1); + while (rewrite != null && rewrite.instrId <= instrId) { + handleRewrite(rewrite, i, context); + queuedRewrites.pop(); + rewrite = queuedRewrites.at(-1); + } + } + if (context.rewrites.length > 0) { + const finalBlock = { + id: context.nextBlockId, + kind: block.kind, + preds: context.nextPreds, + terminal: block.terminal, + instructions: block.instructions.slice(context.instrSliceIdx), + phis: new Set(), + }; + context.rewrites.push(finalBlock); + for (const b of context.rewrites) { + nextBlocks.set(b.id, b); + } + rewrittenFinalBlocks.set(block.id, finalBlock.id); + } + else { + nextBlocks.set(block.id, block); + } + } + const originalBlocks = fn.body.blocks; + fn.body.blocks = nextBlocks; + for (const [, block] of originalBlocks) { + for (const phi of block.phis) { + for (const [originalId, value] of phi.operands) { + const newId = rewrittenFinalBlocks.get(originalId); + if (newId != null) { + phi.operands.delete(originalId); + phi.operands.set(newId, value); + } + } + } + } + reversePostorderBlocks(fn.body); + markPredecessors(fn.body); + markInstructionIds(fn.body); + fixScopeAndIdentifierRanges(fn.body); +} +function pushStartScopeTerminal(scope, context) { + const blockId = context.env.nextBlockId; + const fallthroughId = context.env.nextBlockId; + context.rewrites.push({ + kind: 'StartScope', + blockId, + fallthroughId, + instrId: scope.range.start, + scope, + }); + context.fallthroughs.set(scope.id, fallthroughId); +} +function pushEndScopeTerminal(scope, context) { + const fallthroughId = context.fallthroughs.get(scope.id); + CompilerError.invariant(fallthroughId != null, { + reason: 'Expected scope to exist', + loc: GeneratedSource, + }); + context.rewrites.push({ + kind: 'EndScope', + fallthroughId, + instrId: scope.range.end, + }); +} +function handleRewrite(terminalInfo, idx, context) { + const terminal = terminalInfo.kind === 'StartScope' + ? { + kind: 'scope', + fallthrough: terminalInfo.fallthroughId, + block: terminalInfo.blockId, + scope: terminalInfo.scope, + id: terminalInfo.instrId, + loc: GeneratedSource, + } + : { + kind: 'goto', + variant: GotoVariant.Break, + block: terminalInfo.fallthroughId, + id: terminalInfo.instrId, + loc: GeneratedSource, + }; + const currBlockId = context.nextBlockId; + context.rewrites.push({ + kind: context.source.kind, + id: currBlockId, + instructions: context.source.instructions.slice(context.instrSliceIdx, idx), + preds: context.nextPreds, + phis: context.rewrites.length === 0 ? context.source.phis : new Set(), + terminal, + }); + context.nextPreds = new Set([currBlockId]); + context.nextBlockId = + terminalInfo.kind === 'StartScope' + ? terminalInfo.blockId + : terminalInfo.fallthroughId; + context.instrSliceIdx = idx; +} + +var ansiStylesExports = {}; +var ansiStyles = { + get exports(){ return ansiStylesExports; }, + set exports(v){ ansiStylesExports = v; }, +}; + +var conversionsExports = {}; +var conversions = { + get exports(){ return conversionsExports; }, + set exports(v){ conversionsExports = v; }, +}; + +var colorName; +var hasRequiredColorName; + +function requireColorName () { + if (hasRequiredColorName) return colorName; + hasRequiredColorName = 1; + + colorName = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + return colorName; +} + +var hasRequiredConversions; + +function requireConversions () { + if (hasRequiredConversions) return conversionsExports; + hasRequiredConversions = 1; + var cssKeywords = requireColorName(); + + // NOTE: conversions should only return primitive values (i.e. arrays, or + // values that give correct `typeof` results). + // do not use box values types (i.e. Number(), String(), etc.) + + var reverseKeywords = {}; + for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } + } + + var convert = conversions.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} + }; + + // hide .channels and .labels properties + for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } + } + + convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; + }; + + convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; + }; + + convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; + }; + + convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; + }; + + /** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ + function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); + } + + convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; + }; + + convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; + }; + + convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; + }; + + convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; + }; + + convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; + }; + + convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } + }; + + convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; + }; + + // http://dev.w3.org/csswg/css-color/#hwb-to-rgb + convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; + }; + + convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; + }; + + convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; + }; + + convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + + return [l, c, h]; + }; + + convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + + return [l, a, b]; + }; + + convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; + }; + + convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + + convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; + }; + + convert.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; + }; + + convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; + + return [r, g, b]; + }; + + convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; + + return [r, g, b]; + }; + + convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; + }; + + convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; + }; + + convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; + }; + + convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; + }; + + convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; + }; + + convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + + convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; + }; + + convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; + }; + + convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; + }; + + convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; + }; + + convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; + return conversionsExports; +} + +var route; +var hasRequiredRoute; + +function requireRoute () { + if (hasRequiredRoute) return route; + hasRequiredRoute = 1; + var conversions = requireConversions(); + + /* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. + */ + + function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; + } + + // https://en.wikipedia.org/wiki/Breadth-first_search + function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; + } + + function link(from, to) { + return function (args) { + return to(from(args)); + }; + } + + function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; + } + + route = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; + }; + return route; +} + +var colorConvert; +var hasRequiredColorConvert; + +function requireColorConvert () { + if (hasRequiredColorConvert) return colorConvert; + hasRequiredColorConvert = 1; + var conversions = requireConversions(); + var route = requireRoute(); + + var convert = {}; + + var models = Object.keys(conversions); + + function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; + } + + models.forEach(function (fromModel) { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + var routes = route(fromModel); + var routeModels = Object.keys(routes); + + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); + }); + + colorConvert = convert; + return colorConvert; +} + +var hasRequiredAnsiStyles; + +function requireAnsiStyles () { + if (hasRequiredAnsiStyles) return ansiStylesExports; + hasRequiredAnsiStyles = 1; + (function (module) { + const colorConvert = requireColorConvert(); + + const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; + }; + + const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; + }; + + const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + + function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; + } + + // Make the export immutable + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); +} (ansiStyles)); + return ansiStylesExports; +} + +var collections = {}; + +var hasRequiredCollections; + +function requireCollections () { + if (hasRequiredCollections) return collections; + hasRequiredCollections = 1; + + Object.defineProperty(collections, '__esModule', { + value: true + }); + collections.printIteratorEntries = printIteratorEntries; + collections.printIteratorValues = printIteratorValues; + collections.printListItems = printListItems; + collections.printObjectProperties = printObjectProperties; + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + const getKeysOfEnumerableProperties = object => { + const keys = Object.keys(object).sort(); + + if (Object.getOwnPropertySymbols) { + Object.getOwnPropertySymbols(object).forEach(symbol => { + if (Object.getOwnPropertyDescriptor(object, symbol).enumerable) { + keys.push(symbol); + } + }); + } + + return keys; + }; + /** + * Return entries (for example, of a map) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ + + function printIteratorEntries( // Flow 0.51.0: property `@@iterator` of $Iterator not found in Object + // To allow simplistic getRecordIterator in immutable.js + iterator, + config, + indentation, + depth, + refs, + printer, // Too bad, so sad that separator for ECMAScript Map has been ' => ' + // What a distracting diff if you change a data structure to/from + separator = ': ' + ) { + let result = ''; + let current = iterator.next(); + + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + while (!current.done) { + const name = printer( + current.value[0], + config, + indentationNext, + depth, + refs + ); + const value = printer( + current.value[1], + config, + indentationNext, + depth, + refs + ); + result += indentationNext + name + separator + value; + current = iterator.next(); + + if (!current.done) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; + } + /** + * Return values (for example, of a set) + * with spacing, indentation, and comma + * without surrounding punctuation (braces or brackets) + */ + + function printIteratorValues( + iterator, + config, + indentation, + depth, + refs, + printer + ) { + let result = ''; + let current = iterator.next(); + + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + while (!current.done) { + result += + indentationNext + + printer(current.value, config, indentationNext, depth, refs); + current = iterator.next(); + + if (!current.done) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; + } + /** + * Return items (for example, of an array) + * with spacing, indentation, and comma + * without surrounding punctuation (for example, brackets) + **/ + + function printListItems(list, config, indentation, depth, refs, printer) { + let result = ''; + + if (list.length) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + for (let i = 0; i < list.length; i++) { + result += + indentationNext + + printer(list[i], config, indentationNext, depth, refs); + + if (i < list.length - 1) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; + } + /** + * Return properties of an object + * with spacing, indentation, and comma + * without surrounding punctuation (for example, braces) + */ + + function printObjectProperties(val, config, indentation, depth, refs, printer) { + let result = ''; + const keys = getKeysOfEnumerableProperties(val); + + if (keys.length) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const name = printer(key, config, indentationNext, depth, refs); + const value = printer(val[key], config, indentationNext, depth, refs); + result += indentationNext + name + ': ' + value; + + if (i < keys.length - 1) { + result += ',' + config.spacingInner; + } else if (!config.min) { + result += ','; + } + } + + result += config.spacingOuter + indentation; + } + + return result; + } + return collections; +} + +var AsymmetricMatcher = {}; + +var hasRequiredAsymmetricMatcher; + +function requireAsymmetricMatcher () { + if (hasRequiredAsymmetricMatcher) return AsymmetricMatcher; + hasRequiredAsymmetricMatcher = 1; + + Object.defineProperty(AsymmetricMatcher, '__esModule', { + value: true + }); + AsymmetricMatcher.default = AsymmetricMatcher.test = AsymmetricMatcher.serialize = void 0; + + var _collections = requireCollections(); + + var Symbol = commonjsGlobal['jest-symbol-do-not-touch'] || commonjsGlobal.Symbol; + const asymmetricMatcher = Symbol.for('jest.asymmetricMatcher'); + const SPACE = ' '; + + const serialize = (val, config, indentation, depth, refs, printer) => { + const stringedValue = val.toString(); + + if ( + stringedValue === 'ArrayContaining' || + stringedValue === 'ArrayNotContaining' + ) { + if (++depth > config.maxDepth) { + return '[' + stringedValue + ']'; + } + + return ( + stringedValue + + SPACE + + '[' + + (0, _collections.printListItems)( + val.sample, + config, + indentation, + depth, + refs, + printer + ) + + ']' + ); + } + + if ( + stringedValue === 'ObjectContaining' || + stringedValue === 'ObjectNotContaining' + ) { + if (++depth > config.maxDepth) { + return '[' + stringedValue + ']'; + } + + return ( + stringedValue + + SPACE + + '{' + + (0, _collections.printObjectProperties)( + val.sample, + config, + indentation, + depth, + refs, + printer + ) + + '}' + ); + } + + if ( + stringedValue === 'StringMatching' || + stringedValue === 'StringNotMatching' + ) { + return ( + stringedValue + + SPACE + + printer(val.sample, config, indentation, depth, refs) + ); + } + + if ( + stringedValue === 'StringContaining' || + stringedValue === 'StringNotContaining' + ) { + return ( + stringedValue + + SPACE + + printer(val.sample, config, indentation, depth, refs) + ); + } + + return val.toAsymmetricMatcher(); + }; + + AsymmetricMatcher.serialize = serialize; + + const test = val => val && val.$$typeof === asymmetricMatcher; + + AsymmetricMatcher.test = test; + const plugin = { + serialize, + test + }; + var _default = plugin; + AsymmetricMatcher.default = _default; + return AsymmetricMatcher; +} + +var ConvertAnsi = {}; + +var ansiRegex; +var hasRequiredAnsiRegex; + +function requireAnsiRegex () { + if (hasRequiredAnsiRegex) return ansiRegex; + hasRequiredAnsiRegex = 1; + + ansiRegex = options => { + options = Object.assign({ + onlyFirst: false + }, options); + + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, options.onlyFirst ? undefined : 'g'); + }; + return ansiRegex; +} + +var hasRequiredConvertAnsi; + +function requireConvertAnsi () { + if (hasRequiredConvertAnsi) return ConvertAnsi; + hasRequiredConvertAnsi = 1; + + Object.defineProperty(ConvertAnsi, '__esModule', { + value: true + }); + ConvertAnsi.default = ConvertAnsi.serialize = ConvertAnsi.test = void 0; + + var _ansiRegex = _interopRequireDefault(requireAnsiRegex()); + + var _ansiStyles = _interopRequireDefault(requireAnsiStyles()); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; + } + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + const toHumanReadableAnsi = text => + text.replace((0, _ansiRegex.default)(), match => { + switch (match) { + case _ansiStyles.default.red.close: + case _ansiStyles.default.green.close: + case _ansiStyles.default.cyan.close: + case _ansiStyles.default.gray.close: + case _ansiStyles.default.white.close: + case _ansiStyles.default.yellow.close: + case _ansiStyles.default.bgRed.close: + case _ansiStyles.default.bgGreen.close: + case _ansiStyles.default.bgYellow.close: + case _ansiStyles.default.inverse.close: + case _ansiStyles.default.dim.close: + case _ansiStyles.default.bold.close: + case _ansiStyles.default.reset.open: + case _ansiStyles.default.reset.close: + return ''; + + case _ansiStyles.default.red.open: + return ''; + + case _ansiStyles.default.green.open: + return ''; + + case _ansiStyles.default.cyan.open: + return ''; + + case _ansiStyles.default.gray.open: + return ''; + + case _ansiStyles.default.white.open: + return ''; + + case _ansiStyles.default.yellow.open: + return ''; + + case _ansiStyles.default.bgRed.open: + return ''; + + case _ansiStyles.default.bgGreen.open: + return ''; + + case _ansiStyles.default.bgYellow.open: + return ''; + + case _ansiStyles.default.inverse.open: + return ''; + + case _ansiStyles.default.dim.open: + return ''; + + case _ansiStyles.default.bold.open: + return ''; + + default: + return ''; + } + }); + + const test = val => + typeof val === 'string' && !!val.match((0, _ansiRegex.default)()); + + ConvertAnsi.test = test; + + const serialize = (val, config, indentation, depth, refs, printer) => + printer(toHumanReadableAnsi(val), config, indentation, depth, refs); + + ConvertAnsi.serialize = serialize; + const plugin = { + serialize, + test + }; + var _default = plugin; + ConvertAnsi.default = _default; + return ConvertAnsi; +} + +var DOMCollection = {}; + +var hasRequiredDOMCollection; + +function requireDOMCollection () { + if (hasRequiredDOMCollection) return DOMCollection; + hasRequiredDOMCollection = 1; + + Object.defineProperty(DOMCollection, '__esModule', { + value: true + }); + DOMCollection.default = DOMCollection.serialize = DOMCollection.test = void 0; + + var _collections = requireCollections(); + + function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + var ownKeys = Object.keys(source); + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys = ownKeys.concat( + Object.getOwnPropertySymbols(source).filter(function(sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + }) + ); + } + ownKeys.forEach(function(key) { + _defineProperty(target, key, source[key]); + }); + } + return target; + } + + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; + } + + const SPACE = ' '; + const OBJECT_NAMES = ['DOMStringMap', 'NamedNodeMap']; + const ARRAY_REGEXP = /^(HTML\w*Collection|NodeList)$/; + + const testName = name => + OBJECT_NAMES.indexOf(name) !== -1 || ARRAY_REGEXP.test(name); + + const test = val => + val && + val.constructor && + val.constructor.name && + testName(val.constructor.name); // Convert array of attribute objects to props object. + + DOMCollection.test = test; + + const propsReducer = (props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }; + + const serialize = (collection, config, indentation, depth, refs, printer) => { + const name = collection.constructor.name; + + if (++depth > config.maxDepth) { + return '[' + name + ']'; + } + + return ( + (config.min ? '' : name + SPACE) + + (OBJECT_NAMES.indexOf(name) !== -1 + ? '{' + + (0, _collections.printObjectProperties)( + name === 'NamedNodeMap' + ? Array.prototype.reduce.call(collection, propsReducer, {}) + : _objectSpread({}, collection), + config, + indentation, + depth, + refs, + printer + ) + + '}' + : '[' + + (0, _collections.printListItems)( + Array.from(collection), + config, + indentation, + depth, + refs, + printer + ) + + ']') + ); + }; + + DOMCollection.serialize = serialize; + const plugin = { + serialize, + test + }; + var _default = plugin; + DOMCollection.default = _default; + return DOMCollection; +} + +var DOMElement = {}; + +var markup = {}; + +var escapeHTML = {}; + +var hasRequiredEscapeHTML; + +function requireEscapeHTML () { + if (hasRequiredEscapeHTML) return escapeHTML; + hasRequiredEscapeHTML = 1; + + Object.defineProperty(escapeHTML, '__esModule', { + value: true + }); + escapeHTML.default = escapeHTML$1; + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + function escapeHTML$1(str) { + return str.replace(//g, '>'); + } + return escapeHTML; +} + +var hasRequiredMarkup; + +function requireMarkup () { + if (hasRequiredMarkup) return markup; + hasRequiredMarkup = 1; + + Object.defineProperty(markup, '__esModule', { + value: true + }); + markup.printElementAsLeaf = markup.printElement = markup.printComment = markup.printText = markup.printChildren = markup.printProps = void 0; + + var _escapeHTML = _interopRequireDefault(requireEscapeHTML()); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; + } + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + // Return empty string if keys is empty. + const printProps = (keys, props, config, indentation, depth, refs, printer) => { + const indentationNext = indentation + config.indent; + const colors = config.colors; + return keys + .map(key => { + const value = props[key]; + let printed = printer(value, config, indentationNext, depth, refs); + + if (typeof value !== 'string') { + if (printed.indexOf('\n') !== -1) { + printed = + config.spacingOuter + + indentationNext + + printed + + config.spacingOuter + + indentation; + } + + printed = '{' + printed + '}'; + } + + return ( + config.spacingInner + + indentation + + colors.prop.open + + key + + colors.prop.close + + '=' + + colors.value.open + + printed + + colors.value.close + ); + }) + .join(''); + }; // Return empty string if children is empty. + + markup.printProps = printProps; + + const printChildren = (children, config, indentation, depth, refs, printer) => + children + .map( + child => + config.spacingOuter + + indentation + + (typeof child === 'string' + ? printText(child, config) + : printer(child, config, indentation, depth, refs)) + ) + .join(''); + + markup.printChildren = printChildren; + + const printText = (text, config) => { + const contentColor = config.colors.content; + return ( + contentColor.open + (0, _escapeHTML.default)(text) + contentColor.close + ); + }; + + markup.printText = printText; + + const printComment = (comment, config) => { + const commentColor = config.colors.comment; + return ( + commentColor.open + + '' + + commentColor.close + ); + }; // Separate the functions to format props, children, and element, + // so a plugin could override a particular function, if needed. + // Too bad, so sad: the traditional (but unnecessary) space + // in a self-closing tagColor requires a second test of printedProps. + + markup.printComment = printComment; + + const printElement = ( + type, + printedProps, + printedChildren, + config, + indentation + ) => { + const tagColor = config.colors.tag; + return ( + tagColor.open + + '<' + + type + + (printedProps && + tagColor.close + + printedProps + + config.spacingOuter + + indentation + + tagColor.open) + + (printedChildren + ? '>' + + tagColor.close + + printedChildren + + config.spacingOuter + + indentation + + tagColor.open + + '' + + tagColor.close + ); + }; + + markup.printElement = printElement; + + const printElementAsLeaf = (type, config) => { + const tagColor = config.colors.tag; + return ( + tagColor.open + + '<' + + type + + tagColor.close + + ' …' + + tagColor.open + + ' />' + + tagColor.close + ); + }; + + markup.printElementAsLeaf = printElementAsLeaf; + return markup; +} + +var hasRequiredDOMElement; + +function requireDOMElement () { + if (hasRequiredDOMElement) return DOMElement; + hasRequiredDOMElement = 1; + + Object.defineProperty(DOMElement, '__esModule', { + value: true + }); + DOMElement.default = DOMElement.serialize = DOMElement.test = void 0; + + var _markup = requireMarkup(); + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + const ELEMENT_NODE = 1; + const TEXT_NODE = 3; + const COMMENT_NODE = 8; + const FRAGMENT_NODE = 11; + const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/; + + const testNode = (nodeType, name) => + (nodeType === ELEMENT_NODE && ELEMENT_REGEXP.test(name)) || + (nodeType === TEXT_NODE && name === 'Text') || + (nodeType === COMMENT_NODE && name === 'Comment') || + (nodeType === FRAGMENT_NODE && name === 'DocumentFragment'); + + const test = val => + val && + val.constructor && + val.constructor.name && + testNode(val.nodeType, val.constructor.name); + + DOMElement.test = test; + + function nodeIsText(node) { + return node.nodeType === TEXT_NODE; + } + + function nodeIsComment(node) { + return node.nodeType === COMMENT_NODE; + } + + function nodeIsFragment(node) { + return node.nodeType === FRAGMENT_NODE; + } + + const serialize = (node, config, indentation, depth, refs, printer) => { + if (nodeIsText(node)) { + return (0, _markup.printText)(node.data, config); + } + + if (nodeIsComment(node)) { + return (0, _markup.printComment)(node.data, config); + } + + const type = nodeIsFragment(node) + ? `DocumentFragment` + : node.tagName.toLowerCase(); + + if (++depth > config.maxDepth) { + return (0, _markup.printElementAsLeaf)(type, config); + } + + return (0, _markup.printElement)( + type, + (0, _markup.printProps)( + nodeIsFragment(node) + ? [] + : Array.from(node.attributes) + .map(attr => attr.name) + .sort(), + nodeIsFragment(node) + ? [] + : Array.from(node.attributes).reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}), + config, + indentation + config.indent, + depth, + refs, + printer + ), + (0, _markup.printChildren)( + Array.prototype.slice.call(node.childNodes || node.children), + config, + indentation + config.indent, + depth, + refs, + printer + ), + config, + indentation + ); + }; + + DOMElement.serialize = serialize; + const plugin = { + serialize, + test + }; + var _default = plugin; + DOMElement.default = _default; + return DOMElement; +} + +var Immutable = {}; + +var hasRequiredImmutable; + +function requireImmutable () { + if (hasRequiredImmutable) return Immutable; + hasRequiredImmutable = 1; + + Object.defineProperty(Immutable, '__esModule', { + value: true + }); + Immutable.default = Immutable.test = Immutable.serialize = void 0; + + var _collections = requireCollections(); + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + // SENTINEL constants are from https://github.com/facebook/immutable-js + const IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; + const IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; + const IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; + const IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; + const IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; + const IS_RECORD_SENTINEL = '@@__IMMUTABLE_RECORD__@@'; // immutable v4 + + const IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; + const IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; + const IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; + + const getImmutableName = name => 'Immutable.' + name; + + const printAsLeaf = name => '[' + name + ']'; + + const SPACE = ' '; + const LAZY = '…'; // Seq is lazy if it calls a method like filter + + const printImmutableEntries = ( + val, + config, + indentation, + depth, + refs, + printer, + type + ) => + ++depth > config.maxDepth + ? printAsLeaf(getImmutableName(type)) + : getImmutableName(type) + + SPACE + + '{' + + (0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer + ) + + '}'; // Record has an entries method because it is a collection in immutable v3. + // Return an iterator for Immutable Record from version v3 or v4. + + const getRecordEntries = val => { + let i = 0; + return { + next() { + if (i < val._keys.length) { + const key = val._keys[i++]; + return { + done: false, + value: [key, val.get(key)] + }; + } + + return { + done: true + }; + } + }; + }; + + const printImmutableRecord = ( + val, + config, + indentation, + depth, + refs, + printer + ) => { + // _name property is defined only for an Immutable Record instance + // which was constructed with a second optional descriptive name arg + const name = getImmutableName(val._name || 'Record'); + return ++depth > config.maxDepth + ? printAsLeaf(name) + : name + + SPACE + + '{' + + (0, _collections.printIteratorEntries)( + getRecordEntries(val), + config, + indentation, + depth, + refs, + printer + ) + + '}'; + }; + + const printImmutableSeq = (val, config, indentation, depth, refs, printer) => { + const name = getImmutableName('Seq'); + + if (++depth > config.maxDepth) { + return printAsLeaf(name); + } + + if (val[IS_KEYED_SENTINEL]) { + return ( + name + + SPACE + + '{' + // from Immutable collection of entries or from ECMAScript object + (val._iter || val._object + ? (0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer + ) + : LAZY) + + '}' + ); + } + + return ( + name + + SPACE + + '[' + + (val._iter || // from Immutable collection of values + val._array || // from ECMAScript array + val._collection || // from ECMAScript collection in immutable v4 + val._iterable // from ECMAScript collection in immutable v3 + ? (0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + : LAZY) + + ']' + ); + }; + + const printImmutableValues = ( + val, + config, + indentation, + depth, + refs, + printer, + type + ) => + ++depth > config.maxDepth + ? printAsLeaf(getImmutableName(type)) + : getImmutableName(type) + + SPACE + + '[' + + (0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + + ']'; + + const serialize = (val, config, indentation, depth, refs, printer) => { + if (val[IS_MAP_SENTINEL]) { + return printImmutableEntries( + val, + config, + indentation, + depth, + refs, + printer, + val[IS_ORDERED_SENTINEL] ? 'OrderedMap' : 'Map' + ); + } + + if (val[IS_LIST_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + 'List' + ); + } + + if (val[IS_SET_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + val[IS_ORDERED_SENTINEL] ? 'OrderedSet' : 'Set' + ); + } + + if (val[IS_STACK_SENTINEL]) { + return printImmutableValues( + val, + config, + indentation, + depth, + refs, + printer, + 'Stack' + ); + } + + if (val[IS_SEQ_SENTINEL]) { + return printImmutableSeq(val, config, indentation, depth, refs, printer); + } // For compatibility with immutable v3 and v4, let record be the default. + + return printImmutableRecord(val, config, indentation, depth, refs, printer); + }; // Explicitly comparing sentinel properties to true avoids false positive + // when mock identity-obj-proxy returns the key as the value for any key. + + Immutable.serialize = serialize; + + const test = val => + val && + (val[IS_ITERABLE_SENTINEL] === true || val[IS_RECORD_SENTINEL] === true); + + Immutable.test = test; + const plugin = { + serialize, + test + }; + var _default = plugin; + Immutable.default = _default; + return Immutable; +} + +var ReactElement = {}; + +var reactIsExports = {}; +var reactIs = { + get exports(){ return reactIsExports; }, + set exports(v){ reactIsExports = v; }, +}; + +var reactIs_production_min = {}; + +var hasRequiredReactIs_production_min; + +function requireReactIs_production_min () { + if (hasRequiredReactIs_production_min) return reactIs_production_min; + hasRequiredReactIs_production_min = 1; +var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b? + Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119; + function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}reactIs_production_min.AsyncMode=l;reactIs_production_min.ConcurrentMode=m;reactIs_production_min.ContextConsumer=k;reactIs_production_min.ContextProvider=h;reactIs_production_min.Element=c;reactIs_production_min.ForwardRef=n;reactIs_production_min.Fragment=e;reactIs_production_min.Lazy=t;reactIs_production_min.Memo=r;reactIs_production_min.Portal=d; + reactIs_production_min.Profiler=g;reactIs_production_min.StrictMode=f;reactIs_production_min.Suspense=p;reactIs_production_min.isAsyncMode=function(a){return A(a)||z(a)===l};reactIs_production_min.isConcurrentMode=A;reactIs_production_min.isContextConsumer=function(a){return z(a)===k};reactIs_production_min.isContextProvider=function(a){return z(a)===h};reactIs_production_min.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c};reactIs_production_min.isForwardRef=function(a){return z(a)===n};reactIs_production_min.isFragment=function(a){return z(a)===e};reactIs_production_min.isLazy=function(a){return z(a)===t}; + reactIs_production_min.isMemo=function(a){return z(a)===r};reactIs_production_min.isPortal=function(a){return z(a)===d};reactIs_production_min.isProfiler=function(a){return z(a)===g};reactIs_production_min.isStrictMode=function(a){return z(a)===f};reactIs_production_min.isSuspense=function(a){return z(a)===p}; + reactIs_production_min.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};reactIs_production_min.typeOf=z; + return reactIs_production_min; +} + +var hasRequiredReactIs; + +function requireReactIs () { + if (hasRequiredReactIs) return reactIsExports; + hasRequiredReactIs = 1; + (function (module) { + + { + module.exports = requireReactIs_production_min(); + } +} (reactIs)); + return reactIsExports; +} + +var hasRequiredReactElement; + +function requireReactElement () { + if (hasRequiredReactElement) return ReactElement; + hasRequiredReactElement = 1; + + Object.defineProperty(ReactElement, '__esModule', { + value: true + }); + ReactElement.default = ReactElement.test = ReactElement.serialize = void 0; + + var ReactIs = _interopRequireWildcard(requireReactIs()); + + var _markup = requireMarkup(); + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = + Object.defineProperty && Object.getOwnPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : {}; + if (desc.get || desc.set) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } + newObj.default = obj; + return newObj; + } + } + + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + // Given element.props.children, or subtree during recursive traversal, + // return flattened array of children. + const getChildren = (arg, children = []) => { + if (Array.isArray(arg)) { + arg.forEach(item => { + getChildren(item, children); + }); + } else if (arg != null && arg !== false) { + children.push(arg); + } + + return children; + }; + + const getType = element => { + const type = element.type; + + if (typeof type === 'string') { + return type; + } + + if (typeof type === 'function') { + return type.displayName || type.name || 'Unknown'; + } + + if (ReactIs.isFragment(element)) { + return 'React.Fragment'; + } + + if (ReactIs.isSuspense(element)) { + return 'React.Suspense'; + } + + if (typeof type === 'object' && type !== null) { + if (ReactIs.isContextProvider(element)) { + return 'Context.Provider'; + } + + if (ReactIs.isContextConsumer(element)) { + return 'Context.Consumer'; + } + + if (ReactIs.isForwardRef(element)) { + const functionName = type.render.displayName || type.render.name || ''; + return functionName !== '' + ? 'ForwardRef(' + functionName + ')' + : 'ForwardRef'; + } + + if (ReactIs.isMemo(type)) { + const functionName = + type.displayName || type.type.displayName || type.type.name || ''; + return functionName !== '' ? 'Memo(' + functionName + ')' : 'Memo'; + } + } + + return 'UNDEFINED'; + }; + + const getPropKeys = element => { + const props = element.props; + return Object.keys(props) + .filter(key => key !== 'children' && props[key] !== undefined) + .sort(); + }; + + const serialize = (element, config, indentation, depth, refs, printer) => + ++depth > config.maxDepth + ? (0, _markup.printElementAsLeaf)(getType(element), config) + : (0, _markup.printElement)( + getType(element), + (0, _markup.printProps)( + getPropKeys(element), + element.props, + config, + indentation + config.indent, + depth, + refs, + printer + ), + (0, _markup.printChildren)( + getChildren(element.props.children), + config, + indentation + config.indent, + depth, + refs, + printer + ), + config, + indentation + ); + + ReactElement.serialize = serialize; + + const test = val => val && ReactIs.isElement(val); + + ReactElement.test = test; + const plugin = { + serialize, + test + }; + var _default = plugin; + ReactElement.default = _default; + return ReactElement; +} + +var ReactTestComponent = {}; + +var hasRequiredReactTestComponent; + +function requireReactTestComponent () { + if (hasRequiredReactTestComponent) return ReactTestComponent; + hasRequiredReactTestComponent = 1; + + Object.defineProperty(ReactTestComponent, '__esModule', { + value: true + }); + ReactTestComponent.default = ReactTestComponent.test = ReactTestComponent.serialize = void 0; + + var _markup = requireMarkup(); + + var Symbol = commonjsGlobal['jest-symbol-do-not-touch'] || commonjsGlobal.Symbol; + const testSymbol = Symbol.for('react.test.json'); + + const getPropKeys = object => { + const props = object.props; + return props + ? Object.keys(props) + .filter(key => props[key] !== undefined) + .sort() + : []; + }; + + const serialize = (object, config, indentation, depth, refs, printer) => + ++depth > config.maxDepth + ? (0, _markup.printElementAsLeaf)(object.type, config) + : (0, _markup.printElement)( + object.type, + object.props + ? (0, _markup.printProps)( + getPropKeys(object), + object.props, + config, + indentation + config.indent, + depth, + refs, + printer + ) + : '', + object.children + ? (0, _markup.printChildren)( + object.children, + config, + indentation + config.indent, + depth, + refs, + printer + ) + : '', + config, + indentation + ); + + ReactTestComponent.serialize = serialize; + + const test = val => val && val.$$typeof === testSymbol; + + ReactTestComponent.test = test; + const plugin = { + serialize, + test + }; + var _default = plugin; + ReactTestComponent.default = _default; + return ReactTestComponent; +} + +var build; +var hasRequiredBuild; + +function requireBuild () { + if (hasRequiredBuild) return build; + hasRequiredBuild = 1; + + var _ansiStyles = _interopRequireDefault(requireAnsiStyles()); + + var _collections = requireCollections(); + + var _AsymmetricMatcher = _interopRequireDefault( + requireAsymmetricMatcher() + ); + + var _ConvertAnsi = _interopRequireDefault(requireConvertAnsi()); + + var _DOMCollection = _interopRequireDefault(requireDOMCollection()); + + var _DOMElement = _interopRequireDefault(requireDOMElement()); + + var _Immutable = _interopRequireDefault(requireImmutable()); + + var _ReactElement = _interopRequireDefault(requireReactElement()); + + var _ReactTestComponent = _interopRequireDefault( + requireReactTestComponent() + ); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; + } + + var Symbol = commonjsGlobal['jest-symbol-do-not-touch'] || commonjsGlobal.Symbol; + const toString = Object.prototype.toString; + const toISOString = Date.prototype.toISOString; + const errorToString = Error.prototype.toString; + const regExpToString = RegExp.prototype.toString; + const symbolToString = Symbol.prototype.toString; + /** + * Explicitly comparing typeof constructor to function avoids undefined as name + * when mock identity-obj-proxy returns the key as the value for any key. + */ + + const getConstructorName = val => + (typeof val.constructor === 'function' && val.constructor.name) || 'Object'; + /* global window */ + + /** Is val is equal to global window object? Works even if it does not exist :) */ + + const isWindow = val => typeof window !== 'undefined' && val === window; + + const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; + const NEWLINE_REGEXP = /\n/gi; + + class PrettyFormatPluginError extends Error { + constructor(message, stack) { + super(message); + this.stack = stack; + this.name = this.constructor.name; + } + } + + function isToStringedArrayType(toStringed) { + return ( + toStringed === '[object Array]' || + toStringed === '[object ArrayBuffer]' || + toStringed === '[object DataView]' || + toStringed === '[object Float32Array]' || + toStringed === '[object Float64Array]' || + toStringed === '[object Int8Array]' || + toStringed === '[object Int16Array]' || + toStringed === '[object Int32Array]' || + toStringed === '[object Uint8Array]' || + toStringed === '[object Uint8ClampedArray]' || + toStringed === '[object Uint16Array]' || + toStringed === '[object Uint32Array]' + ); + } + + function printNumber(val) { + return Object.is(val, -0) ? '-0' : String(val); + } + + function printBigInt(val) { + return String(`${val}n`); + } + + function printFunction(val, printFunctionName) { + if (!printFunctionName) { + return '[Function]'; + } + + return '[Function ' + (val.name || 'anonymous') + ']'; + } + + function printSymbol(val) { + return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)'); + } + + function printError(val) { + return '[' + errorToString.call(val) + ']'; + } + /** + * The first port of call for printing an object, handles most of the + * data-types in JS. + */ + + function printBasicValue(val, printFunctionName, escapeRegex, escapeString) { + if (val === true || val === false) { + return '' + val; + } + + if (val === undefined) { + return 'undefined'; + } + + if (val === null) { + return 'null'; + } + + const typeOf = typeof val; + + if (typeOf === 'number') { + return printNumber(val); + } + + if (typeOf === 'bigint') { + return printBigInt(val); + } + + if (typeOf === 'string') { + if (escapeString) { + return '"' + val.replace(/"|\\/g, '\\$&') + '"'; + } + + return '"' + val + '"'; + } + + if (typeOf === 'function') { + return printFunction(val, printFunctionName); + } + + if (typeOf === 'symbol') { + return printSymbol(val); + } + + const toStringed = toString.call(val); + + if (toStringed === '[object WeakMap]') { + return 'WeakMap {}'; + } + + if (toStringed === '[object WeakSet]') { + return 'WeakSet {}'; + } + + if ( + toStringed === '[object Function]' || + toStringed === '[object GeneratorFunction]' + ) { + return printFunction(val, printFunctionName); + } + + if (toStringed === '[object Symbol]') { + return printSymbol(val); + } + + if (toStringed === '[object Date]') { + return isNaN(+val) ? 'Date { NaN }' : toISOString.call(val); + } + + if (toStringed === '[object Error]') { + return printError(val); + } + + if (toStringed === '[object RegExp]') { + if (escapeRegex) { + // https://github.com/benjamingr/RegExp.escape/blob/master/polyfill.js + return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); + } + + return regExpToString.call(val); + } + + if (val instanceof Error) { + return printError(val); + } + + return null; + } + /** + * Handles more complex objects ( such as objects with circular references. + * maps and sets etc ) + */ + + function printComplexValue( + val, + config, + indentation, + depth, + refs, + hasCalledToJSON + ) { + if (refs.indexOf(val) !== -1) { + return '[Circular]'; + } + + refs = refs.slice(); + refs.push(val); + const hitMaxDepth = ++depth > config.maxDepth; + const min = config.min; + + if ( + config.callToJSON && + !hitMaxDepth && + val.toJSON && + typeof val.toJSON === 'function' && + !hasCalledToJSON + ) { + return printer(val.toJSON(), config, indentation, depth, refs, true); + } + + const toStringed = toString.call(val); + + if (toStringed === '[object Arguments]') { + return hitMaxDepth + ? '[Arguments]' + : (min ? '' : 'Arguments ') + + '[' + + (0, _collections.printListItems)( + val, + config, + indentation, + depth, + refs, + printer + ) + + ']'; + } + + if (isToStringedArrayType(toStringed)) { + return hitMaxDepth + ? '[' + val.constructor.name + ']' + : (min ? '' : val.constructor.name + ' ') + + '[' + + (0, _collections.printListItems)( + val, + config, + indentation, + depth, + refs, + printer + ) + + ']'; + } + + if (toStringed === '[object Map]') { + return hitMaxDepth + ? '[Map]' + : 'Map {' + + (0, _collections.printIteratorEntries)( + val.entries(), + config, + indentation, + depth, + refs, + printer, + ' => ' + ) + + '}'; + } + + if (toStringed === '[object Set]') { + return hitMaxDepth + ? '[Set]' + : 'Set {' + + (0, _collections.printIteratorValues)( + val.values(), + config, + indentation, + depth, + refs, + printer + ) + + '}'; + } // Avoid failure to serialize global window object in jsdom test environment. + // For example, not even relevant if window is prop of React element. + + return hitMaxDepth || isWindow(val) + ? '[' + getConstructorName(val) + ']' + : (min ? '' : getConstructorName(val) + ' ') + + '{' + + (0, _collections.printObjectProperties)( + val, + config, + indentation, + depth, + refs, + printer + ) + + '}'; + } + + function isNewPlugin(plugin) { + return plugin.serialize != null; + } + + function printPlugin(plugin, val, config, indentation, depth, refs) { + let printed; + + try { + printed = isNewPlugin(plugin) + ? plugin.serialize(val, config, indentation, depth, refs, printer) + : plugin.print( + val, + valChild => printer(valChild, config, indentation, depth, refs), + str => { + const indentationNext = indentation + config.indent; + return ( + indentationNext + + str.replace(NEWLINE_REGEXP, '\n' + indentationNext) + ); + }, + { + edgeSpacing: config.spacingOuter, + min: config.min, + spacing: config.spacingInner + }, + config.colors + ); + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + + if (typeof printed !== 'string') { + throw new Error( + `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".` + ); + } + + return printed; + } + + function findPlugin(plugins, val) { + for (let p = 0; p < plugins.length; p++) { + try { + if (plugins[p].test(val)) { + return plugins[p]; + } + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + } + + return null; + } + + function printer(val, config, indentation, depth, refs, hasCalledToJSON) { + const plugin = findPlugin(config.plugins, val); + + if (plugin !== null) { + return printPlugin(plugin, val, config, indentation, depth, refs); + } + + const basicResult = printBasicValue( + val, + config.printFunctionName, + config.escapeRegex, + config.escapeString + ); + + if (basicResult !== null) { + return basicResult; + } + + return printComplexValue( + val, + config, + indentation, + depth, + refs, + hasCalledToJSON + ); + } + + const DEFAULT_THEME = { + comment: 'gray', + content: 'reset', + prop: 'yellow', + tag: 'cyan', + value: 'green' + }; + const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME); + const DEFAULT_OPTIONS = { + callToJSON: true, + escapeRegex: false, + escapeString: true, + highlight: false, + indent: 2, + maxDepth: Infinity, + min: false, + plugins: [], + printFunctionName: true, + theme: DEFAULT_THEME + }; + + function validateOptions(options) { + Object.keys(options).forEach(key => { + if (!DEFAULT_OPTIONS.hasOwnProperty(key)) { + throw new Error(`pretty-format: Unknown option "${key}".`); + } + }); + + if (options.min && options.indent !== undefined && options.indent !== 0) { + throw new Error( + 'pretty-format: Options "min" and "indent" cannot be used together.' + ); + } + + if (options.theme !== undefined) { + if (options.theme === null) { + throw new Error(`pretty-format: Option "theme" must not be null.`); + } + + if (typeof options.theme !== 'object') { + throw new Error( + `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".` + ); + } + } + } + + const getColorsHighlight = options => + DEFAULT_THEME_KEYS.reduce((colors, key) => { + const value = + options.theme && options.theme[key] !== undefined + ? options.theme[key] + : DEFAULT_THEME[key]; + const color = value && _ansiStyles.default[value]; + + if ( + color && + typeof color.close === 'string' && + typeof color.open === 'string' + ) { + colors[key] = color; + } else { + throw new Error( + `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.` + ); + } + + return colors; + }, Object.create(null)); + + const getColorsEmpty = () => + DEFAULT_THEME_KEYS.reduce((colors, key) => { + colors[key] = { + close: '', + open: '' + }; + return colors; + }, Object.create(null)); + + const getPrintFunctionName = options => + options && options.printFunctionName !== undefined + ? options.printFunctionName + : DEFAULT_OPTIONS.printFunctionName; + + const getEscapeRegex = options => + options && options.escapeRegex !== undefined + ? options.escapeRegex + : DEFAULT_OPTIONS.escapeRegex; + + const getEscapeString = options => + options && options.escapeString !== undefined + ? options.escapeString + : DEFAULT_OPTIONS.escapeString; + + const getConfig = options => ({ + callToJSON: + options && options.callToJSON !== undefined + ? options.callToJSON + : DEFAULT_OPTIONS.callToJSON, + colors: + options && options.highlight + ? getColorsHighlight(options) + : getColorsEmpty(), + escapeRegex: getEscapeRegex(options), + escapeString: getEscapeString(options), + indent: + options && options.min + ? '' + : createIndent( + options && options.indent !== undefined + ? options.indent + : DEFAULT_OPTIONS.indent + ), + maxDepth: + options && options.maxDepth !== undefined + ? options.maxDepth + : DEFAULT_OPTIONS.maxDepth, + min: options && options.min !== undefined ? options.min : DEFAULT_OPTIONS.min, + plugins: + options && options.plugins !== undefined + ? options.plugins + : DEFAULT_OPTIONS.plugins, + printFunctionName: getPrintFunctionName(options), + spacingInner: options && options.min ? ' ' : '\n', + spacingOuter: options && options.min ? '' : '\n' + }); + + function createIndent(indent) { + return new Array(indent + 1).join(' '); + } + /** + * Returns a presentation string of your `val` object + * @param val any potential JavaScript object + * @param options Custom settings + */ + + function prettyFormat(val, options) { + if (options) { + validateOptions(options); + + if (options.plugins) { + const plugin = findPlugin(options.plugins, val); + + if (plugin !== null) { + return printPlugin(plugin, val, getConfig(options), '', 0, []); + } + } + } + + const basicResult = printBasicValue( + val, + getPrintFunctionName(options), + getEscapeRegex(options), + getEscapeString(options) + ); + + if (basicResult !== null) { + return basicResult; + } + + return printComplexValue(val, getConfig(options), '', 0, []); + } + + prettyFormat.plugins = { + AsymmetricMatcher: _AsymmetricMatcher.default, + ConvertAnsi: _ConvertAnsi.default, + DOMCollection: _DOMCollection.default, + DOMElement: _DOMElement.default, + Immutable: _Immutable.default, + ReactElement: _ReactElement.default, + ReactTestComponent: _ReactTestComponent.default + }; + /* eslint-disable-next-line no-redeclare */ + + build = prettyFormat; + return build; +} + +var buildExports = requireBuild(); +var prettyFormat = /*@__PURE__*/getDefaultExportFromCjs(buildExports); + +var _PostDominator_exit, _PostDominator_nodes; +function computePostDominatorTree(fn, options) { + const graph = buildReverseGraph(fn, options.includeThrowsAsExitNode); + const nodes = computeImmediateDominators(graph); + if (!options.includeThrowsAsExitNode) { + for (const [id] of fn.body.blocks) { + if (!nodes.has(id)) { + nodes.set(id, id); + } + } + } + return new PostDominator(graph.entry, nodes); +} +class PostDominator { + constructor(exit, nodes) { + _PostDominator_exit.set(this, void 0); + _PostDominator_nodes.set(this, void 0); + __classPrivateFieldSet(this, _PostDominator_exit, exit, "f"); + __classPrivateFieldSet(this, _PostDominator_nodes, nodes, "f"); + } + get exit() { + return __classPrivateFieldGet(this, _PostDominator_exit, "f"); + } + get(id) { + const dominator = __classPrivateFieldGet(this, _PostDominator_nodes, "f").get(id); + CompilerError.invariant(dominator !== undefined, { + reason: 'Unknown node', + loc: GeneratedSource, + }); + return dominator === id ? null : dominator; + } + debug() { + const postDominators = new Map(); + for (const [key, value] of __classPrivateFieldGet(this, _PostDominator_nodes, "f")) { + postDominators.set(`bb${key}`, `bb${value}`); + } + return prettyFormat({ + exit: `bb${this.exit}`, + postDominators, + }); + } +} +_PostDominator_exit = new WeakMap(), _PostDominator_nodes = new WeakMap(); +function computeImmediateDominators(graph) { + const nodes = new Map(); + nodes.set(graph.entry, graph.entry); + let changed = true; + while (changed) { + changed = false; + for (const [id, node] of graph.nodes) { + if (node.id === graph.entry) { + continue; + } + let newIdom = null; + for (const pred of node.preds) { + if (nodes.has(pred)) { + newIdom = pred; + break; + } + } + CompilerError.invariant(newIdom !== null, { + reason: `At least one predecessor must have been visited for block ${id}`, + loc: GeneratedSource, + }); + for (const pred of node.preds) { + if (pred === newIdom) { + continue; + } + const predDom = nodes.get(pred); + if (predDom !== undefined) { + newIdom = intersect(pred, newIdom, graph, nodes); + } + } + if (nodes.get(id) !== newIdom) { + nodes.set(id, newIdom); + changed = true; + } + } + } + return nodes; +} +function intersect(a, b, graph, nodes) { + let block1 = graph.nodes.get(a); + let block2 = graph.nodes.get(b); + while (block1 !== block2) { + while (block1.index > block2.index) { + const dom = nodes.get(block1.id); + block1 = graph.nodes.get(dom); + } + while (block2.index > block1.index) { + const dom = nodes.get(block2.id); + block2 = graph.nodes.get(dom); + } + } + return block1.id; +} +function buildReverseGraph(fn, includeThrowsAsExitNode) { + const nodes = new Map(); + const exitId = fn.env.nextBlockId; + const exit = { + id: exitId, + index: 0, + preds: new Set(), + succs: new Set(), + }; + nodes.set(exitId, exit); + for (const [id, block] of fn.body.blocks) { + const node = { + id, + index: 0, + preds: new Set(eachTerminalSuccessor(block.terminal)), + succs: new Set(block.preds), + }; + if (block.terminal.kind === 'return') { + node.preds.add(exitId); + exit.succs.add(id); + } + else if (block.terminal.kind === 'throw' && includeThrowsAsExitNode) { + node.preds.add(exitId); + exit.succs.add(id); + } + nodes.set(id, node); + } + const visited = new Set(); + const postorder = []; + function visit(id) { + if (visited.has(id)) { + return; + } + visited.add(id); + const node = nodes.get(id); + for (const successor of node.succs) { + visit(successor); + } + postorder.push(id); + } + visit(exitId); + const rpo = { entry: exitId, nodes: new Map() }; + let index = 0; + for (const id of postorder.reverse()) { + const node = nodes.get(id); + node.index = index++; + rpo.nodes.set(id, node); + } + return rpo; +} + +const DEFAULT_SHAPES = new Map(BUILTIN_SHAPES); +const UNTYPED_GLOBALS = new Set([ + 'Object', + 'Function', + 'RegExp', + 'Date', + 'Error', + 'TypeError', + 'RangeError', + 'ReferenceError', + 'SyntaxError', + 'URIError', + 'EvalError', + 'DataView', + 'Float32Array', + 'Float64Array', + 'Int8Array', + 'Int16Array', + 'Int32Array', + 'WeakMap', + 'Uint8Array', + 'Uint8ClampedArray', + 'Uint16Array', + 'Uint32Array', + 'ArrayBuffer', + 'JSON', + 'console', + 'eval', +]); +const TYPED_GLOBALS = [ + [ + 'Object', + addObject(DEFAULT_SHAPES, 'Object', [ + [ + 'keys', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'fromEntries', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.ConditionallyMutate], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInObjectId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'entries', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + aliasing: { + receiver: '@receiver', + params: ['@object'], + rest: null, + returns: '@returns', + temporaries: [], + effects: [ + { + kind: 'Create', + into: '@returns', + reason: ValueReason.KnownReturnSignature, + value: ValueKind.Mutable, + }, + { + kind: 'Capture', + from: '@object', + into: '@returns', + }, + ], + }, + }), + ], + [ + 'keys', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + aliasing: { + receiver: '@receiver', + params: ['@object'], + rest: null, + returns: '@returns', + temporaries: [], + effects: [ + { + kind: 'Create', + into: '@returns', + reason: ValueReason.KnownReturnSignature, + value: ValueKind.Mutable, + }, + { + kind: 'ImmutableCapture', + from: '@object', + into: '@returns', + }, + ], + }, + }), + ], + [ + 'values', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.Capture], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + aliasing: { + receiver: '@receiver', + params: ['@object'], + rest: null, + returns: '@returns', + temporaries: [], + effects: [ + { + kind: 'Create', + into: '@returns', + reason: ValueReason.KnownReturnSignature, + value: ValueKind.Mutable, + }, + { + kind: 'Capture', + from: '@object', + into: '@returns', + }, + ], + }, + }), + ], + ]), + ], + [ + 'Array', + addObject(DEFAULT_SHAPES, 'Array', [ + [ + 'isArray', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.Read], + restParam: null, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'from', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [ + Effect.ConditionallyMutateIterator, + Effect.ConditionallyMutate, + Effect.ConditionallyMutate, + ], + restParam: Effect.Read, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'of', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Object', shapeId: BuiltInArrayId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }), + ], + ]), + ], + [ + 'performance', + addObject(DEFAULT_SHAPES, 'performance', [ + [ + 'now', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + impure: true, + canonicalName: 'performance.now', + }), + ], + ]), + ], + [ + 'Date', + addObject(DEFAULT_SHAPES, 'Date', [ + [ + 'now', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + impure: true, + canonicalName: 'Date.now', + }), + ], + ]), + ], + [ + 'Math', + addObject(DEFAULT_SHAPES, 'Math', [ + ['PI', { kind: 'Primitive' }], + [ + 'max', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'min', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'trunc', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'ceil', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'floor', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'pow', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'random', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + impure: true, + canonicalName: 'Math.random', + }), + ], + ]), + ], + ['Infinity', { kind: 'Primitive' }], + ['NaN', { kind: 'Primitive' }], + [ + 'console', + addObject(DEFAULT_SHAPES, 'console', [ + [ + 'error', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'info', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'log', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'table', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'trace', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'warn', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + ]), + ], + [ + 'Boolean', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'Number', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'String', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'parseInt', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'parseFloat', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'isNaN', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'isFinite', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'encodeURI', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'encodeURIComponent', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'decodeURI', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'decodeURIComponent', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Primitive, + }), + ], + [ + 'Map', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.ConditionallyMutateIterator], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInMapId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }, null, true), + ], + [ + 'Set', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.ConditionallyMutateIterator], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInSetId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }, null, true), + ], + [ + 'WeakMap', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.ConditionallyMutateIterator], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInWeakMapId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }, null, true), + ], + [ + 'WeakSet', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [Effect.ConditionallyMutateIterator], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInWeakSetId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }, null, true), + ], +]; +const REACT_APIS = [ + [ + 'useContext', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'useContext', + returnValueKind: ValueKind.Frozen, + returnValueReason: ValueReason.Context, + }, BuiltInUseContextHookId), + ], + [ + 'useState', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Object', shapeId: BuiltInUseStateId }, + calleeEffect: Effect.Read, + hookKind: 'useState', + returnValueKind: ValueKind.Frozen, + returnValueReason: ValueReason.State, + }), + ], + [ + 'useActionState', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Object', shapeId: BuiltInUseActionStateId }, + calleeEffect: Effect.Read, + hookKind: 'useActionState', + returnValueKind: ValueKind.Frozen, + returnValueReason: ValueReason.State, + }), + ], + [ + 'useReducer', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Object', shapeId: BuiltInUseReducerId }, + calleeEffect: Effect.Read, + hookKind: 'useReducer', + returnValueKind: ValueKind.Frozen, + returnValueReason: ValueReason.ReducerState, + }), + ], + [ + 'useRef', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Capture, + returnType: { kind: 'Object', shapeId: BuiltInUseRefId }, + calleeEffect: Effect.Read, + hookKind: 'useRef', + returnValueKind: ValueKind.Mutable, + }), + ], + [ + 'useImperativeHandle', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + hookKind: 'useImperativeHandle', + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'useMemo', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'useMemo', + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'useCallback', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'useCallback', + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'useEffect', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Primitive' }, + calleeEffect: Effect.Read, + hookKind: 'useEffect', + returnValueKind: ValueKind.Frozen, + aliasing: { + receiver: '@receiver', + params: [], + rest: '@rest', + returns: '@returns', + temporaries: ['@effect'], + effects: [ + { + kind: 'Freeze', + value: '@rest', + reason: ValueReason.Effect, + }, + { + kind: 'Create', + into: '@effect', + value: ValueKind.Frozen, + reason: ValueReason.KnownReturnSignature, + }, + { + kind: 'Capture', + from: '@rest', + into: '@effect', + }, + { + kind: 'Create', + into: '@returns', + value: ValueKind.Primitive, + reason: ValueReason.KnownReturnSignature, + }, + ], + }, + }, BuiltInUseEffectHookId), + ], + [ + 'useLayoutEffect', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'useLayoutEffect', + returnValueKind: ValueKind.Frozen, + }, BuiltInUseLayoutEffectHookId), + ], + [ + 'useInsertionEffect', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + hookKind: 'useInsertionEffect', + returnValueKind: ValueKind.Frozen, + }, BuiltInUseInsertionEffectHookId), + ], + [ + 'useTransition', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: null, + returnType: { kind: 'Object', shapeId: BuiltInUseTransitionId }, + calleeEffect: Effect.Read, + hookKind: 'useTransition', + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'useOptimistic', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Object', shapeId: BuiltInUseOptimisticId }, + calleeEffect: Effect.Read, + hookKind: 'useOptimistic', + returnValueKind: ValueKind.Frozen, + returnValueReason: ValueReason.State, + }), + ], + [ + 'use', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Frozen, + }, BuiltInUseOperatorId), + ], + [ + 'useEffectEvent', + addHook(DEFAULT_SHAPES, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { + kind: 'Function', + return: { kind: 'Poly' }, + shapeId: BuiltInEffectEventId, + isConstructor: false, + }, + calleeEffect: Effect.Read, + hookKind: 'useEffectEvent', + returnValueKind: ValueKind.Frozen, + }, BuiltInUseEffectEventId), + ], +]; +TYPED_GLOBALS.push([ + 'React', + addObject(DEFAULT_SHAPES, null, [ + ...REACT_APIS, + [ + 'createElement', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'cloneElement', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Frozen, + }), + ], + [ + 'createRef', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Capture, + returnType: { kind: 'Object', shapeId: BuiltInUseRefId }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + }), + ], + ]), +], [ + '_jsx', + addFunction(DEFAULT_SHAPES, [], { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Frozen, + }), +]); +const DEFAULT_GLOBALS = new Map(REACT_APIS); +for (const name of UNTYPED_GLOBALS) { + DEFAULT_GLOBALS.set(name, { + kind: 'Poly', + }); +} +for (const [name, type_] of TYPED_GLOBALS) { + DEFAULT_GLOBALS.set(name, type_); +} +DEFAULT_GLOBALS.set('globalThis', addObject(DEFAULT_SHAPES, 'globalThis', TYPED_GLOBALS)); +DEFAULT_GLOBALS.set('global', addObject(DEFAULT_SHAPES, 'global', TYPED_GLOBALS)); +function installTypeConfig(globals, shapes, typeConfig, moduleName, loc) { + var _a, _b, _c, _d, _e, _f; + switch (typeConfig.kind) { + case 'type': { + switch (typeConfig.name) { + case 'Array': { + return { kind: 'Object', shapeId: BuiltInArrayId }; + } + case 'MixedReadonly': { + return { kind: 'Object', shapeId: BuiltInMixedReadonlyId }; + } + case 'Primitive': { + return { kind: 'Primitive' }; + } + case 'Ref': { + return { kind: 'Object', shapeId: BuiltInUseRefId }; + } + case 'Any': { + return { kind: 'Poly' }; + } + default: { + assertExhaustive$1(typeConfig.name, `Unexpected type '${typeConfig.name}'`); + } + } + } + case 'function': { + return addFunction(shapes, [], { + positionalParams: typeConfig.positionalParams, + restParam: typeConfig.restParam, + calleeEffect: typeConfig.calleeEffect, + returnType: installTypeConfig(globals, shapes, typeConfig.returnType, moduleName, loc), + returnValueKind: typeConfig.returnValueKind, + noAlias: typeConfig.noAlias === true, + mutableOnlyIfOperandsAreMutable: typeConfig.mutableOnlyIfOperandsAreMutable === true, + aliasing: typeConfig.aliasing, + knownIncompatible: (_a = typeConfig.knownIncompatible) !== null && _a !== void 0 ? _a : null, + }); + } + case 'hook': { + return addHook(shapes, { + hookKind: 'Custom', + positionalParams: (_b = typeConfig.positionalParams) !== null && _b !== void 0 ? _b : [], + restParam: (_c = typeConfig.restParam) !== null && _c !== void 0 ? _c : Effect.Freeze, + calleeEffect: Effect.Read, + returnType: installTypeConfig(globals, shapes, typeConfig.returnType, moduleName, loc), + returnValueKind: (_d = typeConfig.returnValueKind) !== null && _d !== void 0 ? _d : ValueKind.Frozen, + noAlias: typeConfig.noAlias === true, + aliasing: typeConfig.aliasing, + knownIncompatible: (_e = typeConfig.knownIncompatible) !== null && _e !== void 0 ? _e : null, + }); + } + case 'object': { + return addObject(shapes, null, Object.entries((_f = typeConfig.properties) !== null && _f !== void 0 ? _f : {}).map(([key, value]) => { + var _a; + const type = installTypeConfig(globals, shapes, value, moduleName, loc); + const expectHook = isHookName$2(key); + let isHook = false; + if (type.kind === 'Function' && type.shapeId !== null) { + const functionType = shapes.get(type.shapeId); + if (((_a = functionType === null || functionType === void 0 ? void 0 : functionType.functionType) === null || _a === void 0 ? void 0 : _a.hookKind) !== null) { + isHook = true; + } + } + if (expectHook !== isHook) { + CompilerError.throwInvalidConfig({ + reason: `Invalid type configuration for module`, + description: `Expected type for object property '${key}' from module '${moduleName}' ${expectHook ? 'to be a hook' : 'not to be a hook'} based on the property name`, + loc, + }); + } + return [key, type]; + })); + } + default: { + assertExhaustive$1(typeConfig, `Unexpected type kind '${typeConfig.kind}'`); + } + } +} +function getReanimatedModuleType(registry) { + const frozenHooks = [ + 'useFrameCallback', + 'useAnimatedStyle', + 'useAnimatedProps', + 'useAnimatedScrollHandler', + 'useAnimatedReaction', + 'useWorkletCallback', + ]; + const reanimatedType = []; + for (const hook of frozenHooks) { + reanimatedType.push([ + hook, + addHook(registry, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Poly' }, + returnValueKind: ValueKind.Frozen, + noAlias: true, + calleeEffect: Effect.Read, + hookKind: 'Custom', + }), + ]); + } + const mutableHooks = ['useSharedValue', 'useDerivedValue']; + for (const hook of mutableHooks) { + reanimatedType.push([ + hook, + addHook(registry, { + positionalParams: [], + restParam: Effect.Freeze, + returnType: { kind: 'Object', shapeId: ReanimatedSharedValueId }, + returnValueKind: ValueKind.Mutable, + noAlias: true, + calleeEffect: Effect.Read, + hookKind: 'Custom', + }), + ]); + } + const funcs = [ + 'withTiming', + 'withSpring', + 'createAnimatedPropAdapter', + 'withDecay', + 'withRepeat', + 'runOnUI', + 'executeOnUIRuntimeSync', + ]; + for (const fn of funcs) { + reanimatedType.push([ + fn, + addFunction(registry, [], { + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'Poly' }, + calleeEffect: Effect.Read, + returnValueKind: ValueKind.Mutable, + noAlias: true, + }), + ]); + } + return addObject(registry, null, reanimatedType); +} + +const ObjectPropertiesSchema = v4.z + .record(v4.z.string(), v4.z.lazy(() => TypeSchema)) + .refine(record => { + return Object.keys(record).every(key => key === '*' || key === 'default' || libExports$1.isValidIdentifier(key)); +}, 'Expected all "object" property names to be valid identifier, `*` to match any property, of `default` to define a module default export'); +const ObjectTypeSchema = v4.z.object({ + kind: v4.z.literal('object'), + properties: ObjectPropertiesSchema.nullable(), +}); +const LifetimeIdSchema = v4.z.string().refine(id => id.startsWith('@'), { + message: "Placeholder names must start with '@'", +}); +const FreezeEffectSchema = v4.z.object({ + kind: v4.z.literal('Freeze'), + value: LifetimeIdSchema, + reason: ValueReasonSchema, +}); +const MutateEffectSchema = v4.z.object({ + kind: v4.z.literal('Mutate'), + value: LifetimeIdSchema, +}); +const MutateTransitiveConditionallySchema = v4.z.object({ + kind: v4.z.literal('MutateTransitiveConditionally'), + value: LifetimeIdSchema, +}); +const CreateEffectSchema = v4.z.object({ + kind: v4.z.literal('Create'), + into: LifetimeIdSchema, + value: ValueKindSchema, + reason: ValueReasonSchema, +}); +const AssignEffectSchema = v4.z.object({ + kind: v4.z.literal('Assign'), + from: LifetimeIdSchema, + into: LifetimeIdSchema, +}); +const AliasEffectSchema = v4.z.object({ + kind: v4.z.literal('Alias'), + from: LifetimeIdSchema, + into: LifetimeIdSchema, +}); +const ImmutableCaptureEffectSchema = v4.z.object({ + kind: v4.z.literal('ImmutableCapture'), + from: LifetimeIdSchema, + into: LifetimeIdSchema, +}); +const CaptureEffectSchema = v4.z.object({ + kind: v4.z.literal('Capture'), + from: LifetimeIdSchema, + into: LifetimeIdSchema, +}); +const CreateFromEffectSchema = v4.z.object({ + kind: v4.z.literal('CreateFrom'), + from: LifetimeIdSchema, + into: LifetimeIdSchema, +}); +const ApplyArgSchema = v4.z.union([ + LifetimeIdSchema, + v4.z.object({ + kind: v4.z.literal('Spread'), + place: LifetimeIdSchema, + }), + v4.z.object({ + kind: v4.z.literal('Hole'), + }), +]); +const ApplyEffectSchema = v4.z.object({ + kind: v4.z.literal('Apply'), + receiver: LifetimeIdSchema, + function: LifetimeIdSchema, + mutatesFunction: v4.z.boolean(), + args: v4.z.array(ApplyArgSchema), + into: LifetimeIdSchema, +}); +const ImpureEffectSchema = v4.z.object({ + kind: v4.z.literal('Impure'), + place: LifetimeIdSchema, +}); +const AliasingEffectSchema = v4.z.union([ + FreezeEffectSchema, + CreateEffectSchema, + CreateFromEffectSchema, + AssignEffectSchema, + AliasEffectSchema, + CaptureEffectSchema, + ImmutableCaptureEffectSchema, + ImpureEffectSchema, + MutateEffectSchema, + MutateTransitiveConditionallySchema, + ApplyEffectSchema, +]); +const AliasingSignatureSchema = v4.z.object({ + receiver: LifetimeIdSchema, + params: v4.z.array(LifetimeIdSchema), + rest: LifetimeIdSchema.nullable(), + returns: LifetimeIdSchema, + effects: v4.z.array(AliasingEffectSchema), + temporaries: v4.z.array(LifetimeIdSchema), +}); +const FunctionTypeSchema = v4.z.object({ + kind: v4.z.literal('function'), + positionalParams: v4.z.array(EffectSchema), + restParam: EffectSchema.nullable(), + calleeEffect: EffectSchema, + returnType: v4.z.lazy(() => TypeSchema), + returnValueKind: ValueKindSchema, + noAlias: v4.z.boolean().nullable().optional(), + mutableOnlyIfOperandsAreMutable: v4.z.boolean().nullable().optional(), + impure: v4.z.boolean().nullable().optional(), + canonicalName: v4.z.string().nullable().optional(), + aliasing: AliasingSignatureSchema.nullable().optional(), + knownIncompatible: v4.z.string().nullable().optional(), +}); +const HookTypeSchema = v4.z.object({ + kind: v4.z.literal('hook'), + positionalParams: v4.z.array(EffectSchema).nullable().optional(), + restParam: EffectSchema.nullable().optional(), + returnType: v4.z.lazy(() => TypeSchema), + returnValueKind: ValueKindSchema.nullable().optional(), + noAlias: v4.z.boolean().nullable().optional(), + aliasing: AliasingSignatureSchema.nullable().optional(), + knownIncompatible: v4.z.string().nullable().optional(), +}); +const BuiltInTypeSchema = v4.z.union([ + v4.z.literal('Any'), + v4.z.literal('Ref'), + v4.z.literal('Array'), + v4.z.literal('Primitive'), + v4.z.literal('MixedReadonly'), +]); +const TypeReferenceSchema = v4.z.object({ + kind: v4.z.literal('type'), + name: BuiltInTypeSchema, +}); +const TypeSchema = v4.z.union([ + ObjectTypeSchema, + FunctionTypeSchema, + HookTypeSchema, + TypeReferenceSchema, +]); + +function unsupportedTypeAnnotation(desc, loc) { + CompilerError.throwInvalidJS({ + reason: `Typedchecker does not currently support type annotation: ${desc}`, + loc, + }); +} + +var _FlowTypeEnv_nextNominalId, _FlowTypeEnv_nextTypeParameterId, _FlowTypeEnv_types, _FlowTypeEnv_bindings, _FlowTypeEnv_generics, _FlowTypeEnv_flowTypes; +function makeTypeParameterId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected TypeParameterId to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +function makeNominalId(id) { + return id; +} +const DUMMY_NOMINAL = makeNominalId(0); +function convertFlowType(flowType, loc) { + let nextGenericId = 0; + function convertFlowTypeImpl(flowType, loc, genericEnv, platform, poly = null) { + var _a, _b, _c; + switch (flowType.kind) { + case 'TypeApp': { + if (flowType.type.kind === 'Def' && + flowType.type.def.kind === 'Poly' && + flowType.type.def.t_out.kind === 'Def' && + flowType.type.def.t_out.def.kind === 'Type' && + flowType.type.def.t_out.def.type.kind === 'Opaque' && + flowType.type.def.t_out.def.type.opaquetype.opaque_name === + 'Client' && + flowType.targs.length === 1) { + return convertFlowTypeImpl(flowType.targs[0], loc, genericEnv, 'client'); + } + else if (flowType.type.kind === 'Def' && + flowType.type.def.kind === 'Poly' && + flowType.type.def.t_out.kind === 'Def' && + flowType.type.def.t_out.def.kind === 'Type' && + flowType.type.def.t_out.def.type.kind === 'Opaque' && + flowType.type.def.t_out.def.type.opaquetype.opaque_name === + 'Server' && + flowType.targs.length === 1) { + return convertFlowTypeImpl(flowType.targs[0], loc, genericEnv, 'server'); + } + return Resolved.todo(platform); + } + case 'Open': + return Resolved.mixed(platform); + case 'Any': + return Resolved.todo(platform); + case 'Annot': + return convertFlowTypeImpl(flowType.type, loc, genericEnv, platform, poly); + case 'Opaque': { + if (flowType.opaquetype.opaque_name === 'Client' && + flowType.opaquetype.super_t != null) { + return convertFlowTypeImpl(flowType.opaquetype.super_t, loc, genericEnv, 'client'); + } + if (flowType.opaquetype.opaque_name === 'Server' && + flowType.opaquetype.super_t != null) { + return convertFlowTypeImpl(flowType.opaquetype.super_t, loc, genericEnv, 'server'); + } + const t = (_a = flowType.opaquetype.underlying_t) !== null && _a !== void 0 ? _a : flowType.opaquetype.super_t; + if (t != null) { + return convertFlowTypeImpl(t, loc, genericEnv, platform, poly); + } + else { + return Resolved.todo(platform); + } + } + case 'Def': { + switch (flowType.def.kind) { + case 'EnumValue': + return convertFlowTypeImpl(flowType.def.enum_info.representation_t, loc, genericEnv, platform, poly); + case 'EnumObject': + return Resolved.enum(platform); + case 'Empty': + return Resolved.todo(platform); + case 'Instance': { + const members = new Map(); + for (const key in flowType.def.instance.inst.own_props) { + const prop = flowType.def.instance.inst.own_props[key]; + if (prop.kind === 'Field') { + members.set(key, convertFlowTypeImpl(prop.type, loc, genericEnv, platform)); + } + else { + CompilerError.invariant(false, { + reason: `Unsupported property kind ${prop.kind}`, + loc: GeneratedSource, + }); + } + } + return Resolved.class((_b = flowType.def.instance.inst.class_name) !== null && _b !== void 0 ? _b : '[anonymous class]', members, platform); + } + case 'Type': + return convertFlowTypeImpl(flowType.def.type, loc, genericEnv, platform, poly); + case 'NumGeneral': + case 'SingletonNum': + return Resolved.number(platform); + case 'StrGeneral': + case 'SingletonStr': + return Resolved.string(platform); + case 'BoolGeneral': + case 'SingletonBool': + return Resolved.boolean(platform); + case 'Void': + return Resolved.void(platform); + case 'Null': + return Resolved.void(platform); + case 'Mixed': + return Resolved.mixed(platform); + case 'Arr': { + if (flowType.def.arrtype.kind === 'ArrayAT' || + flowType.def.arrtype.kind === 'ROArrayAT') { + return Resolved.array(convertFlowTypeImpl(flowType.def.arrtype.elem_t, loc, genericEnv, platform), platform); + } + else { + return Resolved.tuple(DUMMY_NOMINAL, flowType.def.arrtype.elements.map(t => convertFlowTypeImpl(t.t, loc, genericEnv, platform)), platform); + } + } + case 'Obj': { + const members = new Map(); + for (const key in flowType.def.objtype.props) { + const prop = flowType.def.objtype.props[key]; + if (prop.kind === 'Field') { + members.set(key, convertFlowTypeImpl(prop.type, loc, genericEnv, platform)); + } + else { + CompilerError.invariant(false, { + reason: `Unsupported property kind ${prop.kind}`, + loc: GeneratedSource, + }); + } + } + return Resolved.object(DUMMY_NOMINAL, members, platform); + } + case 'Class': { + if (flowType.def.type.kind === 'ThisInstance') { + const members = new Map(); + for (const key in flowType.def.type.instance.inst.own_props) { + const prop = flowType.def.type.instance.inst.own_props[key]; + if (prop.kind === 'Field') { + members.set(key, convertFlowTypeImpl(prop.type, loc, genericEnv, platform)); + } + else { + CompilerError.invariant(false, { + reason: `Unsupported property kind ${prop.kind}`, + loc: GeneratedSource, + }); + } + } + return Resolved.class((_c = flowType.def.type.instance.inst.class_name) !== null && _c !== void 0 ? _c : '[anonymous class]', members, platform); + } + CompilerError.invariant(false, { + reason: `Unsupported class instance type ${flowType.def.type.kind}`, + loc: GeneratedSource, + }); + } + case 'Fun': + return Resolved.function(poly, flowType.def.funtype.params.map(p => convertFlowTypeImpl(p.type, loc, genericEnv, platform)), convertFlowTypeImpl(flowType.def.funtype.return_t, loc, genericEnv, platform), platform); + case 'Poly': { + let newEnv = genericEnv; + const poly = flowType.def.tparams.map(p => { + const id = makeTypeParameterId(nextGenericId++); + const bound = convertFlowTypeImpl(p.bound, loc, newEnv, platform); + newEnv = new Map(newEnv); + newEnv.set(p.name, id); + return { + name: p.name, + id, + bound, + }; + }); + return convertFlowTypeImpl(flowType.def.t_out, loc, newEnv, platform, poly); + } + case 'ReactAbstractComponent': { + const props = new Map(); + let children = null; + const propsType = convertFlowTypeImpl(flowType.def.config, loc, genericEnv, platform); + if (propsType.type.kind === 'Object') { + propsType.type.members.forEach((v, k) => { + if (k === 'children') { + children = v; + } + else { + props.set(k, v); + } + }); + } + else { + CompilerError.invariant(false, { + reason: `Unsupported component props type ${propsType.type.kind}`, + loc: GeneratedSource, + }); + } + return Resolved.component(props, children, platform); + } + case 'Renders': + return Resolved.todo(platform); + default: + unsupportedTypeAnnotation('Renders', GeneratedSource); + } + } + case 'Generic': { + const id = genericEnv.get(flowType.name); + if (id == null) { + unsupportedTypeAnnotation(flowType.name, GeneratedSource); + } + return Resolved.generic(id, platform, convertFlowTypeImpl(flowType.bound, loc, genericEnv, platform)); + } + case 'Union': { + const members = flowType.members.map(t => convertFlowTypeImpl(t, loc, genericEnv, platform)); + if (members.length === 1) { + return members[0]; + } + if (members[0].type.kind === 'Number' || + members[0].type.kind === 'String' || + members[0].type.kind === 'Boolean') { + const dupes = members.filter(t => t.type.kind === members[0].type.kind); + if (dupes.length === members.length) { + return members[0]; + } + } + if (members[0].type.kind === 'Array' && + (members[0].type.element.type.kind === 'Number' || + members[0].type.element.type.kind === 'String' || + members[0].type.element.type.kind === 'Boolean')) { + const first = members[0].type.element; + const dupes = members.filter(t => t.type.kind === 'Array' && + t.type.element.type.kind === first.type.kind); + if (dupes.length === members.length) { + return members[0]; + } + } + return Resolved.union(members, platform); + } + case 'Eval': { + if (flowType.destructor.kind === 'ReactDRO' || + flowType.destructor.kind === 'ReactCheckComponentConfig') { + return convertFlowTypeImpl(flowType.type, loc, genericEnv, platform, poly); + } + unsupportedTypeAnnotation(`EvalT(${flowType.destructor.kind})`, GeneratedSource); + } + case 'Optional': { + return Resolved.union([ + convertFlowTypeImpl(flowType.type, loc, genericEnv, platform), + Resolved.void(platform), + ], platform); + } + default: + unsupportedTypeAnnotation(flowType.kind, GeneratedSource); + } + } + return convertFlowTypeImpl(flowType, loc, new Map(), 'shared'); +} +function serializeLoc(location) { + return `${location.start.line}:${location.start.column}-${location.end.line}:${location.end.column}`; +} +function buildTypeEnvironment(flowOutput) { + const result = new Map(); + for (const item of flowOutput) { + const loc = { + start: { + line: item.loc.start.line, + column: item.loc.start.column - 1, + index: item.loc.start.index, + }, + end: item.loc.end, + filename: item.loc.filename, + identifierName: item.loc.identifierName, + }; + result.set(serializeLoc(loc), item.type); + } + return result; +} +let lastFlowSource = null; +let lastFlowResult = null; +class FlowTypeEnv { + constructor() { + this.moduleEnv = new Map(); + _FlowTypeEnv_nextNominalId.set(this, 0); + _FlowTypeEnv_nextTypeParameterId.set(this, 0); + _FlowTypeEnv_types.set(this, new Map()); + _FlowTypeEnv_bindings.set(this, new Map()); + _FlowTypeEnv_generics.set(this, []); + _FlowTypeEnv_flowTypes.set(this, new Map()); + } + init(env, source) { + CompilerError.invariant(env.config.flowTypeProvider != null, { + reason: 'Expected flowDumpTypes to be defined in environment config', + loc: GeneratedSource, + }); + let stdout; + if (source === lastFlowSource) { + stdout = lastFlowResult; + } + else { + lastFlowSource = source; + lastFlowResult = env.config.flowTypeProvider(source); + stdout = lastFlowResult; + } + const flowTypes = buildTypeEnvironment(stdout); + const resolvedFlowTypes = new Map(); + for (const [loc, type] of flowTypes) { + if (typeof loc === 'symbol') + continue; + resolvedFlowTypes.set(loc, convertFlowType(JSON.parse(type), loc)); + } + __classPrivateFieldSet(this, _FlowTypeEnv_flowTypes, resolvedFlowTypes, "f"); + } + setType(identifier, type) { + if (typeof identifier.loc !== 'symbol' && + __classPrivateFieldGet(this, _FlowTypeEnv_flowTypes, "f").has(serializeLoc(identifier.loc))) { + return; + } + __classPrivateFieldGet(this, _FlowTypeEnv_types, "f").set(identifier.id, type); + } + getType(identifier) { + const result = this.getTypeOrNull(identifier); + if (result == null) { + throw new Error(`Type not found for ${identifier.id}, ${typeof identifier.loc === 'symbol' ? 'generated loc' : serializeLoc(identifier.loc)}`); + } + return result; + } + getTypeOrNull(identifier) { + var _a; + const result = (_a = __classPrivateFieldGet(this, _FlowTypeEnv_types, "f").get(identifier.id)) !== null && _a !== void 0 ? _a : null; + if (result == null && typeof identifier.loc !== 'symbol') { + const flowType = __classPrivateFieldGet(this, _FlowTypeEnv_flowTypes, "f").get(serializeLoc(identifier.loc)); + return flowType !== null && flowType !== void 0 ? flowType : null; + } + return result; + } + getTypeByLoc(loc) { + if (typeof loc === 'symbol') { + return null; + } + const flowType = __classPrivateFieldGet(this, _FlowTypeEnv_flowTypes, "f").get(serializeLoc(loc)); + return flowType !== null && flowType !== void 0 ? flowType : null; + } + nextNominalId() { + var _a, _b; + return makeNominalId((__classPrivateFieldSet(this, _FlowTypeEnv_nextNominalId, (_b = __classPrivateFieldGet(this, _FlowTypeEnv_nextNominalId, "f"), _a = _b++, _b), "f"), _a)); + } + nextTypeParameterId() { + var _a, _b; + return makeTypeParameterId((__classPrivateFieldSet(this, _FlowTypeEnv_nextTypeParameterId, (_b = __classPrivateFieldGet(this, _FlowTypeEnv_nextTypeParameterId, "f"), _a = _b++, _b), "f"), _a)); + } + addBinding(bindingIdentifier, type) { + __classPrivateFieldGet(this, _FlowTypeEnv_bindings, "f").set(bindingIdentifier, type); + } + resolveBinding(bindingIdentifier) { + var _a; + return (_a = __classPrivateFieldGet(this, _FlowTypeEnv_bindings, "f").get(bindingIdentifier)) !== null && _a !== void 0 ? _a : null; + } + pushGeneric(name, generic) { + __classPrivateFieldGet(this, _FlowTypeEnv_generics, "f").unshift([name, generic]); + } + popGeneric(name) { + for (let i = 0; i < __classPrivateFieldGet(this, _FlowTypeEnv_generics, "f").length; i++) { + if (__classPrivateFieldGet(this, _FlowTypeEnv_generics, "f")[i][0] === name) { + __classPrivateFieldGet(this, _FlowTypeEnv_generics, "f").splice(i, 1); + return; + } + } + } + getGeneric(name) { + for (const [eltName, param] of __classPrivateFieldGet(this, _FlowTypeEnv_generics, "f")) { + if (name === eltName) { + return param; + } + } + return null; + } +} +_FlowTypeEnv_nextNominalId = new WeakMap(), _FlowTypeEnv_nextTypeParameterId = new WeakMap(), _FlowTypeEnv_types = new WeakMap(), _FlowTypeEnv_bindings = new WeakMap(), _FlowTypeEnv_generics = new WeakMap(), _FlowTypeEnv_flowTypes = new WeakMap(); +const Primitives = { + number(platform) { + return { kind: 'Concrete', type: { kind: 'Number' }, platform }; + }, + string(platform) { + return { kind: 'Concrete', type: { kind: 'String' }, platform }; + }, + boolean(platform) { + return { kind: 'Concrete', type: { kind: 'Boolean' }, platform }; + }, + void(platform) { + return { kind: 'Concrete', type: { kind: 'Void' }, platform }; + }, + mixed(platform) { + return { kind: 'Concrete', type: { kind: 'Mixed' }, platform }; + }, + enum(platform) { + return { kind: 'Concrete', type: { kind: 'Enum' }, platform }; + }, + todo(platform) { + return { kind: 'Concrete', type: { kind: 'Mixed' }, platform }; + }, +}; +const Resolved = Object.assign(Object.assign({}, Primitives), { nullable(type, platform) { + return { kind: 'Concrete', type: { kind: 'Nullable', type }, platform }; + }, + array(element, platform) { + return { kind: 'Concrete', type: { kind: 'Array', element }, platform }; + }, + set(element, platform) { + return { kind: 'Concrete', type: { kind: 'Set', element }, platform }; + }, + map(key, value, platform) { + return { kind: 'Concrete', type: { kind: 'Map', key, value }, platform }; + }, + function(typeParameters, params, returnType, platform) { + return { + kind: 'Concrete', + type: { kind: 'Function', typeParameters, params, returnType }, + platform, + }; + }, + component(props, children, platform) { + return { + kind: 'Concrete', + type: { kind: 'Component', props, children }, + platform, + }; + }, + object(id, members, platform) { + return { + kind: 'Concrete', + type: { + kind: 'Object', + id, + members, + }, + platform, + }; + }, + class(name, members, platform) { + return { + kind: 'Concrete', + type: { + kind: 'Instance', + name, + members, + }, + platform, + }; + }, + tuple(id, members, platform) { + return { + kind: 'Concrete', + type: { + kind: 'Tuple', + id, + members, + }, + platform, + }; + }, + generic(id, platform, bound = Primitives.mixed(platform)) { + return { + kind: 'Concrete', + type: { + kind: 'Generic', + id, + bound, + }, + platform, + }; + }, + union(members, platform) { + return { + kind: 'Concrete', + type: { + kind: 'Union', + members, + }, + platform, + }; + } }); + +function defaultModuleTypeProvider(moduleName) { + switch (moduleName) { + case 'react-hook-form': { + return { + kind: 'object', + properties: { + useForm: { + kind: 'hook', + returnType: { + kind: 'object', + properties: { + watch: { + kind: 'function', + positionalParams: [], + restParam: Effect.Read, + calleeEffect: Effect.Read, + returnType: { kind: 'type', name: 'Any' }, + returnValueKind: ValueKind.Mutable, + knownIncompatible: `React Hook Form's \`useForm()\` API returns a \`watch()\` function which cannot be memoized safely.`, + }, + }, + }, + }, + }, + }; + } + case '@tanstack/react-table': { + return { + kind: 'object', + properties: { + useReactTable: { + kind: 'hook', + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'type', name: 'Any' }, + knownIncompatible: `TanStack Table's \`useReactTable()\` API returns functions that cannot be memoized safely`, + }, + }, + }; + } + case '@tanstack/react-virtual': { + return { + kind: 'object', + properties: { + useVirtualizer: { + kind: 'hook', + positionalParams: [], + restParam: Effect.Read, + returnType: { kind: 'type', name: 'Any' }, + knownIncompatible: `TanStack Virtual's \`useVirtualizer()\` API returns functions that cannot be memoized safely`, + }, + }, + }; + } + } + return null; +} + +var _Environment_instances, _Environment_globals, _Environment_shapes, _Environment_moduleTypes, _Environment_nextIdentifer, _Environment_nextBlock, _Environment_nextScope, _Environment_scope, _Environment_outlinedFunctions, _Environment_contextIdentifiers, _Environment_hoistedIdentifiers, _Environment_flowTypeEnvironment, _Environment_errors, _Environment_resolveModuleType, _Environment_isKnownReactModule, _Environment_getCustomHookType; +const ExternalFunctionSchema = v4.z.object({ + source: v4.z.string(), + importSpecifierName: v4.z.string(), +}); +const InstrumentationSchema = v4.z + .object({ + fn: ExternalFunctionSchema, + gating: ExternalFunctionSchema.nullable(), + globalGating: v4.z.string().nullable(), +}) + .refine(opts => opts.gating != null || opts.globalGating != null, 'Expected at least one of gating or globalGating'); +const MacroSchema = v4.z.string(); +const HookSchema = v4.z.object({ + effectKind: v4.z.nativeEnum(Effect), + valueKind: v4.z.nativeEnum(ValueKind), + noAlias: v4.z.boolean().default(false), + transitiveMixedData: v4.z.boolean().default(false), +}); +const EnvironmentConfigSchema = v4.z.object({ + customHooks: v4.z.map(v4.z.string(), HookSchema).default(new Map()), + moduleTypeProvider: v4.z.nullable(v4.z.any()).default(null), + customMacros: v4.z.nullable(v4.z.array(MacroSchema)).default(null), + enableResetCacheOnSourceFileChanges: v4.z.nullable(v4.z.boolean()).default(null), + enablePreserveExistingMemoizationGuarantees: v4.z.boolean().default(true), + validatePreserveExistingMemoizationGuarantees: v4.z.boolean().default(true), + validateExhaustiveMemoizationDependencies: v4.z.boolean().default(true), + validateExhaustiveEffectDependencies: v4.z + .enum(['off', 'all', 'missing-only', 'extra-only']) + .default('off'), + enableForest: v4.z.boolean().default(false), + flowTypeProvider: v4.z.nullable(v4.z.any()).default(null), + enableOptionalDependencies: v4.z.boolean().default(true), + enableNameAnonymousFunctions: v4.z.boolean().default(false), + validateHooksUsage: v4.z.boolean().default(true), + validateRefAccessDuringRender: v4.z.boolean().default(true), + validateNoSetStateInRender: v4.z.boolean().default(true), + enableUseKeyedState: v4.z.boolean().default(false), + validateNoSetStateInEffects: v4.z.boolean().default(false), + validateNoDerivedComputationsInEffects: v4.z.boolean().default(false), + validateNoDerivedComputationsInEffects_exp: v4.z.boolean().default(false), + validateNoJSXInTryStatements: v4.z.boolean().default(false), + validateStaticComponents: v4.z.boolean().default(false), + validateNoCapitalizedCalls: v4.z.nullable(v4.z.array(v4.z.string())).default(null), + validateBlocklistedImports: v4.z.nullable(v4.z.array(v4.z.string())).default(null), + validateSourceLocations: v4.z.boolean().default(false), + validateNoImpureFunctionsInRender: v4.z.boolean().default(false), + validateNoFreezingKnownMutableFunctions: v4.z.boolean().default(false), + enableAssumeHooksFollowRulesOfReact: v4.z.boolean().default(true), + enableTransitivelyFreezeFunctionExpressions: v4.z.boolean().default(true), + enableEmitHookGuards: ExternalFunctionSchema.nullable().default(null), + enableFunctionOutlining: v4.z.boolean().default(true), + enableJsxOutlining: v4.z.boolean().default(false), + enableEmitInstrumentForget: InstrumentationSchema.nullable().default(null), + assertValidMutableRanges: v4.z.boolean().default(false), + throwUnknownException__testonly: v4.z.boolean().default(false), + enableCustomTypeDefinitionForReanimated: v4.z.boolean().default(false), + enableTreatRefLikeIdentifiersAsRefs: v4.z.boolean().default(true), + enableTreatSetIdentifiersAsStateSetters: v4.z.boolean().default(false), + validateNoVoidUseMemo: v4.z.boolean().default(true), + enableAllowSetStateFromRefsInEffects: v4.z.boolean().default(true), + enableVerboseNoSetStateInEffect: v4.z.boolean().default(false), +}); +class Environment { + constructor(scope, fnType, outputMode, config, contextIdentifiers, parentFunction, logger, filename, code, programContext) { + _Environment_instances.add(this); + _Environment_globals.set(this, void 0); + _Environment_shapes.set(this, void 0); + _Environment_moduleTypes.set(this, new Map()); + _Environment_nextIdentifer.set(this, 0); + _Environment_nextBlock.set(this, 0); + _Environment_nextScope.set(this, 0); + _Environment_scope.set(this, void 0); + _Environment_outlinedFunctions.set(this, []); + _Environment_contextIdentifiers.set(this, void 0); + _Environment_hoistedIdentifiers.set(this, void 0); + _Environment_flowTypeEnvironment.set(this, void 0); + _Environment_errors.set(this, new CompilerError()); + __classPrivateFieldSet(this, _Environment_scope, scope, "f"); + this.fnType = fnType; + this.outputMode = outputMode; + this.config = config; + this.filename = filename; + this.code = code; + this.logger = logger; + this.programContext = programContext; + __classPrivateFieldSet(this, _Environment_shapes, new Map(DEFAULT_SHAPES), "f"); + __classPrivateFieldSet(this, _Environment_globals, new Map(DEFAULT_GLOBALS), "f"); + for (const [hookName, hook] of this.config.customHooks) { + CompilerError.invariant(!__classPrivateFieldGet(this, _Environment_globals, "f").has(hookName), { + reason: `[Globals] Found existing definition in global registry for custom hook ${hookName}`, + loc: GeneratedSource, + }); + __classPrivateFieldGet(this, _Environment_globals, "f").set(hookName, addHook(__classPrivateFieldGet(this, _Environment_shapes, "f"), { + positionalParams: [], + restParam: hook.effectKind, + returnType: hook.transitiveMixedData + ? { kind: 'Object', shapeId: BuiltInMixedReadonlyId } + : { kind: 'Poly' }, + returnValueKind: hook.valueKind, + calleeEffect: Effect.Read, + hookKind: 'Custom', + noAlias: hook.noAlias, + })); + } + if (config.enableCustomTypeDefinitionForReanimated) { + const reanimatedModuleType = getReanimatedModuleType(__classPrivateFieldGet(this, _Environment_shapes, "f")); + __classPrivateFieldGet(this, _Environment_moduleTypes, "f").set(REANIMATED_MODULE_NAME, reanimatedModuleType); + } + this.parentFunction = parentFunction; + __classPrivateFieldSet(this, _Environment_contextIdentifiers, contextIdentifiers, "f"); + __classPrivateFieldSet(this, _Environment_hoistedIdentifiers, new Set(), "f"); + if (config.flowTypeProvider != null) { + __classPrivateFieldSet(this, _Environment_flowTypeEnvironment, new FlowTypeEnv(), "f"); + CompilerError.invariant(code != null, { + reason: 'Expected Environment to be initialized with source code when a Flow type provider is specified', + loc: GeneratedSource, + }); + __classPrivateFieldGet(this, _Environment_flowTypeEnvironment, "f").init(this, code); + } + else { + __classPrivateFieldSet(this, _Environment_flowTypeEnvironment, null, "f"); + } + } + get typeContext() { + CompilerError.invariant(__classPrivateFieldGet(this, _Environment_flowTypeEnvironment, "f") != null, { + reason: 'Flow type environment not initialized', + loc: GeneratedSource, + }); + return __classPrivateFieldGet(this, _Environment_flowTypeEnvironment, "f"); + } + get enableDropManualMemoization() { + switch (this.outputMode) { + case 'lint': { + return true; + } + case 'client': + case 'ssr': { + return true; + } + default: { + assertExhaustive$1(this.outputMode, `Unexpected output mode '${this.outputMode}'`); + } + } + } + get enableMemoization() { + switch (this.outputMode) { + case 'client': + case 'lint': { + return true; + } + case 'ssr': { + return false; + } + default: { + assertExhaustive$1(this.outputMode, `Unexpected output mode '${this.outputMode}'`); + } + } + } + get enableValidations() { + switch (this.outputMode) { + case 'client': + case 'lint': + case 'ssr': { + return true; + } + default: { + assertExhaustive$1(this.outputMode, `Unexpected output mode '${this.outputMode}'`); + } + } + } + get nextIdentifierId() { + var _a, _b; + return makeIdentifierId((__classPrivateFieldSet(this, _Environment_nextIdentifer, (_b = __classPrivateFieldGet(this, _Environment_nextIdentifer, "f"), _a = _b++, _b), "f"), _a)); + } + get nextBlockId() { + var _a, _b; + return makeBlockId((__classPrivateFieldSet(this, _Environment_nextBlock, (_b = __classPrivateFieldGet(this, _Environment_nextBlock, "f"), _a = _b++, _b), "f"), _a)); + } + get nextScopeId() { + var _a, _b; + return makeScopeId((__classPrivateFieldSet(this, _Environment_nextScope, (_b = __classPrivateFieldGet(this, _Environment_nextScope, "f"), _a = _b++, _b), "f"), _a)); + } + get scope() { + return __classPrivateFieldGet(this, _Environment_scope, "f"); + } + logErrors(errors) { + if (errors.isOk() || this.logger == null) { + return; + } + for (const error of errors.unwrapErr().details) { + this.logger.logEvent(this.filename, { + kind: 'CompileError', + detail: error, + fnLoc: null, + }); + } + } + recordError(error) { + if (error.category === ErrorCategory.Invariant) { + const compilerError = new CompilerError(); + if (error instanceof CompilerDiagnostic) { + compilerError.pushDiagnostic(error); + } + else { + compilerError.pushErrorDetail(error); + } + throw compilerError; + } + if (error instanceof CompilerDiagnostic) { + __classPrivateFieldGet(this, _Environment_errors, "f").pushDiagnostic(error); + } + else { + __classPrivateFieldGet(this, _Environment_errors, "f").pushErrorDetail(error); + } + } + recordErrors(error) { + for (const detail of error.details) { + this.recordError(detail); + } + } + hasErrors() { + return __classPrivateFieldGet(this, _Environment_errors, "f").hasAnyErrors(); + } + aggregateErrors() { + return __classPrivateFieldGet(this, _Environment_errors, "f"); + } + isContextIdentifier(node) { + return __classPrivateFieldGet(this, _Environment_contextIdentifiers, "f").has(node); + } + isHoistedIdentifier(node) { + return __classPrivateFieldGet(this, _Environment_hoistedIdentifiers, "f").has(node); + } + generateGloballyUniqueIdentifierName(name) { + const identifierNode = __classPrivateFieldGet(this, _Environment_scope, "f").generateUidIdentifier(name !== null && name !== void 0 ? name : undefined); + return makeIdentifierName(identifierNode.name); + } + outlineFunction(fn, type) { + __classPrivateFieldGet(this, _Environment_outlinedFunctions, "f").push({ fn, type }); + } + getOutlinedFunctions() { + return __classPrivateFieldGet(this, _Environment_outlinedFunctions, "f"); + } + getGlobalDeclaration(binding, loc) { + var _a, _b, _c; + switch (binding.kind) { + case 'ModuleLocal': { + return isHookName$2(binding.name) ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) : null; + } + case 'Global': { + return ((_a = __classPrivateFieldGet(this, _Environment_globals, "f").get(binding.name)) !== null && _a !== void 0 ? _a : (isHookName$2(binding.name) ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) : null)); + } + case 'ImportSpecifier': { + if (__classPrivateFieldGet(this, _Environment_instances, "m", _Environment_isKnownReactModule).call(this, binding.module)) { + return ((_b = __classPrivateFieldGet(this, _Environment_globals, "f").get(binding.imported)) !== null && _b !== void 0 ? _b : (isHookName$2(binding.imported) || isHookName$2(binding.name) + ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) + : null)); + } + else { + const moduleType = __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_resolveModuleType).call(this, binding.module, loc); + if (moduleType !== null) { + const importedType = this.getPropertyType(moduleType, binding.imported); + if (importedType != null) { + const expectHook = isHookName$2(binding.imported); + const isHook = getHookKindForType(this, importedType) != null; + if (expectHook !== isHook) { + CompilerError.throwInvalidConfig({ + reason: `Invalid type configuration for module`, + description: `Expected type for \`import {${binding.imported}} from '${binding.module}'\` ${expectHook ? 'to be a hook' : 'not to be a hook'} based on the exported name`, + loc, + }); + } + return importedType; + } + } + return isHookName$2(binding.imported) || isHookName$2(binding.name) + ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) + : null; + } + } + case 'ImportDefault': + case 'ImportNamespace': { + if (__classPrivateFieldGet(this, _Environment_instances, "m", _Environment_isKnownReactModule).call(this, binding.module)) { + return ((_c = __classPrivateFieldGet(this, _Environment_globals, "f").get(binding.name)) !== null && _c !== void 0 ? _c : (isHookName$2(binding.name) ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) : null)); + } + else { + const moduleType = __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_resolveModuleType).call(this, binding.module, loc); + if (moduleType !== null) { + let importedType = null; + if (binding.kind === 'ImportDefault') { + const defaultType = this.getPropertyType(moduleType, 'default'); + if (defaultType !== null) { + importedType = defaultType; + } + } + else { + importedType = moduleType; + } + if (importedType !== null) { + const expectHook = isHookName$2(binding.module); + const isHook = getHookKindForType(this, importedType) != null; + if (expectHook !== isHook) { + CompilerError.throwInvalidConfig({ + reason: `Invalid type configuration for module`, + description: `Expected type for \`import ... from '${binding.module}'\` ${expectHook ? 'to be a hook' : 'not to be a hook'} based on the module name`, + loc, + }); + } + return importedType; + } + } + return isHookName$2(binding.name) ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) : null; + } + } + } + } + getFallthroughPropertyType(receiver, _property) { + var _a; + let shapeId = null; + if (receiver.kind === 'Object' || receiver.kind === 'Function') { + shapeId = receiver.shapeId; + } + if (shapeId !== null) { + const shape = __classPrivateFieldGet(this, _Environment_shapes, "f").get(shapeId); + CompilerError.invariant(shape !== undefined, { + reason: `[HIR] Forget internal error: cannot resolve shape ${shapeId}`, + loc: GeneratedSource, + }); + return (_a = shape.properties.get('*')) !== null && _a !== void 0 ? _a : null; + } + return null; + } + getPropertyType(receiver, property) { + var _a, _b, _c; + let shapeId = null; + if (receiver.kind === 'Object' || receiver.kind === 'Function') { + shapeId = receiver.shapeId; + } + if (shapeId !== null) { + const shape = __classPrivateFieldGet(this, _Environment_shapes, "f").get(shapeId); + CompilerError.invariant(shape !== undefined, { + reason: `[HIR] Forget internal error: cannot resolve shape ${shapeId}`, + loc: GeneratedSource, + }); + if (typeof property === 'string') { + return ((_b = (_a = shape.properties.get(property)) !== null && _a !== void 0 ? _a : shape.properties.get('*')) !== null && _b !== void 0 ? _b : (isHookName$2(property) ? __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this) : null)); + } + else { + return (_c = shape.properties.get('*')) !== null && _c !== void 0 ? _c : null; + } + } + else if (typeof property === 'string' && isHookName$2(property)) { + return __classPrivateFieldGet(this, _Environment_instances, "m", _Environment_getCustomHookType).call(this); + } + return null; + } + getFunctionSignature(type) { + const { shapeId } = type; + if (shapeId !== null) { + const shape = __classPrivateFieldGet(this, _Environment_shapes, "f").get(shapeId); + CompilerError.invariant(shape !== undefined, { + reason: `[HIR] Forget internal error: cannot resolve shape ${shapeId}`, + loc: GeneratedSource, + }); + return shape.functionType; + } + return null; + } + addHoistedIdentifier(node) { + __classPrivateFieldGet(this, _Environment_contextIdentifiers, "f").add(node); + __classPrivateFieldGet(this, _Environment_hoistedIdentifiers, "f").add(node); + } +} +_Environment_globals = new WeakMap(), _Environment_shapes = new WeakMap(), _Environment_moduleTypes = new WeakMap(), _Environment_nextIdentifer = new WeakMap(), _Environment_nextBlock = new WeakMap(), _Environment_nextScope = new WeakMap(), _Environment_scope = new WeakMap(), _Environment_outlinedFunctions = new WeakMap(), _Environment_contextIdentifiers = new WeakMap(), _Environment_hoistedIdentifiers = new WeakMap(), _Environment_flowTypeEnvironment = new WeakMap(), _Environment_errors = new WeakMap(), _Environment_instances = new WeakSet(), _Environment_resolveModuleType = function _Environment_resolveModuleType(moduleName, loc) { + var _a; + let moduleType = __classPrivateFieldGet(this, _Environment_moduleTypes, "f").get(moduleName); + if (moduleType === undefined) { + const moduleTypeProvider = (_a = this.config.moduleTypeProvider) !== null && _a !== void 0 ? _a : defaultModuleTypeProvider; + if (moduleTypeProvider == null) { + return null; + } + if (typeof moduleTypeProvider !== 'function') { + CompilerError.throwInvalidConfig({ + reason: `Expected a function for \`moduleTypeProvider\``, + loc, + }); + } + const unparsedModuleConfig = moduleTypeProvider(moduleName); + if (unparsedModuleConfig != null) { + const parsedModuleConfig = TypeSchema.safeParse(unparsedModuleConfig); + if (!parsedModuleConfig.success) { + CompilerError.throwInvalidConfig({ + reason: `Could not parse module type, the configured \`moduleTypeProvider\` function returned an invalid module description`, + description: parsedModuleConfig.error.toString(), + loc, + }); + } + const moduleConfig = parsedModuleConfig.data; + moduleType = installTypeConfig(__classPrivateFieldGet(this, _Environment_globals, "f"), __classPrivateFieldGet(this, _Environment_shapes, "f"), moduleConfig, moduleName, loc); + } + else { + moduleType = null; + } + __classPrivateFieldGet(this, _Environment_moduleTypes, "f").set(moduleName, moduleType); + } + return moduleType; +}, _Environment_isKnownReactModule = function _Environment_isKnownReactModule(moduleName) { + return (moduleName.toLowerCase() === 'react' || + moduleName.toLowerCase() === 'react-dom'); +}, _Environment_getCustomHookType = function _Environment_getCustomHookType() { + if (this.config.enableAssumeHooksFollowRulesOfReact) { + return DefaultNonmutatingHook; + } + else { + return DefaultMutatingHook; + } +}; +Environment.knownReactModules = ['react', 'react-dom']; +const REANIMATED_MODULE_NAME = 'react-native-reanimated'; +function isHookName$2(name) { + return /^use[A-Z0-9]/.test(name); +} +function parseEnvironmentConfig(partialConfig) { + const config = EnvironmentConfigSchema.safeParse(partialConfig); + if (config.success) { + return Ok(config.data); + } + else { + return Err(config.error); + } +} +function validateEnvironmentConfig(partialConfig) { + const config = EnvironmentConfigSchema.safeParse(partialConfig); + if (config.success) { + return config.data; + } + CompilerError.throwInvalidConfig({ + reason: 'Could not validate environment config. Update React Compiler config to fix the error', + description: `${v4$1.fromZodError(config.error)}`, + loc: null, + suggestions: null, + }); +} +function tryParseExternalFunction(maybeExternalFunction) { + const externalFunction = ExternalFunctionSchema.safeParse(maybeExternalFunction); + if (externalFunction.success) { + return externalFunction.data; + } + CompilerError.throwInvalidConfig({ + reason: 'Could not parse external function. Update React Compiler config to fix the error', + description: `${v4$1.fromZodError(externalFunction.error)}`, + loc: null, + suggestions: null, + }); +} + +var _MergedBlocks_map; +function mergeConsecutiveBlocks(fn) { + const merged = new MergedBlocks(); + const fallthroughBlocks = new Set(); + for (const [, block] of fn.body.blocks) { + const fallthrough = terminalFallthrough(block.terminal); + if (fallthrough !== null) { + fallthroughBlocks.add(fallthrough); + } + for (const instr of block.instructions) { + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + mergeConsecutiveBlocks(instr.value.loweredFunc.func); + } + } + if (block.preds.size !== 1 || + block.kind !== 'block' || + fallthroughBlocks.has(block.id)) { + continue; + } + const originalPredecessorId = Array.from(block.preds)[0]; + const predecessorId = merged.get(originalPredecessorId); + const predecessor = fn.body.blocks.get(predecessorId); + CompilerError.invariant(predecessor !== undefined, { + reason: `Expected predecessor ${predecessorId} to exist`, + loc: GeneratedSource, + }); + if (predecessor.terminal.kind !== 'goto' || predecessor.kind !== 'block') { + continue; + } + for (const phi of block.phis) { + CompilerError.invariant(phi.operands.size === 1, { + reason: `Found a block with a single predecessor but where a phi has multiple (${phi.operands.size}) operands`, + loc: GeneratedSource, + }); + const operand = Array.from(phi.operands.values())[0]; + const lvalue = { + kind: 'Identifier', + identifier: phi.place.identifier, + effect: Effect.ConditionallyMutate, + reactive: false, + loc: GeneratedSource, + }; + const instr = { + id: predecessor.terminal.id, + lvalue: Object.assign({}, lvalue), + value: { + kind: 'LoadLocal', + place: Object.assign({}, operand), + loc: GeneratedSource, + }, + effects: [{ kind: 'Alias', from: Object.assign({}, operand), into: Object.assign({}, lvalue) }], + loc: GeneratedSource, + }; + predecessor.instructions.push(instr); + } + predecessor.instructions.push(...block.instructions); + predecessor.terminal = block.terminal; + merged.merge(block.id, predecessorId); + fn.body.blocks.delete(block.id); + } + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + for (const [predecessorId, operand] of phi.operands) { + const mapped = merged.get(predecessorId); + if (mapped !== predecessorId) { + phi.operands.delete(predecessorId); + phi.operands.set(mapped, operand); + } + } + } + } + markPredecessors(fn.body); + for (const [, { terminal }] of fn.body.blocks) { + if (terminalHasFallthrough(terminal)) { + terminal.fallthrough = merged.get(terminal.fallthrough); + } + } +} +class MergedBlocks { + constructor() { + _MergedBlocks_map.set(this, new Map()); + } + merge(block, into) { + const target = this.get(into); + __classPrivateFieldGet(this, _MergedBlocks_map, "f").set(block, target); + } + get(block) { + var _a; + let current = block; + while (__classPrivateFieldGet(this, _MergedBlocks_map, "f").has(current)) { + current = (_a = __classPrivateFieldGet(this, _MergedBlocks_map, "f").get(current)) !== null && _a !== void 0 ? _a : current; + } + return current; + } +} +_MergedBlocks_map = new WeakMap(); + +var _DisjointSet_entries; +class DisjointSet { + constructor() { + _DisjointSet_entries.set(this, new Map()); + } + union(items) { + const first = items.shift(); + CompilerError.invariant(first != null, { + reason: 'Expected set to be non-empty', + loc: GeneratedSource, + }); + let root = this.find(first); + if (root == null) { + root = first; + __classPrivateFieldGet(this, _DisjointSet_entries, "f").set(first, first); + } + for (const item of items) { + let itemParent = __classPrivateFieldGet(this, _DisjointSet_entries, "f").get(item); + if (itemParent == null) { + __classPrivateFieldGet(this, _DisjointSet_entries, "f").set(item, root); + continue; + } + else if (itemParent === root) { + continue; + } + else { + let current = item; + while (itemParent !== root) { + __classPrivateFieldGet(this, _DisjointSet_entries, "f").set(current, root); + current = itemParent; + itemParent = __classPrivateFieldGet(this, _DisjointSet_entries, "f").get(current); + } + } + } + } + find(item) { + if (!__classPrivateFieldGet(this, _DisjointSet_entries, "f").has(item)) { + return null; + } + const parent = __classPrivateFieldGet(this, _DisjointSet_entries, "f").get(item); + if (parent === item) { + return item; + } + const root = this.find(parent); + __classPrivateFieldGet(this, _DisjointSet_entries, "f").set(item, root); + return root; + } + has(item) { + return __classPrivateFieldGet(this, _DisjointSet_entries, "f").has(item); + } + canonicalize() { + const entries = new Map(); + for (const item of __classPrivateFieldGet(this, _DisjointSet_entries, "f").keys()) { + const root = this.find(item); + entries.set(item, root); + } + return entries; + } + forEach(fn) { + for (const item of __classPrivateFieldGet(this, _DisjointSet_entries, "f").keys()) { + const group = this.find(item); + fn(item, group); + } + } + buildSets() { + const ids = new Map(); + const sets = new Map(); + this.forEach((identifier, groupIdentifier) => { + let id = ids.get(groupIdentifier); + if (id == null) { + id = ids.size; + ids.set(groupIdentifier, id); + } + let set = sets.get(id); + if (set === undefined) { + set = new Set(); + sets.set(id, set); + } + set.add(identifier); + }); + return [...sets.values()]; + } + get size() { + return __classPrivateFieldGet(this, _DisjointSet_entries, "f").size; + } +} +_DisjointSet_entries = new WeakMap(); + +function inferReactiveScopeVariables(fn) { + var _a, _b; + const scopeIdentifiers = findDisjointMutableValues(fn); + const scopes = new Map(); + scopeIdentifiers.forEach((identifier, groupIdentifier) => { + let scope = scopes.get(groupIdentifier); + if (scope === undefined) { + scope = { + id: fn.env.nextScopeId, + range: identifier.mutableRange, + dependencies: new Set(), + declarations: new Map(), + reassignments: new Set(), + earlyReturnValue: null, + merged: new Set(), + loc: identifier.loc, + }; + scopes.set(groupIdentifier, scope); + } + else { + if (scope.range.start === 0) { + scope.range.start = identifier.mutableRange.start; + } + else if (identifier.mutableRange.start !== 0) { + scope.range.start = makeInstructionId(Math.min(scope.range.start, identifier.mutableRange.start)); + } + scope.range.end = makeInstructionId(Math.max(scope.range.end, identifier.mutableRange.end)); + scope.loc = mergeLocation(scope.loc, identifier.loc); + } + identifier.scope = scope; + identifier.mutableRange = scope.range; + }); + let maxInstruction = 0; + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + maxInstruction = makeInstructionId(Math.max(maxInstruction, instr.id)); + } + maxInstruction = makeInstructionId(Math.max(maxInstruction, block.terminal.id)); + } + for (const [, scope] of scopes) { + if (scope.range.start === 0 || + scope.range.end === 0 || + maxInstruction === 0 || + scope.range.end > maxInstruction + 1) { + (_b = (_a = fn.env.logger) === null || _a === void 0 ? void 0 : _a.debugLogIRs) === null || _b === void 0 ? void 0 : _b.call(_a, { + kind: 'hir', + name: 'InferReactiveScopeVariables (invalid scope)', + value: fn, + }); + CompilerError.invariant(false, { + reason: `Invalid mutable range for scope`, + description: `Scope @${scope.id} has range [${scope.range.start}:${scope.range.end}] but the valid range is [1:${maxInstruction + 1}]`, + loc: GeneratedSource, + }); + } + } +} +function mergeLocation(l, r) { + if (l === GeneratedSource) { + return r; + } + else if (r === GeneratedSource) { + return l; + } + else { + return { + filename: l.filename, + identifierName: l.identifierName, + start: { + index: Math.min(l.start.index, r.start.index), + line: Math.min(l.start.line, r.start.line), + column: Math.min(l.start.column, r.start.column), + }, + end: { + index: Math.max(l.end.index, r.end.index), + line: Math.max(l.end.line, r.end.line), + column: Math.max(l.end.column, r.end.column), + }, + }; + } +} +function isMutable(instr, place) { + return inRange(instr, place.identifier.mutableRange); +} +function inRange({ id }, range) { + return id >= range.start && id < range.end; +} +function mayAllocate(_env, instruction) { + const { value } = instruction; + switch (value.kind) { + case 'Destructure': { + return doesPatternContainSpreadElement(value.lvalue.pattern); + } + case 'PostfixUpdate': + case 'PrefixUpdate': + case 'Await': + case 'DeclareLocal': + case 'DeclareContext': + case 'StoreLocal': + case 'LoadGlobal': + case 'MetaProperty': + case 'TypeCastExpression': + case 'LoadLocal': + case 'LoadContext': + case 'StoreContext': + case 'PropertyDelete': + case 'ComputedLoad': + case 'ComputedDelete': + case 'JSXText': + case 'TemplateLiteral': + case 'Primitive': + case 'GetIterator': + case 'IteratorNext': + case 'NextPropertyOf': + case 'Debugger': + case 'StartMemoize': + case 'FinishMemoize': + case 'UnaryExpression': + case 'BinaryExpression': + case 'PropertyLoad': + case 'StoreGlobal': { + return false; + } + case 'TaggedTemplateExpression': + case 'CallExpression': + case 'MethodCall': { + return instruction.lvalue.identifier.type.kind !== 'Primitive'; + } + case 'RegExpLiteral': + case 'PropertyStore': + case 'ComputedStore': + case 'ArrayExpression': + case 'JsxExpression': + case 'JsxFragment': + case 'NewExpression': + case 'ObjectExpression': + case 'UnsupportedNode': + case 'ObjectMethod': + case 'FunctionExpression': { + return true; + } + default: { + assertExhaustive$1(value, `Unexpected value kind \`${value.kind}\``); + } + } +} +function findDisjointMutableValues(fn) { + var _a, _b; + const scopeIdentifiers = new DisjointSet(); + const declarations = new Map(); + function declareIdentifier(lvalue) { + if (!declarations.has(lvalue.identifier.declarationId)) { + declarations.set(lvalue.identifier.declarationId, lvalue.identifier); + } + } + for (const [_, block] of fn.body.blocks) { + for (const phi of block.phis) { + if (phi.place.identifier.mutableRange.start + 1 !== + phi.place.identifier.mutableRange.end && + phi.place.identifier.mutableRange.end > + ((_b = (_a = block.instructions.at(0)) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : block.terminal.id)) { + const operands = [phi.place.identifier]; + const declaration = declarations.get(phi.place.identifier.declarationId); + if (declaration !== undefined) { + operands.push(declaration); + } + for (const [_, phiId] of phi.operands) { + operands.push(phiId.identifier); + } + scopeIdentifiers.union(operands); + } + else if (fn.env.config.enableForest) { + for (const [, phiId] of phi.operands) { + scopeIdentifiers.union([phi.place.identifier, phiId.identifier]); + } + } + } + for (const instr of block.instructions) { + const operands = []; + const range = instr.lvalue.identifier.mutableRange; + if (range.end > range.start + 1 || mayAllocate(fn.env, instr)) { + operands.push(instr.lvalue.identifier); + } + if (instr.value.kind === 'DeclareLocal' || + instr.value.kind === 'DeclareContext') { + declareIdentifier(instr.value.lvalue.place); + } + else if (instr.value.kind === 'StoreLocal' || + instr.value.kind === 'StoreContext') { + declareIdentifier(instr.value.lvalue.place); + if (instr.value.lvalue.place.identifier.mutableRange.end > + instr.value.lvalue.place.identifier.mutableRange.start + 1) { + operands.push(instr.value.lvalue.place.identifier); + } + if (isMutable(instr, instr.value.value) && + instr.value.value.identifier.mutableRange.start > 0) { + operands.push(instr.value.value.identifier); + } + } + else if (instr.value.kind === 'Destructure') { + for (const place of eachPatternOperand(instr.value.lvalue.pattern)) { + declareIdentifier(place); + if (place.identifier.mutableRange.end > + place.identifier.mutableRange.start + 1) { + operands.push(place.identifier); + } + } + if (isMutable(instr, instr.value.value) && + instr.value.value.identifier.mutableRange.start > 0) { + operands.push(instr.value.value.identifier); + } + } + else if (instr.value.kind === 'MethodCall') { + for (const operand of eachInstructionOperand(instr)) { + if (isMutable(instr, operand) && + operand.identifier.mutableRange.start > 0) { + operands.push(operand.identifier); + } + } + operands.push(instr.value.property.identifier); + } + else { + for (const operand of eachInstructionOperand(instr)) { + if (isMutable(instr, operand) && + operand.identifier.mutableRange.start > 0) { + operands.push(operand.identifier); + } + } + } + if (operands.length !== 0) { + scopeIdentifiers.union(operands); + } + } + } + return scopeIdentifiers; +} + +function mergeOverlappingReactiveScopesHIR(fn) { + const scopesInfo = collectScopeInfo(fn); + const joinedScopes = getOverlappingReactiveScopes(fn, scopesInfo); + joinedScopes.forEach((scope, groupScope) => { + if (scope !== groupScope) { + groupScope.range.start = makeInstructionId(Math.min(groupScope.range.start, scope.range.start)); + groupScope.range.end = makeInstructionId(Math.max(groupScope.range.end, scope.range.end)); + } + }); + for (const [place, originalScope] of scopesInfo.placeScopes) { + const nextScope = joinedScopes.find(originalScope); + if (nextScope !== null && nextScope !== originalScope) { + place.identifier.scope = nextScope; + } + } +} +function collectScopeInfo(fn) { + const scopeStarts = new Map(); + const scopeEnds = new Map(); + const placeScopes = new Map(); + function collectPlaceScope(place) { + const scope = place.identifier.scope; + if (scope != null) { + placeScopes.set(place, scope); + if (scope.range.start !== scope.range.end) { + getOrInsertDefault(scopeStarts, scope.range.start, new Set()).add(scope); + getOrInsertDefault(scopeEnds, scope.range.end, new Set()).add(scope); + } + } + } + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + for (const operand of eachInstructionLValue(instr)) { + collectPlaceScope(operand); + } + for (const operand of eachInstructionOperand(instr)) { + collectPlaceScope(operand); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + collectPlaceScope(operand); + } + } + return { + scopeStarts: [...scopeStarts.entries()] + .map(([id, scopes]) => ({ id, scopes })) + .sort((a, b) => b.id - a.id), + scopeEnds: [...scopeEnds.entries()] + .map(([id, scopes]) => ({ id, scopes })) + .sort((a, b) => b.id - a.id), + placeScopes, + }; +} +function visitInstructionId(id, { scopeEnds, scopeStarts }, { activeScopes, joined }) { + const scopeEndTop = scopeEnds.at(-1); + if (scopeEndTop != null && scopeEndTop.id <= id) { + scopeEnds.pop(); + const scopesSortedStartDescending = [...scopeEndTop.scopes].sort((a, b) => b.range.start - a.range.start); + for (const scope of scopesSortedStartDescending) { + const idx = activeScopes.indexOf(scope); + if (idx !== -1) { + if (idx !== activeScopes.length - 1) { + joined.union([scope, ...activeScopes.slice(idx + 1)]); + } + activeScopes.splice(idx, 1); + } + } + } + const scopeStartTop = scopeStarts.at(-1); + if (scopeStartTop != null && scopeStartTop.id <= id) { + scopeStarts.pop(); + const scopesSortedEndDescending = [...scopeStartTop.scopes].sort((a, b) => b.range.end - a.range.end); + activeScopes.push(...scopesSortedEndDescending); + for (let i = 1; i < scopesSortedEndDescending.length; i++) { + const prev = scopesSortedEndDescending[i - 1]; + const curr = scopesSortedEndDescending[i]; + if (prev.range.end === curr.range.end) { + joined.union([prev, curr]); + } + } + } +} +function visitPlace(id, place, { activeScopes, joined }) { + const placeScope = getPlaceScope(id, place); + if (placeScope != null && isMutable({ id }, place)) { + const placeScopeIdx = activeScopes.indexOf(placeScope); + if (placeScopeIdx !== -1 && placeScopeIdx !== activeScopes.length - 1) { + joined.union([placeScope, ...activeScopes.slice(placeScopeIdx + 1)]); + } + } +} +function getOverlappingReactiveScopes(fn, context) { + const state = { + joined: new DisjointSet(), + activeScopes: [], + }; + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + visitInstructionId(instr.id, context, state); + for (const place of eachInstructionOperand(instr)) { + if ((instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') && + place.identifier.type.kind === 'Primitive') { + continue; + } + visitPlace(instr.id, place, state); + } + for (const place of eachInstructionLValue(instr)) { + visitPlace(instr.id, place, state); + } + } + visitInstructionId(block.terminal.id, context, state); + for (const place of eachTerminalOperand(block.terminal)) { + visitPlace(block.terminal.id, place, state); + } + } + return state.joined; +} + +function pruneUnusedLabelsHIR(fn) { + var _a; + const merged = []; + const rewrites = new Map(); + for (const [blockId, block] of fn.body.blocks) { + const terminal = block.terminal; + if (terminal.kind === 'label') { + const { block: nextId, fallthrough: fallthroughId } = terminal; + const next = fn.body.blocks.get(nextId); + const fallthrough = fn.body.blocks.get(fallthroughId); + if (next.terminal.kind === 'goto' && + next.terminal.variant === GotoVariant.Break && + next.terminal.block === fallthroughId) { + if (next.kind === 'block' && fallthrough.kind === 'block') { + merged.push({ + label: blockId, + next: nextId, + fallthrough: fallthroughId, + }); + } + } + } + } + for (const { label: originalLabelId, next: nextId, fallthrough: fallthroughId, } of merged) { + const labelId = (_a = rewrites.get(originalLabelId)) !== null && _a !== void 0 ? _a : originalLabelId; + const label = fn.body.blocks.get(labelId); + const next = fn.body.blocks.get(nextId); + const fallthrough = fn.body.blocks.get(fallthroughId); + CompilerError.invariant(next.phis.size === 0 && fallthrough.phis.size === 0, { + reason: 'Unexpected phis when merging label blocks', + loc: label.terminal.loc, + }); + CompilerError.invariant(next.preds.size === 1 && + fallthrough.preds.size === 1 && + next.preds.has(originalLabelId) && + fallthrough.preds.has(nextId), { + reason: 'Unexpected block predecessors when merging label blocks', + loc: label.terminal.loc, + }); + label.instructions.push(...next.instructions, ...fallthrough.instructions); + label.terminal = fallthrough.terminal; + fn.body.blocks.delete(nextId); + fn.body.blocks.delete(fallthroughId); + rewrites.set(fallthroughId, labelId); + } + for (const [_, block] of fn.body.blocks) { + for (const pred of block.preds) { + const rewritten = rewrites.get(pred); + if (rewritten != null) { + block.preds.delete(pred); + block.preds.add(rewritten); + } + } + } +} + +function insertAdditionalFunctionDeclaration(fnPath, compiled, programContext, gatingFunctionIdentifierName) { + var _a, _b; + const originalFnName = fnPath.node.id; + const originalFnParams = fnPath.node.params; + const compiledParams = fnPath.node.params; + CompilerError.invariant(originalFnName != null && compiled.id != null, { + reason: 'Expected function declarations that are referenced elsewhere to have a named identifier', + loc: (_a = fnPath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + CompilerError.invariant(originalFnParams.length === compiledParams.length, { + reason: 'Expected React Compiler optimized function declarations to have the same number of parameters as source', + loc: (_b = fnPath.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + const gatingCondition = libExports$1.identifier(programContext.newUid(`${gatingFunctionIdentifierName}_result`)); + const unoptimizedFnName = libExports$1.identifier(programContext.newUid(`${originalFnName.name}_unoptimized`)); + const optimizedFnName = libExports$1.identifier(programContext.newUid(`${originalFnName.name}_optimized`)); + compiled.id.name = optimizedFnName.name; + fnPath.get('id').replaceInline(unoptimizedFnName); + const newParams = []; + const genNewArgs = []; + for (let i = 0; i < originalFnParams.length; i++) { + const argName = `arg${i}`; + if (originalFnParams[i].type === 'RestElement') { + newParams.push(libExports$1.restElement(libExports$1.identifier(argName))); + genNewArgs.push(() => libExports$1.spreadElement(libExports$1.identifier(argName))); + } + else { + newParams.push(libExports$1.identifier(argName)); + genNewArgs.push(() => libExports$1.identifier(argName)); + } + } + fnPath.insertAfter(libExports$1.functionDeclaration(originalFnName, newParams, libExports$1.blockStatement([ + libExports$1.ifStatement(gatingCondition, libExports$1.returnStatement(libExports$1.callExpression(compiled.id, genNewArgs.map(fn => fn()))), libExports$1.returnStatement(libExports$1.callExpression(unoptimizedFnName, genNewArgs.map(fn => fn())))), + ]))); + fnPath.insertBefore(libExports$1.variableDeclaration('const', [ + libExports$1.variableDeclarator(gatingCondition, libExports$1.callExpression(libExports$1.identifier(gatingFunctionIdentifierName), [])), + ])); + fnPath.insertBefore(compiled); +} +function insertGatedFunctionDeclaration(fnPath, compiled, programContext, gating, referencedBeforeDeclaration) { + var _a; + const gatingImportedName = programContext.addImportSpecifier(gating).name; + if (referencedBeforeDeclaration && fnPath.isFunctionDeclaration()) { + CompilerError.invariant(compiled.type === 'FunctionDeclaration', { + reason: 'Expected compiled node type to match input type', + description: `Got ${compiled.type} but expected FunctionDeclaration`, + loc: (_a = fnPath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + insertAdditionalFunctionDeclaration(fnPath, compiled, programContext, gatingImportedName); + } + else { + const gatingExpression = libExports$1.conditionalExpression(libExports$1.callExpression(libExports$1.identifier(gatingImportedName), []), buildFunctionExpression(compiled), buildFunctionExpression(fnPath.node)); + if (fnPath.parentPath.node.type !== 'ExportDefaultDeclaration' && + fnPath.node.type === 'FunctionDeclaration' && + fnPath.node.id != null) { + fnPath.replaceWith(libExports$1.variableDeclaration('const', [ + libExports$1.variableDeclarator(fnPath.node.id, gatingExpression), + ])); + } + else if (fnPath.parentPath.node.type === 'ExportDefaultDeclaration' && + fnPath.node.type !== 'ArrowFunctionExpression' && + fnPath.node.id != null) { + fnPath.insertAfter(libExports$1.exportDefaultDeclaration(libExports$1.identifier(fnPath.node.id.name))); + fnPath.parentPath.replaceWith(libExports$1.variableDeclaration('const', [ + libExports$1.variableDeclarator(libExports$1.identifier(fnPath.node.id.name), gatingExpression), + ])); + } + else { + fnPath.replaceWith(gatingExpression); + } + } +} +function buildFunctionExpression(node) { + var _a, _b; + if (node.type === 'ArrowFunctionExpression' || + node.type === 'FunctionExpression') { + return node; + } + else { + const fn = { + type: 'FunctionExpression', + async: node.async, + generator: node.generator, + loc: (_a = node.loc) !== null && _a !== void 0 ? _a : null, + id: (_b = node.id) !== null && _b !== void 0 ? _b : null, + params: node.params, + body: node.body, + }; + return fn; + } +} + +function isComponentDeclaration(node) { + return Object.prototype.hasOwnProperty.call(node, '__componentDeclaration'); +} + +function isHookDeclaration(node) { + return Object.prototype.hasOwnProperty.call(node, '__hookDeclaration'); +} + +const DEFAULT_IDENTIFIER_INFO = { + reassigned: false, + reassignedByInnerFn: false, + referencedByInnerFn: false, +}; +const withFunctionScope = { + enter: function (path, state) { + state.currentFn.push(path); + }, + exit: function (_, state) { + state.currentFn.pop(); + }, +}; +function findContextIdentifiers(func) { + const state = { + currentFn: [], + identifiers: new Map(), + }; + func.traverse({ + FunctionDeclaration: withFunctionScope, + FunctionExpression: withFunctionScope, + ArrowFunctionExpression: withFunctionScope, + ObjectMethod: withFunctionScope, + AssignmentExpression(path, state) { + var _a, _b; + const left = path.get('left'); + if (left.isLVal()) { + const currentFn = (_a = state.currentFn.at(-1)) !== null && _a !== void 0 ? _a : null; + handleAssignment(currentFn, state.identifiers, left); + } + else { + CompilerError.throwTodo({ + reason: `Unsupported syntax on the left side of an AssignmentExpression`, + description: `Expected an LVal, got: ${left.type}`, + loc: (_b = left.node.loc) !== null && _b !== void 0 ? _b : null, + }); + } + }, + UpdateExpression(path, state) { + var _a; + const argument = path.get('argument'); + const currentFn = (_a = state.currentFn.at(-1)) !== null && _a !== void 0 ? _a : null; + if (argument.isLVal()) { + handleAssignment(currentFn, state.identifiers, argument); + } + }, + Identifier(path, state) { + var _a; + const currentFn = (_a = state.currentFn.at(-1)) !== null && _a !== void 0 ? _a : null; + if (path.isReferencedIdentifier()) { + handleIdentifier(currentFn, state.identifiers, path); + } + }, + }, state); + const result = new Set(); + for (const [id, info] of state.identifiers.entries()) { + if (info.reassignedByInnerFn) { + result.add(id); + } + else if (info.reassigned && info.referencedByInnerFn) { + result.add(id); + } + } + return result; +} +function handleIdentifier(currentFn, identifiers, path) { + const name = path.node.name; + const binding = path.scope.getBinding(name); + if (binding == null) { + return; + } + const identifier = getOrInsertDefault(identifiers, binding.identifier, Object.assign({}, DEFAULT_IDENTIFIER_INFO)); + if (currentFn != null) { + const bindingAboveLambdaScope = currentFn.scope.parent.getBinding(name); + if (binding === bindingAboveLambdaScope) { + identifier.referencedByInnerFn = true; + } + } +} +function handleAssignment(currentFn, identifiers, lvalPath) { + var _a, _b, _c; + const lvalNode = lvalPath.node; + switch (lvalNode.type) { + case 'Identifier': { + const path = lvalPath; + const name = path.node.name; + const binding = path.scope.getBinding(name); + if (binding == null) { + break; + } + const state = getOrInsertDefault(identifiers, binding.identifier, Object.assign({}, DEFAULT_IDENTIFIER_INFO)); + state.reassigned = true; + if (currentFn != null) { + const bindingAboveLambdaScope = currentFn.scope.parent.getBinding(name); + if (binding === bindingAboveLambdaScope) { + state.reassignedByInnerFn = true; + } + } + break; + } + case 'ArrayPattern': { + const path = lvalPath; + for (const element of path.get('elements')) { + if (nonNull(element)) { + handleAssignment(currentFn, identifiers, element); + } + } + break; + } + case 'ObjectPattern': { + const path = lvalPath; + for (const property of path.get('properties')) { + if (property.isObjectProperty()) { + const valuePath = property.get('value'); + CompilerError.invariant(valuePath.isLVal(), { + reason: `[FindContextIdentifiers] Expected object property value to be an LVal, got: ${valuePath.type}`, + loc: (_a = valuePath.node.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + handleAssignment(currentFn, identifiers, valuePath); + } + else { + CompilerError.invariant(property.isRestElement(), { + reason: `[FindContextIdentifiers] Invalid assumptions for babel types.`, + loc: (_b = property.node.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + handleAssignment(currentFn, identifiers, property); + } + } + break; + } + case 'AssignmentPattern': { + const path = lvalPath; + const left = path.get('left'); + handleAssignment(currentFn, identifiers, left); + break; + } + case 'RestElement': { + const path = lvalPath; + handleAssignment(currentFn, identifiers, path.get('argument')); + break; + } + case 'MemberExpression': { + break; + } + default: { + CompilerError.throwTodo({ + reason: `[FindContextIdentifiers] Cannot handle Object destructuring assignment target ${lvalNode.type}`, + description: null, + loc: (_c = lvalNode.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + suggestions: null, + }); + } + } +} +function nonNull(t) { + return t.node != null; +} + +function eliminateRedundantPhi(fn, sharedRewrites) { + const ir = fn.body; + const rewrites = sharedRewrites != null ? sharedRewrites : new Map(); + let hasBackEdge = false; + const visited = new Set(); + let size = rewrites.size; + do { + size = rewrites.size; + for (const [blockId, block] of ir.blocks) { + if (!hasBackEdge) { + for (const predId of block.preds) { + if (!visited.has(predId)) { + hasBackEdge = true; + } + } + } + visited.add(blockId); + phis: for (const phi of block.phis) { + phi.operands.forEach((place, _) => rewritePlace(place, rewrites)); + let same = null; + for (const [_, operand] of phi.operands) { + if ((same !== null && operand.identifier.id === same.id) || + operand.identifier.id === phi.place.identifier.id) { + continue; + } + else if (same !== null) { + continue phis; + } + else { + same = operand.identifier; + } + } + CompilerError.invariant(same !== null, { + reason: 'Expected phis to be non-empty', + loc: GeneratedSource, + }); + rewrites.set(phi.place.identifier, same); + block.phis.delete(phi); + } + for (const instr of block.instructions) { + for (const place of eachInstructionLValue(instr)) { + rewritePlace(place, rewrites); + } + for (const place of eachInstructionOperand(instr)) { + rewritePlace(place, rewrites); + } + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + const { context } = instr.value.loweredFunc.func; + for (const place of context) { + rewritePlace(place, rewrites); + } + eliminateRedundantPhi(instr.value.loweredFunc.func, rewrites); + } + } + const { terminal } = block; + for (const place of eachTerminalOperand(terminal)) { + rewritePlace(place, rewrites); + } + } + } while (rewrites.size > size && hasBackEdge); +} +function rewritePlace(place, rewrites) { + const rewrite = rewrites.get(place.identifier); + if (rewrite != null) { + place.identifier = rewrite; + } +} + +var _SSABuilder_states, _SSABuilder_current, _SSABuilder_blocks, _SSABuilder_env, _SSABuilder_unknown, _SSABuilder_context; +class SSABuilder { + constructor(env, blocks) { + _SSABuilder_states.set(this, new Map()); + _SSABuilder_current.set(this, null); + this.unsealedPreds = new Map(); + _SSABuilder_blocks.set(this, void 0); + _SSABuilder_env.set(this, void 0); + _SSABuilder_unknown.set(this, new Set()); + _SSABuilder_context.set(this, new Set()); + __classPrivateFieldSet(this, _SSABuilder_blocks, new Map(blocks), "f"); + __classPrivateFieldSet(this, _SSABuilder_env, env, "f"); + } + get nextSsaId() { + return __classPrivateFieldGet(this, _SSABuilder_env, "f").nextIdentifierId; + } + defineFunction(func) { + for (const [id, block] of func.body.blocks) { + __classPrivateFieldGet(this, _SSABuilder_blocks, "f").set(id, block); + } + } + enter(fn) { + const current = __classPrivateFieldGet(this, _SSABuilder_current, "f"); + fn(); + __classPrivateFieldSet(this, _SSABuilder_current, current, "f"); + } + state() { + CompilerError.invariant(__classPrivateFieldGet(this, _SSABuilder_current, "f") !== null, { + reason: 'we need to be in a block to access state!', + loc: GeneratedSource, + }); + return __classPrivateFieldGet(this, _SSABuilder_states, "f").get(__classPrivateFieldGet(this, _SSABuilder_current, "f")); + } + makeId(oldId) { + return { + id: this.nextSsaId, + declarationId: oldId.declarationId, + name: oldId.name, + mutableRange: { + start: makeInstructionId(0), + end: makeInstructionId(0), + }, + scope: null, + type: makeType(), + loc: oldId.loc, + }; + } + defineContext(oldPlace) { + const newPlace = this.definePlace(oldPlace); + __classPrivateFieldGet(this, _SSABuilder_context, "f").add(oldPlace.identifier); + return newPlace; + } + definePlace(oldPlace) { + const oldId = oldPlace.identifier; + if (__classPrivateFieldGet(this, _SSABuilder_unknown, "f").has(oldId)) { + CompilerError.throwTodo({ + reason: `[hoisting] EnterSSA: Expected identifier to be defined before being used`, + description: `Identifier ${printIdentifier(oldId)} is undefined`, + loc: oldPlace.loc, + suggestions: null, + }); + } + if (__classPrivateFieldGet(this, _SSABuilder_context, "f").has(oldId)) { + return this.getPlace(oldPlace); + } + const newId = this.makeId(oldId); + this.state().defs.set(oldId, newId); + return Object.assign(Object.assign({}, oldPlace), { identifier: newId }); + } + getPlace(oldPlace) { + const newId = this.getIdAt(oldPlace, __classPrivateFieldGet(this, _SSABuilder_current, "f").id); + return Object.assign(Object.assign({}, oldPlace), { identifier: newId }); + } + getIdAt(oldPlace, blockId) { + const block = __classPrivateFieldGet(this, _SSABuilder_blocks, "f").get(blockId); + const state = __classPrivateFieldGet(this, _SSABuilder_states, "f").get(block); + if (state.defs.has(oldPlace.identifier)) { + return state.defs.get(oldPlace.identifier); + } + if (block.preds.size == 0) { + __classPrivateFieldGet(this, _SSABuilder_unknown, "f").add(oldPlace.identifier); + return oldPlace.identifier; + } + if (this.unsealedPreds.get(block) > 0) { + const newId = this.makeId(oldPlace.identifier); + state.incompletePhis.push({ + oldPlace, + newPlace: Object.assign(Object.assign({}, oldPlace), { identifier: newId }), + }); + state.defs.set(oldPlace.identifier, newId); + return newId; + } + if (block.preds.size == 1) { + const [pred] = block.preds; + const newId = this.getIdAt(oldPlace, pred); + state.defs.set(oldPlace.identifier, newId); + return newId; + } + const newId = this.makeId(oldPlace.identifier); + state.defs.set(oldPlace.identifier, newId); + return this.addPhi(block, oldPlace, Object.assign(Object.assign({}, oldPlace), { identifier: newId })); + } + addPhi(block, oldPlace, newPlace) { + const predDefs = new Map(); + for (const predBlockId of block.preds) { + const predId = this.getIdAt(oldPlace, predBlockId); + predDefs.set(predBlockId, Object.assign(Object.assign({}, oldPlace), { identifier: predId })); + } + const phi = { + kind: 'Phi', + place: newPlace, + operands: predDefs, + }; + block.phis.add(phi); + return newPlace.identifier; + } + fixIncompletePhis(block) { + const state = __classPrivateFieldGet(this, _SSABuilder_states, "f").get(block); + for (const phi of state.incompletePhis) { + this.addPhi(block, phi.oldPlace, phi.newPlace); + } + } + startBlock(block) { + __classPrivateFieldSet(this, _SSABuilder_current, block, "f"); + __classPrivateFieldGet(this, _SSABuilder_states, "f").set(block, { + defs: new Map(), + incompletePhis: [], + }); + } + print() { + var _a; + const text = []; + for (const [block, state] of __classPrivateFieldGet(this, _SSABuilder_states, "f")) { + text.push(`bb${block.id}:`); + for (const [oldId, newId] of state.defs) { + text.push(` \$${printIdentifier(oldId)}: \$${printIdentifier(newId)}`); + } + for (const incompletePhi of state.incompletePhis) { + text.push(` iphi \$${printPlace(incompletePhi.newPlace)} = \$${printPlace(incompletePhi.oldPlace)}`); + } + } + text.push(`current block: bb${(_a = __classPrivateFieldGet(this, _SSABuilder_current, "f")) === null || _a === void 0 ? void 0 : _a.id}`); + console.log(text.join('\n')); + } +} +_SSABuilder_states = new WeakMap(), _SSABuilder_current = new WeakMap(), _SSABuilder_blocks = new WeakMap(), _SSABuilder_env = new WeakMap(), _SSABuilder_unknown = new WeakMap(), _SSABuilder_context = new WeakMap(); +function enterSSA(func) { + const builder = new SSABuilder(func.env, func.body.blocks); + enterSSAImpl(func, builder, func.body.entry); +} +function enterSSAImpl(func, builder, rootEntry) { + const visitedBlocks = new Set(); + for (const [blockId, block] of func.body.blocks) { + CompilerError.invariant(!visitedBlocks.has(block), { + reason: `found a cycle! visiting bb${block.id} again`, + loc: GeneratedSource, + }); + visitedBlocks.add(block); + builder.startBlock(block); + if (blockId === rootEntry) { + CompilerError.invariant(func.context.length === 0, { + reason: `Expected function context to be empty for outer function declarations`, + loc: func.loc, + }); + func.params = func.params.map(param => { + if (param.kind === 'Identifier') { + return builder.definePlace(param); + } + else { + return { + kind: 'Spread', + place: builder.definePlace(param.place), + }; + } + }); + } + for (const instr of block.instructions) { + mapInstructionOperands(instr, place => builder.getPlace(place)); + mapInstructionLValues(instr, lvalue => builder.definePlace(lvalue)); + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + const loweredFunc = instr.value.loweredFunc.func; + const entry = loweredFunc.body.blocks.get(loweredFunc.body.entry); + CompilerError.invariant(entry.preds.size === 0, { + reason: 'Expected function expression entry block to have zero predecessors', + loc: GeneratedSource, + }); + entry.preds.add(blockId); + builder.defineFunction(loweredFunc); + builder.enter(() => { + loweredFunc.params = loweredFunc.params.map(param => { + if (param.kind === 'Identifier') { + return builder.definePlace(param); + } + else { + return { + kind: 'Spread', + place: builder.definePlace(param.place), + }; + } + }); + enterSSAImpl(loweredFunc, builder, rootEntry); + }); + entry.preds.clear(); + } + } + mapTerminalOperands(block.terminal, place => builder.getPlace(place)); + for (const outputId of eachTerminalSuccessor(block.terminal)) { + const output = func.body.blocks.get(outputId); + let count; + if (builder.unsealedPreds.has(output)) { + count = builder.unsealedPreds.get(output) - 1; + } + else { + count = output.preds.size - 1; + } + builder.unsealedPreds.set(output, count); + if (count === 0 && visitedBlocks.has(output)) { + builder.fixIncompletePhis(output); + } + } + } +} + +function rewriteInstructionKindsBasedOnReassignment(fn) { + const declarations = new Map(); + for (const param of fn.params) { + let place = param.kind === 'Identifier' ? param : param.place; + if (place.identifier.name !== null) { + declarations.set(place.identifier.declarationId, { + kind: InstructionKind.Let, + place, + }); + } + } + for (const place of fn.context) { + if (place.identifier.name !== null) { + declarations.set(place.identifier.declarationId, { + kind: InstructionKind.Let, + place, + }); + } + } + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'DeclareLocal': { + const lvalue = value.lvalue; + CompilerError.invariant(!declarations.has(lvalue.place.identifier.declarationId), { + reason: `Expected variable not to be defined prior to declaration`, + description: `${printPlace(lvalue.place)} was already defined`, + loc: lvalue.place.loc, + }); + declarations.set(lvalue.place.identifier.declarationId, lvalue); + break; + } + case 'StoreLocal': { + const lvalue = value.lvalue; + if (lvalue.place.identifier.name !== null) { + const declaration = declarations.get(lvalue.place.identifier.declarationId); + if (declaration === undefined) { + CompilerError.invariant(!declarations.has(lvalue.place.identifier.declarationId), { + reason: `Expected variable not to be defined prior to declaration`, + description: `${printPlace(lvalue.place)} was already defined`, + loc: lvalue.place.loc, + }); + declarations.set(lvalue.place.identifier.declarationId, lvalue); + lvalue.kind = InstructionKind.Const; + } + else { + declaration.kind = InstructionKind.Let; + lvalue.kind = InstructionKind.Reassign; + } + } + break; + } + case 'Destructure': { + const lvalue = value.lvalue; + let kind = null; + for (const place of eachPatternOperand(lvalue.pattern)) { + if (place.identifier.name === null) { + CompilerError.invariant(kind === null || kind === InstructionKind.Const, { + reason: `Expected consistent kind for destructuring`, + description: `other places were \`${kind}\` but '${printPlace(place)}' is const`, + loc: place.loc, + }); + kind = InstructionKind.Const; + } + else { + const declaration = declarations.get(place.identifier.declarationId); + if (declaration === undefined) { + CompilerError.invariant(block.kind !== 'value', { + reason: `TODO: Handle reassignment in a value block where the original declaration was removed by dead code elimination (DCE)`, + loc: place.loc, + }); + declarations.set(place.identifier.declarationId, lvalue); + CompilerError.invariant(kind === null || kind === InstructionKind.Const, { + reason: `Expected consistent kind for destructuring`, + description: `Other places were \`${kind}\` but '${printPlace(place)}' is const`, + loc: place.loc, + }); + kind = InstructionKind.Const; + } + else { + CompilerError.invariant(kind === null || kind === InstructionKind.Reassign, { + reason: `Expected consistent kind for destructuring`, + description: `Other places were \`${kind}\` but '${printPlace(place)}' is reassigned`, + loc: place.loc, + }); + kind = InstructionKind.Reassign; + declaration.kind = InstructionKind.Let; + } + } + } + CompilerError.invariant(kind !== null, { + reason: 'Expected at least one operand', + loc: GeneratedSource, + }); + lvalue.kind = kind; + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + const lvalue = value.lvalue; + const declaration = declarations.get(lvalue.identifier.declarationId); + CompilerError.invariant(declaration !== undefined, { + reason: `Expected variable to have been defined`, + description: `No declaration for ${printPlace(lvalue)}`, + loc: lvalue.loc, + }); + declaration.kind = InstructionKind.Let; + break; + } + } + } + } +} + +function constantPropagation(fn) { + const constants = new Map(); + constantPropagationImpl(fn, constants); +} +function constantPropagationImpl(fn, constants) { + while (true) { + const haveTerminalsChanged = applyConstantPropagation(fn, constants); + if (!haveTerminalsChanged) { + break; + } + reversePostorderBlocks(fn.body); + removeUnreachableForUpdates(fn.body); + removeDeadDoWhileStatements(fn.body); + removeUnnecessaryTryCatch(fn.body); + markInstructionIds(fn.body); + markPredecessors(fn.body); + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + for (const [predecessor] of phi.operands) { + if (!block.preds.has(predecessor)) { + phi.operands.delete(predecessor); + } + } + } + } + eliminateRedundantPhi(fn); + mergeConsecutiveBlocks(fn); + assertConsistentIdentifiers(fn); + assertTerminalSuccessorsExist(fn); + } +} +function applyConstantPropagation(fn, constants) { + let hasChanges = false; + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + let value = evaluatePhi(phi, constants); + if (value !== null) { + constants.set(phi.place.identifier.id, value); + } + } + for (let i = 0; i < block.instructions.length; i++) { + if (block.kind === 'sequence' && i === block.instructions.length - 1) { + continue; + } + const instr = block.instructions[i]; + const value = evaluateInstruction(constants, instr); + if (value !== null) { + constants.set(instr.lvalue.identifier.id, value); + } + } + const terminal = block.terminal; + switch (terminal.kind) { + case 'if': { + const testValue = read(constants, terminal.test); + if (testValue !== null && testValue.kind === 'Primitive') { + hasChanges = true; + const targetBlockId = testValue.value + ? terminal.consequent + : terminal.alternate; + block.terminal = { + kind: 'goto', + variant: GotoVariant.Break, + block: targetBlockId, + id: terminal.id, + loc: terminal.loc, + }; + } + break; + } + } + } + return hasChanges; +} +function evaluatePhi(phi, constants) { + var _a; + let value = null; + for (const [, operand] of phi.operands) { + const operandValue = (_a = constants.get(operand.identifier.id)) !== null && _a !== void 0 ? _a : null; + if (operandValue === null) { + return null; + } + if (value === null) { + value = operandValue; + continue; + } + if (operandValue.kind !== value.kind) { + return null; + } + switch (operandValue.kind) { + case 'Primitive': { + CompilerError.invariant(value.kind === 'Primitive', { + reason: 'value kind expected to be Primitive', + loc: GeneratedSource, + }); + if (operandValue.value !== value.value) { + return null; + } + break; + } + case 'LoadGlobal': { + CompilerError.invariant(value.kind === 'LoadGlobal', { + reason: 'value kind expected to be LoadGlobal', + loc: GeneratedSource, + }); + if (operandValue.binding.name !== value.binding.name) { + return null; + } + break; + } + default: + return null; + } + } + return value; +} +function evaluateInstruction(constants, instr) { + const value = instr.value; + switch (value.kind) { + case 'Primitive': { + return value; + } + case 'LoadGlobal': { + return value; + } + case 'ComputedLoad': { + const property = read(constants, value.property); + if (property !== null && + property.kind === 'Primitive' && + ((typeof property.value === 'string' && + libExports$1.isValidIdentifier(property.value)) || + typeof property.value === 'number')) { + const nextValue = { + kind: 'PropertyLoad', + loc: value.loc, + property: makePropertyLiteral(property.value), + object: value.object, + }; + instr.value = nextValue; + } + return null; + } + case 'ComputedStore': { + const property = read(constants, value.property); + if (property !== null && + property.kind === 'Primitive' && + ((typeof property.value === 'string' && + libExports$1.isValidIdentifier(property.value)) || + typeof property.value === 'number')) { + const nextValue = { + kind: 'PropertyStore', + loc: value.loc, + property: makePropertyLiteral(property.value), + object: value.object, + value: value.value, + }; + instr.value = nextValue; + } + return null; + } + case 'PostfixUpdate': { + const previous = read(constants, value.value); + if (previous !== null && + previous.kind === 'Primitive' && + typeof previous.value === 'number') { + const next = value.operation === '++' ? previous.value + 1 : previous.value - 1; + constants.set(value.lvalue.identifier.id, { + kind: 'Primitive', + value: next, + loc: value.loc, + }); + return previous; + } + return null; + } + case 'PrefixUpdate': { + const previous = read(constants, value.value); + if (previous !== null && + previous.kind === 'Primitive' && + typeof previous.value === 'number') { + const next = { + kind: 'Primitive', + value: value.operation === '++' ? previous.value + 1 : previous.value - 1, + loc: value.loc, + }; + constants.set(value.lvalue.identifier.id, next); + return next; + } + return null; + } + case 'UnaryExpression': { + switch (value.operator) { + case '!': { + const operand = read(constants, value.value); + if (operand !== null && operand.kind === 'Primitive') { + const result = { + kind: 'Primitive', + value: !operand.value, + loc: value.loc, + }; + instr.value = result; + return result; + } + return null; + } + case '-': { + const operand = read(constants, value.value); + if (operand !== null && + operand.kind === 'Primitive' && + typeof operand.value === 'number') { + const result = { + kind: 'Primitive', + value: operand.value * -1, + loc: value.loc, + }; + instr.value = result; + return result; + } + return null; + } + default: + return null; + } + } + case 'BinaryExpression': { + const lhsValue = read(constants, value.left); + const rhsValue = read(constants, value.right); + if (lhsValue !== null && + rhsValue !== null && + lhsValue.kind === 'Primitive' && + rhsValue.kind === 'Primitive') { + const lhs = lhsValue.value; + const rhs = rhsValue.value; + let result = null; + switch (value.operator) { + case '+': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs + rhs, loc: value.loc }; + } + else if (typeof lhs === 'string' && typeof rhs === 'string') { + result = { kind: 'Primitive', value: lhs + rhs, loc: value.loc }; + } + break; + } + case '-': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs - rhs, loc: value.loc }; + } + break; + } + case '*': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs * rhs, loc: value.loc }; + } + break; + } + case '/': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs / rhs, loc: value.loc }; + } + break; + } + case '|': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs | rhs, loc: value.loc }; + } + break; + } + case '&': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs & rhs, loc: value.loc }; + } + break; + } + case '^': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs ^ rhs, loc: value.loc }; + } + break; + } + case '<<': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs << rhs, loc: value.loc }; + } + break; + } + case '>>': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs >> rhs, loc: value.loc }; + } + break; + } + case '>>>': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { + kind: 'Primitive', + value: lhs >>> rhs, + loc: value.loc, + }; + } + break; + } + case '%': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs % rhs, loc: value.loc }; + } + break; + } + case '**': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: Math.pow(lhs, rhs), loc: value.loc }; + } + break; + } + case '<': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs < rhs, loc: value.loc }; + } + break; + } + case '<=': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs <= rhs, loc: value.loc }; + } + break; + } + case '>': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs > rhs, loc: value.loc }; + } + break; + } + case '>=': { + if (typeof lhs === 'number' && typeof rhs === 'number') { + result = { kind: 'Primitive', value: lhs >= rhs, loc: value.loc }; + } + break; + } + case '==': { + result = { kind: 'Primitive', value: lhs == rhs, loc: value.loc }; + break; + } + case '===': { + result = { kind: 'Primitive', value: lhs === rhs, loc: value.loc }; + break; + } + case '!=': { + result = { kind: 'Primitive', value: lhs != rhs, loc: value.loc }; + break; + } + case '!==': { + result = { kind: 'Primitive', value: lhs !== rhs, loc: value.loc }; + break; + } + } + if (result !== null) { + instr.value = result; + return result; + } + } + return null; + } + case 'PropertyLoad': { + const objectValue = read(constants, value.object); + if (objectValue !== null) { + if (objectValue.kind === 'Primitive' && + typeof objectValue.value === 'string' && + value.property === 'length') { + const result = { + kind: 'Primitive', + value: objectValue.value.length, + loc: value.loc, + }; + instr.value = result; + return result; + } + } + return null; + } + case 'TemplateLiteral': { + if (value.subexprs.length === 0) { + const result = { + kind: 'Primitive', + value: value.quasis.map(q => q.cooked).join(''), + loc: value.loc, + }; + instr.value = result; + return result; + } + if (value.subexprs.length !== value.quasis.length - 1) { + return null; + } + if (value.quasis.some(q => q.cooked === undefined)) { + return null; + } + let quasiIndex = 0; + let resultString = value.quasis[quasiIndex].cooked; + ++quasiIndex; + for (const subExpr of value.subexprs) { + const subExprValue = read(constants, subExpr); + if (!subExprValue || subExprValue.kind !== 'Primitive') { + return null; + } + const expressionValue = subExprValue.value; + if (typeof expressionValue !== 'number' && + typeof expressionValue !== 'string' && + typeof expressionValue !== 'boolean' && + !(typeof expressionValue === 'object' && expressionValue === null)) { + return null; + } + const suffix = value.quasis[quasiIndex].cooked; + ++quasiIndex; + if (suffix === undefined) { + return null; + } + resultString = resultString.concat(expressionValue, suffix); + } + const result = { + kind: 'Primitive', + value: resultString, + loc: value.loc, + }; + instr.value = result; + return result; + } + case 'LoadLocal': { + const placeValue = read(constants, value.place); + if (placeValue !== null) { + instr.value = placeValue; + } + return placeValue; + } + case 'StoreLocal': { + const placeValue = read(constants, value.value); + if (placeValue !== null) { + constants.set(value.lvalue.place.identifier.id, placeValue); + } + return placeValue; + } + case 'ObjectMethod': + case 'FunctionExpression': { + constantPropagationImpl(value.loweredFunc.func, constants); + return null; + } + case 'StartMemoize': { + if (value.deps != null) { + for (const dep of value.deps) { + if (dep.root.kind === 'NamedLocal') { + const placeValue = read(constants, dep.root.value); + if (placeValue != null && placeValue.kind === 'Primitive') { + dep.root.constant = true; + } + } + } + } + return null; + } + default: { + return null; + } + } +} +function read(constants, place) { + var _a; + return (_a = constants.get(place.identifier.id)) !== null && _a !== void 0 ? _a : null; +} + +function deadCodeElimination(fn) { + const state = findReferencedIdentifiers(fn); + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + if (!state.isIdOrNameUsed(phi.place.identifier)) { + block.phis.delete(phi); + } + } + retainWhere(block.instructions, instr => state.isIdOrNameUsed(instr.lvalue.identifier)); + for (let i = 0; i < block.instructions.length; i++) { + const isBlockValue = block.kind !== 'block' && i === block.instructions.length - 1; + if (!isBlockValue) { + rewriteInstruction(block.instructions[i], state); + } + } + } + retainWhere(fn.context, contextVar => state.isIdOrNameUsed(contextVar.identifier)); +} +let State$2 = class State { + constructor(env) { + this.named = new Set(); + this.identifiers = new Set(); + this.env = env; + } + reference(identifier) { + this.identifiers.add(identifier.id); + if (identifier.name !== null) { + this.named.add(identifier.name.value); + } + } + isIdOrNameUsed(identifier) { + return (this.identifiers.has(identifier.id) || + (identifier.name !== null && this.named.has(identifier.name.value))); + } + isIdUsed(identifier) { + return this.identifiers.has(identifier.id); + } + get count() { + return this.identifiers.size; + } +}; +function findReferencedIdentifiers(fn) { + const hasLoop = hasBackEdge(fn); + const reversedBlocks = [...fn.body.blocks.values()].reverse(); + const state = new State$2(fn.env); + let size = state.count; + do { + size = state.count; + for (const block of reversedBlocks) { + for (const operand of eachTerminalOperand(block.terminal)) { + state.reference(operand.identifier); + } + for (let i = block.instructions.length - 1; i >= 0; i--) { + const instr = block.instructions[i]; + const isBlockValue = block.kind !== 'block' && i === block.instructions.length - 1; + if (isBlockValue) { + state.reference(instr.lvalue.identifier); + for (const place of eachInstructionValueOperand(instr.value)) { + state.reference(place.identifier); + } + } + else if (state.isIdOrNameUsed(instr.lvalue.identifier) || + !pruneableValue(instr.value, state)) { + state.reference(instr.lvalue.identifier); + if (instr.value.kind === 'StoreLocal') { + if (instr.value.lvalue.kind === InstructionKind.Reassign || + state.isIdUsed(instr.value.lvalue.place.identifier)) { + state.reference(instr.value.value.identifier); + } + } + else { + for (const operand of eachInstructionValueOperand(instr.value)) { + state.reference(operand.identifier); + } + } + } + } + for (const phi of block.phis) { + if (state.isIdOrNameUsed(phi.place.identifier)) { + for (const [_pred, operand] of phi.operands) { + state.reference(operand.identifier); + } + } + } + } + } while (state.count > size && hasLoop); + return state; +} +function rewriteInstruction(instr, state) { + if (instr.value.kind === 'Destructure') { + switch (instr.value.lvalue.pattern.kind) { + case 'ArrayPattern': { + let lastEntryIndex = 0; + const items = instr.value.lvalue.pattern.items; + for (let i = 0; i < items.length; i++) { + const item = items[i]; + if (item.kind === 'Identifier') { + if (!state.isIdOrNameUsed(item.identifier)) { + items[i] = { kind: 'Hole' }; + } + else { + lastEntryIndex = i; + } + } + else if (item.kind === 'Spread') { + if (!state.isIdOrNameUsed(item.place.identifier)) { + items[i] = { kind: 'Hole' }; + } + else { + lastEntryIndex = i; + } + } + } + items.length = lastEntryIndex + 1; + break; + } + case 'ObjectPattern': { + let nextProperties = null; + for (const property of instr.value.lvalue.pattern.properties) { + if (property.kind === 'ObjectProperty') { + if (state.isIdOrNameUsed(property.place.identifier)) { + nextProperties !== null && nextProperties !== void 0 ? nextProperties : (nextProperties = []); + nextProperties.push(property); + } + } + else { + if (state.isIdOrNameUsed(property.place.identifier)) { + nextProperties = null; + break; + } + } + } + if (nextProperties !== null) { + instr.value.lvalue.pattern.properties = nextProperties; + } + break; + } + default: { + assertExhaustive$1(instr.value.lvalue.pattern, `Unexpected pattern kind '${instr.value.lvalue.pattern.kind}'`); + } + } + } + else if (instr.value.kind === 'StoreLocal') { + if (instr.value.lvalue.kind !== InstructionKind.Reassign && + !state.isIdUsed(instr.value.lvalue.place.identifier)) { + instr.value = { + kind: 'DeclareLocal', + lvalue: instr.value.lvalue, + type: instr.value.type, + loc: instr.value.loc, + }; + } + } +} +function pruneableValue(value, state) { + switch (value.kind) { + case 'DeclareLocal': { + return !state.isIdOrNameUsed(value.lvalue.place.identifier); + } + case 'StoreLocal': { + if (value.lvalue.kind === InstructionKind.Reassign) { + return !state.isIdUsed(value.lvalue.place.identifier); + } + return !state.isIdOrNameUsed(value.lvalue.place.identifier); + } + case 'Destructure': { + let isIdOrNameUsed = false; + let isIdUsed = false; + for (const place of eachPatternOperand(value.lvalue.pattern)) { + if (state.isIdUsed(place.identifier)) { + isIdOrNameUsed = true; + isIdUsed = true; + } + else if (state.isIdOrNameUsed(place.identifier)) { + isIdOrNameUsed = true; + } + } + if (value.lvalue.kind === InstructionKind.Reassign) { + return !isIdUsed; + } + else { + return !isIdOrNameUsed; + } + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + return !state.isIdUsed(value.lvalue.identifier); + } + case 'Debugger': { + return false; + } + case 'CallExpression': + case 'MethodCall': { + if (state.env.outputMode === 'ssr') { + const calleee = value.kind === 'CallExpression' ? value.callee : value.property; + const hookKind = getHookKind(state.env, calleee.identifier); + switch (hookKind) { + case 'useState': + case 'useReducer': + case 'useRef': { + return true; + } + } + } + return false; + } + case 'Await': + case 'ComputedDelete': + case 'ComputedStore': + case 'PropertyDelete': + case 'PropertyStore': + case 'StoreGlobal': { + return false; + } + case 'NewExpression': + case 'UnsupportedNode': + case 'TaggedTemplateExpression': { + return false; + } + case 'GetIterator': + case 'NextPropertyOf': + case 'IteratorNext': { + return false; + } + case 'LoadContext': + case 'DeclareContext': + case 'StoreContext': { + return false; + } + case 'StartMemoize': + case 'FinishMemoize': { + return false; + } + case 'RegExpLiteral': + case 'MetaProperty': + case 'LoadGlobal': + case 'ArrayExpression': + case 'BinaryExpression': + case 'ComputedLoad': + case 'ObjectMethod': + case 'FunctionExpression': + case 'LoadLocal': + case 'JsxExpression': + case 'JsxFragment': + case 'JSXText': + case 'ObjectExpression': + case 'Primitive': + case 'PropertyLoad': + case 'TemplateLiteral': + case 'TypeCastExpression': + case 'UnaryExpression': { + return true; + } + default: { + assertExhaustive$1(value, `Unexepcted value kind \`${value.kind}\``); + } + } +} +function hasBackEdge(fn) { + return findBlocksWithBackEdges(fn).size > 0; +} +function findBlocksWithBackEdges(fn) { + const visited = new Set(); + const blocks = new Set(); + for (const [blockId, block] of fn.body.blocks) { + for (const predId of block.preds) { + if (!visited.has(predId)) { + blocks.add(blockId); + } + } + visited.add(blockId); + } + return blocks; +} + +function pruneMaybeThrows(fn) { + const terminalMapping = pruneMaybeThrowsImpl(fn); + if (terminalMapping) { + reversePostorderBlocks(fn.body); + removeUnreachableForUpdates(fn.body); + removeDeadDoWhileStatements(fn.body); + removeUnnecessaryTryCatch(fn.body); + markInstructionIds(fn.body); + mergeConsecutiveBlocks(fn); + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + for (const [predecessor, operand] of phi.operands) { + if (!block.preds.has(predecessor)) { + const mappedTerminal = terminalMapping.get(predecessor); + CompilerError.invariant(mappedTerminal != null, { + reason: `Expected non-existing phi operand's predecessor to have been mapped to a new terminal`, + description: `Could not find mapping for predecessor bb${predecessor} in block bb${block.id} for phi ${printPlace(phi.place)}`, + loc: GeneratedSource, + }); + phi.operands.delete(predecessor); + phi.operands.set(mappedTerminal, operand); + } + } + } + } + assertConsistentIdentifiers(fn); + assertTerminalSuccessorsExist(fn); + } +} +function pruneMaybeThrowsImpl(fn) { + var _a; + const terminalMapping = new Map(); + for (const [_, block] of fn.body.blocks) { + const terminal = block.terminal; + if (terminal.kind !== 'maybe-throw') { + continue; + } + const canThrow = block.instructions.some(instr => instructionMayThrow(instr)); + if (!canThrow) { + const source = (_a = terminalMapping.get(block.id)) !== null && _a !== void 0 ? _a : block.id; + terminalMapping.set(terminal.continuation, source); + terminal.handler = null; + } + } + return terminalMapping.size > 0 ? terminalMapping : null; +} +function instructionMayThrow(instr) { + switch (instr.value.kind) { + case 'Primitive': + case 'ArrayExpression': + case 'ObjectExpression': { + return false; + } + default: { + return true; + } + } +} + +function findScopesToMerge(fn) { + const objectMethodDecls = new Set(); + const mergeScopesBuilder = new DisjointSet(); + for (const [_, block] of fn.body.blocks) { + for (const { lvalue, value } of block.instructions) { + if (value.kind === 'ObjectMethod') { + objectMethodDecls.add(lvalue.identifier); + } + else if (value.kind === 'ObjectExpression') { + for (const operand of eachInstructionValueOperand(value)) { + if (objectMethodDecls.has(operand.identifier)) { + const operandScope = operand.identifier.scope; + const lvalueScope = lvalue.identifier.scope; + CompilerError.invariant(operandScope != null && lvalueScope != null, { + reason: 'Internal error: Expected all ObjectExpressions and ObjectMethods to have non-null scope.', + loc: GeneratedSource, + }); + mergeScopesBuilder.union([operandScope, lvalueScope]); + } + } + } + } + } + return mergeScopesBuilder; +} +function alignObjectMethodScopes(fn) { + for (const [_, block] of fn.body.blocks) { + for (const { value } of block.instructions) { + if (value.kind === 'ObjectMethod' || + value.kind === 'FunctionExpression') { + alignObjectMethodScopes(value.loweredFunc.func); + } + } + } + const scopeGroupsMap = findScopesToMerge(fn).canonicalize(); + for (const [scope, root] of scopeGroupsMap) { + if (scope !== root) { + root.range.start = makeInstructionId(Math.min(scope.range.start, root.range.start)); + root.range.end = makeInstructionId(Math.max(scope.range.end, root.range.end)); + } + } + for (const [_, block] of fn.body.blocks) { + for (const { lvalue: { identifier }, } of block.instructions) { + if (identifier.scope != null) { + const root = scopeGroupsMap.get(identifier.scope); + if (root != null) { + identifier.scope = root; + } + } + } + } +} + +function visitReactiveFunction(fn, visitor, state) { + visitor.visitBlock(fn.body, state); +} +class ReactiveFunctionVisitor { + visitID(_id, _state) { } + visitParam(_place, _state) { } + visitLValue(_id, _lvalue, _state) { } + visitPlace(_id, _place, _state) { } + visitReactiveFunctionValue(_id, _dependencies, _fn, _state) { } + visitValue(id, value, state) { + this.traverseValue(id, value, state); + } + traverseValue(id, value, state) { + switch (value.kind) { + case 'OptionalExpression': { + this.visitValue(id, value.value, state); + break; + } + case 'LogicalExpression': { + this.visitValue(id, value.left, state); + this.visitValue(id, value.right, state); + break; + } + case 'ConditionalExpression': { + this.visitValue(id, value.test, state); + this.visitValue(id, value.consequent, state); + this.visitValue(id, value.alternate, state); + break; + } + case 'SequenceExpression': { + for (const instr of value.instructions) { + this.visitInstruction(instr, state); + } + this.visitValue(value.id, value.value, state); + break; + } + default: { + for (const place of eachInstructionValueOperand(value)) { + this.visitPlace(id, place, state); + } + } + } + } + visitInstruction(instruction, state) { + this.traverseInstruction(instruction, state); + } + traverseInstruction(instruction, state) { + this.visitID(instruction.id, state); + for (const operand of eachInstructionLValue(instruction)) { + this.visitLValue(instruction.id, operand, state); + } + this.visitValue(instruction.id, instruction.value, state); + } + visitTerminal(stmt, state) { + this.traverseTerminal(stmt, state); + } + traverseTerminal(stmt, state) { + const { terminal } = stmt; + if (terminal.id !== null) { + this.visitID(terminal.id, state); + } + switch (terminal.kind) { + case 'break': + case 'continue': { + break; + } + case 'return': { + this.visitPlace(terminal.id, terminal.value, state); + break; + } + case 'throw': { + this.visitPlace(terminal.id, terminal.value, state); + break; + } + case 'for': { + this.visitValue(terminal.id, terminal.init, state); + this.visitValue(terminal.id, terminal.test, state); + this.visitBlock(terminal.loop, state); + if (terminal.update !== null) { + this.visitValue(terminal.id, terminal.update, state); + } + break; + } + case 'for-of': { + this.visitValue(terminal.id, terminal.init, state); + this.visitValue(terminal.id, terminal.test, state); + this.visitBlock(terminal.loop, state); + break; + } + case 'for-in': { + this.visitValue(terminal.id, terminal.init, state); + this.visitBlock(terminal.loop, state); + break; + } + case 'do-while': { + this.visitBlock(terminal.loop, state); + this.visitValue(terminal.id, terminal.test, state); + break; + } + case 'while': { + this.visitValue(terminal.id, terminal.test, state); + this.visitBlock(terminal.loop, state); + break; + } + case 'if': { + this.visitPlace(terminal.id, terminal.test, state); + this.visitBlock(terminal.consequent, state); + if (terminal.alternate !== null) { + this.visitBlock(terminal.alternate, state); + } + break; + } + case 'switch': { + this.visitPlace(terminal.id, terminal.test, state); + for (const case_ of terminal.cases) { + if (case_.test !== null) { + this.visitPlace(terminal.id, case_.test, state); + } + if (case_.block !== undefined) { + this.visitBlock(case_.block, state); + } + } + break; + } + case 'label': { + this.visitBlock(terminal.block, state); + break; + } + case 'try': { + this.visitBlock(terminal.block, state); + this.visitBlock(terminal.handler, state); + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } + } + visitScope(scope, state) { + this.traverseScope(scope, state); + } + traverseScope(scope, state) { + this.visitBlock(scope.instructions, state); + } + visitPrunedScope(scopeBlock, state) { + this.traversePrunedScope(scopeBlock, state); + } + traversePrunedScope(scopeBlock, state) { + this.visitBlock(scopeBlock.instructions, state); + } + visitBlock(block, state) { + this.traverseBlock(block, state); + } + traverseBlock(block, state) { + for (const instr of block) { + switch (instr.kind) { + case 'instruction': { + this.visitInstruction(instr.instruction, state); + break; + } + case 'scope': { + this.visitScope(instr, state); + break; + } + case 'pruned-scope': { + this.visitPrunedScope(instr, state); + break; + } + case 'terminal': { + this.visitTerminal(instr, state); + break; + } + default: { + assertExhaustive$1(instr, `Unexpected instruction kind \`${instr.kind}\``); + } + } + } + } + visitHirFunction(fn, state) { + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + this.visitParam(place, state); + } + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + this.visitInstruction(instr, state); + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + this.visitHirFunction(instr.value.loweredFunc.func, state); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + this.visitPlace(block.terminal.id, operand, state); + } + } + } +} +class ReactiveFunctionTransform extends ReactiveFunctionVisitor { + traverseBlock(block, state) { + let nextBlock = null; + for (let i = 0; i < block.length; i++) { + const instr = block[i]; + let transformed; + switch (instr.kind) { + case 'instruction': { + transformed = this.transformInstruction(instr.instruction, state); + break; + } + case 'scope': { + transformed = this.transformScope(instr, state); + break; + } + case 'pruned-scope': { + transformed = this.transformPrunedScope(instr, state); + break; + } + case 'terminal': { + transformed = this.transformTerminal(instr, state); + break; + } + default: { + assertExhaustive$1(instr, `Unexpected instruction kind \`${instr.kind}\``); + } + } + switch (transformed.kind) { + case 'keep': { + if (nextBlock !== null) { + nextBlock.push(instr); + } + break; + } + case 'remove': { + if (nextBlock === null) { + nextBlock = block.slice(0, i); + } + break; + } + case 'replace': { + nextBlock !== null && nextBlock !== void 0 ? nextBlock : (nextBlock = block.slice(0, i)); + nextBlock.push(transformed.value); + break; + } + case 'replace-many': { + nextBlock !== null && nextBlock !== void 0 ? nextBlock : (nextBlock = block.slice(0, i)); + nextBlock.push(...transformed.value); + break; + } + } + } + if (nextBlock !== null) { + block.length = 0; + block.push(...nextBlock); + } + } + transformInstruction(instruction, state) { + this.visitInstruction(instruction, state); + return { kind: 'keep' }; + } + transformTerminal(stmt, state) { + this.visitTerminal(stmt, state); + return { kind: 'keep' }; + } + transformScope(scope, state) { + this.visitScope(scope, state); + return { kind: 'keep' }; + } + transformPrunedScope(scope, state) { + this.visitPrunedScope(scope, state); + return { kind: 'keep' }; + } + transformValue(id, value, state) { + this.visitValue(id, value, state); + return { kind: 'keep' }; + } + transformReactiveFunctionValue(id, dependencies, fn, state) { + this.visitReactiveFunctionValue(id, dependencies, fn, state); + return { kind: 'keep' }; + } + traverseValue(id, value, state) { + switch (value.kind) { + case 'OptionalExpression': { + const nextValue = this.transformValue(id, value.value, state); + if (nextValue.kind === 'replace') { + value.value = nextValue.value; + } + break; + } + case 'LogicalExpression': { + const left = this.transformValue(id, value.left, state); + if (left.kind === 'replace') { + value.left = left.value; + } + const right = this.transformValue(id, value.right, state); + if (right.kind === 'replace') { + value.right = right.value; + } + break; + } + case 'ConditionalExpression': { + const test = this.transformValue(id, value.test, state); + if (test.kind === 'replace') { + value.test = test.value; + } + const consequent = this.transformValue(id, value.consequent, state); + if (consequent.kind === 'replace') { + value.consequent = consequent.value; + } + const alternate = this.transformValue(id, value.alternate, state); + if (alternate.kind === 'replace') { + value.alternate = alternate.value; + } + break; + } + case 'SequenceExpression': { + for (const instr of value.instructions) { + this.visitInstruction(instr, state); + } + const nextValue = this.transformValue(value.id, value.value, state); + if (nextValue.kind === 'replace') { + value.value = nextValue.value; + } + break; + } + default: { + for (const place of eachInstructionValueOperand(value)) { + this.visitPlace(id, place, state); + } + } + } + } + traverseInstruction(instruction, state) { + this.visitID(instruction.id, state); + for (const operand of eachInstructionLValue(instruction)) { + this.visitLValue(instruction.id, operand, state); + } + const nextValue = this.transformValue(instruction.id, instruction.value, state); + if (nextValue.kind === 'replace') { + instruction.value = nextValue.value; + } + } + traverseTerminal(stmt, state) { + const { terminal } = stmt; + if (terminal.id !== null) { + this.visitID(terminal.id, state); + } + switch (terminal.kind) { + case 'break': + case 'continue': { + break; + } + case 'return': { + this.visitPlace(terminal.id, terminal.value, state); + break; + } + case 'throw': { + this.visitPlace(terminal.id, terminal.value, state); + break; + } + case 'for': { + const init = this.transformValue(terminal.id, terminal.init, state); + if (init.kind === 'replace') { + terminal.init = init.value; + } + const test = this.transformValue(terminal.id, terminal.test, state); + if (test.kind === 'replace') { + terminal.test = test.value; + } + if (terminal.update !== null) { + const update = this.transformValue(terminal.id, terminal.update, state); + if (update.kind === 'replace') { + terminal.update = update.value; + } + } + this.visitBlock(terminal.loop, state); + break; + } + case 'for-of': { + const init = this.transformValue(terminal.id, terminal.init, state); + if (init.kind === 'replace') { + terminal.init = init.value; + } + const test = this.transformValue(terminal.id, terminal.test, state); + if (test.kind === 'replace') { + terminal.test = test.value; + } + this.visitBlock(terminal.loop, state); + break; + } + case 'for-in': { + const init = this.transformValue(terminal.id, terminal.init, state); + if (init.kind === 'replace') { + terminal.init = init.value; + } + this.visitBlock(terminal.loop, state); + break; + } + case 'do-while': { + this.visitBlock(terminal.loop, state); + const test = this.transformValue(terminal.id, terminal.test, state); + if (test.kind === 'replace') { + terminal.test = test.value; + } + break; + } + case 'while': { + const test = this.transformValue(terminal.id, terminal.test, state); + if (test.kind === 'replace') { + terminal.test = test.value; + } + this.visitBlock(terminal.loop, state); + break; + } + case 'if': { + this.visitPlace(terminal.id, terminal.test, state); + this.visitBlock(terminal.consequent, state); + if (terminal.alternate !== null) { + this.visitBlock(terminal.alternate, state); + } + break; + } + case 'switch': { + this.visitPlace(terminal.id, terminal.test, state); + for (const case_ of terminal.cases) { + if (case_.test !== null) { + this.visitPlace(terminal.id, case_.test, state); + } + if (case_.block !== undefined) { + this.visitBlock(case_.block, state); + } + } + break; + } + case 'label': { + this.visitBlock(terminal.block, state); + break; + } + case 'try': { + this.visitBlock(terminal.block, state); + if (terminal.handlerBinding !== null) { + this.visitPlace(terminal.id, terminal.handlerBinding, state); + } + this.visitBlock(terminal.handler, state); + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } + } +} +function* eachReactiveValueOperand(instrValue) { + switch (instrValue.kind) { + case 'OptionalExpression': { + yield* eachReactiveValueOperand(instrValue.value); + break; + } + case 'LogicalExpression': { + yield* eachReactiveValueOperand(instrValue.left); + yield* eachReactiveValueOperand(instrValue.right); + break; + } + case 'SequenceExpression': { + for (const instr of instrValue.instructions) { + yield* eachReactiveValueOperand(instr.value); + } + yield* eachReactiveValueOperand(instrValue.value); + break; + } + case 'ConditionalExpression': { + yield* eachReactiveValueOperand(instrValue.test); + yield* eachReactiveValueOperand(instrValue.consequent); + yield* eachReactiveValueOperand(instrValue.alternate); + break; + } + default: { + yield* eachInstructionValueOperand(instrValue); + } + } +} + +function assertScopeInstructionsWithinScopes(fn) { + const existingScopes = new Set(); + visitReactiveFunction(fn, new FindAllScopesVisitor(), existingScopes); + visitReactiveFunction(fn, new CheckInstructionsAgainstScopesVisitor(), existingScopes); +} +class FindAllScopesVisitor extends ReactiveFunctionVisitor { + visitScope(block, state) { + this.traverseScope(block, state); + state.add(block.scope.id); + } +} +class CheckInstructionsAgainstScopesVisitor extends ReactiveFunctionVisitor { + constructor() { + super(...arguments); + this.activeScopes = new Set(); + } + visitPlace(id, place, state) { + const scope = getPlaceScope(id, place); + if (scope !== null && + state.has(scope.id) && + !this.activeScopes.has(scope.id)) { + CompilerError.invariant(false, { + reason: 'Encountered an instruction that should be part of a scope, but where that scope has already completed', + description: `Instruction [${id}] is part of scope @${scope.id}, but that scope has already completed`, + loc: place.loc, + }); + } + } + visitScope(block, state) { + this.activeScopes.add(block.scope.id); + this.traverseScope(block, state); + this.activeScopes.delete(block.scope.id); + } +} + +function assertWellFormedBreakTargets(fn) { + visitReactiveFunction(fn, new Visitor$8(), new Set()); +} +let Visitor$8 = class Visitor extends ReactiveFunctionVisitor { + visitTerminal(stmt, seenLabels) { + if (stmt.label != null) { + seenLabels.add(stmt.label.id); + } + const terminal = stmt.terminal; + if (terminal.kind === 'break' || terminal.kind === 'continue') { + CompilerError.invariant(seenLabels.has(terminal.target), { + reason: 'Unexpected break to invalid label', + loc: stmt.terminal.loc, + }); + } + } +}; + +var _Context_nextScheduleId, _Context_scheduled, _Context_catchHandlers, _Context_controlFlowStack; +function buildReactiveFunction(fn) { + const cx = new Context$2(fn.body); + const driver = new Driver(cx); + const body = driver.traverseBlock(cx.block(fn.body.entry)); + return { + loc: fn.loc, + id: fn.id, + nameHint: fn.nameHint, + params: fn.params, + generator: fn.generator, + async: fn.async, + body, + env: fn.env, + directives: fn.directives, + }; +} +class Driver { + constructor(cx) { + this.cx = cx; + } + wrapWithSequence(instructions, continuation, loc) { + if (instructions.length === 0) { + return continuation; + } + const sequence = { + kind: 'SequenceExpression', + instructions, + id: continuation.id, + value: continuation.value, + loc, + }; + return { + block: continuation.block, + value: sequence, + place: continuation.place, + id: continuation.id, + }; + } + extractValueBlockResult(instructions, blockId, loc) { + CompilerError.invariant(instructions.length !== 0, { + reason: `Expected non-empty instructions in extractValueBlockResult`, + description: null, + loc, + }); + const instr = instructions.at(-1); + let place = instr.lvalue; + let value = instr.value; + if (value.kind === 'StoreLocal' && + value.lvalue.place.identifier.name === null) { + place = value.lvalue.place; + value = { + kind: 'LoadLocal', + place: value.value, + loc: value.value.loc, + }; + } + if (instructions.length === 1) { + return { block: blockId, place, value, id: instr.id }; + } + const sequence = { + kind: 'SequenceExpression', + instructions: instructions.slice(0, -1), + id: instr.id, + value, + loc, + }; + return { block: blockId, place, value: sequence, id: instr.id }; + } + valueBlockResultToSequence(result, loc) { + const instructions = []; + let innerValue = result.value; + while (innerValue.kind === 'SequenceExpression') { + instructions.push(...innerValue.instructions); + innerValue = innerValue.value; + } + const isLoadOfSamePlace = innerValue.kind === 'LoadLocal' && + innerValue.place.identifier.id === result.place.identifier.id; + if (!isLoadOfSamePlace) { + instructions.push({ + id: result.id, + lvalue: result.place, + value: innerValue, + loc, + }); + } + return { + kind: 'SequenceExpression', + instructions, + id: result.id, + value: { kind: 'Primitive', value: undefined, loc }, + loc, + }; + } + traverseBlock(block) { + const blockValue = []; + this.visitBlock(block, blockValue); + return blockValue; + } + visitBlock(block, blockValue) { + var _a; + CompilerError.invariant(!this.cx.emitted.has(block.id), { + reason: `Cannot emit the same block twice: bb${block.id}`, + loc: GeneratedSource, + }); + this.cx.emitted.add(block.id); + for (const instruction of block.instructions) { + blockValue.push({ + kind: 'instruction', + instruction, + }); + } + const terminal = block.terminal; + const scheduleIds = []; + switch (terminal.kind) { + case 'return': { + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'return', + loc: terminal.loc, + value: terminal.value, + id: terminal.id, + }, + label: null, + }); + break; + } + case 'throw': { + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'throw', + loc: terminal.loc, + value: terminal.value, + id: terminal.id, + }, + label: null, + }); + break; + } + case 'if': { + const fallthroughId = this.cx.reachable(terminal.fallthrough) && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const alternateId = terminal.alternate !== terminal.fallthrough + ? terminal.alternate + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'if'); + scheduleIds.push(scheduleId); + } + let consequent = null; + if (this.cx.isScheduled(terminal.consequent)) { + CompilerError.invariant(false, { + reason: `Unexpected 'if' where the consequent is already scheduled`, + loc: terminal.loc, + }); + } + else { + consequent = this.traverseBlock(this.cx.ir.blocks.get(terminal.consequent)); + } + let alternate = null; + if (alternateId !== null) { + if (this.cx.isScheduled(alternateId)) { + CompilerError.invariant(false, { + reason: `Unexpected 'if' where the alternate is already scheduled`, + loc: terminal.loc, + }); + } + else { + alternate = this.traverseBlock(this.cx.ir.blocks.get(alternateId)); + } + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'if', + loc: terminal.loc, + test: terminal.test, + consequent: consequent !== null && consequent !== void 0 ? consequent : this.emptyBlock(), + alternate: alternate, + id: terminal.id, + }, + label: fallthroughId == null + ? null + : { + id: fallthroughId, + implicit: false, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'switch': { + const fallthroughId = this.cx.reachable(terminal.fallthrough) && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'switch'); + scheduleIds.push(scheduleId); + } + const cases = []; + [...terminal.cases].reverse().forEach((case_, _index) => { + const test = case_.test; + let consequent; + if (this.cx.isScheduled(case_.block)) { + CompilerError.invariant(case_.block === terminal.fallthrough, { + reason: `Unexpected 'switch' where a case is already scheduled and block is not the fallthrough`, + loc: terminal.loc, + }); + return; + } + else { + consequent = this.traverseBlock(this.cx.ir.blocks.get(case_.block)); + const scheduleId = this.cx.schedule(case_.block, 'case'); + scheduleIds.push(scheduleId); + } + cases.push({ test, block: consequent }); + }); + cases.reverse(); + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'switch', + loc: terminal.loc, + test: terminal.test, + cases, + id: terminal.id, + }, + label: fallthroughId == null + ? null + : { + id: fallthroughId, + implicit: false, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'do-while': { + const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const loopId = !this.cx.isScheduled(terminal.loop) && + terminal.loop !== terminal.fallthrough + ? terminal.loop + : null; + const scheduleId = this.cx.scheduleLoop(terminal.fallthrough, terminal.test, terminal.loop); + scheduleIds.push(scheduleId); + let loopBody; + if (loopId) { + loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); + } + else { + CompilerError.invariant(false, { + reason: `Unexpected 'do-while' where the loop is already scheduled`, + loc: terminal.loc, + }); + } + const testValue = this.visitValueBlock(terminal.test, terminal.loc).value; + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'do-while', + loc: terminal.loc, + test: testValue, + loop: loopBody, + id: terminal.id, + }, + label: fallthroughId == null + ? null + : { + id: fallthroughId, + implicit: false, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'while': { + const fallthroughId = this.cx.reachable(terminal.fallthrough) && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const loopId = !this.cx.isScheduled(terminal.loop) && + terminal.loop !== terminal.fallthrough + ? terminal.loop + : null; + const scheduleId = this.cx.scheduleLoop(terminal.fallthrough, terminal.test, terminal.loop); + scheduleIds.push(scheduleId); + const testValue = this.visitValueBlock(terminal.test, terminal.loc).value; + let loopBody; + if (loopId) { + loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); + } + else { + CompilerError.invariant(false, { + reason: `Unexpected 'while' where the loop is already scheduled`, + loc: terminal.loc, + }); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'while', + loc: terminal.loc, + test: testValue, + loop: loopBody, + id: terminal.id, + }, + label: fallthroughId == null + ? null + : { + id: fallthroughId, + implicit: false, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'for': { + const loopId = !this.cx.isScheduled(terminal.loop) && + terminal.loop !== terminal.fallthrough + ? terminal.loop + : null; + const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const scheduleId = this.cx.scheduleLoop(terminal.fallthrough, (_a = terminal.update) !== null && _a !== void 0 ? _a : terminal.test, terminal.loop); + scheduleIds.push(scheduleId); + const init = this.visitValueBlock(terminal.init, terminal.loc); + const initValue = this.valueBlockResultToSequence(init, terminal.loc); + const testValue = this.visitValueBlock(terminal.test, terminal.loc).value; + const updateValue = terminal.update !== null + ? this.visitValueBlock(terminal.update, terminal.loc).value + : null; + let loopBody; + if (loopId) { + loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); + } + else { + CompilerError.invariant(false, { + reason: `Unexpected 'for' where the loop is already scheduled`, + loc: terminal.loc, + }); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'for', + loc: terminal.loc, + init: initValue, + test: testValue, + update: updateValue, + loop: loopBody, + id: terminal.id, + }, + label: fallthroughId == null ? null : { id: fallthroughId, implicit: false }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'for-of': { + const loopId = !this.cx.isScheduled(terminal.loop) && + terminal.loop !== terminal.fallthrough + ? terminal.loop + : null; + const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const scheduleId = this.cx.scheduleLoop(terminal.fallthrough, terminal.init, terminal.loop); + scheduleIds.push(scheduleId); + const init = this.visitValueBlock(terminal.init, terminal.loc); + const initValue = this.valueBlockResultToSequence(init, terminal.loc); + const test = this.visitValueBlock(terminal.test, terminal.loc); + const testValue = this.valueBlockResultToSequence(test, terminal.loc); + let loopBody; + if (loopId) { + loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); + } + else { + CompilerError.invariant(false, { + reason: `Unexpected 'for-of' where the loop is already scheduled`, + loc: terminal.loc, + }); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'for-of', + loc: terminal.loc, + init: initValue, + test: testValue, + loop: loopBody, + id: terminal.id, + }, + label: fallthroughId == null ? null : { id: fallthroughId, implicit: false }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'for-in': { + const loopId = !this.cx.isScheduled(terminal.loop) && + terminal.loop !== terminal.fallthrough + ? terminal.loop + : null; + const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + const scheduleId = this.cx.scheduleLoop(terminal.fallthrough, terminal.init, terminal.loop); + scheduleIds.push(scheduleId); + const init = this.visitValueBlock(terminal.init, terminal.loc); + const initValue = this.valueBlockResultToSequence(init, terminal.loc); + let loopBody; + if (loopId) { + loopBody = this.traverseBlock(this.cx.ir.blocks.get(loopId)); + } + else { + CompilerError.invariant(false, { + reason: `Unexpected 'for-in' where the loop is already scheduled`, + loc: terminal.loc, + }); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'for-in', + loc: terminal.loc, + init: initValue, + loop: loopBody, + id: terminal.id, + }, + label: fallthroughId == null ? null : { id: fallthroughId, implicit: false }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'branch': { + let consequent = null; + if (this.cx.isScheduled(terminal.consequent)) { + const break_ = this.visitBreak(terminal.consequent, terminal.id, terminal.loc); + if (break_ !== null) { + consequent = [break_]; + } + } + else { + consequent = this.traverseBlock(this.cx.ir.blocks.get(terminal.consequent)); + } + let alternate = null; + if (this.cx.isScheduled(terminal.alternate)) { + CompilerError.invariant(false, { + reason: `Unexpected 'branch' where the alternate is already scheduled`, + loc: terminal.loc, + }); + } + else { + alternate = this.traverseBlock(this.cx.ir.blocks.get(terminal.alternate)); + } + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'if', + loc: terminal.loc, + test: terminal.test, + consequent: consequent !== null && consequent !== void 0 ? consequent : this.emptyBlock(), + alternate: alternate, + id: terminal.id, + }, + label: null, + }); + break; + } + case 'label': { + const fallthroughId = this.cx.reachable(terminal.fallthrough) && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'if'); + scheduleIds.push(scheduleId); + } + let block; + if (this.cx.isScheduled(terminal.block)) { + CompilerError.invariant(false, { + reason: `Unexpected 'label' where the block is already scheduled`, + loc: terminal.loc, + }); + } + else { + block = this.traverseBlock(this.cx.ir.blocks.get(terminal.block)); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + terminal: { + kind: 'label', + loc: terminal.loc, + block, + id: terminal.id, + }, + label: fallthroughId == null ? null : { id: fallthroughId, implicit: false }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'sequence': + case 'optional': + case 'ternary': + case 'logical': { + const fallthroughId = terminal.fallthrough !== null && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'if'); + scheduleIds.push(scheduleId); + } + const { place, value } = this.visitValueBlockTerminal(terminal); + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'instruction', + instruction: { + id: terminal.id, + lvalue: place, + value, + loc: terminal.loc, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'goto': { + switch (terminal.variant) { + case GotoVariant.Break: { + const break_ = this.visitBreak(terminal.block, terminal.id, terminal.loc); + if (break_ !== null) { + blockValue.push(break_); + } + break; + } + case GotoVariant.Continue: { + const continue_ = this.visitContinue(terminal.block, terminal.id, terminal.loc); + if (continue_ !== null) { + blockValue.push(continue_); + } + break; + } + case GotoVariant.Try: { + break; + } + default: { + assertExhaustive$1(terminal.variant, `Unexpected goto variant \`${terminal.variant}\``); + } + } + break; + } + case 'maybe-throw': { + if (!this.cx.isScheduled(terminal.continuation)) { + this.visitBlock(this.cx.ir.blocks.get(terminal.continuation), blockValue); + } + break; + } + case 'try': { + const fallthroughId = this.cx.reachable(terminal.fallthrough) && + !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'if'); + scheduleIds.push(scheduleId); + } + this.cx.scheduleCatchHandler(terminal.handler); + const block = this.traverseBlock(this.cx.ir.blocks.get(terminal.block)); + const handler = this.traverseBlock(this.cx.ir.blocks.get(terminal.handler)); + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: 'terminal', + label: fallthroughId == null ? null : { id: fallthroughId, implicit: false }, + terminal: { + kind: 'try', + loc: terminal.loc, + block, + handlerBinding: terminal.handlerBinding, + handler, + id: terminal.id, + }, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'pruned-scope': + case 'scope': { + const fallthroughId = !this.cx.isScheduled(terminal.fallthrough) + ? terminal.fallthrough + : null; + if (fallthroughId !== null) { + const scheduleId = this.cx.schedule(fallthroughId, 'if'); + scheduleIds.push(scheduleId); + this.cx.scopeFallthroughs.add(fallthroughId); + } + let block; + if (this.cx.isScheduled(terminal.block)) { + CompilerError.invariant(false, { + reason: `Unexpected 'scope' where the block is already scheduled`, + loc: terminal.loc, + }); + } + else { + block = this.traverseBlock(this.cx.ir.blocks.get(terminal.block)); + } + this.cx.unscheduleAll(scheduleIds); + blockValue.push({ + kind: terminal.kind, + instructions: block, + scope: terminal.scope, + }); + if (fallthroughId !== null) { + this.visitBlock(this.cx.ir.blocks.get(fallthroughId), blockValue); + } + break; + } + case 'unreachable': { + break; + } + case 'unsupported': { + CompilerError.invariant(false, { + reason: 'Unexpected unsupported terminal', + loc: terminal.loc, + }); + } + default: { + assertExhaustive$1(terminal, 'Unexpected terminal'); + } + } + } + visitValueBlock(blockId, loc, fallthrough = null) { + const block = this.cx.ir.blocks.get(blockId); + if (fallthrough !== null && blockId === fallthrough) { + CompilerError.invariant(false, { + reason: 'Did not expect to reach the fallthrough of a value block', + description: `Reached bb${blockId}, which is the fallthrough for this value block`, + loc, + }); + } + if (block.terminal.kind === 'branch') { + if (block.instructions.length === 0) { + return { + block: block.id, + place: block.terminal.test, + value: { + kind: 'LoadLocal', + place: block.terminal.test, + loc: block.terminal.test.loc, + }, + id: block.terminal.id, + }; + } + return this.extractValueBlockResult(block.instructions, block.id, loc); + } + else if (block.terminal.kind === 'goto') { + if (block.instructions.length === 0) { + CompilerError.invariant(false, { + reason: 'Unexpected empty block with `goto` terminal', + description: `Block bb${block.id} is empty`, + loc, + }); + } + return this.extractValueBlockResult(block.instructions, block.id, loc); + } + else if (block.terminal.kind === 'maybe-throw') { + const continuationId = block.terminal.continuation; + const continuationBlock = this.cx.ir.blocks.get(continuationId); + if (continuationBlock.instructions.length === 0 && + continuationBlock.terminal.kind === 'goto') { + return this.extractValueBlockResult(block.instructions, continuationBlock.id, loc); + } + const continuation = this.visitValueBlock(continuationId, loc, fallthrough); + return this.wrapWithSequence(block.instructions, continuation, loc); + } + else { + const init = this.visitValueBlockTerminal(block.terminal); + const final = this.visitValueBlock(init.fallthrough, loc); + return this.wrapWithSequence([ + ...block.instructions, + { id: init.id, loc, lvalue: init.place, value: init.value }, + ], final, loc); + } + } + visitTestBlock(testBlockId, loc, terminalKind) { + const test = this.visitValueBlock(testBlockId, loc); + const testBlock = this.cx.ir.blocks.get(test.block); + if (testBlock.terminal.kind !== 'branch') { + CompilerError.invariant(false, { + reason: `Expected a branch terminal for ${terminalKind} test block`, + description: `Got \`${testBlock.terminal.kind}\``, + loc: testBlock.terminal.loc, + }); + } + return { + test, + branch: { + consequent: testBlock.terminal.consequent, + alternate: testBlock.terminal.alternate, + loc: testBlock.terminal.loc, + }, + }; + } + visitValueBlockTerminal(terminal) { + switch (terminal.kind) { + case 'sequence': { + const block = this.visitValueBlock(terminal.block, terminal.loc, terminal.fallthrough); + return { + value: block.value, + place: block.place, + fallthrough: terminal.fallthrough, + id: terminal.id, + }; + } + case 'optional': { + const { test, branch } = this.visitTestBlock(terminal.test, terminal.loc, 'optional'); + const consequent = this.visitValueBlock(branch.consequent, terminal.loc, terminal.fallthrough); + const call = { + kind: 'SequenceExpression', + instructions: [ + { + id: test.id, + loc: branch.loc, + lvalue: test.place, + value: test.value, + }, + ], + id: consequent.id, + value: consequent.value, + loc: terminal.loc, + }; + return { + place: Object.assign({}, consequent.place), + value: { + kind: 'OptionalExpression', + optional: terminal.optional, + value: call, + id: terminal.id, + loc: terminal.loc, + }, + fallthrough: terminal.fallthrough, + id: terminal.id, + }; + } + case 'logical': { + const { test, branch } = this.visitTestBlock(terminal.test, terminal.loc, 'logical'); + const leftFinal = this.visitValueBlock(branch.consequent, terminal.loc, terminal.fallthrough); + const left = { + kind: 'SequenceExpression', + instructions: [ + { + id: test.id, + loc: terminal.loc, + lvalue: test.place, + value: test.value, + }, + ], + id: leftFinal.id, + value: leftFinal.value, + loc: terminal.loc, + }; + const right = this.visitValueBlock(branch.alternate, terminal.loc, terminal.fallthrough); + const value = { + kind: 'LogicalExpression', + operator: terminal.operator, + left: left, + right: right.value, + loc: terminal.loc, + }; + return { + place: Object.assign({}, leftFinal.place), + value, + fallthrough: terminal.fallthrough, + id: terminal.id, + }; + } + case 'ternary': { + const { test, branch } = this.visitTestBlock(terminal.test, terminal.loc, 'ternary'); + const consequent = this.visitValueBlock(branch.consequent, terminal.loc, terminal.fallthrough); + const alternate = this.visitValueBlock(branch.alternate, terminal.loc, terminal.fallthrough); + const value = { + kind: 'ConditionalExpression', + test: test.value, + consequent: consequent.value, + alternate: alternate.value, + loc: terminal.loc, + }; + return { + place: Object.assign({}, consequent.place), + value, + fallthrough: terminal.fallthrough, + id: terminal.id, + }; + } + case 'maybe-throw': { + CompilerError.invariant(false, { + reason: `Unexpected maybe-throw in visitValueBlockTerminal - should be handled in visitValueBlock`, + description: null, + loc: terminal.loc, + }); + } + case 'label': { + CompilerError.throwTodo({ + reason: `Support labeled statements combined with value blocks (conditional, logical, optional chaining, etc)`, + description: null, + loc: terminal.loc, + suggestions: null, + }); + } + default: { + CompilerError.throwTodo({ + reason: `Support \`${terminal.kind}\` as a value block terminal (conditional, logical, optional chaining, etc)`, + description: null, + loc: terminal.loc, + suggestions: null, + }); + } + } + } + emptyBlock() { + return []; + } + visitBreak(block, id, loc) { + const target = this.cx.getBreakTarget(block); + if (target === null) { + CompilerError.invariant(false, { + reason: 'Expected a break target', + loc: GeneratedSource, + }); + } + if (this.cx.scopeFallthroughs.has(target.block)) { + CompilerError.invariant(target.type === 'implicit', { + reason: 'Expected reactive scope to implicitly break to fallthrough', + loc, + }); + return null; + } + return { + kind: 'terminal', + terminal: { + kind: 'break', + loc, + target: target.block, + id, + targetKind: target.type, + }, + label: null, + }; + } + visitContinue(block, id, loc) { + const target = this.cx.getContinueTarget(block); + CompilerError.invariant(target !== null, { + reason: `Expected continue target to be scheduled for bb${block}`, + loc: GeneratedSource, + }); + return { + kind: 'terminal', + terminal: { + kind: 'continue', + loc, + target: target.block, + id, + targetKind: target.type, + }, + label: null, + }; + } +} +let Context$2 = class Context { + constructor(ir) { + _Context_nextScheduleId.set(this, 0); + this.emitted = new Set(); + this.scopeFallthroughs = new Set(); + _Context_scheduled.set(this, new Set()); + _Context_catchHandlers.set(this, new Set()); + _Context_controlFlowStack.set(this, []); + this.ir = ir; + } + block(id) { + return this.ir.blocks.get(id); + } + scheduleCatchHandler(block) { + __classPrivateFieldGet(this, _Context_catchHandlers, "f").add(block); + } + reachable(id) { + const block = this.ir.blocks.get(id); + return block.terminal.kind !== 'unreachable'; + } + schedule(block, type) { + var _a, _b; + const id = (__classPrivateFieldSet(this, _Context_nextScheduleId, (_b = __classPrivateFieldGet(this, _Context_nextScheduleId, "f"), _a = _b++, _b), "f"), _a); + CompilerError.invariant(!__classPrivateFieldGet(this, _Context_scheduled, "f").has(block), { + reason: `Break block is already scheduled: bb${block}`, + loc: GeneratedSource, + }); + __classPrivateFieldGet(this, _Context_scheduled, "f").add(block); + __classPrivateFieldGet(this, _Context_controlFlowStack, "f").push({ block, id, type }); + return id; + } + scheduleLoop(fallthroughBlock, continueBlock, loopBlock) { + var _a, _b; + const id = (__classPrivateFieldSet(this, _Context_nextScheduleId, (_b = __classPrivateFieldGet(this, _Context_nextScheduleId, "f"), _a = _b++, _b), "f"), _a); + const ownsBlock = !__classPrivateFieldGet(this, _Context_scheduled, "f").has(fallthroughBlock); + __classPrivateFieldGet(this, _Context_scheduled, "f").add(fallthroughBlock); + CompilerError.invariant(!__classPrivateFieldGet(this, _Context_scheduled, "f").has(continueBlock), { + reason: `Continue block is already scheduled: bb${continueBlock}`, + loc: GeneratedSource, + }); + __classPrivateFieldGet(this, _Context_scheduled, "f").add(continueBlock); + let ownsLoop = false; + if (loopBlock !== null) { + ownsLoop = !__classPrivateFieldGet(this, _Context_scheduled, "f").has(loopBlock); + __classPrivateFieldGet(this, _Context_scheduled, "f").add(loopBlock); + } + __classPrivateFieldGet(this, _Context_controlFlowStack, "f").push({ + block: fallthroughBlock, + ownsBlock, + id, + type: 'loop', + continueBlock, + loopBlock, + ownsLoop, + }); + return id; + } + unschedule(scheduleId) { + const last = __classPrivateFieldGet(this, _Context_controlFlowStack, "f").pop(); + CompilerError.invariant(last !== undefined && last.id === scheduleId, { + reason: 'Can only unschedule the last target', + loc: GeneratedSource, + }); + if (last.type !== 'loop' || last.ownsBlock !== null) { + __classPrivateFieldGet(this, _Context_scheduled, "f").delete(last.block); + } + if (last.type === 'loop') { + __classPrivateFieldGet(this, _Context_scheduled, "f").delete(last.continueBlock); + if (last.ownsLoop && last.loopBlock !== null) { + __classPrivateFieldGet(this, _Context_scheduled, "f").delete(last.loopBlock); + } + } + } + unscheduleAll(scheduleIds) { + for (let i = scheduleIds.length - 1; i >= 0; i--) { + this.unschedule(scheduleIds[i]); + } + } + isScheduled(block) { + return __classPrivateFieldGet(this, _Context_scheduled, "f").has(block) || __classPrivateFieldGet(this, _Context_catchHandlers, "f").has(block); + } + getBreakTarget(block) { + let hasPrecedingLoop = false; + for (let i = __classPrivateFieldGet(this, _Context_controlFlowStack, "f").length - 1; i >= 0; i--) { + const target = __classPrivateFieldGet(this, _Context_controlFlowStack, "f")[i]; + if (target.block === block) { + let type; + if (target.type === 'loop') { + type = hasPrecedingLoop ? 'labeled' : 'unlabeled'; + } + else if (i === __classPrivateFieldGet(this, _Context_controlFlowStack, "f").length - 1) { + type = 'implicit'; + } + else { + type = 'labeled'; + } + return { + block: target.block, + type, + }; + } + hasPrecedingLoop || (hasPrecedingLoop = target.type === 'loop'); + } + CompilerError.invariant(false, { + reason: 'Expected a break target', + loc: GeneratedSource, + }); + } + getContinueTarget(block) { + let hasPrecedingLoop = false; + for (let i = __classPrivateFieldGet(this, _Context_controlFlowStack, "f").length - 1; i >= 0; i--) { + const target = __classPrivateFieldGet(this, _Context_controlFlowStack, "f")[i]; + if (target.type == 'loop' && target.continueBlock === block) { + let type; + if (hasPrecedingLoop) { + type = 'labeled'; + } + else if (i === __classPrivateFieldGet(this, _Context_controlFlowStack, "f").length - 1) { + type = 'implicit'; + } + else { + type = 'unlabeled'; + } + return { + block: target.block, + type, + }; + } + hasPrecedingLoop || (hasPrecedingLoop = target.type === 'loop'); + } + return null; + } + debugBreakTargets() { + return __classPrivateFieldGet(this, _Context_controlFlowStack, "f").map(target => (Object.assign({}, target))); + } +}; +_Context_nextScheduleId = new WeakMap(), _Context_scheduled = new WeakMap(), _Context_catchHandlers = new WeakMap(), _Context_controlFlowStack = new WeakMap(); + +var GuardKind; +(function (GuardKind) { + GuardKind[GuardKind["PushHookGuard"] = 0] = "PushHookGuard"; + GuardKind[GuardKind["PopHookGuard"] = 1] = "PopHookGuard"; + GuardKind[GuardKind["AllowHook"] = 2] = "AllowHook"; + GuardKind[GuardKind["DisallowHook"] = 3] = "DisallowHook"; +})(GuardKind || (GuardKind = {})); + +var InlineLevel; +(function (InlineLevel) { + InlineLevel["Transitive"] = "Transitive"; + InlineLevel["Shallow"] = "Shallow"; +})(InlineLevel || (InlineLevel = {})); +const SHALLOW_MACRO = { + level: InlineLevel.Shallow, + properties: null, +}; +const TRANSITIVE_MACRO = { + level: InlineLevel.Transitive, + properties: null, +}; +const FBT_MACRO = { + level: InlineLevel.Transitive, + properties: new Map([['*', SHALLOW_MACRO]]), +}; +FBT_MACRO.properties.set('enum', FBT_MACRO); +function memoizeFbtAndMacroOperandsInSameScope(fn) { + var _a; + const macroKinds = new Map([ + ...Array.from(FBT_TAGS.entries()), + ...((_a = fn.env.config.customMacros) !== null && _a !== void 0 ? _a : []).map(name => [name, TRANSITIVE_MACRO]), + ]); + const macroTags = populateMacroTags(fn, macroKinds); + const macroValues = mergeMacroArguments(fn, macroTags, macroKinds); + return macroValues; +} +const FBT_TAGS = new Map([ + ['fbt', FBT_MACRO], + ['fbt:param', SHALLOW_MACRO], + ['fbt:enum', FBT_MACRO], + ['fbt:plural', SHALLOW_MACRO], + ['fbs', FBT_MACRO], + ['fbs:param', SHALLOW_MACRO], + ['fbs:enum', FBT_MACRO], + ['fbs:plural', SHALLOW_MACRO], +]); +const SINGLE_CHILD_FBT_TAGS = new Set([ + 'fbt:param', + 'fbs:param', +]); +function populateMacroTags(fn, macroKinds) { + var _a; + const macroTags = new Map(); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'Primitive': { + if (typeof value.value === 'string') { + const macroDefinition = macroKinds.get(value.value); + if (macroDefinition != null) { + macroTags.set(lvalue.identifier.id, macroDefinition); + } + } + break; + } + case 'LoadGlobal': { + let macroDefinition = macroKinds.get(value.binding.name); + if (macroDefinition != null) { + macroTags.set(lvalue.identifier.id, macroDefinition); + } + break; + } + case 'PropertyLoad': { + if (typeof value.property === 'string') { + const macroDefinition = macroTags.get(value.object.identifier.id); + if (macroDefinition != null) { + const propertyDefinition = macroDefinition.properties != null + ? ((_a = macroDefinition.properties.get(value.property)) !== null && _a !== void 0 ? _a : macroDefinition.properties.get('*')) + : null; + const propertyMacro = propertyDefinition !== null && propertyDefinition !== void 0 ? propertyDefinition : macroDefinition; + macroTags.set(lvalue.identifier.id, propertyMacro); + } + } + break; + } + } + } + } + return macroTags; +} +function mergeMacroArguments(fn, macroTags, macroKinds) { + var _a; + const macroValues = new Set(macroTags.keys()); + for (const block of Array.from(fn.body.blocks.values()).reverse()) { + for (let i = block.instructions.length - 1; i >= 0; i--) { + const instr = block.instructions[i]; + const { lvalue, value } = instr; + switch (value.kind) { + case 'DeclareContext': + case 'DeclareLocal': + case 'Destructure': + case 'LoadContext': + case 'LoadLocal': + case 'PostfixUpdate': + case 'PrefixUpdate': + case 'StoreContext': + case 'StoreLocal': { + break; + } + case 'CallExpression': + case 'MethodCall': { + const scope = lvalue.identifier.scope; + if (scope == null) { + continue; + } + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + const macroDefinition = (_a = macroTags.get(callee.identifier.id)) !== null && _a !== void 0 ? _a : macroTags.get(lvalue.identifier.id); + if (macroDefinition != null) { + visitOperands(macroDefinition, scope, lvalue, value, macroValues, macroTags); + } + break; + } + case 'JsxExpression': { + const scope = lvalue.identifier.scope; + if (scope == null) { + continue; + } + let macroDefinition; + if (value.tag.kind === 'Identifier') { + macroDefinition = macroTags.get(value.tag.identifier.id); + } + else { + macroDefinition = macroKinds.get(value.tag.name); + } + macroDefinition !== null && macroDefinition !== void 0 ? macroDefinition : (macroDefinition = macroTags.get(lvalue.identifier.id)); + if (macroDefinition != null) { + visitOperands(macroDefinition, scope, lvalue, value, macroValues, macroTags); + } + break; + } + default: { + const scope = lvalue.identifier.scope; + if (scope == null) { + continue; + } + const macroDefinition = macroTags.get(lvalue.identifier.id); + if (macroDefinition != null) { + visitOperands(macroDefinition, scope, lvalue, value, macroValues, macroTags); + } + break; + } + } + } + for (const phi of block.phis) { + const scope = phi.place.identifier.scope; + if (scope == null) { + continue; + } + const macroDefinition = macroTags.get(phi.place.identifier.id); + if (macroDefinition == null || + macroDefinition.level === InlineLevel.Shallow) { + continue; + } + macroValues.add(phi.place.identifier.id); + for (const operand of phi.operands.values()) { + operand.identifier.scope = scope; + expandFbtScopeRange(scope.range, operand.identifier.mutableRange); + macroTags.set(operand.identifier.id, macroDefinition); + macroValues.add(operand.identifier.id); + } + } + } + return macroValues; +} +function expandFbtScopeRange(fbtRange, extendWith) { + if (extendWith.start !== 0) { + fbtRange.start = makeInstructionId(Math.min(fbtRange.start, extendWith.start)); + } +} +function visitOperands(macroDefinition, scope, lvalue, value, macroValues, macroTags) { + macroValues.add(lvalue.identifier.id); + for (const operand of eachInstructionValueOperand(value)) { + if (macroDefinition.level === InlineLevel.Transitive) { + operand.identifier.scope = scope; + expandFbtScopeRange(scope.range, operand.identifier.mutableRange); + macroTags.set(operand.identifier.id, macroDefinition); + } + macroValues.add(operand.identifier.id); + } +} + +var _Context_nextCacheIndex, _Context_declarations; +const MEMO_CACHE_SENTINEL = 'react.memo_cache_sentinel'; +const EARLY_RETURN_SENTINEL = 'react.early_return_sentinel'; +function codegenFunction(fn, { uniqueIdentifiers, fbtOperands, }) { + var _a, _b, _c; + const cx = new Context$1(fn.env, (_a = fn.id) !== null && _a !== void 0 ? _a : '[[ anonymous ]]', uniqueIdentifiers, fbtOperands, null); + let fastRefreshState = null; + if (fn.env.config.enableResetCacheOnSourceFileChanges && + fn.env.code !== null) { + const hash = crypto.createHmac('sha256', fn.env.code).digest('hex'); + fastRefreshState = { + cacheIndex: cx.nextCacheIndex, + hash, + }; + } + const compiled = codegenReactiveFunction(cx, fn); + const hookGuard = fn.env.config.enableEmitHookGuards; + if (hookGuard != null && fn.env.outputMode === 'client') { + compiled.body = libExports$1.blockStatement([ + createHookGuard(hookGuard, fn.env.programContext, compiled.body.body, GuardKind.PushHookGuard, GuardKind.PopHookGuard), + ]); + } + const cacheCount = compiled.memoSlotsUsed; + if (cacheCount !== 0) { + const preface = []; + const useMemoCacheIdentifier = fn.env.programContext.addMemoCacheImport().name; + preface.push(libExports$1.variableDeclaration('const', [ + libExports$1.variableDeclarator(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.callExpression(libExports$1.identifier(useMemoCacheIdentifier), [ + libExports$1.numericLiteral(cacheCount), + ])), + ])); + if (fastRefreshState !== null) { + const index = cx.synthesizeName('$i'); + preface.push(libExports$1.ifStatement(libExports$1.binaryExpression('!==', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(fastRefreshState.cacheIndex), true), libExports$1.stringLiteral(fastRefreshState.hash)), libExports$1.blockStatement([ + libExports$1.forStatement(libExports$1.variableDeclaration('let', [ + libExports$1.variableDeclarator(libExports$1.identifier(index), libExports$1.numericLiteral(0)), + ]), libExports$1.binaryExpression('<', libExports$1.identifier(index), libExports$1.numericLiteral(cacheCount)), libExports$1.assignmentExpression('+=', libExports$1.identifier(index), libExports$1.numericLiteral(1)), libExports$1.blockStatement([ + libExports$1.expressionStatement(libExports$1.assignmentExpression('=', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.identifier(index), true), libExports$1.callExpression(libExports$1.memberExpression(libExports$1.identifier('Symbol'), libExports$1.identifier('for')), [libExports$1.stringLiteral(MEMO_CACHE_SENTINEL)]))), + ])), + libExports$1.expressionStatement(libExports$1.assignmentExpression('=', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(fastRefreshState.cacheIndex), true), libExports$1.stringLiteral(fastRefreshState.hash))), + ]))); + } + compiled.body.body.unshift(...preface); + } + const emitInstrumentForget = fn.env.config.enableEmitInstrumentForget; + if (emitInstrumentForget != null && + fn.id != null && + fn.env.outputMode === 'client') { + const gating = emitInstrumentForget.gating != null + ? libExports$1.identifier(fn.env.programContext.addImportSpecifier(emitInstrumentForget.gating).name) + : null; + const globalGating = emitInstrumentForget.globalGating != null + ? libExports$1.identifier(emitInstrumentForget.globalGating) + : null; + if (emitInstrumentForget.globalGating != null) { + const assertResult = fn.env.programContext.assertGlobalBinding(emitInstrumentForget.globalGating); + if (assertResult.isErr()) { + fn.env.recordErrors(assertResult.unwrapErr()); + } + } + let ifTest; + if (gating != null && globalGating != null) { + ifTest = libExports$1.logicalExpression('&&', globalGating, gating); + } + else if (gating != null) { + ifTest = gating; + } + else { + CompilerError.invariant(globalGating != null, { + reason: 'Bad config not caught! Expected at least one of gating or globalGating', + loc: GeneratedSource, + }); + ifTest = globalGating; + } + const instrumentFnIdentifier = fn.env.programContext.addImportSpecifier(emitInstrumentForget.fn).name; + const test = libExports$1.ifStatement(ifTest, libExports$1.expressionStatement(libExports$1.callExpression(libExports$1.identifier(instrumentFnIdentifier), [ + libExports$1.stringLiteral(fn.id), + libExports$1.stringLiteral((_b = fn.env.filename) !== null && _b !== void 0 ? _b : ''), + ]))); + compiled.body.body.unshift(test); + } + const outlined = []; + for (const { fn: outlinedFunction, type } of cx.env.getOutlinedFunctions()) { + const reactiveFunction = buildReactiveFunction(outlinedFunction); + pruneUnusedLabels(reactiveFunction); + pruneUnusedLValues(reactiveFunction); + pruneHoistedContexts(reactiveFunction); + const identifiers = renameVariables(reactiveFunction); + const codegen = codegenReactiveFunction(new Context$1(cx.env, (_c = reactiveFunction.id) !== null && _c !== void 0 ? _c : '[[ anonymous ]]', identifiers, cx.fbtOperands), reactiveFunction); + outlined.push({ fn: codegen, type }); + } + compiled.outlined = outlined; + return compiled; +} +function codegenReactiveFunction(cx, fn) { + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + cx.temp.set(place.identifier.declarationId, null); + cx.declare(place.identifier); + } + const params = fn.params.map(param => convertParameter(param)); + const body = codegenBlock(cx, fn.body); + body.directives = fn.directives.map(d => libExports$1.directive(libExports$1.directiveLiteral(d))); + const statements = body.body; + if (statements.length !== 0) { + const last = statements[statements.length - 1]; + if (last.type === 'ReturnStatement' && last.argument == null) { + statements.pop(); + } + } + const countMemoBlockVisitor = new CountMemoBlockVisitor(fn.env); + visitReactiveFunction(fn, countMemoBlockVisitor, undefined); + return { + type: 'CodegenFunction', + loc: fn.loc, + id: fn.id !== null ? libExports$1.identifier(fn.id) : null, + nameHint: fn.nameHint, + params, + body, + generator: fn.generator, + async: fn.async, + memoSlotsUsed: cx.nextCacheIndex, + memoBlocks: countMemoBlockVisitor.memoBlocks, + memoValues: countMemoBlockVisitor.memoValues, + prunedMemoBlocks: countMemoBlockVisitor.prunedMemoBlocks, + prunedMemoValues: countMemoBlockVisitor.prunedMemoValues, + outlined: [], + }; +} +class CountMemoBlockVisitor extends ReactiveFunctionVisitor { + constructor(env) { + super(); + this.memoBlocks = 0; + this.memoValues = 0; + this.prunedMemoBlocks = 0; + this.prunedMemoValues = 0; + this.env = env; + } + visitScope(scopeBlock, state) { + this.memoBlocks += 1; + this.memoValues += scopeBlock.scope.declarations.size; + this.traverseScope(scopeBlock, state); + } + visitPrunedScope(scopeBlock, state) { + this.prunedMemoBlocks += 1; + this.prunedMemoValues += scopeBlock.scope.declarations.size; + this.traversePrunedScope(scopeBlock, state); + } +} +function convertParameter(param) { + if (param.kind === 'Identifier') { + return convertIdentifier(param.identifier); + } + else { + return libExports$1.restElement(convertIdentifier(param.place.identifier)); + } +} +let Context$1 = class Context { + constructor(env, fnName, uniqueIdentifiers, fbtOperands, temporaries = null) { + _Context_nextCacheIndex.set(this, 0); + _Context_declarations.set(this, new Set()); + this.objectMethods = new Map(); + this.synthesizedNames = new Map(); + this.env = env; + this.fnName = fnName; + this.uniqueIdentifiers = uniqueIdentifiers; + this.fbtOperands = fbtOperands; + this.temp = temporaries !== null ? new Map(temporaries) : new Map(); + } + recordError(error) { + this.env.recordError(error); + } + get nextCacheIndex() { + var _a, _b; + return __classPrivateFieldSet(this, _Context_nextCacheIndex, (_b = __classPrivateFieldGet(this, _Context_nextCacheIndex, "f"), _a = _b++, _b), "f"), _a; + } + declare(identifier) { + __classPrivateFieldGet(this, _Context_declarations, "f").add(identifier.declarationId); + } + hasDeclared(identifier) { + return __classPrivateFieldGet(this, _Context_declarations, "f").has(identifier.declarationId); + } + synthesizeName(name) { + const previous = this.synthesizedNames.get(name); + if (previous !== undefined) { + return previous; + } + let validated = makeIdentifierName(name).value; + let index = 0; + while (this.uniqueIdentifiers.has(validated)) { + validated = makeIdentifierName(`${name}${index++}`).value; + } + this.uniqueIdentifiers.add(validated); + this.synthesizedNames.set(name, validated); + return validated; + } +}; +_Context_nextCacheIndex = new WeakMap(), _Context_declarations = new WeakMap(); +function codegenBlock(cx, block) { + const temp = new Map(cx.temp); + const result = codegenBlockNoReset(cx, block); + for (const [key, value] of cx.temp) { + if (!temp.has(key)) { + continue; + } + CompilerError.invariant(temp.get(key) === value, { + reason: 'Expected temporary value to be unchanged', + loc: GeneratedSource, + }); + } + cx.temp = temp; + return result; +} +function codegenBlockNoReset(cx, block) { + const statements = []; + for (const item of block) { + switch (item.kind) { + case 'instruction': { + const statement = codegenInstructionNullable(cx, item.instruction); + if (statement !== null) { + statements.push(statement); + } + break; + } + case 'pruned-scope': { + const scopeBlock = codegenBlockNoReset(cx, item.instructions); + statements.push(...scopeBlock.body); + break; + } + case 'scope': { + const temp = new Map(cx.temp); + codegenReactiveScope(cx, statements, item.scope, item.instructions); + cx.temp = temp; + break; + } + case 'terminal': { + const statement = codegenTerminal(cx, item.terminal); + if (statement === null) { + break; + } + if (item.label !== null && !item.label.implicit) { + const block = statement.type === 'BlockStatement' && statement.body.length === 1 + ? statement.body[0] + : statement; + statements.push(libExports$1.labeledStatement(libExports$1.identifier(codegenLabel(item.label.id)), block)); + } + else if (statement.type === 'BlockStatement') { + statements.push(...statement.body); + } + else { + statements.push(statement); + } + break; + } + default: { + assertExhaustive$1(item, `Unexpected item kind \`${item.kind}\``); + } + } + } + return libExports$1.blockStatement(statements); +} +function codegenReactiveScope(cx, statements, scope, block) { + const cacheStoreStatements = []; + const cacheLoadStatements = []; + const cacheLoads = []; + const changeExpressions = []; + for (const dep of [...scope.dependencies].sort(compareScopeDependency)) { + const index = cx.nextCacheIndex; + const comparison = libExports$1.binaryExpression('!==', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(index), true), codegenDependency(cx, dep)); + changeExpressions.push(comparison); + cacheStoreStatements.push(libExports$1.expressionStatement(libExports$1.assignmentExpression('=', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(index), true), codegenDependency(cx, dep)))); + } + let firstOutputIndex = null; + for (const [, { identifier }] of [...scope.declarations].sort(([, a], [, b]) => compareScopeDeclaration(a, b))) { + const index = cx.nextCacheIndex; + if (firstOutputIndex === null) { + firstOutputIndex = index; + } + CompilerError.invariant(identifier.name != null, { + reason: `Expected scope declaration identifier to be named`, + description: `Declaration \`${printIdentifier(identifier)}\` is unnamed in scope @${scope.id}`, + loc: GeneratedSource, + }); + const name = convertIdentifier(identifier); + if (!cx.hasDeclared(identifier)) { + statements.push(libExports$1.variableDeclaration('let', [createVariableDeclarator(name, null)])); + } + cacheLoads.push({ name, index, value: name }); + cx.declare(identifier); + } + for (const reassignment of scope.reassignments) { + const index = cx.nextCacheIndex; + if (firstOutputIndex === null) { + firstOutputIndex = index; + } + const name = convertIdentifier(reassignment); + cacheLoads.push({ name, index, value: name }); + } + let testCondition = changeExpressions.reduce((acc, ident) => { + if (acc == null) { + return ident; + } + return libExports$1.logicalExpression('||', acc, ident); + }, null); + if (testCondition === null) { + CompilerError.invariant(firstOutputIndex !== null, { + reason: `Expected scope to have at least one declaration`, + description: `Scope '@${scope.id}' has no declarations`, + loc: GeneratedSource, + }); + testCondition = libExports$1.binaryExpression('===', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(firstOutputIndex), true), libExports$1.callExpression(libExports$1.memberExpression(libExports$1.identifier('Symbol'), libExports$1.identifier('for')), [libExports$1.stringLiteral(MEMO_CACHE_SENTINEL)])); + } + let computationBlock = codegenBlock(cx, block); + let memoStatement; + for (const { name, index, value } of cacheLoads) { + cacheStoreStatements.push(libExports$1.expressionStatement(libExports$1.assignmentExpression('=', libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(index), true), value))); + cacheLoadStatements.push(libExports$1.expressionStatement(libExports$1.assignmentExpression('=', name, libExports$1.memberExpression(libExports$1.identifier(cx.synthesizeName('$')), libExports$1.numericLiteral(index), true)))); + } + computationBlock.body.push(...cacheStoreStatements); + memoStatement = libExports$1.ifStatement(testCondition, computationBlock, libExports$1.blockStatement(cacheLoadStatements)); + statements.push(memoStatement); + const earlyReturnValue = scope.earlyReturnValue; + if (earlyReturnValue !== null) { + CompilerError.invariant(earlyReturnValue.value.name !== null && + earlyReturnValue.value.name.kind === 'named', { + reason: `Expected early return value to be promoted to a named variable`, + loc: earlyReturnValue.loc, + }); + const name = earlyReturnValue.value.name.value; + statements.push(libExports$1.ifStatement(libExports$1.binaryExpression('!==', libExports$1.identifier(name), libExports$1.callExpression(libExports$1.memberExpression(libExports$1.identifier('Symbol'), libExports$1.identifier('for')), [libExports$1.stringLiteral(EARLY_RETURN_SENTINEL)])), libExports$1.blockStatement([libExports$1.returnStatement(libExports$1.identifier(name))]))); + } +} +function codegenTerminal(cx, terminal) { + switch (terminal.kind) { + case 'break': { + if (terminal.targetKind === 'implicit') { + return null; + } + return createBreakStatement(terminal.loc, terminal.targetKind === 'labeled' + ? libExports$1.identifier(codegenLabel(terminal.target)) + : null); + } + case 'continue': { + if (terminal.targetKind === 'implicit') { + return null; + } + return createContinueStatement(terminal.loc, terminal.targetKind === 'labeled' + ? libExports$1.identifier(codegenLabel(terminal.target)) + : null); + } + case 'for': { + return createForStatement(terminal.loc, codegenForInit(cx, terminal.init), codegenInstructionValueToExpression(cx, terminal.test), terminal.update !== null + ? codegenInstructionValueToExpression(cx, terminal.update) + : null, codegenBlock(cx, terminal.loop)); + } + case 'for-in': { + CompilerError.invariant(terminal.init.kind === 'SequenceExpression', { + reason: `Expected a sequence expression init for for..in`, + description: `Got \`${terminal.init.kind}\` expression instead`, + loc: terminal.init.loc, + }); + if (terminal.init.instructions.length !== 2) { + cx.recordError(new CompilerErrorDetail({ + reason: 'Support non-trivial for..in inits', + category: ErrorCategory.Todo, + loc: terminal.init.loc, + suggestions: null, + })); + return libExports$1.emptyStatement(); + } + const iterableCollection = terminal.init.instructions[0]; + const iterableItem = terminal.init.instructions[1]; + let lval; + switch (iterableItem.value.kind) { + case 'StoreLocal': { + lval = codegenLValue(cx, iterableItem.value.lvalue.place); + break; + } + case 'Destructure': { + lval = codegenLValue(cx, iterableItem.value.lvalue.pattern); + break; + } + case 'StoreContext': { + cx.recordError(new CompilerErrorDetail({ + reason: 'Support non-trivial for..in inits', + category: ErrorCategory.Todo, + loc: terminal.init.loc, + suggestions: null, + })); + return libExports$1.emptyStatement(); + } + default: + CompilerError.invariant(false, { + reason: `Expected a StoreLocal or Destructure to be assigned to the collection`, + description: `Found ${iterableItem.value.kind}`, + loc: iterableItem.value.loc, + }); + } + let varDeclKind; + switch (iterableItem.value.lvalue.kind) { + case InstructionKind.Const: + varDeclKind = 'const'; + break; + case InstructionKind.Let: + varDeclKind = 'let'; + break; + case InstructionKind.Reassign: + CompilerError.invariant(false, { + reason: 'Destructure should never be Reassign as it would be an Object/ArrayPattern', + loc: iterableItem.loc, + }); + case InstructionKind.Catch: + case InstructionKind.HoistedConst: + case InstructionKind.HoistedLet: + case InstructionKind.HoistedFunction: + case InstructionKind.Function: + CompilerError.invariant(false, { + reason: `Unexpected ${iterableItem.value.lvalue.kind} variable in for..in collection`, + loc: iterableItem.loc, + }); + default: + assertExhaustive$1(iterableItem.value.lvalue.kind, `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}`); + } + return createForInStatement(terminal.loc, createVariableDeclaration(iterableItem.value.loc, varDeclKind, [ + libExports$1.variableDeclarator(lval, null), + ]), codegenInstructionValueToExpression(cx, iterableCollection.value), codegenBlock(cx, terminal.loop)); + } + case 'for-of': { + CompilerError.invariant(terminal.init.kind === 'SequenceExpression' && + terminal.init.instructions.length === 1 && + terminal.init.instructions[0].value.kind === 'GetIterator', { + reason: `Expected a single-expression sequence expression init for for..of`, + description: `Got \`${terminal.init.kind}\` expression instead`, + loc: terminal.init.loc, + }); + const iterableCollection = terminal.init.instructions[0].value; + CompilerError.invariant(terminal.test.kind === 'SequenceExpression', { + reason: `Expected a sequence expression test for for..of`, + description: `Got \`${terminal.init.kind}\` expression instead`, + loc: terminal.test.loc, + }); + if (terminal.test.instructions.length !== 2) { + cx.recordError(new CompilerErrorDetail({ + reason: 'Support non-trivial for..of inits', + category: ErrorCategory.Todo, + loc: terminal.init.loc, + suggestions: null, + })); + return libExports$1.emptyStatement(); + } + const iterableItem = terminal.test.instructions[1]; + let lval; + switch (iterableItem.value.kind) { + case 'StoreLocal': { + lval = codegenLValue(cx, iterableItem.value.lvalue.place); + break; + } + case 'Destructure': { + lval = codegenLValue(cx, iterableItem.value.lvalue.pattern); + break; + } + case 'StoreContext': { + cx.recordError(new CompilerErrorDetail({ + reason: 'Support non-trivial for..of inits', + category: ErrorCategory.Todo, + loc: terminal.init.loc, + suggestions: null, + })); + return libExports$1.emptyStatement(); + } + default: + CompilerError.invariant(false, { + reason: `Expected a StoreLocal or Destructure to be assigned to the collection`, + description: `Found ${iterableItem.value.kind}`, + loc: iterableItem.value.loc, + }); + } + let varDeclKind; + switch (iterableItem.value.lvalue.kind) { + case InstructionKind.Const: + varDeclKind = 'const'; + break; + case InstructionKind.Let: + varDeclKind = 'let'; + break; + case InstructionKind.Reassign: + case InstructionKind.Catch: + case InstructionKind.HoistedConst: + case InstructionKind.HoistedLet: + case InstructionKind.HoistedFunction: + case InstructionKind.Function: + CompilerError.invariant(false, { + reason: `Unexpected ${iterableItem.value.lvalue.kind} variable in for..of collection`, + loc: iterableItem.loc, + }); + default: + assertExhaustive$1(iterableItem.value.lvalue.kind, `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}`); + } + return createForOfStatement(terminal.loc, createVariableDeclaration(iterableItem.value.loc, varDeclKind, [ + libExports$1.variableDeclarator(lval, null), + ]), codegenInstructionValueToExpression(cx, iterableCollection), codegenBlock(cx, terminal.loop)); + } + case 'if': { + const test = codegenPlaceToExpression(cx, terminal.test); + const consequent = codegenBlock(cx, terminal.consequent); + let alternate = null; + if (terminal.alternate !== null) { + const block = codegenBlock(cx, terminal.alternate); + if (block.body.length !== 0) { + alternate = block; + } + } + return createIfStatement(terminal.loc, test, consequent, alternate); + } + case 'return': { + const value = codegenPlaceToExpression(cx, terminal.value); + if (value.type === 'Identifier' && value.name === 'undefined') { + return createReturnStatement(terminal.loc); + } + return createReturnStatement(terminal.loc, value); + } + case 'switch': { + return createSwitchStatement(terminal.loc, codegenPlaceToExpression(cx, terminal.test), terminal.cases.map(case_ => { + const test = case_.test !== null + ? codegenPlaceToExpression(cx, case_.test) + : null; + const block = codegenBlock(cx, case_.block); + return libExports$1.switchCase(test, block.body.length === 0 ? [] : [block]); + })); + } + case 'throw': { + return createThrowStatement(terminal.loc, codegenPlaceToExpression(cx, terminal.value)); + } + case 'do-while': { + const test = codegenInstructionValueToExpression(cx, terminal.test); + return createDoWhileStatement(terminal.loc, test, codegenBlock(cx, terminal.loop)); + } + case 'while': { + const test = codegenInstructionValueToExpression(cx, terminal.test); + return createWhileStatement(terminal.loc, test, codegenBlock(cx, terminal.loop)); + } + case 'label': { + return codegenBlock(cx, terminal.block); + } + case 'try': { + let catchParam = null; + if (terminal.handlerBinding !== null) { + catchParam = convertIdentifier(terminal.handlerBinding.identifier); + cx.temp.set(terminal.handlerBinding.identifier.declarationId, null); + } + return createTryStatement(terminal.loc, codegenBlock(cx, terminal.block), libExports$1.catchClause(catchParam, codegenBlock(cx, terminal.handler))); + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } +} +function codegenInstructionNullable(cx, instr) { + if (instr.value.kind === 'StoreLocal' || + instr.value.kind === 'StoreContext' || + instr.value.kind === 'Destructure' || + instr.value.kind === 'DeclareLocal' || + instr.value.kind === 'DeclareContext') { + let kind = instr.value.lvalue.kind; + let lvalue; + let value; + if (instr.value.kind === 'StoreLocal') { + kind = cx.hasDeclared(instr.value.lvalue.place.identifier) + ? InstructionKind.Reassign + : kind; + lvalue = instr.value.lvalue.place; + value = codegenPlaceToExpression(cx, instr.value.value); + } + else if (instr.value.kind === 'StoreContext') { + lvalue = instr.value.lvalue.place; + value = codegenPlaceToExpression(cx, instr.value.value); + } + else if (instr.value.kind === 'DeclareLocal' || + instr.value.kind === 'DeclareContext') { + if (cx.hasDeclared(instr.value.lvalue.place.identifier)) { + return null; + } + kind = instr.value.lvalue.kind; + lvalue = instr.value.lvalue.place; + value = null; + } + else { + lvalue = instr.value.lvalue.pattern; + for (const place of eachPatternOperand(lvalue)) { + if (kind !== InstructionKind.Reassign && + place.identifier.name === null) { + cx.temp.set(place.identifier.declarationId, null); + } + } + value = codegenPlaceToExpression(cx, instr.value.value); + } + switch (kind) { + case InstructionKind.Const: { + CompilerError.invariant(instr.lvalue === null, { + reason: `Const declaration cannot be referenced as an expression`, + message: `this is ${kind}`, + loc: instr.value.loc, + }); + return createVariableDeclaration(instr.loc, 'const', [ + createVariableDeclarator(codegenLValue(cx, lvalue), value), + ]); + } + case InstructionKind.Function: { + CompilerError.invariant(instr.lvalue === null, { + reason: `Function declaration cannot be referenced as an expression`, + loc: instr.value.loc, + }); + const genLvalue = codegenLValue(cx, lvalue); + CompilerError.invariant(genLvalue.type === 'Identifier', { + reason: 'Expected an identifier as a function declaration lvalue', + loc: instr.value.loc, + }); + CompilerError.invariant((value === null || value === void 0 ? void 0 : value.type) === 'FunctionExpression', { + reason: 'Expected a function as a function declaration value', + description: `Got ${value == null ? String(value) : value.type} at ${printInstruction(instr)}`, + loc: instr.value.loc, + }); + return createFunctionDeclaration(instr.loc, genLvalue, value.params, value.body, value.generator, value.async); + } + case InstructionKind.Let: { + CompilerError.invariant(instr.lvalue === null, { + reason: `Const declaration cannot be referenced as an expression`, + message: `this is ${kind}`, + loc: instr.value.loc, + }); + return createVariableDeclaration(instr.loc, 'let', [ + createVariableDeclarator(codegenLValue(cx, lvalue), value), + ]); + } + case InstructionKind.Reassign: { + CompilerError.invariant(value !== null, { + reason: 'Expected a value for reassignment', + loc: instr.value.loc, + }); + const expr = libExports$1.assignmentExpression('=', codegenLValue(cx, lvalue), value); + if (instr.lvalue !== null) { + if (instr.value.kind !== 'StoreContext') { + cx.temp.set(instr.lvalue.identifier.declarationId, expr); + return null; + } + else { + const statement = codegenInstruction(cx, instr, expr); + if (statement.type === 'EmptyStatement') { + return null; + } + return statement; + } + } + else { + return createExpressionStatement(instr.loc, expr); + } + } + case InstructionKind.Catch: { + return libExports$1.emptyStatement(); + } + case InstructionKind.HoistedLet: + case InstructionKind.HoistedConst: + case InstructionKind.HoistedFunction: { + CompilerError.invariant(false, { + reason: `Expected ${kind} to have been pruned in PruneHoistedContexts`, + loc: instr.loc, + }); + } + default: { + assertExhaustive$1(kind, `Unexpected instruction kind \`${kind}\``); + } + } + } + else if (instr.value.kind === 'StartMemoize' || + instr.value.kind === 'FinishMemoize') { + return null; + } + else if (instr.value.kind === 'Debugger') { + return libExports$1.debuggerStatement(); + } + else if (instr.value.kind === 'ObjectMethod') { + CompilerError.invariant(instr.lvalue, { + reason: 'Expected object methods to have a temp lvalue', + loc: GeneratedSource, + }); + cx.objectMethods.set(instr.lvalue.identifier.id, instr.value); + return null; + } + else { + const value = codegenInstructionValue(cx, instr.value); + const statement = codegenInstruction(cx, instr, value); + if (statement.type === 'EmptyStatement') { + return null; + } + return statement; + } +} +function codegenForInit(cx, init) { + if (init.kind === 'SequenceExpression') { + const body = codegenBlock(cx, init.instructions.map(instruction => ({ + kind: 'instruction', + instruction, + }))).body; + const declarators = []; + let kind = 'const'; + body.forEach(instr => { + var _a; + let top = undefined; + if (instr.type === 'ExpressionStatement' && + instr.expression.type === 'AssignmentExpression' && + instr.expression.operator === '=' && + instr.expression.left.type === 'Identifier' && + ((_a = (top = declarators.at(-1))) === null || _a === void 0 ? void 0 : _a.id.type) === 'Identifier' && + (top === null || top === void 0 ? void 0 : top.id.name) === instr.expression.left.name && + (top === null || top === void 0 ? void 0 : top.init) == null) { + top.init = instr.expression.right; + } + else { + CompilerError.invariant(instr.type === 'VariableDeclaration' && + (instr.kind === 'let' || instr.kind === 'const'), { + reason: 'Expected a variable declaration', + description: `Got ${instr.type}`, + loc: init.loc, + }); + if (instr.kind === 'let') { + kind = 'let'; + } + declarators.push(...instr.declarations); + } + }); + CompilerError.invariant(declarators.length > 0, { + reason: 'Expected a variable declaration', + loc: init.loc, + }); + return libExports$1.variableDeclaration(kind, declarators); + } + else { + return codegenInstructionValueToExpression(cx, init); + } +} +function codegenDependency(cx, dependency) { + let object = convertIdentifier(dependency.identifier); + if (dependency.path.length !== 0) { + const hasOptional = dependency.path.some(path => path.optional); + for (const path of dependency.path) { + const property = typeof path.property === 'string' + ? libExports$1.identifier(path.property) + : libExports$1.numericLiteral(path.property); + const isComputed = typeof path.property !== 'string'; + if (hasOptional) { + object = libExports$1.optionalMemberExpression(object, property, isComputed, path.optional); + } + else { + object = libExports$1.memberExpression(object, property, isComputed); + } + } + } + return object; +} +function withLoc(fn) { + return (loc, ...args) => { + const node = fn(...args); + if (loc != null && loc != GeneratedSource) { + node.loc = loc; + } + return node; + }; +} +const createIdentifier = withLoc(libExports$1.identifier); +const createArrayPattern = withLoc(libExports$1.arrayPattern); +const createObjectPattern = withLoc(libExports$1.objectPattern); +const createBinaryExpression = withLoc(libExports$1.binaryExpression); +const createExpressionStatement = withLoc(libExports$1.expressionStatement); +const createVariableDeclaration = withLoc(libExports$1.variableDeclaration); +const createFunctionDeclaration = withLoc(libExports$1.functionDeclaration); +const createWhileStatement = withLoc(libExports$1.whileStatement); +const createDoWhileStatement = withLoc(libExports$1.doWhileStatement); +const createSwitchStatement = withLoc(libExports$1.switchStatement); +const createIfStatement = withLoc(libExports$1.ifStatement); +const createForStatement = withLoc(libExports$1.forStatement); +const createForOfStatement = withLoc(libExports$1.forOfStatement); +const createForInStatement = withLoc(libExports$1.forInStatement); +const createTaggedTemplateExpression = withLoc(libExports$1.taggedTemplateExpression); +const createLogicalExpression = withLoc(libExports$1.logicalExpression); +const createSequenceExpression = withLoc(libExports$1.sequenceExpression); +const createConditionalExpression = withLoc(libExports$1.conditionalExpression); +const createTemplateLiteral = withLoc(libExports$1.templateLiteral); +const createJsxNamespacedName = withLoc(libExports$1.jsxNamespacedName); +const createJsxElement = withLoc(libExports$1.jsxElement); +const createJsxAttribute = withLoc(libExports$1.jsxAttribute); +const createJsxIdentifier = withLoc(libExports$1.jsxIdentifier); +const createJsxExpressionContainer = withLoc(libExports$1.jsxExpressionContainer); +const createJsxText = withLoc(libExports$1.jsxText); +const createJsxClosingElement = withLoc(libExports$1.jsxClosingElement); +const createJsxOpeningElement = withLoc(libExports$1.jsxOpeningElement); +const createStringLiteral = withLoc(libExports$1.stringLiteral); +const createThrowStatement = withLoc(libExports$1.throwStatement); +const createTryStatement = withLoc(libExports$1.tryStatement); +const createBreakStatement = withLoc(libExports$1.breakStatement); +const createContinueStatement = withLoc(libExports$1.continueStatement); +const createReturnStatement = withLoc(libExports$1.returnStatement); +function createVariableDeclarator(id, init) { + var _a, _b; + const node = libExports$1.variableDeclarator(id, init); + if (id.loc && (init === null || (init === null || init === void 0 ? void 0 : init.loc))) { + node.loc = { + start: id.loc.start, + end: (_b = (_a = init === null || init === void 0 ? void 0 : init.loc) === null || _a === void 0 ? void 0 : _a.end) !== null && _b !== void 0 ? _b : id.loc.end, + filename: id.loc.filename, + identifierName: undefined, + }; + } + return node; +} +function createHookGuard(guard, context, stmts, before, after) { + const guardFnName = context.addImportSpecifier(guard).name; + function createHookGuardImpl(kind) { + return libExports$1.expressionStatement(libExports$1.callExpression(libExports$1.identifier(guardFnName), [libExports$1.numericLiteral(kind)])); + } + return libExports$1.tryStatement(libExports$1.blockStatement([createHookGuardImpl(before), ...stmts]), null, libExports$1.blockStatement([createHookGuardImpl(after)])); +} +function createCallExpression(env, callee, args, loc, isHook) { + const callExpr = libExports$1.callExpression(callee, args); + if (loc != null && loc != GeneratedSource) { + callExpr.loc = loc; + } + const hookGuard = env.config.enableEmitHookGuards; + if (hookGuard != null && isHook && env.outputMode === 'client') { + const iife = libExports$1.functionExpression(null, [], libExports$1.blockStatement([ + createHookGuard(hookGuard, env.programContext, [libExports$1.returnStatement(callExpr)], GuardKind.AllowHook, GuardKind.DisallowHook), + ])); + return libExports$1.callExpression(iife, []); + } + else { + return callExpr; + } +} +function codegenLabel(id) { + return `bb${id}`; +} +function codegenInstruction(cx, instr, value) { + if (libExports$1.isStatement(value)) { + return value; + } + if (instr.lvalue === null) { + return libExports$1.expressionStatement(convertValueToExpression(value)); + } + if (instr.lvalue.identifier.name === null) { + cx.temp.set(instr.lvalue.identifier.declarationId, value); + return libExports$1.emptyStatement(); + } + else { + const expressionValue = convertValueToExpression(value); + if (cx.hasDeclared(instr.lvalue.identifier)) { + return createExpressionStatement(instr.loc, libExports$1.assignmentExpression('=', convertIdentifier(instr.lvalue.identifier), expressionValue)); + } + else { + return createVariableDeclaration(instr.loc, 'const', [ + createVariableDeclarator(convertIdentifier(instr.lvalue.identifier), expressionValue), + ]); + } + } +} +function convertValueToExpression(value) { + if (value.type === 'JSXText') { + return createStringLiteral(value.loc, value.value); + } + return value; +} +function codegenInstructionValueToExpression(cx, instrValue) { + const value = codegenInstructionValue(cx, instrValue); + return convertValueToExpression(value); +} +function codegenInstructionValue(cx, instrValue) { + var _a, _b, _c, _d, _e, _f, _g; + let value; + switch (instrValue.kind) { + case 'ArrayExpression': { + const elements = instrValue.elements.map(element => { + if (element.kind === 'Identifier') { + return codegenPlaceToExpression(cx, element); + } + else if (element.kind === 'Spread') { + return libExports$1.spreadElement(codegenPlaceToExpression(cx, element.place)); + } + else { + return null; + } + }); + value = libExports$1.arrayExpression(elements); + break; + } + case 'BinaryExpression': { + const left = codegenPlaceToExpression(cx, instrValue.left); + const right = codegenPlaceToExpression(cx, instrValue.right); + value = createBinaryExpression(instrValue.loc, instrValue.operator, left, right); + break; + } + case 'UnaryExpression': { + value = libExports$1.unaryExpression(instrValue.operator, codegenPlaceToExpression(cx, instrValue.value)); + break; + } + case 'Primitive': { + value = codegenValue(cx, instrValue.loc, instrValue.value); + break; + } + case 'CallExpression': { + if (cx.env.config.enableForest) { + const callee = codegenPlaceToExpression(cx, instrValue.callee); + const args = instrValue.args.map(arg => codegenArgument(cx, arg)); + value = libExports$1.callExpression(callee, args); + if (instrValue.typeArguments != null) { + value.typeArguments = libExports$1.typeParameterInstantiation(instrValue.typeArguments); + } + break; + } + const isHook = getHookKind(cx.env, instrValue.callee.identifier) != null; + const callee = codegenPlaceToExpression(cx, instrValue.callee); + const args = instrValue.args.map(arg => codegenArgument(cx, arg)); + value = createCallExpression(cx.env, callee, args, instrValue.loc, isHook); + break; + } + case 'OptionalExpression': { + const optionalValue = codegenInstructionValueToExpression(cx, instrValue.value); + switch (optionalValue.type) { + case 'OptionalCallExpression': + case 'CallExpression': { + CompilerError.invariant(libExports$1.isExpression(optionalValue.callee), { + reason: 'v8 intrinsics are validated during lowering', + loc: (_a = optionalValue.callee.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + value = libExports$1.optionalCallExpression(optionalValue.callee, optionalValue.arguments, instrValue.optional); + break; + } + case 'OptionalMemberExpression': + case 'MemberExpression': { + const property = optionalValue.property; + CompilerError.invariant(libExports$1.isExpression(property), { + reason: 'Private names are validated during lowering', + loc: (_b = property.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + value = libExports$1.optionalMemberExpression(optionalValue.object, property, optionalValue.computed, instrValue.optional); + break; + } + default: { + CompilerError.invariant(false, { + reason: 'Expected an optional value to resolve to a call expression or member expression', + description: `Got a \`${optionalValue.type}\``, + loc: instrValue.loc, + }); + } + } + break; + } + case 'MethodCall': { + const isHook = getHookKind(cx.env, instrValue.property.identifier) != null; + const memberExpr = codegenPlaceToExpression(cx, instrValue.property); + CompilerError.invariant(libExports$1.isMemberExpression(memberExpr) || + libExports$1.isOptionalMemberExpression(memberExpr), { + reason: '[Codegen] Internal error: MethodCall::property must be an unpromoted + unmemoized MemberExpression', + message: `Got: '${memberExpr.type}'`, + loc: (_c = memberExpr.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + }); + CompilerError.invariant(libExports$1.isNodesEquivalent(memberExpr.object, codegenPlaceToExpression(cx, instrValue.receiver)), { + reason: '[Codegen] Internal error: Forget should always generate MethodCall::property ' + + 'as a MemberExpression of MethodCall::receiver', + loc: (_d = memberExpr.loc) !== null && _d !== void 0 ? _d : GeneratedSource, + }); + const args = instrValue.args.map(arg => codegenArgument(cx, arg)); + value = createCallExpression(cx.env, memberExpr, args, instrValue.loc, isHook); + break; + } + case 'NewExpression': { + const callee = codegenPlaceToExpression(cx, instrValue.callee); + const args = instrValue.args.map(arg => codegenArgument(cx, arg)); + value = libExports$1.newExpression(callee, args); + break; + } + case 'ObjectExpression': { + const properties = []; + for (const property of instrValue.properties) { + if (property.kind === 'ObjectProperty') { + const key = codegenObjectPropertyKey(cx, property.key); + switch (property.type) { + case 'property': { + const value = codegenPlaceToExpression(cx, property.place); + properties.push(libExports$1.objectProperty(key, value, property.key.kind === 'computed', key.type === 'Identifier' && + value.type === 'Identifier' && + value.name === key.name)); + break; + } + case 'method': { + const method = cx.objectMethods.get(property.place.identifier.id); + CompilerError.invariant(method, { + reason: 'Expected ObjectMethod instruction', + loc: GeneratedSource, + }); + const loweredFunc = method.loweredFunc; + const reactiveFunction = buildReactiveFunction(loweredFunc.func); + pruneUnusedLabels(reactiveFunction); + pruneUnusedLValues(reactiveFunction); + const fn = codegenReactiveFunction(new Context$1(cx.env, (_e = reactiveFunction.id) !== null && _e !== void 0 ? _e : '[[ anonymous ]]', cx.uniqueIdentifiers, cx.fbtOperands, cx.temp), reactiveFunction); + const babelNode = libExports$1.objectMethod('method', key, fn.params, fn.body, false); + babelNode.async = fn.async; + babelNode.generator = fn.generator; + properties.push(babelNode); + break; + } + default: + assertExhaustive$1(property.type, `Unexpected property type: ${property.type}`); + } + } + else { + properties.push(libExports$1.spreadElement(codegenPlaceToExpression(cx, property.place))); + } + } + value = libExports$1.objectExpression(properties); + break; + } + case 'JSXText': { + value = createJsxText(instrValue.loc, instrValue.value); + break; + } + case 'JsxExpression': { + const attributes = []; + for (const attribute of instrValue.props) { + attributes.push(codegenJsxAttribute(cx, attribute)); + } + let tagValue = instrValue.tag.kind === 'Identifier' + ? codegenPlaceToExpression(cx, instrValue.tag) + : libExports$1.stringLiteral(instrValue.tag.name); + let tag; + if (tagValue.type === 'Identifier') { + tag = createJsxIdentifier(instrValue.tag.loc, tagValue.name); + } + else if (tagValue.type === 'MemberExpression') { + tag = convertMemberExpressionToJsx(tagValue); + } + else { + CompilerError.invariant(tagValue.type === 'StringLiteral', { + reason: `Expected JSX tag to be an identifier or string, got \`${tagValue.type}\``, + loc: (_f = tagValue.loc) !== null && _f !== void 0 ? _f : GeneratedSource, + }); + if (tagValue.value.indexOf(':') >= 0) { + const [namespace, name] = tagValue.value.split(':', 2); + tag = createJsxNamespacedName(instrValue.tag.loc, createJsxIdentifier(instrValue.tag.loc, namespace), createJsxIdentifier(instrValue.tag.loc, name)); + } + else { + tag = createJsxIdentifier(instrValue.loc, tagValue.value); + } + } + let children; + if (tagValue.type === 'StringLiteral' && + SINGLE_CHILD_FBT_TAGS.has(tagValue.value)) { + CompilerError.invariant(instrValue.children != null, { + reason: 'Expected fbt element to have children', + loc: instrValue.loc, + }); + children = instrValue.children.map(child => codegenJsxFbtChildElement(cx, child)); + } + else { + children = + instrValue.children !== null + ? instrValue.children.map(child => codegenJsxElement(cx, child)) + : []; + } + value = createJsxElement(instrValue.loc, createJsxOpeningElement(instrValue.openingLoc, tag, attributes, instrValue.children === null), instrValue.children !== null + ? createJsxClosingElement(instrValue.closingLoc, tag) + : null, children, instrValue.children === null); + break; + } + case 'JsxFragment': { + value = libExports$1.jsxFragment(libExports$1.jsxOpeningFragment(), libExports$1.jsxClosingFragment(), instrValue.children.map(child => codegenJsxElement(cx, child))); + break; + } + case 'UnsupportedNode': { + const node = instrValue.node; + if (!libExports$1.isExpression(node)) { + return node; + } + value = node; + break; + } + case 'PropertyStore': + case 'PropertyLoad': + case 'PropertyDelete': { + let memberExpr; + if (typeof instrValue.property === 'string') { + memberExpr = libExports$1.memberExpression(codegenPlaceToExpression(cx, instrValue.object), libExports$1.identifier(instrValue.property)); + } + else { + memberExpr = libExports$1.memberExpression(codegenPlaceToExpression(cx, instrValue.object), libExports$1.numericLiteral(instrValue.property), true); + } + if (instrValue.kind === 'PropertyStore') { + value = libExports$1.assignmentExpression('=', memberExpr, codegenPlaceToExpression(cx, instrValue.value)); + } + else if (instrValue.kind === 'PropertyLoad') { + value = memberExpr; + } + else { + value = libExports$1.unaryExpression('delete', memberExpr); + } + break; + } + case 'ComputedStore': { + value = libExports$1.assignmentExpression('=', libExports$1.memberExpression(codegenPlaceToExpression(cx, instrValue.object), codegenPlaceToExpression(cx, instrValue.property), true), codegenPlaceToExpression(cx, instrValue.value)); + break; + } + case 'ComputedLoad': { + const object = codegenPlaceToExpression(cx, instrValue.object); + const property = codegenPlaceToExpression(cx, instrValue.property); + value = libExports$1.memberExpression(object, property, true); + break; + } + case 'ComputedDelete': { + value = libExports$1.unaryExpression('delete', libExports$1.memberExpression(codegenPlaceToExpression(cx, instrValue.object), codegenPlaceToExpression(cx, instrValue.property), true)); + break; + } + case 'LoadLocal': + case 'LoadContext': { + value = codegenPlaceToExpression(cx, instrValue.place); + break; + } + case 'FunctionExpression': { + const loweredFunc = instrValue.loweredFunc.func; + const reactiveFunction = buildReactiveFunction(loweredFunc); + pruneUnusedLabels(reactiveFunction); + pruneUnusedLValues(reactiveFunction); + pruneHoistedContexts(reactiveFunction); + const fn = codegenReactiveFunction(new Context$1(cx.env, (_g = reactiveFunction.id) !== null && _g !== void 0 ? _g : '[[ anonymous ]]', cx.uniqueIdentifiers, cx.fbtOperands, cx.temp), reactiveFunction); + if (instrValue.type === 'ArrowFunctionExpression') { + let body = fn.body; + if (body.body.length === 1 && loweredFunc.directives.length == 0) { + const stmt = body.body[0]; + if (stmt.type === 'ReturnStatement' && stmt.argument != null) { + body = stmt.argument; + } + } + value = libExports$1.arrowFunctionExpression(fn.params, body, fn.async); + } + else { + value = libExports$1.functionExpression(instrValue.name != null ? libExports$1.identifier(instrValue.name) : null, fn.params, fn.body, fn.generator, fn.async); + } + if (cx.env.config.enableNameAnonymousFunctions && + instrValue.name == null && + instrValue.nameHint != null) { + const name = instrValue.nameHint; + value = libExports$1.memberExpression(libExports$1.objectExpression([libExports$1.objectProperty(libExports$1.stringLiteral(name), value)]), libExports$1.stringLiteral(name), true, false); + } + break; + } + case 'TaggedTemplateExpression': { + value = createTaggedTemplateExpression(instrValue.loc, codegenPlaceToExpression(cx, instrValue.tag), libExports$1.templateLiteral([libExports$1.templateElement(instrValue.value)], [])); + break; + } + case 'TypeCastExpression': { + if (libExports$1.isTSType(instrValue.typeAnnotation)) { + if (instrValue.typeAnnotationKind === 'satisfies') { + value = libExports$1.tsSatisfiesExpression(codegenPlaceToExpression(cx, instrValue.value), instrValue.typeAnnotation); + } + else { + value = libExports$1.tsAsExpression(codegenPlaceToExpression(cx, instrValue.value), instrValue.typeAnnotation); + } + } + else { + value = libExports$1.typeCastExpression(codegenPlaceToExpression(cx, instrValue.value), libExports$1.typeAnnotation(instrValue.typeAnnotation)); + } + break; + } + case 'LogicalExpression': { + value = createLogicalExpression(instrValue.loc, instrValue.operator, codegenInstructionValueToExpression(cx, instrValue.left), codegenInstructionValueToExpression(cx, instrValue.right)); + break; + } + case 'ConditionalExpression': { + value = createConditionalExpression(instrValue.loc, codegenInstructionValueToExpression(cx, instrValue.test), codegenInstructionValueToExpression(cx, instrValue.consequent), codegenInstructionValueToExpression(cx, instrValue.alternate)); + break; + } + case 'SequenceExpression': { + const body = codegenBlockNoReset(cx, instrValue.instructions.map(instruction => ({ + kind: 'instruction', + instruction, + }))).body; + const expressions = body.map(stmt => { + var _a, _b; + if (stmt.type === 'ExpressionStatement') { + return stmt.expression; + } + else { + if (libExports$1.isVariableDeclaration(stmt)) { + const declarator = stmt.declarations[0]; + cx.recordError(new CompilerErrorDetail({ + reason: `(CodegenReactiveFunction::codegenInstructionValue) Cannot declare variables in a value block, tried to declare '${declarator.id.name}'`, + category: ErrorCategory.Todo, + loc: (_a = declarator.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + })); + return libExports$1.stringLiteral(`TODO handle ${declarator.id}`); + } + else { + cx.recordError(new CompilerErrorDetail({ + reason: `(CodegenReactiveFunction::codegenInstructionValue) Handle conversion of ${stmt.type} to expression`, + category: ErrorCategory.Todo, + loc: (_b = stmt.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + })); + return libExports$1.stringLiteral(`TODO handle ${stmt.type}`); + } + } + }); + if (expressions.length === 0) { + value = codegenInstructionValueToExpression(cx, instrValue.value); + } + else { + value = createSequenceExpression(instrValue.loc, [ + ...expressions, + codegenInstructionValueToExpression(cx, instrValue.value), + ]); + } + break; + } + case 'TemplateLiteral': { + value = createTemplateLiteral(instrValue.loc, instrValue.quasis.map(q => libExports$1.templateElement(q)), instrValue.subexprs.map(p => codegenPlaceToExpression(cx, p))); + break; + } + case 'LoadGlobal': { + value = libExports$1.identifier(instrValue.binding.name); + break; + } + case 'RegExpLiteral': { + value = libExports$1.regExpLiteral(instrValue.pattern, instrValue.flags); + break; + } + case 'MetaProperty': { + value = libExports$1.metaProperty(libExports$1.identifier(instrValue.meta), libExports$1.identifier(instrValue.property)); + break; + } + case 'Await': { + value = libExports$1.awaitExpression(codegenPlaceToExpression(cx, instrValue.value)); + break; + } + case 'GetIterator': { + value = codegenPlaceToExpression(cx, instrValue.collection); + break; + } + case 'IteratorNext': { + value = codegenPlaceToExpression(cx, instrValue.iterator); + break; + } + case 'NextPropertyOf': { + value = codegenPlaceToExpression(cx, instrValue.value); + break; + } + case 'PostfixUpdate': { + value = libExports$1.updateExpression(instrValue.operation, codegenPlaceToExpression(cx, instrValue.lvalue), false); + break; + } + case 'PrefixUpdate': { + value = libExports$1.updateExpression(instrValue.operation, codegenPlaceToExpression(cx, instrValue.lvalue), true); + break; + } + case 'StoreLocal': { + CompilerError.invariant(instrValue.lvalue.kind === InstructionKind.Reassign, { + reason: `Unexpected StoreLocal in codegenInstructionValue`, + loc: instrValue.loc, + }); + value = libExports$1.assignmentExpression('=', codegenLValue(cx, instrValue.lvalue.place), codegenPlaceToExpression(cx, instrValue.value)); + break; + } + case 'StoreGlobal': { + value = libExports$1.assignmentExpression('=', libExports$1.identifier(instrValue.name), codegenPlaceToExpression(cx, instrValue.value)); + break; + } + case 'StartMemoize': + case 'FinishMemoize': + case 'Debugger': + case 'DeclareLocal': + case 'DeclareContext': + case 'Destructure': + case 'ObjectMethod': + case 'StoreContext': { + CompilerError.invariant(false, { + reason: `Unexpected ${instrValue.kind} in codegenInstructionValue`, + loc: instrValue.loc, + }); + } + default: { + assertExhaustive$1(instrValue, `Unexpected instruction value kind \`${instrValue.kind}\``); + } + } + if (instrValue.loc != null && instrValue.loc != GeneratedSource) { + value.loc = instrValue.loc; + } + return value; +} +const STRING_REQUIRES_EXPR_CONTAINER_PATTERN = /[\u{0000}-\u{001F}\u{007F}\u{0080}-\u{FFFF}\u{010000}-\u{10FFFF}]|"|\\/u; +function codegenJsxAttribute(cx, attribute) { + switch (attribute.kind) { + case 'JsxAttribute': { + let propName; + if (attribute.name.indexOf(':') === -1) { + propName = createJsxIdentifier(attribute.place.loc, attribute.name); + } + else { + const [namespace, name] = attribute.name.split(':', 2); + propName = createJsxNamespacedName(attribute.place.loc, createJsxIdentifier(attribute.place.loc, namespace), createJsxIdentifier(attribute.place.loc, name)); + } + const innerValue = codegenPlaceToExpression(cx, attribute.place); + let value; + switch (innerValue.type) { + case 'StringLiteral': { + value = innerValue; + if (STRING_REQUIRES_EXPR_CONTAINER_PATTERN.test(value.value) && + !cx.fbtOperands.has(attribute.place.identifier.id)) { + value = createJsxExpressionContainer(value.loc, value); + } + break; + } + default: { + value = createJsxExpressionContainer(attribute.place.loc, innerValue); + break; + } + } + return createJsxAttribute(attribute.place.loc, propName, value); + } + case 'JsxSpreadAttribute': { + return libExports$1.jsxSpreadAttribute(codegenPlaceToExpression(cx, attribute.argument)); + } + default: { + assertExhaustive$1(attribute, `Unexpected attribute kind \`${attribute.kind}\``); + } + } +} +const JSX_TEXT_CHILD_REQUIRES_EXPR_CONTAINER_PATTERN = /[<>&{}]/; +function codegenJsxElement(cx, place) { + const value = codegenPlace(cx, place); + switch (value.type) { + case 'JSXText': { + if (JSX_TEXT_CHILD_REQUIRES_EXPR_CONTAINER_PATTERN.test(value.value)) { + return createJsxExpressionContainer(place.loc, createStringLiteral(place.loc, value.value)); + } + return createJsxText(place.loc, value.value); + } + case 'JSXElement': + case 'JSXFragment': { + return value; + } + default: { + return createJsxExpressionContainer(place.loc, value); + } + } +} +function codegenJsxFbtChildElement(cx, place) { + const value = codegenPlace(cx, place); + switch (value.type) { + case 'JSXText': + case 'JSXElement': { + return value; + } + default: { + return createJsxExpressionContainer(place.loc, value); + } + } +} +function convertMemberExpressionToJsx(expr) { + var _a, _b; + CompilerError.invariant(expr.property.type === 'Identifier', { + reason: 'Expected JSX member expression property to be a string', + loc: (_a = expr.loc) !== null && _a !== void 0 ? _a : GeneratedSource, + }); + const property = libExports$1.jsxIdentifier(expr.property.name); + if (expr.object.type === 'Identifier') { + return libExports$1.jsxMemberExpression(libExports$1.jsxIdentifier(expr.object.name), property); + } + else { + CompilerError.invariant(expr.object.type === 'MemberExpression', { + reason: 'Expected JSX member expression to be an identifier or nested member expression', + loc: (_b = expr.object.loc) !== null && _b !== void 0 ? _b : GeneratedSource, + }); + const object = convertMemberExpressionToJsx(expr.object); + return libExports$1.jsxMemberExpression(object, property); + } +} +function codegenObjectPropertyKey(cx, key) { + switch (key.kind) { + case 'string': { + return libExports$1.stringLiteral(key.name); + } + case 'identifier': { + return libExports$1.identifier(key.name); + } + case 'computed': { + const expr = codegenPlace(cx, key.name); + CompilerError.invariant(libExports$1.isExpression(expr), { + reason: 'Expected object property key to be an expression', + loc: key.name.loc, + }); + return expr; + } + case 'number': { + return libExports$1.numericLiteral(key.name); + } + } +} +function codegenArrayPattern(cx, pattern) { + const hasHoles = !pattern.items.every(e => e.kind !== 'Hole'); + if (hasHoles) { + const result = createArrayPattern(pattern.loc, []); + for (const item of pattern.items) { + if (item.kind === 'Hole') { + result.elements.push(null); + } + else { + result.elements.push(codegenLValue(cx, item)); + } + } + return result; + } + else { + return createArrayPattern(pattern.loc, pattern.items.map(item => { + if (item.kind === 'Hole') { + return null; + } + return codegenLValue(cx, item); + })); + } +} +function codegenLValue(cx, pattern) { + switch (pattern.kind) { + case 'ArrayPattern': { + return codegenArrayPattern(cx, pattern); + } + case 'ObjectPattern': { + return createObjectPattern(pattern.loc, pattern.properties.map(property => { + if (property.kind === 'ObjectProperty') { + const key = codegenObjectPropertyKey(cx, property.key); + const value = codegenLValue(cx, property.place); + return libExports$1.objectProperty(key, value, property.key.kind === 'computed', key.type === 'Identifier' && + value.type === 'Identifier' && + value.name === key.name); + } + else { + return libExports$1.restElement(codegenLValue(cx, property.place)); + } + })); + } + case 'Spread': { + return libExports$1.restElement(codegenLValue(cx, pattern.place)); + } + case 'Identifier': { + return convertIdentifier(pattern.identifier); + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } +} +function codegenValue(cx, loc, value) { + if (typeof value === 'number') { + if (value < 0) { + return libExports$1.unaryExpression('-', libExports$1.numericLiteral(-value), false); + } + else { + return libExports$1.numericLiteral(value); + } + } + else if (typeof value === 'boolean') { + return libExports$1.booleanLiteral(value); + } + else if (typeof value === 'string') { + return createStringLiteral(loc, value); + } + else if (value === null) { + return libExports$1.nullLiteral(); + } + else if (value === undefined) { + return libExports$1.identifier('undefined'); + } + else { + assertExhaustive$1(value, 'Unexpected primitive value kind'); + } +} +function codegenArgument(cx, arg) { + if (arg.kind === 'Identifier') { + return codegenPlaceToExpression(cx, arg); + } + else { + return libExports$1.spreadElement(codegenPlaceToExpression(cx, arg.place)); + } +} +function codegenPlaceToExpression(cx, place) { + const value = codegenPlace(cx, place); + return convertValueToExpression(value); +} +function codegenPlace(cx, place) { + let tmp = cx.temp.get(place.identifier.declarationId); + if (tmp != null) { + return tmp; + } + CompilerError.invariant(place.identifier.name !== null || tmp !== undefined, { + reason: `[Codegen] No value found for temporary`, + description: `Value for '${printPlace(place)}' was not set in the codegen context`, + loc: place.loc, + }); + const identifier = convertIdentifier(place.identifier); + identifier.loc = place.loc; + return identifier; +} +function convertIdentifier(identifier) { + CompilerError.invariant(identifier.name !== null && identifier.name.kind === 'named', { + reason: `Expected temporaries to be promoted to named identifiers in an earlier pass`, + description: `identifier ${identifier.id} is unnamed`, + loc: GeneratedSource, + }); + return createIdentifier(identifier.loc, identifier.name.value); +} +function compareScopeDependency(a, b) { + var _a, _b; + CompilerError.invariant(((_a = a.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named' && ((_b = b.identifier.name) === null || _b === void 0 ? void 0 : _b.kind) === 'named', { + reason: '[Codegen] Expected named identifier for dependency', + loc: a.identifier.loc, + }); + const aName = [ + a.identifier.name.value, + ...a.path.map(entry => `${entry.optional ? '?' : ''}${entry.property}`), + ].join('.'); + const bName = [ + b.identifier.name.value, + ...b.path.map(entry => `${entry.optional ? '?' : ''}${entry.property}`), + ].join('.'); + if (aName < bName) + return -1; + else if (aName > bName) + return 1; + else + return 0; +} +function compareScopeDeclaration(a, b) { + var _a, _b; + CompilerError.invariant(((_a = a.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named' && ((_b = b.identifier.name) === null || _b === void 0 ? void 0 : _b.kind) === 'named', { + reason: '[Codegen] Expected named identifier for declaration', + loc: a.identifier.loc, + }); + const aName = a.identifier.name.value; + const bName = b.identifier.name.value; + if (aName < bName) + return -1; + else if (aName > bName) + return 1; + else + return 0; +} + +function extractScopeDeclarationsFromDestructuring(fn) { + const state = new State$1(fn.env); + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + state.declared.add(place.identifier.declarationId); + } + visitReactiveFunction(fn, new Visitor$7(), state); +} +let State$1 = class State { + constructor(env) { + this.declared = new Set(); + this.env = env; + } +}; +let Visitor$7 = class Visitor extends ReactiveFunctionTransform { + visitScope(scope, state) { + for (const [, declaration] of scope.scope.declarations) { + state.declared.add(declaration.identifier.declarationId); + } + this.traverseScope(scope, state); + } + transformInstruction(instruction, state) { + this.visitInstruction(instruction, state); + let instructionsToProcess = [instruction]; + let result = { kind: 'keep' }; + if (instruction.value.kind === 'Destructure') { + const transformed = transformDestructuring(state, instruction, instruction.value); + if (transformed) { + instructionsToProcess = transformed; + result = { + kind: 'replace-many', + value: transformed.map(instruction => ({ + kind: 'instruction', + instruction, + })), + }; + } + } + for (const instr of instructionsToProcess) { + for (const [place, kind] of eachInstructionLValueWithKind(instr)) { + if (kind !== InstructionKind.Reassign) { + state.declared.add(place.identifier.declarationId); + } + } + } + return result; + } +}; +function transformDestructuring(state, instr, destructure) { + let reassigned = new Set(); + let hasDeclaration = false; + for (const place of eachPatternOperand(destructure.lvalue.pattern)) { + const isDeclared = state.declared.has(place.identifier.declarationId); + if (isDeclared) { + reassigned.add(place.identifier.id); + } + else { + hasDeclaration = true; + } + } + if (!hasDeclaration) { + destructure.lvalue.kind = InstructionKind.Reassign; + return null; + } + const instructions = []; + const renamed = new Map(); + mapPatternOperands(destructure.lvalue.pattern, place => { + if (!reassigned.has(place.identifier.id)) { + return place; + } + const temporary = clonePlaceToTemporary(state.env, place); + promoteTemporary(temporary.identifier); + renamed.set(place, temporary); + return temporary; + }); + instructions.push(instr); + for (const [original, temporary] of renamed) { + instructions.push({ + id: instr.id, + lvalue: null, + value: { + kind: 'StoreLocal', + lvalue: { + kind: InstructionKind.Reassign, + place: original, + }, + value: temporary, + type: null, + loc: destructure.loc, + }, + loc: instr.loc, + }); + } + return instructions; +} + +function mergeReactiveScopesThatInvalidateTogether(fn) { + const lastUsageVisitor = new FindLastUsageVisitor(); + visitReactiveFunction(fn, lastUsageVisitor, undefined); + visitReactiveFunction(fn, new Transform$4(lastUsageVisitor.lastUsage), null); +} +function log(msg) { +} +class FindLastUsageVisitor extends ReactiveFunctionVisitor { + constructor() { + super(...arguments); + this.lastUsage = new Map(); + } + visitPlace(id, place, _state) { + const previousUsage = this.lastUsage.get(place.identifier.declarationId); + const lastUsage = previousUsage !== undefined + ? makeInstructionId(Math.max(previousUsage, id)) + : id; + this.lastUsage.set(place.identifier.declarationId, lastUsage); + } +} +let Transform$4 = class Transform extends ReactiveFunctionTransform { + constructor(lastUsage) { + super(); + this.temporaries = new Map(); + this.lastUsage = lastUsage; + } + transformScope(scopeBlock, state) { + this.visitScope(scopeBlock, scopeBlock.scope.dependencies); + if (state !== null && + areEqualDependencies(state, scopeBlock.scope.dependencies)) { + return { kind: 'replace-many', value: scopeBlock.instructions }; + } + else { + return { kind: 'keep' }; + } + } + visitBlock(block, state) { + var _a; + this.traverseBlock(block, state); + let current = null; + const merged = []; + function reset() { + CompilerError.invariant(current !== null, { + reason: 'MergeConsecutiveScopes: expected current scope to be non-null if reset()', + loc: GeneratedSource, + }); + if (current.to > current.from + 1) { + merged.push(current); + } + current = null; + } + for (let i = 0; i < block.length; i++) { + const instr = block[i]; + switch (instr.kind) { + case 'terminal': { + if (current !== null) { + reset(); + } + break; + } + case 'pruned-scope': { + if (current !== null) { + reset(); + } + break; + } + case 'instruction': { + switch (instr.instruction.value.kind) { + case 'BinaryExpression': + case 'ComputedLoad': + case 'JSXText': + case 'LoadGlobal': + case 'LoadLocal': + case 'Primitive': + case 'PropertyLoad': + case 'TemplateLiteral': + case 'UnaryExpression': { + if (current !== null && instr.instruction.lvalue !== null) { + current.lvalues.add(instr.instruction.lvalue.identifier.declarationId); + if (instr.instruction.value.kind === 'LoadLocal') { + this.temporaries.set(instr.instruction.lvalue.identifier.declarationId, instr.instruction.value.place.identifier.declarationId); + } + } + break; + } + case 'StoreLocal': { + if (current !== null) { + if (instr.instruction.value.lvalue.kind === InstructionKind.Const) { + for (const lvalue of eachInstructionLValue(instr.instruction)) { + current.lvalues.add(lvalue.identifier.declarationId); + } + this.temporaries.set(instr.instruction.value.lvalue.place.identifier + .declarationId, (_a = this.temporaries.get(instr.instruction.value.value.identifier.declarationId)) !== null && _a !== void 0 ? _a : instr.instruction.value.value.identifier.declarationId); + } + else { + reset(); + } + } + break; + } + default: { + if (current !== null) { + reset(); + } + } + } + break; + } + case 'scope': { + if (current !== null && + canMergeScopes(current.block, instr, this.temporaries) && + areLValuesLastUsedByScope(instr.scope, current.lvalues, this.lastUsage)) { + current.block.scope.range.end = makeInstructionId(Math.max(current.block.scope.range.end, instr.scope.range.end)); + for (const [key, value] of instr.scope.declarations) { + current.block.scope.declarations.set(key, value); + } + updateScopeDeclarations(current.block.scope, this.lastUsage); + current.to = i + 1; + current.lvalues.clear(); + if (!scopeIsEligibleForMerging(instr)) { + reset(); + } + } + else { + if (current !== null) { + reset(); + } + if (scopeIsEligibleForMerging(instr)) { + current = { + block: instr, + from: i, + to: i + 1, + lvalues: new Set(), + }; + } + } + break; + } + default: { + assertExhaustive$1(instr, `Unexpected instruction kind \`${instr.kind}\``); + } + } + } + if (current !== null) { + reset(); + } + if (merged.length) { + for (const entry of merged) { + log(printReactiveScopeSummary(entry.block.scope) + + ` from=${entry.from} to=${entry.to}`); + } + } + if (merged.length === 0) { + return; + } + const nextInstructions = []; + let index = 0; + for (const entry of merged) { + if (index < entry.from) { + nextInstructions.push(...block.slice(index, entry.from)); + index = entry.from; + } + const mergedScope = block[entry.from]; + CompilerError.invariant(mergedScope.kind === 'scope', { + reason: 'MergeConsecutiveScopes: Expected scope starting index to be a scope', + loc: GeneratedSource, + }); + nextInstructions.push(mergedScope); + index++; + while (index < entry.to) { + const instr = block[index++]; + if (instr.kind === 'scope') { + mergedScope.instructions.push(...instr.instructions); + mergedScope.scope.merged.add(instr.scope.id); + } + else { + mergedScope.instructions.push(instr); + } + } + } + while (index < block.length) { + nextInstructions.push(block[index++]); + } + block.length = 0; + block.push(...nextInstructions); + } +}; +function updateScopeDeclarations(scope, lastUsage) { + for (const [id, decl] of scope.declarations) { + const lastUsedAt = lastUsage.get(decl.identifier.declarationId); + if (lastUsedAt < scope.range.end) { + scope.declarations.delete(id); + } + } +} +function areLValuesLastUsedByScope(scope, lvalues, lastUsage) { + for (const lvalue of lvalues) { + const lastUsedAt = lastUsage.get(lvalue); + if (lastUsedAt >= scope.range.end) { + return false; + } + } + return true; +} +function canMergeScopes(current, next, temporaries) { + if (current.scope.reassignments.size !== 0 || + next.scope.reassignments.size !== 0) { + return false; + } + if (areEqualDependencies(current.scope.dependencies, next.scope.dependencies)) { + return true; + } + if (areEqualDependencies(new Set([...current.scope.declarations.values()].map(declaration => ({ + identifier: declaration.identifier, + reactive: true, + path: [], + loc: GeneratedSource, + }))), next.scope.dependencies) || + (next.scope.dependencies.size !== 0 && + [...next.scope.dependencies].every(dep => dep.path.length === 0 && + isAlwaysInvalidatingType(dep.identifier.type) && + Iterable_some(current.scope.declarations.values(), decl => decl.identifier.declarationId === dep.identifier.declarationId || + decl.identifier.declarationId === + temporaries.get(dep.identifier.declarationId))))) { + return true; + } + log(` ${printReactiveScopeSummary(current.scope)} ${[...current.scope.declarations.values()].map(decl => decl.identifier.declarationId)}`); + log(` ${printReactiveScopeSummary(next.scope)} ${[...next.scope.dependencies].map(dep => { var _a; return `${dep.identifier.declarationId} ${(_a = temporaries.get(dep.identifier.declarationId)) !== null && _a !== void 0 ? _a : dep.identifier.declarationId}`; })}`); + return false; +} +function isAlwaysInvalidatingType(type) { + switch (type.kind) { + case 'Object': { + switch (type.shapeId) { + case BuiltInArrayId: + case BuiltInObjectId: + case BuiltInFunctionId: + case BuiltInJsxId: { + return true; + } + } + break; + } + case 'Function': { + return true; + } + } + return false; +} +function areEqualDependencies(a, b) { + if (a.size !== b.size) { + return false; + } + for (const aValue of a) { + let found = false; + for (const bValue of b) { + if (aValue.identifier.declarationId === bValue.identifier.declarationId && + areEqualPaths(aValue.path, bValue.path)) { + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; +} +function scopeIsEligibleForMerging(scopeBlock) { + if (scopeBlock.scope.dependencies.size === 0) { + return true; + } + return [...scopeBlock.scope.declarations].some(([, decl]) => isAlwaysInvalidatingType(decl.identifier.type)); +} + +var _PromoteInterposedTemporaries_promotable, _PromoteInterposedTemporaries_consts, _PromoteInterposedTemporaries_globals; +class PromoteTemporaries extends ReactiveFunctionVisitor { + visitScope(scopeBlock, state) { + for (const dep of scopeBlock.scope.dependencies) { + const { identifier } = dep; + if (identifier.name == null) { + promoteIdentifier(identifier, state); + } + } + for (const [, declaration] of scopeBlock.scope.declarations) { + if (declaration.identifier.name == null) { + promoteIdentifier(declaration.identifier, state); + } + } + this.traverseScope(scopeBlock, state); + } + visitPrunedScope(scopeBlock, state) { + var _a; + for (const [, declaration] of scopeBlock.scope.declarations) { + if (declaration.identifier.name == null && + ((_a = state.pruned.get(declaration.identifier.declarationId)) === null || _a === void 0 ? void 0 : _a.usedOutsideScope) === true) { + promoteIdentifier(declaration.identifier, state); + } + } + this.traversePrunedScope(scopeBlock, state); + } + visitParam(place, state) { + if (place.identifier.name === null) { + promoteIdentifier(place.identifier, state); + } + } + visitValue(id, value, state) { + this.traverseValue(id, value, state); + if (value.kind === 'FunctionExpression' || value.kind === 'ObjectMethod') { + this.visitHirFunction(value.loweredFunc.func, state); + } + } + visitReactiveFunctionValue(_id, _dependencies, fn, state) { + for (const operand of fn.params) { + const place = operand.kind === 'Identifier' ? operand : operand.place; + if (place.identifier.name === null) { + promoteIdentifier(place.identifier, state); + } + } + visitReactiveFunction(fn, this, state); + } +} +class PromoteAllInstancedOfPromotedTemporaries extends ReactiveFunctionVisitor { + visitPlace(_id, place, state) { + if (place.identifier.name === null && + state.promoted.has(place.identifier.declarationId)) { + promoteIdentifier(place.identifier, state); + } + } + visitLValue(_id, _lvalue, _state) { + this.visitPlace(_id, _lvalue, _state); + } + traverseScopeIdentifiers(scope, state) { + for (const [, decl] of scope.declarations) { + if (decl.identifier.name === null && + state.promoted.has(decl.identifier.declarationId)) { + promoteIdentifier(decl.identifier, state); + } + } + for (const dep of scope.dependencies) { + if (dep.identifier.name === null && + state.promoted.has(dep.identifier.declarationId)) { + promoteIdentifier(dep.identifier, state); + } + } + for (const reassignment of scope.reassignments) { + if (reassignment.name === null && + state.promoted.has(reassignment.declarationId)) { + promoteIdentifier(reassignment, state); + } + } + } + visitScope(scope, state) { + this.traverseScope(scope, state); + this.traverseScopeIdentifiers(scope.scope, state); + } + visitPrunedScope(scopeBlock, state) { + this.traversePrunedScope(scopeBlock, state); + this.traverseScopeIdentifiers(scopeBlock.scope, state); + } + visitReactiveFunctionValue(_id, _dependencies, fn, state) { + visitReactiveFunction(fn, this, state); + } +} +class CollectPromotableTemporaries extends ReactiveFunctionVisitor { + constructor() { + super(...arguments); + this.activeScopes = []; + } + visitPlace(_id, place, state) { + if (this.activeScopes.length !== 0 && + state.pruned.has(place.identifier.declarationId)) { + const prunedPlace = state.pruned.get(place.identifier.declarationId); + if (prunedPlace.activeScopes.indexOf(this.activeScopes.at(-1)) === -1) { + prunedPlace.usedOutsideScope = true; + } + } + } + visitValue(id, value, state) { + this.traverseValue(id, value, state); + if (value.kind === 'JsxExpression' && value.tag.kind === 'Identifier') { + state.tags.add(value.tag.identifier.declarationId); + } + } + visitPrunedScope(scopeBlock, state) { + for (const [_id, decl] of scopeBlock.scope.declarations) { + state.pruned.set(decl.identifier.declarationId, { + activeScopes: [...this.activeScopes], + usedOutsideScope: false, + }); + } + this.visitBlock(scopeBlock.instructions, state); + } + visitScope(scopeBlock, state) { + this.activeScopes.push(scopeBlock.scope.id); + this.traverseScope(scopeBlock, state); + this.activeScopes.pop(); + } +} +class PromoteInterposedTemporaries extends ReactiveFunctionVisitor { + constructor(promotable, params) { + super(); + _PromoteInterposedTemporaries_promotable.set(this, void 0); + _PromoteInterposedTemporaries_consts.set(this, new Set()); + _PromoteInterposedTemporaries_globals.set(this, new Set()); + params.forEach(param => { + switch (param.kind) { + case 'Identifier': + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(param.identifier.id); + break; + case 'Spread': + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(param.place.identifier.id); + break; + } + }); + __classPrivateFieldSet(this, _PromoteInterposedTemporaries_promotable, promotable, "f"); + } + visitPlace(_id, place, state) { + const promo = state.get(place.identifier.id); + if (promo) { + const [identifier, needsPromotion] = promo; + if (needsPromotion && + identifier.name === null && + !__classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").has(identifier.id)) { + promoteIdentifier(identifier, __classPrivateFieldGet(this, _PromoteInterposedTemporaries_promotable, "f")); + } + } + } + visitInstruction(instruction, state) { + for (const lval of eachInstructionValueLValue(instruction.value)) { + CompilerError.invariant(lval.identifier.name != null, { + reason: 'PromoteInterposedTemporaries: Assignment targets not expected to be temporaries', + loc: instruction.loc, + }); + } + switch (instruction.value.kind) { + case 'CallExpression': + case 'MethodCall': + case 'Await': + case 'PropertyStore': + case 'PropertyDelete': + case 'ComputedStore': + case 'ComputedDelete': + case 'PostfixUpdate': + case 'PrefixUpdate': + case 'StoreLocal': + case 'StoreContext': + case 'StoreGlobal': + case 'Destructure': { + let constStore = false; + if ((instruction.value.kind === 'StoreContext' || + instruction.value.kind === 'StoreLocal') && + (instruction.value.lvalue.kind === 'Const' || + instruction.value.lvalue.kind === 'HoistedConst')) { + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(instruction.value.lvalue.place.identifier.id); + constStore = true; + } + if (instruction.value.kind === 'Destructure' && + (instruction.value.lvalue.kind === 'Const' || + instruction.value.lvalue.kind === 'HoistedConst')) { + [...eachPatternOperand(instruction.value.lvalue.pattern)].forEach(ident => __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(ident.identifier.id)); + constStore = true; + } + if (instruction.value.kind === 'MethodCall') { + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(instruction.value.property.identifier.id); + } + super.visitInstruction(instruction, state); + if (!constStore && + (instruction.lvalue == null || + instruction.lvalue.identifier.name != null)) { + for (const [key, [ident, _]] of state.entries()) { + state.set(key, [ident, true]); + } + } + if (instruction.lvalue && instruction.lvalue.identifier.name === null) { + state.set(instruction.lvalue.identifier.id, [ + instruction.lvalue.identifier, + false, + ]); + } + break; + } + case 'DeclareContext': + case 'DeclareLocal': { + if (instruction.value.lvalue.kind === 'Const' || + instruction.value.lvalue.kind === 'HoistedConst') { + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(instruction.value.lvalue.place.identifier.id); + } + super.visitInstruction(instruction, state); + break; + } + case 'LoadContext': + case 'LoadLocal': { + if (instruction.lvalue && instruction.lvalue.identifier.name === null) { + if (__classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").has(instruction.value.place.identifier.id)) { + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(instruction.lvalue.identifier.id); + } + state.set(instruction.lvalue.identifier.id, [ + instruction.lvalue.identifier, + false, + ]); + } + super.visitInstruction(instruction, state); + break; + } + case 'PropertyLoad': + case 'ComputedLoad': { + if (instruction.lvalue) { + if (__classPrivateFieldGet(this, _PromoteInterposedTemporaries_globals, "f").has(instruction.value.object.identifier.id)) { + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_globals, "f").add(instruction.lvalue.identifier.id); + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_consts, "f").add(instruction.lvalue.identifier.id); + } + if (instruction.lvalue.identifier.name === null) { + state.set(instruction.lvalue.identifier.id, [ + instruction.lvalue.identifier, + false, + ]); + } + } + super.visitInstruction(instruction, state); + break; + } + case 'LoadGlobal': { + instruction.lvalue && + __classPrivateFieldGet(this, _PromoteInterposedTemporaries_globals, "f").add(instruction.lvalue.identifier.id); + super.visitInstruction(instruction, state); + break; + } + default: { + super.visitInstruction(instruction, state); + } + } + } +} +_PromoteInterposedTemporaries_promotable = new WeakMap(), _PromoteInterposedTemporaries_consts = new WeakMap(), _PromoteInterposedTemporaries_globals = new WeakMap(); +function promoteUsedTemporaries(fn) { + const state = { + tags: new Set(), + promoted: new Set(), + pruned: new Map(), + }; + visitReactiveFunction(fn, new CollectPromotableTemporaries(), state); + for (const operand of fn.params) { + const place = operand.kind === 'Identifier' ? operand : operand.place; + if (place.identifier.name === null) { + promoteIdentifier(place.identifier, state); + } + } + visitReactiveFunction(fn, new PromoteTemporaries(), state); + visitReactiveFunction(fn, new PromoteInterposedTemporaries(state, fn.params), new Map()); + visitReactiveFunction(fn, new PromoteAllInstancedOfPromotedTemporaries(), state); +} +function promoteIdentifier(identifier, state) { + CompilerError.invariant(identifier.name === null, { + reason: 'promoteTemporary: Expected to be called only for temporary variables', + loc: GeneratedSource, + }); + if (state.tags.has(identifier.declarationId)) { + promoteTemporaryJsxTag(identifier); + } + else { + promoteTemporary(identifier); + } + state.promoted.add(identifier.declarationId); +} + +function propagateEarlyReturns(fn) { + visitReactiveFunction(fn, new Transform$3(fn.env), { + withinReactiveScope: false, + earlyReturnValue: null, + }); +} +let Transform$3 = class Transform extends ReactiveFunctionTransform { + constructor(env) { + super(); + this.env = env; + } + visitScope(scopeBlock, parentState) { + if (scopeBlock.scope.earlyReturnValue !== null) { + return; + } + const innerState = { + withinReactiveScope: true, + earlyReturnValue: parentState.earlyReturnValue, + }; + this.traverseScope(scopeBlock, innerState); + const earlyReturnValue = innerState.earlyReturnValue; + if (earlyReturnValue !== null) { + if (!parentState.withinReactiveScope) { + scopeBlock.scope.earlyReturnValue = earlyReturnValue; + scopeBlock.scope.declarations.set(earlyReturnValue.value.id, { + identifier: earlyReturnValue.value, + scope: scopeBlock.scope, + }); + const instructions = scopeBlock.instructions; + const loc = earlyReturnValue.loc; + const sentinelTemp = createTemporaryPlace(this.env, loc); + const symbolTemp = createTemporaryPlace(this.env, loc); + const forTemp = createTemporaryPlace(this.env, loc); + const argTemp = createTemporaryPlace(this.env, loc); + scopeBlock.instructions = [ + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: Object.assign({}, symbolTemp), + value: { + kind: 'LoadGlobal', + binding: { + kind: 'Global', + name: 'Symbol', + }, + loc, + }, + }, + }, + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: Object.assign({}, forTemp), + value: { + kind: 'PropertyLoad', + object: Object.assign({}, symbolTemp), + property: makePropertyLiteral('for'), + loc, + }, + }, + }, + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: Object.assign({}, argTemp), + value: { + kind: 'Primitive', + value: EARLY_RETURN_SENTINEL, + loc, + }, + }, + }, + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: Object.assign({}, sentinelTemp), + value: { + kind: 'MethodCall', + receiver: symbolTemp, + property: forTemp, + args: [argTemp], + loc, + }, + }, + }, + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: null, + value: { + kind: 'StoreLocal', + loc, + type: null, + lvalue: { + kind: InstructionKind.Let, + place: { + kind: 'Identifier', + effect: Effect.ConditionallyMutate, + loc, + reactive: true, + identifier: earlyReturnValue.value, + }, + }, + value: Object.assign({}, sentinelTemp), + }, + }, + }, + { + kind: 'terminal', + label: { + id: earlyReturnValue.label, + implicit: false, + }, + terminal: { + kind: 'label', + id: makeInstructionId(0), + loc: GeneratedSource, + block: instructions, + }, + }, + ]; + } + else { + parentState.earlyReturnValue = earlyReturnValue; + } + } + } + transformTerminal(stmt, state) { + if (state.withinReactiveScope && stmt.terminal.kind === 'return') { + const loc = stmt.terminal.value.loc; + let earlyReturnValue; + if (state.earlyReturnValue !== null) { + earlyReturnValue = state.earlyReturnValue; + } + else { + const identifier = createTemporaryPlace(this.env, loc).identifier; + promoteTemporary(identifier); + earlyReturnValue = { + label: this.env.nextBlockId, + loc, + value: identifier, + }; + } + state.earlyReturnValue = earlyReturnValue; + return { + kind: 'replace-many', + value: [ + { + kind: 'instruction', + instruction: { + id: makeInstructionId(0), + loc, + lvalue: null, + value: { + kind: 'StoreLocal', + loc, + type: null, + lvalue: { + kind: InstructionKind.Reassign, + place: { + kind: 'Identifier', + identifier: earlyReturnValue.value, + effect: Effect.Capture, + loc, + reactive: true, + }, + }, + value: stmt.terminal.value, + }, + }, + }, + { + kind: 'terminal', + label: null, + terminal: { + kind: 'break', + id: makeInstructionId(0), + loc, + targetKind: 'labeled', + target: earlyReturnValue.label, + }, + }, + ], + }; + } + this.traverseTerminal(stmt, state); + return { kind: 'keep' }; + } +}; + +var _Node_value, _Node_next; +function empty() { + return EMPTY; +} +class Node { + constructor(value, next = EMPTY) { + _Node_value.set(this, void 0); + _Node_next.set(this, void 0); + __classPrivateFieldSet(this, _Node_value, value, "f"); + __classPrivateFieldSet(this, _Node_next, next, "f"); + } + push(value) { + return new Node(value, this); + } + pop() { + return __classPrivateFieldGet(this, _Node_next, "f"); + } + find(fn) { + return fn(__classPrivateFieldGet(this, _Node_value, "f")) ? true : __classPrivateFieldGet(this, _Node_next, "f").find(fn); + } + contains(value) { + return (value === __classPrivateFieldGet(this, _Node_value, "f") || + (__classPrivateFieldGet(this, _Node_next, "f") !== null && __classPrivateFieldGet(this, _Node_next, "f").contains(value))); + } + each(fn) { + fn(__classPrivateFieldGet(this, _Node_value, "f")); + __classPrivateFieldGet(this, _Node_next, "f").each(fn); + } + get value() { + return __classPrivateFieldGet(this, _Node_value, "f"); + } + print(fn) { + return fn(__classPrivateFieldGet(this, _Node_value, "f")) + __classPrivateFieldGet(this, _Node_next, "f").print(fn); + } +} +_Node_value = new WeakMap(), _Node_next = new WeakMap(); +class Empty { + push(value) { + return new Node(value, this); + } + pop() { + return this; + } + find(_fn) { + return false; + } + contains(_value) { + return false; + } + each(_fn) { + return; + } + get value() { + return null; + } + print(_) { + return ''; + } +} +const EMPTY = new Empty(); + +function pruneHoistedContexts(fn) { + visitReactiveFunction(fn, new Visitor$6(), { + activeScopes: empty(), + uninitialized: new Map(), + }); +} +let Visitor$6 = class Visitor extends ReactiveFunctionTransform { + visitScope(scope, state) { + state.activeScopes = state.activeScopes.push(new Set(scope.scope.declarations.keys())); + for (const decl of scope.scope.declarations.values()) { + state.uninitialized.set(decl.identifier.id, { kind: 'unknown-kind' }); + } + this.traverseScope(scope, state); + state.activeScopes.pop(); + for (const decl of scope.scope.declarations.values()) { + state.uninitialized.delete(decl.identifier.id); + } + } + visitPlace(_id, place, state) { + const maybeHoistedFn = state.uninitialized.get(place.identifier.id); + if ((maybeHoistedFn === null || maybeHoistedFn === void 0 ? void 0 : maybeHoistedFn.kind) === 'func' && + maybeHoistedFn.definition !== place) { + CompilerError.throwTodo({ + reason: '[PruneHoistedContexts] Rewrite hoisted function references', + loc: place.loc, + }); + } + } + transformInstruction(instruction, state) { + if (instruction.value.kind === 'DeclareContext') { + const maybeNonHoisted = convertHoistedLValueKind(instruction.value.lvalue.kind); + if (maybeNonHoisted != null) { + if (maybeNonHoisted === InstructionKind.Function && + state.uninitialized.has(instruction.value.lvalue.place.identifier.id)) { + state.uninitialized.set(instruction.value.lvalue.place.identifier.id, { + kind: 'func', + definition: null, + }); + } + return { kind: 'remove' }; + } + } + if (instruction.value.kind === 'StoreContext' && + instruction.value.lvalue.kind !== InstructionKind.Reassign) { + const lvalueId = instruction.value.lvalue.place.identifier.id; + const isDeclaredByScope = state.activeScopes.find(scope => scope.has(lvalueId)); + if (isDeclaredByScope) { + if (instruction.value.lvalue.kind === InstructionKind.Let || + instruction.value.lvalue.kind === InstructionKind.Const) { + instruction.value.lvalue.kind = InstructionKind.Reassign; + } + else if (instruction.value.lvalue.kind === InstructionKind.Function) { + const maybeHoistedFn = state.uninitialized.get(lvalueId); + if (maybeHoistedFn != null) { + CompilerError.invariant(maybeHoistedFn.kind === 'func', { + reason: '[PruneHoistedContexts] Unexpected hoisted function', + loc: instruction.loc, + }); + maybeHoistedFn.definition = instruction.value.lvalue.place; + state.uninitialized.delete(lvalueId); + } + } + else { + CompilerError.throwTodo({ + reason: '[PruneHoistedContexts] Unexpected kind', + description: `(${instruction.value.lvalue.kind})`, + loc: instruction.loc, + }); + } + } + } + this.visitInstruction(instruction, state); + return { kind: 'keep' }; + } +}; + +function hashEffect(effect) { + var _a; + switch (effect.kind) { + case 'Apply': { + return [ + effect.kind, + effect.receiver.identifier.id, + effect.function.identifier.id, + effect.mutatesFunction, + effect.args + .map(a => { + if (a.kind === 'Hole') { + return ''; + } + else if (a.kind === 'Identifier') { + return a.identifier.id; + } + else { + return `...${a.place.identifier.id}`; + } + }) + .join(','), + effect.into.identifier.id, + ].join(':'); + } + case 'CreateFrom': + case 'ImmutableCapture': + case 'Assign': + case 'Alias': + case 'Capture': + case 'MaybeAlias': { + return [ + effect.kind, + effect.from.identifier.id, + effect.into.identifier.id, + ].join(':'); + } + case 'Create': { + return [ + effect.kind, + effect.into.identifier.id, + effect.value, + effect.reason, + ].join(':'); + } + case 'Freeze': { + return [effect.kind, effect.value.identifier.id, effect.reason].join(':'); + } + case 'Impure': + case 'Render': { + return [effect.kind, effect.place.identifier.id].join(':'); + } + case 'MutateFrozen': + case 'MutateGlobal': { + return [ + effect.kind, + effect.place.identifier.id, + effect.error.severity, + effect.error.reason, + effect.error.description, + printSourceLocation((_a = effect.error.primaryLocation()) !== null && _a !== void 0 ? _a : GeneratedSource), + ].join(':'); + } + case 'Mutate': + case 'MutateConditionally': + case 'MutateTransitive': + case 'MutateTransitiveConditionally': { + return [effect.kind, effect.value.identifier.id].join(':'); + } + case 'CreateFunction': { + return [ + effect.kind, + effect.into.identifier.id, + effect.function.loweredFunc.func.returns.identifier.id, + effect.captures.map(p => p.identifier.id).join(','), + ].join(':'); + } + } +} + +var _InferenceState_isFunctionExpression, _InferenceState_values, _InferenceState_variables; +function inferMutationAliasingEffects(fn, { isFunctionExpression } = { + isFunctionExpression: false, +}) { + const initialState = InferenceState.empty(fn.env, isFunctionExpression); + const statesByBlock = new Map(); + for (const ref of fn.context) { + const value = { + kind: 'ObjectExpression', + properties: [], + loc: ref.loc, + }; + initialState.initialize(value, { + kind: ValueKind.Context, + reason: new Set([ValueReason.Other]), + }); + initialState.define(ref, value); + } + const paramKind = isFunctionExpression + ? { + kind: ValueKind.Mutable, + reason: new Set([ValueReason.Other]), + } + : { + kind: ValueKind.Frozen, + reason: new Set([ValueReason.ReactiveFunctionArgument]), + }; + if (fn.fnType === 'Component') { + CompilerError.invariant(fn.params.length <= 2, { + reason: 'Expected React component to have not more than two parameters: one for props and for ref', + loc: fn.loc, + }); + const [props, ref] = fn.params; + if (props != null) { + inferParam(props, initialState, paramKind); + } + if (ref != null) { + const place = ref.kind === 'Identifier' ? ref : ref.place; + const value = { + kind: 'ObjectExpression', + properties: [], + loc: place.loc, + }; + initialState.initialize(value, { + kind: ValueKind.Mutable, + reason: new Set([ValueReason.Other]), + }); + initialState.define(place, value); + } + } + else { + for (const param of fn.params) { + inferParam(param, initialState, paramKind); + } + } + const queuedStates = new Map(); + function queue(blockId, state) { + var _a; + let queuedState = queuedStates.get(blockId); + if (queuedState != null) { + state = (_a = queuedState.merge(state)) !== null && _a !== void 0 ? _a : queuedState; + queuedStates.set(blockId, state); + } + else { + const prevState = statesByBlock.get(blockId); + const nextState = prevState != null ? prevState.merge(state) : state; + if (nextState != null) { + queuedStates.set(blockId, nextState); + } + } + } + queue(fn.body.entry, initialState); + const hoistedContextDeclarations = findHoistedContextDeclarations(fn); + const context = new Context(isFunctionExpression, fn, hoistedContextDeclarations, findNonMutatedDestructureSpreads(fn)); + let iterationCount = 0; + while (queuedStates.size !== 0) { + iterationCount++; + if (iterationCount > 100) { + CompilerError.invariant(false, { + reason: `[InferMutationAliasingEffects] Potential infinite loop`, + description: `A value, temporary place, or effect was not cached properly`, + loc: fn.loc, + }); + } + for (const [blockId, block] of fn.body.blocks) { + const incomingState = queuedStates.get(blockId); + queuedStates.delete(blockId); + if (incomingState == null) { + continue; + } + statesByBlock.set(blockId, incomingState); + const state = incomingState.clone(); + inferBlock(context, state, block); + for (const nextBlockId of eachTerminalSuccessor(block.terminal)) { + queue(nextBlockId, state); + } + } + } + return; +} +function findHoistedContextDeclarations(fn) { + const hoisted = new Map(); + function visit(place) { + if (hoisted.has(place.identifier.declarationId) && + hoisted.get(place.identifier.declarationId) == null) { + hoisted.set(place.identifier.declarationId, place); + } + } + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + if (instr.value.kind === 'DeclareContext') { + const kind = instr.value.lvalue.kind; + if (kind == InstructionKind.HoistedConst || + kind == InstructionKind.HoistedFunction || + kind == InstructionKind.HoistedLet) { + hoisted.set(instr.value.lvalue.place.identifier.declarationId, null); + } + } + else { + for (const operand of eachInstructionValueOperand(instr.value)) { + visit(operand); + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + visit(operand); + } + } + return hoisted; +} +class Context { + constructor(isFunctionExpression, fn, hoistedContextDeclarations, nonMutatingSpreads) { + this.internedEffects = new Map(); + this.instructionSignatureCache = new Map(); + this.effectInstructionValueCache = new Map(); + this.applySignatureCache = new Map(); + this.catchHandlers = new Map(); + this.functionSignatureCache = new Map(); + this.isFuctionExpression = isFunctionExpression; + this.fn = fn; + this.hoistedContextDeclarations = hoistedContextDeclarations; + this.nonMutatingSpreads = nonMutatingSpreads; + } + cacheApplySignature(signature, effect, f) { + const inner = getOrInsertDefault(this.applySignatureCache, signature, new Map()); + return getOrInsertWith(inner, effect, f); + } + internEffect(effect) { + const hash = hashEffect(effect); + let interned = this.internedEffects.get(hash); + if (interned == null) { + this.internedEffects.set(hash, effect); + interned = effect; + } + return interned; + } +} +function findNonMutatedDestructureSpreads(fn) { + const knownFrozen = new Set(); + if (fn.fnType === 'Component') { + const [props] = fn.params; + if (props != null && props.kind === 'Identifier') { + knownFrozen.add(props.identifier.id); + } + } + else { + for (const param of fn.params) { + if (param.kind === 'Identifier') { + knownFrozen.add(param.identifier.id); + } + } + } + const candidateNonMutatingSpreads = new Map(); + for (const block of fn.body.blocks.values()) { + if (candidateNonMutatingSpreads.size !== 0) { + for (const phi of block.phis) { + for (const operand of phi.operands.values()) { + const spread = candidateNonMutatingSpreads.get(operand.identifier.id); + if (spread != null) { + candidateNonMutatingSpreads.delete(spread); + } + } + } + } + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'Destructure': { + if (!knownFrozen.has(value.value.identifier.id) || + !(value.lvalue.kind === InstructionKind.Let || + value.lvalue.kind === InstructionKind.Const) || + value.lvalue.pattern.kind !== 'ObjectPattern') { + continue; + } + for (const item of value.lvalue.pattern.properties) { + if (item.kind !== 'Spread') { + continue; + } + candidateNonMutatingSpreads.set(item.place.identifier.id, item.place.identifier.id); + } + break; + } + case 'LoadLocal': { + const spread = candidateNonMutatingSpreads.get(value.place.identifier.id); + if (spread != null) { + candidateNonMutatingSpreads.set(lvalue.identifier.id, spread); + } + break; + } + case 'StoreLocal': { + const spread = candidateNonMutatingSpreads.get(value.value.identifier.id); + if (spread != null) { + candidateNonMutatingSpreads.set(lvalue.identifier.id, spread); + candidateNonMutatingSpreads.set(value.lvalue.place.identifier.id, spread); + } + break; + } + case 'JsxFragment': + case 'JsxExpression': { + break; + } + case 'PropertyLoad': { + break; + } + case 'CallExpression': + case 'MethodCall': { + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + if (getHookKind(fn.env, callee.identifier) != null) { + if (!isRefOrRefValue(lvalue.identifier)) { + knownFrozen.add(lvalue.identifier.id); + } + } + else { + if (candidateNonMutatingSpreads.size !== 0) { + for (const operand of eachInstructionValueOperand(value)) { + const spread = candidateNonMutatingSpreads.get(operand.identifier.id); + if (spread != null) { + candidateNonMutatingSpreads.delete(spread); + } + } + } + } + break; + } + default: { + if (candidateNonMutatingSpreads.size !== 0) { + for (const operand of eachInstructionValueOperand(value)) { + const spread = candidateNonMutatingSpreads.get(operand.identifier.id); + if (spread != null) { + candidateNonMutatingSpreads.delete(spread); + } + } + } + } + } + } + } + const nonMutatingSpreads = new Set(); + for (const [key, value] of candidateNonMutatingSpreads) { + if (key === value) { + nonMutatingSpreads.add(key); + } + } + return nonMutatingSpreads; +} +function inferParam(param, initialState, paramKind) { + const place = param.kind === 'Identifier' ? param : param.place; + const value = { + kind: 'Primitive', + loc: place.loc, + value: undefined, + }; + initialState.initialize(value, paramKind); + initialState.define(place, value); +} +function inferBlock(context, state, block) { + for (const phi of block.phis) { + state.inferPhi(phi); + } + for (const instr of block.instructions) { + let instructionSignature = context.instructionSignatureCache.get(instr); + if (instructionSignature == null) { + instructionSignature = computeSignatureForInstruction(context, state.env, instr); + context.instructionSignatureCache.set(instr, instructionSignature); + } + const effects = applySignature(context, state, instructionSignature, instr); + instr.effects = effects; + } + const terminal = block.terminal; + if (terminal.kind === 'try' && terminal.handlerBinding != null) { + context.catchHandlers.set(terminal.handler, terminal.handlerBinding); + } + else if (terminal.kind === 'maybe-throw' && terminal.handler !== null) { + const handlerParam = context.catchHandlers.get(terminal.handler); + if (handlerParam != null) { + CompilerError.invariant(state.kind(handlerParam) != null, { + reason: 'Expected catch binding to be initialized with a DeclareLocal Catch instruction', + loc: terminal.loc, + }); + const effects = []; + for (const instr of block.instructions) { + if (instr.value.kind === 'CallExpression' || + instr.value.kind === 'MethodCall') { + state.appendAlias(handlerParam, instr.lvalue); + const kind = state.kind(instr.lvalue).kind; + if (kind === ValueKind.Mutable || kind == ValueKind.Context) { + effects.push(context.internEffect({ + kind: 'Alias', + from: instr.lvalue, + into: handlerParam, + })); + } + } + } + terminal.effects = effects.length !== 0 ? effects : null; + } + } + else if (terminal.kind === 'return') { + if (!context.isFuctionExpression) { + terminal.effects = [ + context.internEffect({ + kind: 'Freeze', + value: terminal.value, + reason: ValueReason.JsxCaptured, + }), + ]; + } + } +} +function applySignature(context, state, signature, instruction) { + var _a, _b; + const effects = []; + if (instruction.value.kind === 'FunctionExpression' || + instruction.value.kind === 'ObjectMethod') { + const aliasingEffects = (_a = instruction.value.loweredFunc.func.aliasingEffects) !== null && _a !== void 0 ? _a : []; + const context = new Set(instruction.value.loweredFunc.func.context.map(p => p.identifier.id)); + for (const effect of aliasingEffects) { + if (effect.kind === 'Mutate' || effect.kind === 'MutateTransitive') { + if (!context.has(effect.value.identifier.id)) { + continue; + } + const value = state.kind(effect.value); + switch (value.kind) { + case ValueKind.Frozen: { + const reason = getWriteErrorReason({ + kind: value.kind, + reason: value.reason, + }); + const variable = effect.value.identifier.name !== null && + effect.value.identifier.name.kind === 'named' + ? `\`${effect.value.identifier.name.value}\`` + : 'value'; + const diagnostic = CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'This value cannot be modified', + description: reason, + }).withDetails({ + kind: 'error', + loc: effect.value.loc, + message: `${variable} cannot be modified`, + }); + if (effect.kind === 'Mutate' && + ((_b = effect.reason) === null || _b === void 0 ? void 0 : _b.kind) === 'AssignCurrentProperty') { + diagnostic.withDetails({ + kind: 'hint', + message: `Hint: If this value is a Ref (value returned by \`useRef()\`), rename the variable to end in "Ref".`, + }); + } + effects.push({ + kind: 'MutateFrozen', + place: effect.value, + error: diagnostic, + }); + } + } + } + } + } + const initialized = new Set(); + for (const effect of signature.effects) { + applyEffect(context, state, effect, initialized, effects); + } + if (!(state.isDefined(instruction.lvalue) && state.kind(instruction.lvalue))) { + CompilerError.invariant(false, { + reason: `Expected instruction lvalue to be initialized`, + loc: instruction.loc, + }); + } + return effects.length !== 0 ? effects : null; +} +function applyEffect(context, state, _effect, initialized, effects) { + var _a, _b, _c, _d, _e; + const effect = context.internEffect(_effect); + switch (effect.kind) { + case 'Freeze': { + const didFreeze = state.freeze(effect.value, effect.reason); + if (didFreeze) { + effects.push(effect); + } + break; + } + case 'Create': { + CompilerError.invariant(!initialized.has(effect.into.identifier.id), { + reason: `Cannot re-initialize variable within an instruction`, + description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, + loc: effect.into.loc, + }); + initialized.add(effect.into.identifier.id); + let value = context.effectInstructionValueCache.get(effect); + if (value == null) { + value = { + kind: 'ObjectExpression', + properties: [], + loc: effect.into.loc, + }; + context.effectInstructionValueCache.set(effect, value); + } + state.initialize(value, { + kind: effect.value, + reason: new Set([effect.reason]), + }); + state.define(effect.into, value); + effects.push(effect); + break; + } + case 'ImmutableCapture': { + const kind = state.kind(effect.from).kind; + switch (kind) { + case ValueKind.Global: + case ValueKind.Primitive: { + break; + } + default: { + effects.push(effect); + } + } + break; + } + case 'CreateFrom': { + CompilerError.invariant(!initialized.has(effect.into.identifier.id), { + reason: `Cannot re-initialize variable within an instruction`, + description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, + loc: effect.into.loc, + }); + initialized.add(effect.into.identifier.id); + const fromValue = state.kind(effect.from); + let value = context.effectInstructionValueCache.get(effect); + if (value == null) { + value = { + kind: 'ObjectExpression', + properties: [], + loc: effect.into.loc, + }; + context.effectInstructionValueCache.set(effect, value); + } + state.initialize(value, { + kind: fromValue.kind, + reason: new Set(fromValue.reason), + }); + state.define(effect.into, value); + switch (fromValue.kind) { + case ValueKind.Primitive: + case ValueKind.Global: { + effects.push({ + kind: 'Create', + value: fromValue.kind, + into: effect.into, + reason: (_a = [...fromValue.reason][0]) !== null && _a !== void 0 ? _a : ValueReason.Other, + }); + break; + } + case ValueKind.Frozen: { + effects.push({ + kind: 'Create', + value: fromValue.kind, + into: effect.into, + reason: (_b = [...fromValue.reason][0]) !== null && _b !== void 0 ? _b : ValueReason.Other, + }); + applyEffect(context, state, { + kind: 'ImmutableCapture', + from: effect.from, + into: effect.into, + }, initialized, effects); + break; + } + default: { + effects.push(effect); + } + } + break; + } + case 'CreateFunction': { + CompilerError.invariant(!initialized.has(effect.into.identifier.id), { + reason: `Cannot re-initialize variable within an instruction`, + description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, + loc: effect.into.loc, + }); + initialized.add(effect.into.identifier.id); + effects.push(effect); + const hasCaptures = effect.captures.some(capture => { + switch (state.kind(capture).kind) { + case ValueKind.Context: + case ValueKind.Mutable: { + return true; + } + default: { + return false; + } + } + }); + const hasTrackedSideEffects = (_c = effect.function.loweredFunc.func.aliasingEffects) === null || _c === void 0 ? void 0 : _c.some(effect => effect.kind === 'MutateFrozen' || + effect.kind === 'MutateGlobal' || + effect.kind === 'Impure'); + const capturesRef = effect.function.loweredFunc.func.context.some(operand => isRefOrRefValue(operand.identifier)); + const isMutable = hasCaptures || hasTrackedSideEffects || capturesRef; + for (const operand of effect.function.loweredFunc.func.context) { + if (operand.effect !== Effect.Capture) { + continue; + } + const kind = state.kind(operand).kind; + if (kind === ValueKind.Primitive || + kind == ValueKind.Frozen || + kind == ValueKind.Global) { + operand.effect = Effect.Read; + } + } + state.initialize(effect.function, { + kind: isMutable ? ValueKind.Mutable : ValueKind.Frozen, + reason: new Set([]), + }); + state.define(effect.into, effect.function); + for (const capture of effect.captures) { + applyEffect(context, state, { + kind: 'Capture', + from: capture, + into: effect.into, + }, initialized, effects); + } + break; + } + case 'MaybeAlias': + case 'Alias': + case 'Capture': { + CompilerError.invariant(effect.kind === 'Capture' || + effect.kind === 'MaybeAlias' || + initialized.has(effect.into.identifier.id), { + reason: `Expected destination to already be initialized within this instruction`, + description: `Destination ${printPlace(effect.into)} is not initialized in this ` + + `instruction for effect ${printAliasingEffect(effect)}`, + loc: effect.into.loc, + }); + const intoKind = state.kind(effect.into).kind; + let destinationType = null; + switch (intoKind) { + case ValueKind.Context: { + destinationType = 'context'; + break; + } + case ValueKind.Mutable: + case ValueKind.MaybeFrozen: { + destinationType = 'mutable'; + break; + } + } + const fromKind = state.kind(effect.from).kind; + let sourceType = null; + switch (fromKind) { + case ValueKind.Context: { + sourceType = 'context'; + break; + } + case ValueKind.Global: + case ValueKind.Primitive: { + break; + } + case ValueKind.MaybeFrozen: + case ValueKind.Frozen: { + sourceType = 'frozen'; + break; + } + default: { + sourceType = 'mutable'; + break; + } + } + if (sourceType === 'frozen') { + applyEffect(context, state, { + kind: 'ImmutableCapture', + from: effect.from, + into: effect.into, + }, initialized, effects); + } + else if ((sourceType === 'mutable' && destinationType === 'mutable') || + effect.kind === 'MaybeAlias') { + effects.push(effect); + } + else if ((sourceType === 'context' && destinationType != null) || + (sourceType === 'mutable' && destinationType === 'context')) { + applyEffect(context, state, { kind: 'MaybeAlias', from: effect.from, into: effect.into }, initialized, effects); + } + break; + } + case 'Assign': { + CompilerError.invariant(!initialized.has(effect.into.identifier.id), { + reason: `Cannot re-initialize variable within an instruction`, + description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`, + loc: effect.into.loc, + }); + initialized.add(effect.into.identifier.id); + const fromValue = state.kind(effect.from); + const fromKind = fromValue.kind; + switch (fromKind) { + case ValueKind.Frozen: { + applyEffect(context, state, { + kind: 'ImmutableCapture', + from: effect.from, + into: effect.into, + }, initialized, effects); + let value = context.effectInstructionValueCache.get(effect); + if (value == null) { + value = { + kind: 'Primitive', + value: undefined, + loc: effect.from.loc, + }; + context.effectInstructionValueCache.set(effect, value); + } + state.initialize(value, { + kind: fromKind, + reason: new Set(fromValue.reason), + }); + state.define(effect.into, value); + break; + } + case ValueKind.Global: + case ValueKind.Primitive: { + let value = context.effectInstructionValueCache.get(effect); + if (value == null) { + value = { + kind: 'Primitive', + value: undefined, + loc: effect.from.loc, + }; + context.effectInstructionValueCache.set(effect, value); + } + state.initialize(value, { + kind: fromKind, + reason: new Set(fromValue.reason), + }); + state.define(effect.into, value); + break; + } + default: { + state.assign(effect.into, effect.from); + effects.push(effect); + break; + } + } + break; + } + case 'Apply': { + const functionValues = state.values(effect.function); + if (functionValues.length === 1 && + functionValues[0].kind === 'FunctionExpression' && + functionValues[0].loweredFunc.func.aliasingEffects != null) { + const functionExpr = functionValues[0]; + let signature = context.functionSignatureCache.get(functionExpr); + if (signature == null) { + signature = buildSignatureFromFunctionExpression(state.env, functionExpr); + context.functionSignatureCache.set(functionExpr, signature); + } + const signatureEffects = context.cacheApplySignature(signature, effect, () => computeEffectsForSignature(state.env, signature, effect.into, effect.receiver, effect.args, functionExpr.loweredFunc.func.context, effect.loc)); + if (signatureEffects != null) { + applyEffect(context, state, { kind: 'MutateTransitiveConditionally', value: effect.function }, initialized, effects); + for (const signatureEffect of signatureEffects) { + applyEffect(context, state, signatureEffect, initialized, effects); + } + break; + } + } + let signatureEffects = null; + if (((_d = effect.signature) === null || _d === void 0 ? void 0 : _d.aliasing) != null) { + const signature = effect.signature.aliasing; + signatureEffects = context.cacheApplySignature(effect.signature.aliasing, effect, () => computeEffectsForSignature(state.env, signature, effect.into, effect.receiver, effect.args, [], effect.loc)); + } + if (signatureEffects != null) { + for (const signatureEffect of signatureEffects) { + applyEffect(context, state, signatureEffect, initialized, effects); + } + } + else if (effect.signature != null) { + const legacyEffects = computeEffectsForLegacySignature(state, effect.signature, effect.into, effect.receiver, effect.args, effect.loc); + for (const legacyEffect of legacyEffects) { + applyEffect(context, state, legacyEffect, initialized, effects); + } + } + else { + applyEffect(context, state, { + kind: 'Create', + into: effect.into, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }, initialized, effects); + for (const arg of [effect.receiver, effect.function, ...effect.args]) { + if (arg.kind === 'Hole') { + continue; + } + const operand = arg.kind === 'Identifier' ? arg : arg.place; + if (operand !== effect.function || effect.mutatesFunction) { + applyEffect(context, state, { + kind: 'MutateTransitiveConditionally', + value: operand, + }, initialized, effects); + } + const mutateIterator = arg.kind === 'Spread' ? conditionallyMutateIterator(operand) : null; + if (mutateIterator) { + applyEffect(context, state, mutateIterator, initialized, effects); + } + applyEffect(context, state, { kind: 'MaybeAlias', from: operand, into: effect.into }, initialized, effects); + for (const otherArg of [ + effect.receiver, + effect.function, + ...effect.args, + ]) { + if (otherArg.kind === 'Hole') { + continue; + } + const other = otherArg.kind === 'Identifier' ? otherArg : otherArg.place; + if (other === arg) { + continue; + } + applyEffect(context, state, { + kind: 'Capture', + from: operand, + into: other, + }, initialized, effects); + } + } + } + break; + } + case 'Mutate': + case 'MutateConditionally': + case 'MutateTransitive': + case 'MutateTransitiveConditionally': { + const mutationKind = state.mutate(effect.kind, effect.value); + if (mutationKind === 'mutate') { + effects.push(effect); + } + else if (mutationKind === 'mutate-ref') ; + else if (mutationKind !== 'none' && + (effect.kind === 'Mutate' || effect.kind === 'MutateTransitive')) { + const value = state.kind(effect.value); + if (mutationKind === 'mutate-frozen' && + context.hoistedContextDeclarations.has(effect.value.identifier.declarationId)) { + const variable = effect.value.identifier.name !== null && + effect.value.identifier.name.kind === 'named' + ? `\`${effect.value.identifier.name.value}\`` + : null; + const hoistedAccess = context.hoistedContextDeclarations.get(effect.value.identifier.declarationId); + const diagnostic = CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'Cannot access variable before it is declared', + description: `${variable !== null && variable !== void 0 ? variable : 'This variable'} is accessed before it is declared, which prevents the earlier access from updating when this value changes over time`, + }); + if (hoistedAccess != null && hoistedAccess.loc != effect.value.loc) { + diagnostic.withDetails({ + kind: 'error', + loc: hoistedAccess.loc, + message: `${variable !== null && variable !== void 0 ? variable : 'variable'} accessed before it is declared`, + }); + } + diagnostic.withDetails({ + kind: 'error', + loc: effect.value.loc, + message: `${variable !== null && variable !== void 0 ? variable : 'variable'} is declared here`, + }); + applyEffect(context, state, { + kind: 'MutateFrozen', + place: effect.value, + error: diagnostic, + }, initialized, effects); + } + else { + const reason = getWriteErrorReason({ + kind: value.kind, + reason: value.reason, + }); + const variable = effect.value.identifier.name !== null && + effect.value.identifier.name.kind === 'named' + ? `\`${effect.value.identifier.name.value}\`` + : 'value'; + const diagnostic = CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'This value cannot be modified', + description: reason, + }).withDetails({ + kind: 'error', + loc: effect.value.loc, + message: `${variable} cannot be modified`, + }); + if (effect.kind === 'Mutate' && + ((_e = effect.reason) === null || _e === void 0 ? void 0 : _e.kind) === 'AssignCurrentProperty') { + diagnostic.withDetails({ + kind: 'hint', + message: `Hint: If this value is a Ref (value returned by \`useRef()\`), rename the variable to end in "Ref".`, + }); + } + applyEffect(context, state, { + kind: value.kind === ValueKind.Frozen + ? 'MutateFrozen' + : 'MutateGlobal', + place: effect.value, + error: diagnostic, + }, initialized, effects); + } + } + break; + } + case 'Impure': + case 'Render': + case 'MutateFrozen': + case 'MutateGlobal': { + effects.push(effect); + break; + } + default: { + assertExhaustive$1(effect, `Unexpected effect kind '${effect.kind}'`); + } + } +} +class InferenceState { + constructor(env, isFunctionExpression, values, variables) { + _InferenceState_isFunctionExpression.set(this, void 0); + _InferenceState_values.set(this, void 0); + _InferenceState_variables.set(this, void 0); + this.env = env; + __classPrivateFieldSet(this, _InferenceState_isFunctionExpression, isFunctionExpression, "f"); + __classPrivateFieldSet(this, _InferenceState_values, values, "f"); + __classPrivateFieldSet(this, _InferenceState_variables, variables, "f"); + } + static empty(env, isFunctionExpression) { + return new InferenceState(env, isFunctionExpression, new Map(), new Map()); + } + get isFunctionExpression() { + return __classPrivateFieldGet(this, _InferenceState_isFunctionExpression, "f"); + } + initialize(value, kind) { + CompilerError.invariant(value.kind !== 'LoadLocal', { + reason: '[InferMutationAliasingEffects] Expected all top-level identifiers to be defined as variables, not values', + loc: value.loc, + }); + __classPrivateFieldGet(this, _InferenceState_values, "f").set(value, kind); + } + values(place) { + const values = __classPrivateFieldGet(this, _InferenceState_variables, "f").get(place.identifier.id); + CompilerError.invariant(values != null, { + reason: `[InferMutationAliasingEffects] Expected value kind to be initialized`, + description: `${printPlace(place)}`, + message: 'this is uninitialized', + loc: place.loc, + }); + return Array.from(values); + } + kind(place) { + const values = __classPrivateFieldGet(this, _InferenceState_variables, "f").get(place.identifier.id); + CompilerError.invariant(values != null, { + reason: `[InferMutationAliasingEffects] Expected value kind to be initialized`, + description: `${printPlace(place)}`, + message: 'this is uninitialized', + loc: place.loc, + }); + let mergedKind = null; + for (const value of values) { + const kind = __classPrivateFieldGet(this, _InferenceState_values, "f").get(value); + mergedKind = + mergedKind !== null ? mergeAbstractValues(mergedKind, kind) : kind; + } + CompilerError.invariant(mergedKind !== null, { + reason: `[InferMutationAliasingEffects] Expected at least one value`, + description: `No value found at \`${printPlace(place)}\``, + loc: place.loc, + }); + return mergedKind; + } + assign(place, value) { + const values = __classPrivateFieldGet(this, _InferenceState_variables, "f").get(value.identifier.id); + CompilerError.invariant(values != null, { + reason: `[InferMutationAliasingEffects] Expected value for identifier to be initialized`, + description: `${printIdentifier(value.identifier)}`, + message: 'Expected value for identifier to be initialized', + loc: value.loc, + }); + __classPrivateFieldGet(this, _InferenceState_variables, "f").set(place.identifier.id, new Set(values)); + } + appendAlias(place, value) { + const values = __classPrivateFieldGet(this, _InferenceState_variables, "f").get(value.identifier.id); + CompilerError.invariant(values != null, { + reason: `[InferMutationAliasingEffects] Expected value for identifier to be initialized`, + description: `${printIdentifier(value.identifier)}`, + message: 'Expected value for identifier to be initialized', + loc: value.loc, + }); + const prevValues = this.values(place); + __classPrivateFieldGet(this, _InferenceState_variables, "f").set(place.identifier.id, new Set([...prevValues, ...values])); + } + define(place, value) { + CompilerError.invariant(__classPrivateFieldGet(this, _InferenceState_values, "f").has(value), { + reason: `[InferMutationAliasingEffects] Expected value to be initialized`, + description: printInstructionValue(value), + loc: value.loc, + }); + __classPrivateFieldGet(this, _InferenceState_variables, "f").set(place.identifier.id, new Set([value])); + } + isDefined(place) { + return __classPrivateFieldGet(this, _InferenceState_variables, "f").has(place.identifier.id); + } + freeze(place, reason) { + const value = this.kind(place); + switch (value.kind) { + case ValueKind.Context: + case ValueKind.Mutable: + case ValueKind.MaybeFrozen: { + const values = this.values(place); + for (const instrValue of values) { + this.freezeValue(instrValue, reason); + } + return true; + } + case ValueKind.Frozen: + case ValueKind.Global: + case ValueKind.Primitive: { + return false; + } + default: { + assertExhaustive$1(value.kind, `Unexpected value kind '${value.kind}'`); + } + } + } + freezeValue(value, reason) { + __classPrivateFieldGet(this, _InferenceState_values, "f").set(value, { + kind: ValueKind.Frozen, + reason: new Set([reason]), + }); + if (value.kind === 'FunctionExpression' && + (this.env.config.enablePreserveExistingMemoizationGuarantees || + this.env.config.enableTransitivelyFreezeFunctionExpressions)) { + for (const place of value.loweredFunc.func.context) { + this.freeze(place, reason); + } + } + } + mutate(variant, place) { + if (isRefOrRefValue(place.identifier)) { + return 'mutate-ref'; + } + const kind = this.kind(place).kind; + switch (variant) { + case 'MutateConditionally': + case 'MutateTransitiveConditionally': { + switch (kind) { + case ValueKind.Mutable: + case ValueKind.Context: { + return 'mutate'; + } + default: { + return 'none'; + } + } + } + case 'Mutate': + case 'MutateTransitive': { + switch (kind) { + case ValueKind.Mutable: + case ValueKind.Context: { + return 'mutate'; + } + case ValueKind.Primitive: { + return 'none'; + } + case ValueKind.Frozen: { + return 'mutate-frozen'; + } + case ValueKind.Global: { + return 'mutate-global'; + } + case ValueKind.MaybeFrozen: { + return 'mutate-frozen'; + } + default: { + assertExhaustive$1(kind, `Unexpected kind ${kind}`); + } + } + } + default: { + assertExhaustive$1(variant, `Unexpected mutation variant ${variant}`); + } + } + } + merge(other) { + let nextValues = null; + let nextVariables = null; + for (const [id, thisValue] of __classPrivateFieldGet(this, _InferenceState_values, "f")) { + const otherValue = __classPrivateFieldGet(other, _InferenceState_values, "f").get(id); + if (otherValue !== undefined) { + const mergedValue = mergeAbstractValues(thisValue, otherValue); + if (mergedValue !== thisValue) { + nextValues = nextValues !== null && nextValues !== void 0 ? nextValues : new Map(__classPrivateFieldGet(this, _InferenceState_values, "f")); + nextValues.set(id, mergedValue); + } + } + } + for (const [id, otherValue] of __classPrivateFieldGet(other, _InferenceState_values, "f")) { + if (__classPrivateFieldGet(this, _InferenceState_values, "f").has(id)) { + continue; + } + nextValues = nextValues !== null && nextValues !== void 0 ? nextValues : new Map(__classPrivateFieldGet(this, _InferenceState_values, "f")); + nextValues.set(id, otherValue); + } + for (const [id, thisValues] of __classPrivateFieldGet(this, _InferenceState_variables, "f")) { + const otherValues = __classPrivateFieldGet(other, _InferenceState_variables, "f").get(id); + if (otherValues !== undefined) { + let mergedValues = null; + for (const otherValue of otherValues) { + if (!thisValues.has(otherValue)) { + mergedValues = mergedValues !== null && mergedValues !== void 0 ? mergedValues : new Set(thisValues); + mergedValues.add(otherValue); + } + } + if (mergedValues !== null) { + nextVariables = nextVariables !== null && nextVariables !== void 0 ? nextVariables : new Map(__classPrivateFieldGet(this, _InferenceState_variables, "f")); + nextVariables.set(id, mergedValues); + } + } + } + for (const [id, otherValues] of __classPrivateFieldGet(other, _InferenceState_variables, "f")) { + if (__classPrivateFieldGet(this, _InferenceState_variables, "f").has(id)) { + continue; + } + nextVariables = nextVariables !== null && nextVariables !== void 0 ? nextVariables : new Map(__classPrivateFieldGet(this, _InferenceState_variables, "f")); + nextVariables.set(id, new Set(otherValues)); + } + if (nextVariables === null && nextValues === null) { + return null; + } + else { + return new InferenceState(this.env, __classPrivateFieldGet(this, _InferenceState_isFunctionExpression, "f"), nextValues !== null && nextValues !== void 0 ? nextValues : new Map(__classPrivateFieldGet(this, _InferenceState_values, "f")), nextVariables !== null && nextVariables !== void 0 ? nextVariables : new Map(__classPrivateFieldGet(this, _InferenceState_variables, "f"))); + } + } + clone() { + return new InferenceState(this.env, __classPrivateFieldGet(this, _InferenceState_isFunctionExpression, "f"), new Map(__classPrivateFieldGet(this, _InferenceState_values, "f")), new Map(__classPrivateFieldGet(this, _InferenceState_variables, "f"))); + } + debug() { + const result = { values: {}, variables: {} }; + const objects = new Map(); + function identify(value) { + let id = objects.get(value); + if (id == null) { + id = objects.size; + objects.set(value, id); + } + return id; + } + for (const [value, kind] of __classPrivateFieldGet(this, _InferenceState_values, "f")) { + const id = identify(value); + result.values[id] = { + abstract: this.debugAbstractValue(kind), + value: printInstructionValue(value), + }; + } + for (const [variable, values] of __classPrivateFieldGet(this, _InferenceState_variables, "f")) { + result.variables[`$${variable}`] = [...values].map(identify); + } + return result; + } + debugAbstractValue(value) { + return { + kind: value.kind, + reason: [...value.reason], + }; + } + inferPhi(phi) { + const values = new Set(); + for (const [_, operand] of phi.operands) { + const operandValues = __classPrivateFieldGet(this, _InferenceState_variables, "f").get(operand.identifier.id); + if (operandValues === undefined) + continue; + for (const v of operandValues) { + values.add(v); + } + } + if (values.size > 0) { + __classPrivateFieldGet(this, _InferenceState_variables, "f").set(phi.place.identifier.id, values); + } + } +} +_InferenceState_isFunctionExpression = new WeakMap(), _InferenceState_values = new WeakMap(), _InferenceState_variables = new WeakMap(); +function mergeAbstractValues(a, b) { + const kind = mergeValueKinds(a.kind, b.kind); + if (kind === a.kind && + kind === b.kind && + Set_isSuperset(a.reason, b.reason)) { + return a; + } + const reason = new Set(a.reason); + for (const r of b.reason) { + reason.add(r); + } + return { kind, reason }; +} +function conditionallyMutateIterator(place) { + if (!(isArrayType(place.identifier) || + isSetType(place.identifier) || + isMapType(place.identifier))) { + return { + kind: 'MutateTransitiveConditionally', + value: place, + }; + } + return null; +} +function computeSignatureForInstruction(context, env, instr) { + const { lvalue, value } = instr; + const effects = []; + switch (value.kind) { + case 'ArrayExpression': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + for (const element of value.elements) { + if (element.kind === 'Identifier') { + effects.push({ + kind: 'Capture', + from: element, + into: lvalue, + }); + } + else if (element.kind === 'Spread') { + const mutateIterator = conditionallyMutateIterator(element.place); + if (mutateIterator != null) { + effects.push(mutateIterator); + } + effects.push({ + kind: 'Capture', + from: element.place, + into: lvalue, + }); + } + else { + continue; + } + } + break; + } + case 'ObjectExpression': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + for (const property of value.properties) { + if (property.kind === 'ObjectProperty') { + effects.push({ + kind: 'Capture', + from: property.place, + into: lvalue, + }); + } + else { + effects.push({ + kind: 'Capture', + from: property.place, + into: lvalue, + }); + } + } + break; + } + case 'Await': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + effects.push({ kind: 'MutateTransitiveConditionally', value: value.value }); + effects.push({ + kind: 'Capture', + from: value.value, + into: lvalue, + }); + break; + } + case 'NewExpression': + case 'CallExpression': + case 'MethodCall': { + let callee; + let receiver; + let mutatesCallee; + if (value.kind === 'NewExpression') { + callee = value.callee; + receiver = value.callee; + mutatesCallee = false; + } + else if (value.kind === 'CallExpression') { + callee = value.callee; + receiver = value.callee; + mutatesCallee = true; + } + else if (value.kind === 'MethodCall') { + callee = value.property; + receiver = value.receiver; + mutatesCallee = false; + } + else { + assertExhaustive$1(value, `Unexpected value kind '${value.kind}'`); + } + const signature = getFunctionCallSignature(env, callee.identifier.type); + effects.push({ + kind: 'Apply', + receiver, + function: callee, + mutatesFunction: mutatesCallee, + args: value.args, + into: lvalue, + signature, + loc: value.loc, + }); + break; + } + case 'PropertyDelete': + case 'ComputedDelete': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + effects.push({ kind: 'Mutate', value: value.object }); + break; + } + case 'PropertyLoad': + case 'ComputedLoad': { + if (isPrimitiveType(lvalue.identifier)) { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + } + else { + effects.push({ + kind: 'CreateFrom', + from: value.object, + into: lvalue, + }); + } + break; + } + case 'PropertyStore': + case 'ComputedStore': { + const mutationReason = value.kind === 'PropertyStore' && + value.property === 'current' && + value.object.identifier.type.kind === 'Type' + ? { kind: 'AssignCurrentProperty' } + : null; + effects.push({ + kind: 'Mutate', + value: value.object, + reason: mutationReason, + }); + effects.push({ + kind: 'Capture', + from: value.value, + into: value.object, + }); + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + effects.push({ + kind: 'CreateFunction', + into: lvalue, + function: value, + captures: value.loweredFunc.func.context.filter(operand => operand.effect === Effect.Capture), + }); + break; + } + case 'GetIterator': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + if (isArrayType(value.collection.identifier) || + isMapType(value.collection.identifier) || + isSetType(value.collection.identifier)) { + effects.push({ + kind: 'Capture', + from: value.collection, + into: lvalue, + }); + } + else { + effects.push({ kind: 'Alias', from: value.collection, into: lvalue }); + effects.push({ + kind: 'MutateTransitiveConditionally', + value: value.collection, + }); + } + break; + } + case 'IteratorNext': { + effects.push({ kind: 'MutateConditionally', value: value.iterator }); + effects.push({ + kind: 'CreateFrom', + from: value.collection, + into: lvalue, + }); + break; + } + case 'NextPropertyOf': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'JsxExpression': + case 'JsxFragment': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Frozen, + reason: ValueReason.JsxCaptured, + }); + for (const operand of eachInstructionValueOperand(value)) { + effects.push({ + kind: 'Freeze', + value: operand, + reason: ValueReason.JsxCaptured, + }); + effects.push({ + kind: 'Capture', + from: operand, + into: lvalue, + }); + } + if (value.kind === 'JsxExpression') { + if (value.tag.kind === 'Identifier') { + effects.push({ + kind: 'Render', + place: value.tag, + }); + } + if (value.children != null) { + for (const child of value.children) { + effects.push({ + kind: 'Render', + place: child, + }); + } + } + for (const prop of value.props) { + if (prop.kind === 'JsxAttribute' && + prop.place.identifier.type.kind === 'Function' && + (isJsxType(prop.place.identifier.type.return) || + (prop.place.identifier.type.return.kind === 'Phi' && + prop.place.identifier.type.return.operands.some(operand => isJsxType(operand))))) { + effects.push({ + kind: 'Render', + place: prop.place, + }); + } + } + } + break; + } + case 'DeclareLocal': { + effects.push({ + kind: 'Create', + into: value.lvalue.place, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'Destructure': { + for (const patternItem of eachPatternItem(value.lvalue.pattern)) { + const place = patternItem.kind === 'Identifier' ? patternItem : patternItem.place; + if (isPrimitiveType(place.identifier)) { + effects.push({ + kind: 'Create', + into: place, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + } + else if (patternItem.kind === 'Identifier') { + effects.push({ + kind: 'CreateFrom', + from: value.value, + into: place, + }); + } + else { + effects.push({ + kind: 'Create', + into: place, + reason: ValueReason.Other, + value: context.nonMutatingSpreads.has(place.identifier.id) + ? ValueKind.Frozen + : ValueKind.Mutable, + }); + effects.push({ + kind: 'Capture', + from: value.value, + into: place, + }); + } + } + effects.push({ kind: 'Assign', from: value.value, into: lvalue }); + break; + } + case 'LoadContext': { + effects.push({ kind: 'CreateFrom', from: value.place, into: lvalue }); + break; + } + case 'DeclareContext': { + const kind = value.lvalue.kind; + if (!context.hoistedContextDeclarations.has(value.lvalue.place.identifier.declarationId) || + kind === InstructionKind.HoistedConst || + kind === InstructionKind.HoistedFunction || + kind === InstructionKind.HoistedLet) { + effects.push({ + kind: 'Create', + into: value.lvalue.place, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + } + else { + effects.push({ kind: 'Mutate', value: value.lvalue.place }); + } + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'StoreContext': { + if (value.lvalue.kind === InstructionKind.Reassign || + context.hoistedContextDeclarations.has(value.lvalue.place.identifier.declarationId)) { + effects.push({ kind: 'Mutate', value: value.lvalue.place }); + } + else { + effects.push({ + kind: 'Create', + into: value.lvalue.place, + value: ValueKind.Mutable, + reason: ValueReason.Other, + }); + } + effects.push({ + kind: 'Capture', + from: value.value, + into: value.lvalue.place, + }); + effects.push({ kind: 'Assign', from: value.value, into: lvalue }); + break; + } + case 'LoadLocal': { + effects.push({ kind: 'Assign', from: value.place, into: lvalue }); + break; + } + case 'StoreLocal': { + effects.push({ + kind: 'Assign', + from: value.value, + into: value.lvalue.place, + }); + effects.push({ kind: 'Assign', from: value.value, into: lvalue }); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + effects.push({ + kind: 'Create', + into: value.lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'StoreGlobal': { + const variable = `\`${value.name}\``; + effects.push({ + kind: 'MutateGlobal', + place: value.value, + error: CompilerDiagnostic.create({ + category: ErrorCategory.Globals, + reason: 'Cannot reassign variables declared outside of the component/hook', + description: `Variable ${variable} is declared outside of the component/hook. Reassigning this value during render is a form of side effect, which can cause unpredictable behavior depending on when the component happens to re-render. If this variable is used in rendering, use useState instead. Otherwise, consider updating it in an effect. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render)`, + }).withDetails({ + kind: 'error', + loc: instr.loc, + message: `${variable} cannot be reassigned`, + }), + }); + effects.push({ kind: 'Assign', from: value.value, into: lvalue }); + break; + } + case 'TypeCastExpression': { + effects.push({ kind: 'Assign', from: value.value, into: lvalue }); + break; + } + case 'LoadGlobal': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Global, + reason: ValueReason.Global, + }); + break; + } + case 'StartMemoize': + case 'FinishMemoize': { + if (env.config.enablePreserveExistingMemoizationGuarantees) { + for (const operand of eachInstructionValueOperand(value)) { + effects.push({ + kind: 'Freeze', + value: operand, + reason: ValueReason.HookCaptured, + }); + } + } + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + case 'TaggedTemplateExpression': + case 'BinaryExpression': + case 'Debugger': + case 'JSXText': + case 'MetaProperty': + case 'Primitive': + case 'RegExpLiteral': + case 'TemplateLiteral': + case 'UnaryExpression': + case 'UnsupportedNode': { + effects.push({ + kind: 'Create', + into: lvalue, + value: ValueKind.Primitive, + reason: ValueReason.Other, + }); + break; + } + } + return { + effects, + }; +} +function computeEffectsForLegacySignature(state, signature, lvalue, receiver, args, loc) { + var _a, _b; + const returnValueReason = (_a = signature.returnValueReason) !== null && _a !== void 0 ? _a : ValueReason.Other; + const effects = []; + effects.push({ + kind: 'Create', + into: lvalue, + value: signature.returnValueKind, + reason: returnValueReason, + }); + if (signature.impure && state.env.config.validateNoImpureFunctionsInRender) { + effects.push({ + kind: 'Impure', + place: receiver, + error: CompilerDiagnostic.create({ + category: ErrorCategory.Purity, + reason: 'Cannot call impure function during render', + description: (signature.canonicalName != null + ? `\`${signature.canonicalName}\` is an impure function. ` + : '') + + 'Calling an impure function can produce unstable results that update unpredictably when the component happens to re-render. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent)', + }).withDetails({ + kind: 'error', + loc, + message: 'Cannot call impure function', + }), + }); + } + if (signature.knownIncompatible != null && state.env.enableValidations) { + const errors = new CompilerError(); + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.IncompatibleLibrary, + reason: 'Use of incompatible library', + description: [ + 'This API returns functions which cannot be memoized without leading to stale UI. ' + + 'To prevent this, by default React Compiler will skip memoizing this component/hook. ' + + 'However, you may see issues if values from this API are passed to other components/hooks that are ' + + 'memoized', + ].join(''), + }).withDetails({ + kind: 'error', + loc: receiver.loc, + message: signature.knownIncompatible, + })); + throw errors; + } + const stores = []; + const captures = []; + function visit(place, effect) { + switch (effect) { + case Effect.Store: { + effects.push({ + kind: 'Mutate', + value: place, + }); + stores.push(place); + break; + } + case Effect.Capture: { + captures.push(place); + break; + } + case Effect.ConditionallyMutate: { + effects.push({ + kind: 'MutateTransitiveConditionally', + value: place, + }); + break; + } + case Effect.ConditionallyMutateIterator: { + const mutateIterator = conditionallyMutateIterator(place); + if (mutateIterator != null) { + effects.push(mutateIterator); + } + effects.push({ + kind: 'Capture', + from: place, + into: lvalue, + }); + break; + } + case Effect.Freeze: { + effects.push({ + kind: 'Freeze', + value: place, + reason: returnValueReason, + }); + break; + } + case Effect.Mutate: { + effects.push({ kind: 'MutateTransitive', value: place }); + break; + } + case Effect.Read: { + effects.push({ + kind: 'ImmutableCapture', + from: place, + into: lvalue, + }); + break; + } + } + } + if (signature.mutableOnlyIfOperandsAreMutable && + areArgumentsImmutableAndNonMutating(state, args)) { + effects.push({ + kind: 'Alias', + from: receiver, + into: lvalue, + }); + for (const arg of args) { + if (arg.kind === 'Hole') { + continue; + } + const place = arg.kind === 'Identifier' ? arg : arg.place; + effects.push({ + kind: 'ImmutableCapture', + from: place, + into: lvalue, + }); + } + return effects; + } + if (signature.calleeEffect !== Effect.Capture) { + effects.push({ + kind: 'Alias', + from: receiver, + into: lvalue, + }); + } + visit(receiver, signature.calleeEffect); + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg.kind === 'Hole') { + continue; + } + const place = arg.kind === 'Identifier' ? arg : arg.place; + const signatureEffect = arg.kind === 'Identifier' && i < signature.positionalParams.length + ? signature.positionalParams[i] + : ((_b = signature.restParam) !== null && _b !== void 0 ? _b : Effect.ConditionallyMutate); + const effect = getArgumentEffect(signatureEffect, arg); + visit(place, effect); + } + if (captures.length !== 0) { + if (stores.length === 0) { + for (const capture of captures) { + effects.push({ kind: 'Alias', from: capture, into: lvalue }); + } + } + else { + for (const capture of captures) { + for (const store of stores) { + effects.push({ kind: 'Capture', from: capture, into: store }); + } + } + } + } + return effects; +} +function areArgumentsImmutableAndNonMutating(state, args) { + for (const arg of args) { + if (arg.kind === 'Hole') { + continue; + } + if (arg.kind === 'Identifier' && arg.identifier.type.kind === 'Function') { + const fnShape = state.env.getFunctionSignature(arg.identifier.type); + if (fnShape != null) { + return (!fnShape.positionalParams.some(isKnownMutableEffect) && + (fnShape.restParam == null || + !isKnownMutableEffect(fnShape.restParam))); + } + } + const place = arg.kind === 'Identifier' ? arg : arg.place; + const kind = state.kind(place).kind; + switch (kind) { + case ValueKind.Primitive: + case ValueKind.Frozen: { + break; + } + default: { + return false; + } + } + const values = state.values(place); + for (const value of values) { + if (value.kind === 'FunctionExpression' && + value.loweredFunc.func.params.some(param => { + const place = param.kind === 'Identifier' ? param : param.place; + const range = place.identifier.mutableRange; + return range.end > range.start + 1; + })) { + return false; + } + } + } + return true; +} +function computeEffectsForSignature(env, signature, lvalue, receiver, args, context = [], loc) { + var _a, _b, _c, _d, _e, _f, _g; + if (signature.params.length > args.length || + (args.length > signature.params.length && signature.rest == null)) { + return null; + } + const mutableSpreads = new Set(); + const substitutions = new Map(); + substitutions.set(signature.receiver, [receiver]); + substitutions.set(signature.returns, [lvalue]); + const params = signature.params; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg.kind === 'Hole') { + continue; + } + else if (params == null || i >= params.length || arg.kind === 'Spread') { + if (signature.rest == null) { + return null; + } + const place = arg.kind === 'Identifier' ? arg : arg.place; + getOrInsertWith(substitutions, signature.rest, () => []).push(place); + if (arg.kind === 'Spread') { + const mutateIterator = conditionallyMutateIterator(arg.place); + if (mutateIterator != null) { + mutableSpreads.add(arg.place.identifier.id); + } + } + } + else { + const param = params[i]; + substitutions.set(param, [arg]); + } + } + for (const operand of context) { + substitutions.set(operand.identifier.id, [operand]); + } + const effects = []; + for (const signatureTemporary of signature.temporaries) { + const temp = createTemporaryPlace(env, receiver.loc); + substitutions.set(signatureTemporary.identifier.id, [temp]); + } + for (const effect of signature.effects) { + switch (effect.kind) { + case 'MaybeAlias': + case 'Assign': + case 'ImmutableCapture': + case 'Alias': + case 'CreateFrom': + case 'Capture': { + const from = (_a = substitutions.get(effect.from.identifier.id)) !== null && _a !== void 0 ? _a : []; + const to = (_b = substitutions.get(effect.into.identifier.id)) !== null && _b !== void 0 ? _b : []; + for (const fromId of from) { + for (const toId of to) { + effects.push({ + kind: effect.kind, + from: fromId, + into: toId, + }); + } + } + break; + } + case 'Impure': + case 'MutateFrozen': + case 'MutateGlobal': { + const values = (_c = substitutions.get(effect.place.identifier.id)) !== null && _c !== void 0 ? _c : []; + for (const value of values) { + effects.push({ kind: effect.kind, place: value, error: effect.error }); + } + break; + } + case 'Render': { + const values = (_d = substitutions.get(effect.place.identifier.id)) !== null && _d !== void 0 ? _d : []; + for (const value of values) { + effects.push({ kind: effect.kind, place: value }); + } + break; + } + case 'Mutate': + case 'MutateTransitive': + case 'MutateTransitiveConditionally': + case 'MutateConditionally': { + const values = (_e = substitutions.get(effect.value.identifier.id)) !== null && _e !== void 0 ? _e : []; + for (const id of values) { + effects.push({ kind: effect.kind, value: id }); + } + break; + } + case 'Freeze': { + const values = (_f = substitutions.get(effect.value.identifier.id)) !== null && _f !== void 0 ? _f : []; + for (const value of values) { + if (mutableSpreads.has(value.identifier.id)) { + CompilerError.throwTodo({ + reason: 'Support spread syntax for hook arguments', + loc: value.loc, + }); + } + effects.push({ kind: 'Freeze', value, reason: effect.reason }); + } + break; + } + case 'Create': { + const into = (_g = substitutions.get(effect.into.identifier.id)) !== null && _g !== void 0 ? _g : []; + for (const value of into) { + effects.push({ + kind: 'Create', + into: value, + value: effect.value, + reason: effect.reason, + }); + } + break; + } + case 'Apply': { + const applyReceiver = substitutions.get(effect.receiver.identifier.id); + if (applyReceiver == null || applyReceiver.length !== 1) { + return null; + } + const applyFunction = substitutions.get(effect.function.identifier.id); + if (applyFunction == null || applyFunction.length !== 1) { + return null; + } + const applyInto = substitutions.get(effect.into.identifier.id); + if (applyInto == null || applyInto.length !== 1) { + return null; + } + const applyArgs = []; + for (const arg of effect.args) { + if (arg.kind === 'Hole') { + applyArgs.push(arg); + } + else if (arg.kind === 'Identifier') { + const applyArg = substitutions.get(arg.identifier.id); + if (applyArg == null || applyArg.length !== 1) { + return null; + } + applyArgs.push(applyArg[0]); + } + else { + const applyArg = substitutions.get(arg.place.identifier.id); + if (applyArg == null || applyArg.length !== 1) { + return null; + } + applyArgs.push({ kind: 'Spread', place: applyArg[0] }); + } + } + effects.push({ + kind: 'Apply', + mutatesFunction: effect.mutatesFunction, + receiver: applyReceiver[0], + args: applyArgs, + function: applyFunction[0], + into: applyInto[0], + signature: effect.signature, + loc, + }); + break; + } + case 'CreateFunction': { + CompilerError.throwTodo({ + reason: `Support CreateFrom effects in signatures`, + loc: receiver.loc, + }); + } + default: { + assertExhaustive$1(effect, `Unexpected effect kind '${effect.kind}'`); + } + } + } + return effects; +} +function buildSignatureFromFunctionExpression(env, fn) { + var _a; + let rest = null; + const params = []; + for (const param of fn.loweredFunc.func.params) { + if (param.kind === 'Identifier') { + params.push(param.identifier.id); + } + else { + rest = param.place.identifier.id; + } + } + return { + receiver: makeIdentifierId(0), + params, + rest: rest !== null && rest !== void 0 ? rest : createTemporaryPlace(env, fn.loc).identifier.id, + returns: fn.loweredFunc.func.returns.identifier.id, + effects: (_a = fn.loweredFunc.func.aliasingEffects) !== null && _a !== void 0 ? _a : [], + temporaries: [], + }; +} +function getWriteErrorReason(abstractValue) { + if (abstractValue.reason.has(ValueReason.Global)) { + return 'Modifying a variable defined outside a component or hook is not allowed. Consider using an effect'; + } + else if (abstractValue.reason.has(ValueReason.JsxCaptured)) { + return 'Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX'; + } + else if (abstractValue.reason.has(ValueReason.Context)) { + return `Modifying a value returned from 'useContext()' is not allowed.`; + } + else if (abstractValue.reason.has(ValueReason.KnownReturnSignature)) { + return 'Modifying a value returned from a function whose return value should not be mutated'; + } + else if (abstractValue.reason.has(ValueReason.ReactiveFunctionArgument)) { + return 'Modifying component props or hook arguments is not allowed. Consider using a local variable instead'; + } + else if (abstractValue.reason.has(ValueReason.State)) { + return "Modifying a value returned from 'useState()', which should not be modified directly. Use the setter function to update instead"; + } + else if (abstractValue.reason.has(ValueReason.ReducerState)) { + return "Modifying a value returned from 'useReducer()', which should not be modified directly. Use the dispatch function to update instead"; + } + else if (abstractValue.reason.has(ValueReason.Effect)) { + return 'Modifying a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the modification before calling useEffect()'; + } + else if (abstractValue.reason.has(ValueReason.HookCaptured)) { + return 'Modifying a value previously passed as an argument to a hook is not allowed. Consider moving the modification before calling the hook'; + } + else if (abstractValue.reason.has(ValueReason.HookReturn)) { + return 'Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed'; + } + else { + return 'This modifies a variable that React considers immutable'; + } +} +function getArgumentEffect(signatureEffect, arg) { + if (signatureEffect != null) { + if (arg.kind === 'Identifier') { + return signatureEffect; + } + else if (signatureEffect === Effect.Mutate || + signatureEffect === Effect.ConditionallyMutate) { + return signatureEffect; + } + else { + if (signatureEffect === Effect.Freeze) { + CompilerError.throwTodo({ + reason: 'Support spread syntax for hook arguments', + loc: arg.place.loc, + }); + } + return Effect.ConditionallyMutateIterator; + } + } + else { + return Effect.ConditionallyMutate; + } +} +function getFunctionCallSignature(env, type) { + if (type.kind !== 'Function') { + return null; + } + return env.getFunctionSignature(type); +} +function isKnownMutableEffect(effect) { + switch (effect) { + case Effect.Store: + case Effect.ConditionallyMutate: + case Effect.ConditionallyMutateIterator: + case Effect.Mutate: { + return true; + } + case Effect.Unknown: { + CompilerError.invariant(false, { + reason: 'Unexpected unknown effect', + loc: GeneratedSource, + }); + } + case Effect.Read: + case Effect.Capture: + case Effect.Freeze: { + return false; + } + default: { + assertExhaustive$1(effect, `Unexpected effect \`${effect}\``); + } + } +} +function mergeValueKinds(a, b) { + if (a === b) { + return a; + } + else if (a === ValueKind.MaybeFrozen || b === ValueKind.MaybeFrozen) { + return ValueKind.MaybeFrozen; + } + else if (a === ValueKind.Mutable || b === ValueKind.Mutable) { + if (a === ValueKind.Frozen || b === ValueKind.Frozen) { + return ValueKind.MaybeFrozen; + } + else if (a === ValueKind.Context || b === ValueKind.Context) { + return ValueKind.Context; + } + else { + return ValueKind.Mutable; + } + } + else if (a === ValueKind.Context || b === ValueKind.Context) { + if (a === ValueKind.Frozen || b === ValueKind.Frozen) { + return ValueKind.MaybeFrozen; + } + else { + return ValueKind.Context; + } + } + else if (a === ValueKind.Frozen || b === ValueKind.Frozen) { + return ValueKind.Frozen; + } + else if (a === ValueKind.Global || b === ValueKind.Global) { + return ValueKind.Global; + } + else { + CompilerError.invariant(a === ValueKind.Primitive && b == ValueKind.Primitive, { + reason: `Unexpected value kind in mergeValues()`, + description: `Found kinds ${a} and ${b}`, + loc: GeneratedSource, + }); + return ValueKind.Primitive; + } +} + +function pruneNonEscapingScopes(fn) { + const state = new State(fn.env); + for (const param of fn.params) { + if (param.kind === 'Identifier') { + state.declare(param.identifier.declarationId); + } + else { + state.declare(param.place.identifier.declarationId); + } + } + visitReactiveFunction(fn, new CollectDependenciesVisitor(fn.env, state), []); + const memoized = computeMemoizedIdentifiers(state); + visitReactiveFunction(fn, new PruneScopesTransform(), memoized); +} +var MemoizationLevel; +(function (MemoizationLevel) { + MemoizationLevel["Memoized"] = "Memoized"; + MemoizationLevel["Conditional"] = "Conditional"; + MemoizationLevel["Unmemoized"] = "Unmemoized"; + MemoizationLevel["Never"] = "Never"; +})(MemoizationLevel || (MemoizationLevel = {})); +function joinAliases(kind1, kind2) { + if (kind1 === MemoizationLevel.Memoized || + kind2 === MemoizationLevel.Memoized) { + return MemoizationLevel.Memoized; + } + else if (kind1 === MemoizationLevel.Conditional || + kind2 === MemoizationLevel.Conditional) { + return MemoizationLevel.Conditional; + } + else if (kind1 === MemoizationLevel.Unmemoized || + kind2 === MemoizationLevel.Unmemoized) { + return MemoizationLevel.Unmemoized; + } + else { + return MemoizationLevel.Never; + } +} +class State { + constructor(env) { + this.definitions = new Map(); + this.identifiers = new Map(); + this.scopes = new Map(); + this.escapingValues = new Set(); + this.env = env; + } + declare(id) { + this.identifiers.set(id, { + level: MemoizationLevel.Never, + memoized: false, + dependencies: new Set(), + scopes: new Set(), + seen: false, + }); + } + visitOperand(id, place, identifier) { + const scope = getPlaceScope(id, place); + if (scope !== null) { + let node = this.scopes.get(scope.id); + if (node === undefined) { + node = { + dependencies: [...scope.dependencies].map(dep => dep.identifier.declarationId), + seen: false, + }; + this.scopes.set(scope.id, node); + } + const identifierNode = this.identifiers.get(identifier); + CompilerError.invariant(identifierNode !== undefined, { + reason: 'Expected identifier to be initialized', + description: `[${id}] operand=${printPlace(place)} for identifier declaration ${identifier}`, + loc: place.loc, + }); + identifierNode.scopes.add(scope.id); + } + } +} +function computeMemoizedIdentifiers(state) { + const memoized = new Set(); + function visit(id, forceMemoize = false) { + const node = state.identifiers.get(id); + CompilerError.invariant(node !== undefined, { + reason: `Expected a node for all identifiers, none found for \`${id}\``, + loc: GeneratedSource, + }); + if (node.seen) { + return node.memoized; + } + node.seen = true; + node.memoized = false; + let hasMemoizedDependency = false; + for (const dep of node.dependencies) { + const isDepMemoized = visit(dep); + hasMemoizedDependency || (hasMemoizedDependency = isDepMemoized); + } + if (node.level === MemoizationLevel.Memoized || + (node.level === MemoizationLevel.Conditional && + (hasMemoizedDependency || forceMemoize)) || + (node.level === MemoizationLevel.Unmemoized && forceMemoize)) { + node.memoized = true; + memoized.add(id); + for (const scope of node.scopes) { + forceMemoizeScopeDependencies(scope); + } + } + return node.memoized; + } + function forceMemoizeScopeDependencies(id) { + const node = state.scopes.get(id); + CompilerError.invariant(node !== undefined, { + reason: 'Expected a node for all scopes', + loc: GeneratedSource, + }); + if (node.seen) { + return; + } + node.seen = true; + for (const dep of node.dependencies) { + visit(dep, true); + } + return; + } + for (const value of state.escapingValues) { + visit(value); + } + return memoized; +} +function computePatternLValues(pattern) { + const lvalues = []; + switch (pattern.kind) { + case 'ArrayPattern': { + for (const item of pattern.items) { + if (item.kind === 'Identifier') { + lvalues.push({ place: item, level: MemoizationLevel.Conditional }); + } + else if (item.kind === 'Spread') { + lvalues.push({ place: item.place, level: MemoizationLevel.Memoized }); + } + } + break; + } + case 'ObjectPattern': { + for (const property of pattern.properties) { + if (property.kind === 'ObjectProperty') { + lvalues.push({ + place: property.place, + level: MemoizationLevel.Conditional, + }); + } + else { + lvalues.push({ + place: property.place, + level: MemoizationLevel.Memoized, + }); + } + } + break; + } + default: { + assertExhaustive$1(pattern, `Unexpected pattern kind \`${pattern.kind}\``); + } + } + return lvalues; +} +class CollectDependenciesVisitor extends ReactiveFunctionVisitor { + constructor(env, state) { + super(); + this.env = env; + this.state = state; + this.options = { + memoizeJsxElements: !this.env.config.enableForest, + forceMemoizePrimitives: this.env.config.enableForest || + this.env.config.enablePreserveExistingMemoizationGuarantees, + }; + } + computeMemoizationInputs(value, lvalue) { + const env = this.env; + const options = this.options; + switch (value.kind) { + case 'ConditionalExpression': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [ + ...this.computeMemoizationInputs(value.consequent, null).rvalues, + ...this.computeMemoizationInputs(value.alternate, null).rvalues, + ], + }; + } + case 'LogicalExpression': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [ + ...this.computeMemoizationInputs(value.left, null).rvalues, + ...this.computeMemoizationInputs(value.right, null).rvalues, + ], + }; + } + case 'SequenceExpression': { + for (const instr of value.instructions) { + this.visitValueForMemoization(instr.id, instr.value, instr.lvalue); + } + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: this.computeMemoizationInputs(value.value, null).rvalues, + }; + } + case 'JsxExpression': { + const operands = []; + if (value.tag.kind === 'Identifier') { + operands.push(value.tag); + } + for (const prop of value.props) { + if (prop.kind === 'JsxAttribute') { + operands.push(prop.place); + } + else { + operands.push(prop.argument); + } + } + if (value.children !== null) { + for (const child of value.children) { + operands.push(child); + } + } + const level = options.memoizeJsxElements + ? MemoizationLevel.Memoized + : MemoizationLevel.Unmemoized; + return { + lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], + rvalues: operands, + }; + } + case 'JsxFragment': { + const level = options.memoizeJsxElements + ? MemoizationLevel.Memoized + : MemoizationLevel.Unmemoized; + return { + lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], + rvalues: value.children, + }; + } + case 'NextPropertyOf': + case 'StartMemoize': + case 'FinishMemoize': + case 'Debugger': + case 'ComputedDelete': + case 'PropertyDelete': + case 'LoadGlobal': + case 'MetaProperty': + case 'TemplateLiteral': + case 'Primitive': + case 'JSXText': + case 'BinaryExpression': + case 'UnaryExpression': { + if (options.forceMemoizePrimitives) { + const level = MemoizationLevel.Conditional; + return { + lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], + rvalues: [...eachReactiveValueOperand(value)], + }; + } + const level = MemoizationLevel.Never; + return { + lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], + rvalues: [], + }; + } + case 'Await': + case 'TypeCastExpression': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.value], + }; + } + case 'IteratorNext': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.iterator, value.collection], + }; + } + case 'GetIterator': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.collection], + }; + } + case 'LoadLocal': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.place], + }; + } + case 'LoadContext': { + return { + lvalues: lvalue !== null + ? [{ place: lvalue, level: MemoizationLevel.Conditional }] + : [], + rvalues: [value.place], + }; + } + case 'DeclareContext': { + const lvalues = [ + { place: value.lvalue.place, level: MemoizationLevel.Memoized }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Unmemoized }); + } + return { + lvalues, + rvalues: [], + }; + } + case 'DeclareLocal': { + const lvalues = [ + { place: value.lvalue.place, level: MemoizationLevel.Unmemoized }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Unmemoized }); + } + return { + lvalues, + rvalues: [], + }; + } + case 'PrefixUpdate': + case 'PostfixUpdate': { + const lvalues = [ + { place: value.lvalue, level: MemoizationLevel.Conditional }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + return { + lvalues, + rvalues: [value.value], + }; + } + case 'StoreLocal': { + const lvalues = [ + { place: value.lvalue.place, level: MemoizationLevel.Conditional }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + return { + lvalues, + rvalues: [value.value], + }; + } + case 'StoreContext': { + const lvalues = [ + { place: value.lvalue.place, level: MemoizationLevel.Memoized }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + return { + lvalues, + rvalues: [value.value], + }; + } + case 'StoreGlobal': { + const lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Unmemoized }); + } + return { + lvalues, + rvalues: [value.value], + }; + } + case 'Destructure': { + const lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + lvalues.push(...computePatternLValues(value.lvalue.pattern)); + return { + lvalues: lvalues, + rvalues: [value.value], + }; + } + case 'ComputedLoad': + case 'PropertyLoad': { + const level = MemoizationLevel.Conditional; + return { + lvalues: lvalue !== null ? [{ place: lvalue, level }] : [], + rvalues: [value.object], + }; + } + case 'ComputedStore': { + const lvalues = [ + { place: value.object, level: MemoizationLevel.Conditional }, + ]; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + return { + lvalues, + rvalues: [value.value], + }; + } + case 'OptionalExpression': { + const lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional }); + } + return { + lvalues: lvalues, + rvalues: [ + ...this.computeMemoizationInputs(value.value, null).rvalues, + ], + }; + } + case 'TaggedTemplateExpression': { + const signature = getFunctionCallSignature(env, value.tag.identifier.type); + let lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Memoized }); + } + if ((signature === null || signature === void 0 ? void 0 : signature.noAlias) === true) { + return { + lvalues, + rvalues: [], + }; + } + const operands = [...eachReactiveValueOperand(value)]; + lvalues.push(...operands + .filter(operand => isMutableEffect(operand.effect, operand.loc)) + .map(place => ({ place, level: MemoizationLevel.Memoized }))); + return { + lvalues, + rvalues: operands, + }; + } + case 'CallExpression': { + const signature = getFunctionCallSignature(env, value.callee.identifier.type); + let lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Memoized }); + } + if ((signature === null || signature === void 0 ? void 0 : signature.noAlias) === true) { + return { + lvalues, + rvalues: [], + }; + } + const operands = [...eachReactiveValueOperand(value)]; + lvalues.push(...operands + .filter(operand => isMutableEffect(operand.effect, operand.loc)) + .map(place => ({ place, level: MemoizationLevel.Memoized }))); + return { + lvalues, + rvalues: operands, + }; + } + case 'MethodCall': { + const signature = getFunctionCallSignature(env, value.property.identifier.type); + let lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Memoized }); + } + if ((signature === null || signature === void 0 ? void 0 : signature.noAlias) === true) { + return { + lvalues, + rvalues: [], + }; + } + const operands = [...eachReactiveValueOperand(value)]; + lvalues.push(...operands + .filter(operand => isMutableEffect(operand.effect, operand.loc)) + .map(place => ({ place, level: MemoizationLevel.Memoized }))); + return { + lvalues, + rvalues: operands, + }; + } + case 'RegExpLiteral': + case 'ObjectMethod': + case 'FunctionExpression': + case 'ArrayExpression': + case 'NewExpression': + case 'ObjectExpression': + case 'PropertyStore': { + const operands = [...eachReactiveValueOperand(value)]; + const lvalues = operands + .filter(operand => isMutableEffect(operand.effect, operand.loc)) + .map(place => ({ place, level: MemoizationLevel.Memoized })); + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Memoized }); + } + return { + lvalues, + rvalues: operands, + }; + } + case 'UnsupportedNode': { + const lvalues = []; + if (lvalue !== null) { + lvalues.push({ place: lvalue, level: MemoizationLevel.Never }); + } + return { + lvalues, + rvalues: [], + }; + } + default: { + assertExhaustive$1(value, `Unexpected value kind \`${value.kind}\``); + } + } + } + visitValueForMemoization(id, value, lvalue) { + var _a, _b, _c; + const state = this.state; + const aliasing = this.computeMemoizationInputs(value, lvalue); + for (const operand of aliasing.rvalues) { + const operandId = (_a = state.definitions.get(operand.identifier.declarationId)) !== null && _a !== void 0 ? _a : operand.identifier.declarationId; + state.visitOperand(id, operand, operandId); + } + for (const { place: lvalue, level } of aliasing.lvalues) { + const lvalueId = (_b = state.definitions.get(lvalue.identifier.declarationId)) !== null && _b !== void 0 ? _b : lvalue.identifier.declarationId; + let node = state.identifiers.get(lvalueId); + if (node === undefined) { + node = { + level: MemoizationLevel.Never, + memoized: false, + dependencies: new Set(), + scopes: new Set(), + seen: false, + }; + state.identifiers.set(lvalueId, node); + } + node.level = joinAliases(node.level, level); + for (const operand of aliasing.rvalues) { + const operandId = (_c = state.definitions.get(operand.identifier.declarationId)) !== null && _c !== void 0 ? _c : operand.identifier.declarationId; + if (operandId === lvalueId) { + continue; + } + node.dependencies.add(operandId); + } + state.visitOperand(id, lvalue, lvalueId); + } + if (value.kind === 'LoadLocal' && lvalue !== null) { + state.definitions.set(lvalue.identifier.declarationId, value.place.identifier.declarationId); + } + else if (value.kind === 'CallExpression' || value.kind === 'MethodCall') { + let callee = value.kind === 'CallExpression' ? value.callee : value.property; + if (getHookKind(state.env, callee.identifier) != null) { + const signature = getFunctionCallSignature(this.env, callee.identifier.type); + if (signature && signature.noAlias === true) { + return; + } + for (const operand of value.args) { + const place = operand.kind === 'Spread' ? operand.place : operand; + state.escapingValues.add(place.identifier.declarationId); + } + } + } + } + visitInstruction(instruction, _scopes) { + this.visitValueForMemoization(instruction.id, instruction.value, instruction.lvalue); + } + visitTerminal(stmt, scopes) { + this.traverseTerminal(stmt, scopes); + if (stmt.terminal.kind === 'return') { + this.state.escapingValues.add(stmt.terminal.value.identifier.declarationId); + const identifierNode = this.state.identifiers.get(stmt.terminal.value.identifier.declarationId); + CompilerError.invariant(identifierNode !== undefined, { + reason: 'Expected identifier to be initialized', + loc: stmt.terminal.loc, + }); + for (const scope of scopes) { + identifierNode.scopes.add(scope.id); + } + } + } + visitScope(scope, scopes) { + for (const reassignment of scope.scope.reassignments) { + const identifierNode = this.state.identifiers.get(reassignment.declarationId); + CompilerError.invariant(identifierNode !== undefined, { + reason: 'Expected identifier to be initialized', + loc: reassignment.loc, + }); + for (const scope of scopes) { + identifierNode.scopes.add(scope.id); + } + identifierNode.scopes.add(scope.scope.id); + } + this.traverseScope(scope, [...scopes, scope.scope]); + } +} +class PruneScopesTransform extends ReactiveFunctionTransform { + constructor() { + super(...arguments); + this.prunedScopes = new Set(); + this.reassignments = new Map(); + } + transformScope(scopeBlock, state) { + this.visitScope(scopeBlock, state); + if ((scopeBlock.scope.declarations.size === 0 && + scopeBlock.scope.reassignments.size === 0) || + scopeBlock.scope.earlyReturnValue !== null) { + return { kind: 'keep' }; + } + const hasMemoizedOutput = Array.from(scopeBlock.scope.declarations.values()).some(decl => state.has(decl.identifier.declarationId)) || + Array.from(scopeBlock.scope.reassignments).some(identifier => state.has(identifier.declarationId)); + if (hasMemoizedOutput) { + return { kind: 'keep' }; + } + else { + this.prunedScopes.add(scopeBlock.scope.id); + return { + kind: 'replace-many', + value: scopeBlock.instructions, + }; + } + } + transformInstruction(instruction, state) { + var _a; + this.traverseInstruction(instruction, state); + const value = instruction.value; + if (value.kind === 'StoreLocal' && value.lvalue.kind === 'Reassign') { + const ids = getOrInsertDefault(this.reassignments, value.lvalue.place.identifier.declarationId, new Set()); + ids.add(value.value.identifier); + } + else if (value.kind === 'LoadLocal' && + value.place.identifier.scope != null && + instruction.lvalue != null && + instruction.lvalue.identifier.scope == null) { + const ids = getOrInsertDefault(this.reassignments, instruction.lvalue.identifier.declarationId, new Set()); + ids.add(value.place.identifier); + } + else if (value.kind === 'FinishMemoize') { + let decls; + if (value.decl.identifier.scope == null) { + decls = (_a = this.reassignments.get(value.decl.identifier.declarationId)) !== null && _a !== void 0 ? _a : [ + value.decl.identifier, + ]; + } + else { + decls = [value.decl.identifier]; + } + if ([...decls].every(decl => decl.scope == null || this.prunedScopes.has(decl.scope.id))) { + value.pruned = true; + } + } + return { kind: 'keep' }; + } +} + +let Visitor$5 = class Visitor extends ReactiveFunctionVisitor { + visitLValue(id, lvalue, state) { + this.visitPlace(id, lvalue, state); + } + visitPlace(_id, place, state) { + if (place.reactive) { + state.add(place.identifier.id); + } + } + visitPrunedScope(scopeBlock, state) { + this.traversePrunedScope(scopeBlock, state); + for (const [id, decl] of scopeBlock.scope.declarations) { + if (!isPrimitiveType(decl.identifier) && + !isStableRefType(decl.identifier, state)) { + state.add(id); + } + } + } +}; +function isStableRefType(identifier, reactiveIdentifiers) { + return isUseRefType(identifier) && !reactiveIdentifiers.has(identifier.id); +} +function collectReactiveIdentifiers(fn) { + const visitor = new Visitor$5(); + const state = new Set(); + visitReactiveFunction(fn, visitor, state); + return state; +} + +function pruneNonReactiveDependencies(fn) { + const reactiveIdentifiers = collectReactiveIdentifiers(fn); + visitReactiveFunction(fn, new Visitor$4(), reactiveIdentifiers); +} +let Visitor$4 = class Visitor extends ReactiveFunctionVisitor { + visitInstruction(instruction, state) { + this.traverseInstruction(instruction, state); + const { lvalue, value } = instruction; + switch (value.kind) { + case 'LoadLocal': { + if (lvalue !== null && state.has(value.place.identifier.id)) { + state.add(lvalue.identifier.id); + } + break; + } + case 'StoreLocal': { + if (state.has(value.value.identifier.id)) { + state.add(value.lvalue.place.identifier.id); + if (lvalue !== null) { + state.add(lvalue.identifier.id); + } + } + break; + } + case 'Destructure': { + if (state.has(value.value.identifier.id)) { + for (const lvalue of eachPatternOperand(value.lvalue.pattern)) { + if (isStableType(lvalue.identifier)) { + continue; + } + state.add(lvalue.identifier.id); + } + if (lvalue !== null) { + state.add(lvalue.identifier.id); + } + } + break; + } + case 'PropertyLoad': { + if (lvalue !== null && + state.has(value.object.identifier.id) && + !isStableType(lvalue.identifier)) { + state.add(lvalue.identifier.id); + } + break; + } + case 'ComputedLoad': { + if (lvalue !== null && + (state.has(value.object.identifier.id) || + state.has(value.property.identifier.id))) { + state.add(lvalue.identifier.id); + } + break; + } + } + } + visitScope(scopeBlock, state) { + this.traverseScope(scopeBlock, state); + for (const dep of scopeBlock.scope.dependencies) { + const isReactive = state.has(dep.identifier.id); + if (!isReactive) { + scopeBlock.scope.dependencies.delete(dep); + } + } + if (scopeBlock.scope.dependencies.size !== 0) { + for (const [, declaration] of scopeBlock.scope.declarations) { + state.add(declaration.identifier.id); + } + for (const reassignment of scopeBlock.scope.reassignments) { + state.add(reassignment.id); + } + } + } +}; + +function pruneUnusedLValues(fn) { + const lvalues = new Map(); + visitReactiveFunction(fn, new Visitor$3(), lvalues); + for (const [, instr] of lvalues) { + instr.lvalue = null; + } +} +let Visitor$3 = class Visitor extends ReactiveFunctionVisitor { + visitPlace(id, place, state) { + state.delete(place.identifier.declarationId); + } + visitInstruction(instruction, state) { + this.traverseInstruction(instruction, state); + if (instruction.lvalue !== null && + instruction.lvalue.identifier.name === null) { + state.set(instruction.lvalue.identifier.declarationId, instruction); + } + } +}; + +function pruneUnusedLabels(fn) { + const labels = new Set(); + visitReactiveFunction(fn, new Transform$2(), labels); +} +let Transform$2 = class Transform extends ReactiveFunctionTransform { + transformTerminal(stmt, state) { + this.traverseTerminal(stmt, state); + const { terminal } = stmt; + if ((terminal.kind === 'break' || terminal.kind === 'continue') && + terminal.targetKind === 'labeled') { + state.add(terminal.target); + } + const isReachableLabel = stmt.label !== null && state.has(stmt.label.id); + if (stmt.terminal.kind === 'label' && !isReachableLabel) { + const block = [...stmt.terminal.block]; + const last = block.at(-1); + if (last !== undefined && + last.kind === 'terminal' && + last.terminal.kind === 'break' && + last.terminal.target === null) { + block.pop(); + } + return { kind: 'replace-many', value: block }; + } + else { + if (!isReachableLabel && stmt.label != null) { + stmt.label.implicit = true; + } + return { kind: 'keep' }; + } + } +}; + +function pruneUnusedScopes(fn) { + visitReactiveFunction(fn, new Transform$1(), { + hasReturnStatement: false, + }); +} +let Transform$1 = class Transform extends ReactiveFunctionTransform { + visitTerminal(stmt, state) { + this.traverseTerminal(stmt, state); + if (stmt.terminal.kind === 'return') { + state.hasReturnStatement = true; + } + } + transformScope(scopeBlock, _state) { + const scopeState = { hasReturnStatement: false }; + this.visitScope(scopeBlock, scopeState); + if (!scopeState.hasReturnStatement && + scopeBlock.scope.reassignments.size === 0 && + (scopeBlock.scope.declarations.size === 0 || + !hasOwnDeclaration(scopeBlock))) { + return { + kind: 'replace', + value: { + kind: 'pruned-scope', + scope: scopeBlock.scope, + instructions: scopeBlock.instructions, + }, + }; + } + else { + return { kind: 'keep' }; + } + } +}; +function hasOwnDeclaration(block) { + for (const declaration of block.scope.declarations.values()) { + if (declaration.scope.id === block.scope.id) { + return true; + } + } + return false; +} + +function collectReferencedGlobals(fn) { + const identifiers = new Set(); + visitReactiveFunction(fn, new Visitor$2(), identifiers); + return identifiers; +} +let Visitor$2 = class Visitor extends ReactiveFunctionVisitor { + visitValue(id, value, state) { + this.traverseValue(id, value, state); + if (value.kind === 'FunctionExpression' || value.kind === 'ObjectMethod') { + this.visitHirFunction(value.loweredFunc.func, state); + } + else if (value.kind === 'LoadGlobal') { + state.add(value.binding.name); + } + } + visitReactiveFunctionValue(_id, _dependencies, fn, state) { + visitReactiveFunction(fn, this, state); + } +}; + +var _Scopes_instances, _Scopes_seen, _Scopes_stack, _Scopes_globals, _Scopes_programContext, _Scopes_lookup; +function renameVariables(fn) { + const globals = collectReferencedGlobals(fn); + const scopes = new Scopes(globals, fn.env.programContext); + renameVariablesImpl(fn, new Visitor$1(), scopes); + return new Set([...scopes.names, ...globals]); +} +function renameVariablesImpl(fn, visitor, scopes) { + scopes.enter(() => { + for (const param of fn.params) { + if (param.kind === 'Identifier') { + scopes.visit(param.identifier); + } + else { + scopes.visit(param.place.identifier); + } + } + visitReactiveFunction(fn, visitor, scopes); + }); +} +let Visitor$1 = class Visitor extends ReactiveFunctionVisitor { + visitParam(place, state) { + state.visit(place.identifier); + } + visitLValue(_id, lvalue, state) { + state.visit(lvalue.identifier); + } + visitPlace(id, place, state) { + state.visit(place.identifier); + } + visitBlock(block, state) { + state.enter(() => { + this.traverseBlock(block, state); + }); + } + visitPrunedScope(scopeBlock, state) { + this.traverseBlock(scopeBlock.instructions, state); + } + visitScope(scope, state) { + for (const [_, declaration] of scope.scope.declarations) { + state.visit(declaration.identifier); + } + this.traverseScope(scope, state); + } + visitValue(id, value, state) { + this.traverseValue(id, value, state); + if (value.kind === 'FunctionExpression' || value.kind === 'ObjectMethod') { + this.visitHirFunction(value.loweredFunc.func, state); + } + } + visitReactiveFunctionValue(_id, _dependencies, _fn, _state) { + renameVariablesImpl(_fn, this, _state); + } +}; +class Scopes { + constructor(globals, programContext) { + _Scopes_instances.add(this); + _Scopes_seen.set(this, new Map()); + _Scopes_stack.set(this, [new Map()]); + _Scopes_globals.set(this, void 0); + _Scopes_programContext.set(this, void 0); + this.names = new Set(); + __classPrivateFieldSet(this, _Scopes_globals, globals, "f"); + __classPrivateFieldSet(this, _Scopes_programContext, programContext, "f"); + } + visit(identifier) { + const originalName = identifier.name; + if (originalName === null) { + return; + } + const mappedName = __classPrivateFieldGet(this, _Scopes_seen, "f").get(identifier.declarationId); + if (mappedName !== undefined) { + identifier.name = mappedName; + return; + } + let name = originalName.value; + let id = 0; + if (isPromotedTemporary(originalName.value)) { + name = `t${id++}`; + } + else if (isPromotedJsxTemporary(originalName.value)) { + name = `T${id++}`; + } + while (__classPrivateFieldGet(this, _Scopes_instances, "m", _Scopes_lookup).call(this, name) !== null || __classPrivateFieldGet(this, _Scopes_globals, "f").has(name)) { + if (isPromotedTemporary(originalName.value)) { + name = `t${id++}`; + } + else if (isPromotedJsxTemporary(originalName.value)) { + name = `T${id++}`; + } + else { + name = `${originalName.value}$${id++}`; + } + } + __classPrivateFieldGet(this, _Scopes_programContext, "f").addNewReference(name); + const identifierName = makeIdentifierName(name); + identifier.name = identifierName; + __classPrivateFieldGet(this, _Scopes_seen, "f").set(identifier.declarationId, identifierName); + __classPrivateFieldGet(this, _Scopes_stack, "f").at(-1).set(identifierName.value, identifier.declarationId); + this.names.add(identifierName.value); + } + enter(fn) { + const next = new Map(); + __classPrivateFieldGet(this, _Scopes_stack, "f").push(next); + fn(); + const last = __classPrivateFieldGet(this, _Scopes_stack, "f").pop(); + CompilerError.invariant(last === next, { + reason: 'Mismatch push/pop calls', + loc: GeneratedSource, + }); + } +} +_Scopes_seen = new WeakMap(), _Scopes_stack = new WeakMap(), _Scopes_globals = new WeakMap(), _Scopes_programContext = new WeakMap(), _Scopes_instances = new WeakSet(), _Scopes_lookup = function _Scopes_lookup(name) { + for (let i = __classPrivateFieldGet(this, _Scopes_stack, "f").length - 1; i >= 0; i--) { + const scope = __classPrivateFieldGet(this, _Scopes_stack, "f")[i]; + const entry = scope.get(name); + if (entry !== undefined) { + return entry; + } + } + return null; +}; + +function stabilizeBlockIds(fn) { + const referenced = new Set(); + visitReactiveFunction(fn, new CollectReferencedLabels(), referenced); + const mappings = new Map(); + for (const blockId of referenced) { + mappings.set(blockId, makeBlockId(mappings.size)); + } + visitReactiveFunction(fn, new RewriteBlockIds(), mappings); +} +class CollectReferencedLabels extends ReactiveFunctionVisitor { + visitScope(scope, state) { + const { earlyReturnValue } = scope.scope; + if (earlyReturnValue != null) { + state.add(earlyReturnValue.label); + } + this.traverseScope(scope, state); + } + visitTerminal(stmt, state) { + if (stmt.label != null) { + if (!stmt.label.implicit) { + state.add(stmt.label.id); + } + } + this.traverseTerminal(stmt, state); + } +} +class RewriteBlockIds extends ReactiveFunctionVisitor { + visitScope(scope, state) { + const { earlyReturnValue } = scope.scope; + if (earlyReturnValue != null) { + const rewrittenId = getOrInsertDefault(state, earlyReturnValue.label, state.size); + earlyReturnValue.label = makeBlockId(rewrittenId); + } + this.traverseScope(scope, state); + } + visitTerminal(stmt, state) { + if (stmt.label != null) { + const rewrittenId = getOrInsertDefault(state, stmt.label.id, state.size); + stmt.label.id = makeBlockId(rewrittenId); + } + const terminal = stmt.terminal; + if (terminal.kind === 'break' || terminal.kind === 'continue') { + const rewrittenId = getOrInsertDefault(state, terminal.target, state.size); + terminal.target = makeBlockId(rewrittenId); + } + this.traverseTerminal(stmt, state); + } +} + +function inferMutationAliasingRanges(fn, { isFunctionExpression }) { + var _a, _b, _c, _d, _e, _f, _g; + const functionEffects = []; + const state = new AliasingState(); + const pendingPhis = new Map(); + const mutations = []; + const renders = []; + let index = 0; + const shouldRecordErrors = !isFunctionExpression && fn.env.enableValidations; + for (const param of [...fn.params, ...fn.context, fn.returns]) { + const place = param.kind === 'Identifier' ? param : param.place; + state.create(place, { kind: 'Object' }); + } + const seenBlocks = new Set(); + for (const block of fn.body.blocks.values()) { + for (const phi of block.phis) { + state.create(phi.place, { kind: 'Phi' }); + for (const [pred, operand] of phi.operands) { + if (!seenBlocks.has(pred)) { + const blockPhis = getOrInsertWith(pendingPhis, pred, () => []); + blockPhis.push({ from: operand, into: phi.place, index: index++ }); + } + else { + state.assign(index++, operand, phi.place); + } + } + } + seenBlocks.add(block.id); + for (const instr of block.instructions) { + if (instr.effects == null) + continue; + for (const effect of instr.effects) { + if (effect.kind === 'Create') { + state.create(effect.into, { kind: 'Object' }); + } + else if (effect.kind === 'CreateFunction') { + state.create(effect.into, { + kind: 'Function', + function: effect.function.loweredFunc.func, + }); + } + else if (effect.kind === 'CreateFrom') { + state.createFrom(index++, effect.from, effect.into); + } + else if (effect.kind === 'Assign') { + if (!state.nodes.has(effect.into.identifier)) { + state.create(effect.into, { kind: 'Object' }); + } + state.assign(index++, effect.from, effect.into); + } + else if (effect.kind === 'Alias') { + state.assign(index++, effect.from, effect.into); + } + else if (effect.kind === 'MaybeAlias') { + state.maybeAlias(index++, effect.from, effect.into); + } + else if (effect.kind === 'Capture') { + state.capture(index++, effect.from, effect.into); + } + else if (effect.kind === 'MutateTransitive' || + effect.kind === 'MutateTransitiveConditionally') { + mutations.push({ + index: index++, + id: instr.id, + transitive: true, + kind: effect.kind === 'MutateTransitive' + ? MutationKind.Definite + : MutationKind.Conditional, + reason: null, + place: effect.value, + }); + } + else if (effect.kind === 'Mutate' || + effect.kind === 'MutateConditionally') { + mutations.push({ + index: index++, + id: instr.id, + transitive: false, + kind: effect.kind === 'Mutate' + ? MutationKind.Definite + : MutationKind.Conditional, + reason: effect.kind === 'Mutate' ? ((_a = effect.reason) !== null && _a !== void 0 ? _a : null) : null, + place: effect.value, + }); + } + else if (effect.kind === 'MutateFrozen' || + effect.kind === 'MutateGlobal' || + effect.kind === 'Impure') { + if (shouldRecordErrors) { + fn.env.recordError(effect.error); + } + functionEffects.push(effect); + } + else if (effect.kind === 'Render') { + renders.push({ index: index++, place: effect.place }); + functionEffects.push(effect); + } + } + } + const blockPhis = pendingPhis.get(block.id); + if (blockPhis != null) { + for (const { from, into, index } of blockPhis) { + state.assign(index, from, into); + } + } + if (block.terminal.kind === 'return') { + state.assign(index++, block.terminal.value, fn.returns); + } + if ((block.terminal.kind === 'maybe-throw' || + block.terminal.kind === 'return') && + block.terminal.effects != null) { + for (const effect of block.terminal.effects) { + if (effect.kind === 'Alias') { + state.assign(index++, effect.from, effect.into); + } + else { + CompilerError.invariant(effect.kind === 'Freeze', { + reason: `Unexpected '${effect.kind}' effect for MaybeThrow terminal`, + loc: block.terminal.loc, + }); + } + } + } + } + for (const mutation of mutations) { + state.mutate(mutation.index, mutation.place.identifier, makeInstructionId(mutation.id + 1), mutation.transitive, mutation.kind, mutation.place.loc, mutation.reason, shouldRecordErrors ? fn.env : null); + } + for (const render of renders) { + state.render(render.index, render.place.identifier, shouldRecordErrors ? fn.env : null); + } + for (const param of [...fn.context, ...fn.params]) { + const place = param.kind === 'Identifier' ? param : param.place; + const node = state.nodes.get(place.identifier); + if (node == null) { + continue; + } + let mutated = false; + if (node.local != null) { + if (node.local.kind === MutationKind.Conditional) { + mutated = true; + functionEffects.push({ + kind: 'MutateConditionally', + value: Object.assign(Object.assign({}, place), { loc: node.local.loc }), + }); + } + else if (node.local.kind === MutationKind.Definite) { + mutated = true; + functionEffects.push({ + kind: 'Mutate', + value: Object.assign(Object.assign({}, place), { loc: node.local.loc }), + reason: node.mutationReason, + }); + } + } + if (node.transitive != null) { + if (node.transitive.kind === MutationKind.Conditional) { + mutated = true; + functionEffects.push({ + kind: 'MutateTransitiveConditionally', + value: Object.assign(Object.assign({}, place), { loc: node.transitive.loc }), + }); + } + else if (node.transitive.kind === MutationKind.Definite) { + mutated = true; + functionEffects.push({ + kind: 'MutateTransitive', + value: Object.assign(Object.assign({}, place), { loc: node.transitive.loc }), + }); + } + } + if (mutated) { + place.effect = Effect.Capture; + } + } + for (const block of fn.body.blocks.values()) { + for (const phi of block.phis) { + phi.place.effect = Effect.Store; + const isPhiMutatedAfterCreation = phi.place.identifier.mutableRange.end > + ((_c = (_b = block.instructions.at(0)) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : block.terminal.id); + for (const operand of phi.operands.values()) { + operand.effect = isPhiMutatedAfterCreation + ? Effect.Capture + : Effect.Read; + } + if (isPhiMutatedAfterCreation && + phi.place.identifier.mutableRange.start === 0) { + const firstInstructionIdOfBlock = (_e = (_d = block.instructions.at(0)) === null || _d === void 0 ? void 0 : _d.id) !== null && _e !== void 0 ? _e : block.terminal.id; + phi.place.identifier.mutableRange.start = makeInstructionId(firstInstructionIdOfBlock - 1); + } + } + for (const instr of block.instructions) { + for (const lvalue of eachInstructionLValue(instr)) { + lvalue.effect = Effect.ConditionallyMutate; + if (lvalue.identifier.mutableRange.start === 0) { + lvalue.identifier.mutableRange.start = instr.id; + } + if (lvalue.identifier.mutableRange.end === 0) { + lvalue.identifier.mutableRange.end = makeInstructionId(Math.max(instr.id + 1, lvalue.identifier.mutableRange.end)); + } + } + for (const operand of eachInstructionValueOperand(instr.value)) { + operand.effect = Effect.Read; + } + if (instr.effects == null) { + continue; + } + const operandEffects = new Map(); + for (const effect of instr.effects) { + switch (effect.kind) { + case 'Assign': + case 'Alias': + case 'Capture': + case 'CreateFrom': + case 'MaybeAlias': { + const isMutatedOrReassigned = effect.into.identifier.mutableRange.end > instr.id; + if (isMutatedOrReassigned) { + operandEffects.set(effect.from.identifier.id, Effect.Capture); + operandEffects.set(effect.into.identifier.id, Effect.Store); + } + else { + operandEffects.set(effect.from.identifier.id, Effect.Read); + operandEffects.set(effect.into.identifier.id, Effect.Store); + } + break; + } + case 'CreateFunction': + case 'Create': { + break; + } + case 'Mutate': { + operandEffects.set(effect.value.identifier.id, Effect.Store); + break; + } + case 'Apply': { + CompilerError.invariant(false, { + reason: `[AnalyzeFunctions] Expected Apply effects to be replaced with more precise effects`, + loc: effect.function.loc, + }); + } + case 'MutateTransitive': + case 'MutateConditionally': + case 'MutateTransitiveConditionally': { + operandEffects.set(effect.value.identifier.id, Effect.ConditionallyMutate); + break; + } + case 'Freeze': { + operandEffects.set(effect.value.identifier.id, Effect.Freeze); + break; + } + case 'ImmutableCapture': { + break; + } + case 'Impure': + case 'Render': + case 'MutateFrozen': + case 'MutateGlobal': { + break; + } + default: { + assertExhaustive$1(effect, `Unexpected effect kind ${effect.kind}`); + } + } + } + for (const lvalue of eachInstructionLValue(instr)) { + const effect = (_f = operandEffects.get(lvalue.identifier.id)) !== null && _f !== void 0 ? _f : Effect.ConditionallyMutate; + lvalue.effect = effect; + } + for (const operand of eachInstructionValueOperand(instr.value)) { + if (operand.identifier.mutableRange.end > instr.id && + operand.identifier.mutableRange.start === 0) { + operand.identifier.mutableRange.start = instr.id; + } + const effect = (_g = operandEffects.get(operand.identifier.id)) !== null && _g !== void 0 ? _g : Effect.Read; + operand.effect = effect; + } + if (instr.value.kind === 'StoreContext' && + instr.value.value.identifier.mutableRange.end <= instr.id) { + instr.value.value.identifier.mutableRange.end = makeInstructionId(instr.id + 1); + } + } + if (block.terminal.kind === 'return') { + block.terminal.value.effect = isFunctionExpression + ? Effect.Read + : Effect.Freeze; + } + else { + for (const operand of eachTerminalOperand(block.terminal)) { + operand.effect = Effect.Read; + } + } + } + const returns = fn.returns.identifier; + functionEffects.push({ + kind: 'Create', + into: fn.returns, + value: isPrimitiveType(returns) + ? ValueKind.Primitive + : isJsxType(returns.type) + ? ValueKind.Frozen + : ValueKind.Mutable, + reason: ValueReason.KnownReturnSignature, + }); + const tracked = []; + for (const param of [...fn.params, ...fn.context, fn.returns]) { + const place = param.kind === 'Identifier' ? param : param.place; + tracked.push(place); + } + for (const into of tracked) { + const mutationIndex = index++; + state.mutate(mutationIndex, into.identifier, null, true, MutationKind.Conditional, into.loc, null, null); + for (const from of tracked) { + if (from.identifier.id === into.identifier.id || + from.identifier.id === fn.returns.identifier.id) { + continue; + } + const fromNode = state.nodes.get(from.identifier); + CompilerError.invariant(fromNode != null, { + reason: `Expected a node to exist for all parameters and context variables`, + loc: into.loc, + }); + if (fromNode.lastMutated === mutationIndex) { + if (into.identifier.id === fn.returns.identifier.id) { + functionEffects.push({ + kind: 'Alias', + from, + into, + }); + } + else { + functionEffects.push({ + kind: 'Capture', + from, + into, + }); + } + } + } + } + return functionEffects; +} +function appendFunctionErrors(env, fn) { + var _a; + if (env == null) + return; + for (const effect of (_a = fn.aliasingEffects) !== null && _a !== void 0 ? _a : []) { + switch (effect.kind) { + case 'Impure': + case 'MutateFrozen': + case 'MutateGlobal': { + env.recordError(effect.error); + break; + } + } + } +} +var MutationKind; +(function (MutationKind) { + MutationKind[MutationKind["None"] = 0] = "None"; + MutationKind[MutationKind["Conditional"] = 1] = "Conditional"; + MutationKind[MutationKind["Definite"] = 2] = "Definite"; +})(MutationKind || (MutationKind = {})); +class AliasingState { + constructor() { + this.nodes = new Map(); + } + create(place, value) { + this.nodes.set(place.identifier, { + id: place.identifier, + createdFrom: new Map(), + captures: new Map(), + aliases: new Map(), + maybeAliases: new Map(), + edges: [], + transitive: null, + local: null, + lastMutated: 0, + mutationReason: null, + value, + }); + } + createFrom(index, from, into) { + this.create(into, { kind: 'Object' }); + const fromNode = this.nodes.get(from.identifier); + const toNode = this.nodes.get(into.identifier); + if (fromNode == null || toNode == null) { + return; + } + fromNode.edges.push({ index, node: into.identifier, kind: 'alias' }); + if (!toNode.createdFrom.has(from.identifier)) { + toNode.createdFrom.set(from.identifier, index); + } + } + capture(index, from, into) { + const fromNode = this.nodes.get(from.identifier); + const toNode = this.nodes.get(into.identifier); + if (fromNode == null || toNode == null) { + return; + } + fromNode.edges.push({ index, node: into.identifier, kind: 'capture' }); + if (!toNode.captures.has(from.identifier)) { + toNode.captures.set(from.identifier, index); + } + } + assign(index, from, into) { + const fromNode = this.nodes.get(from.identifier); + const toNode = this.nodes.get(into.identifier); + if (fromNode == null || toNode == null) { + return; + } + fromNode.edges.push({ index, node: into.identifier, kind: 'alias' }); + if (!toNode.aliases.has(from.identifier)) { + toNode.aliases.set(from.identifier, index); + } + } + maybeAlias(index, from, into) { + const fromNode = this.nodes.get(from.identifier); + const toNode = this.nodes.get(into.identifier); + if (fromNode == null || toNode == null) { + return; + } + fromNode.edges.push({ index, node: into.identifier, kind: 'maybeAlias' }); + if (!toNode.maybeAliases.has(from.identifier)) { + toNode.maybeAliases.set(from.identifier, index); + } + } + render(index, start, env) { + const seen = new Set(); + const queue = [start]; + while (queue.length !== 0) { + const current = queue.pop(); + if (seen.has(current)) { + continue; + } + seen.add(current); + const node = this.nodes.get(current); + if (node == null || node.transitive != null || node.local != null) { + continue; + } + if (node.value.kind === 'Function') { + appendFunctionErrors(env, node.value.function); + } + for (const [alias, when] of node.createdFrom) { + if (when >= index) { + continue; + } + queue.push(alias); + } + for (const [alias, when] of node.aliases) { + if (when >= index) { + continue; + } + queue.push(alias); + } + for (const [capture, when] of node.captures) { + if (when >= index) { + continue; + } + queue.push(capture); + } + } + } + mutate(index, start, end, transitive, startKind, loc, reason, env) { + var _a; + const seen = new Map(); + const queue = [{ place: start, transitive, direction: 'backwards', kind: startKind }]; + while (queue.length !== 0) { + const { place: current, transitive, direction, kind } = queue.pop(); + const previousKind = seen.get(current); + if (previousKind != null && previousKind >= kind) { + continue; + } + seen.set(current, kind); + const node = this.nodes.get(current); + if (node == null) { + continue; + } + (_a = node.mutationReason) !== null && _a !== void 0 ? _a : (node.mutationReason = reason); + node.lastMutated = Math.max(node.lastMutated, index); + if (end != null) { + node.id.mutableRange.end = makeInstructionId(Math.max(node.id.mutableRange.end, end)); + } + if (node.value.kind === 'Function' && + node.transitive == null && + node.local == null) { + appendFunctionErrors(env, node.value.function); + } + if (transitive) { + if (node.transitive == null || node.transitive.kind < kind) { + node.transitive = { kind, loc }; + } + } + else { + if (node.local == null || node.local.kind < kind) { + node.local = { kind, loc }; + } + } + for (const edge of node.edges) { + if (edge.index >= index) { + break; + } + queue.push({ + place: edge.node, + transitive, + direction: 'forwards', + kind: edge.kind === 'maybeAlias' ? MutationKind.Conditional : kind, + }); + } + for (const [alias, when] of node.createdFrom) { + if (when >= index) { + continue; + } + queue.push({ + place: alias, + transitive: true, + direction: 'backwards', + kind, + }); + } + if (direction === 'backwards' || node.value.kind !== 'Phi') { + for (const [alias, when] of node.aliases) { + if (when >= index) { + continue; + } + queue.push({ + place: alias, + transitive, + direction: 'backwards', + kind, + }); + } + for (const [alias, when] of node.maybeAliases) { + if (when >= index) { + continue; + } + queue.push({ + place: alias, + transitive, + direction: 'backwards', + kind: MutationKind.Conditional, + }); + } + } + if (transitive) { + for (const [capture, when] of node.captures) { + if (when >= index) { + continue; + } + queue.push({ + place: capture, + transitive, + direction: 'backwards', + kind, + }); + } + } + } + } +} + +function analyseFunctions(func) { + for (const [_, block] of func.body.blocks) { + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'ObjectMethod': + case 'FunctionExpression': { + lowerWithMutationAliasing(instr.value.loweredFunc.func); + for (const operand of instr.value.loweredFunc.func.context) { + operand.identifier.mutableRange = { + start: makeInstructionId(0), + end: makeInstructionId(0), + }; + operand.identifier.scope = null; + } + break; + } + } + } + } +} +function lowerWithMutationAliasing(fn) { + var _a, _b; + analyseFunctions(fn); + inferMutationAliasingEffects(fn, { isFunctionExpression: true }); + deadCodeElimination(fn); + const functionEffects = inferMutationAliasingRanges(fn, { + isFunctionExpression: true, + }); + rewriteInstructionKindsBasedOnReassignment(fn); + inferReactiveScopeVariables(fn); + fn.aliasingEffects = functionEffects; + const capturedOrMutated = new Set(); + for (const effect of functionEffects) { + switch (effect.kind) { + case 'Assign': + case 'Alias': + case 'Capture': + case 'CreateFrom': + case 'MaybeAlias': { + capturedOrMutated.add(effect.from.identifier.id); + break; + } + case 'Apply': { + CompilerError.invariant(false, { + reason: `[AnalyzeFunctions] Expected Apply effects to be replaced with more precise effects`, + loc: effect.function.loc, + }); + } + case 'Mutate': + case 'MutateConditionally': + case 'MutateTransitive': + case 'MutateTransitiveConditionally': { + capturedOrMutated.add(effect.value.identifier.id); + break; + } + case 'Impure': + case 'Render': + case 'MutateFrozen': + case 'MutateGlobal': + case 'CreateFunction': + case 'Create': + case 'Freeze': + case 'ImmutableCapture': { + break; + } + default: { + assertExhaustive$1(effect, `Unexpected effect kind ${effect.kind}`); + } + } + } + for (const operand of fn.context) { + if (capturedOrMutated.has(operand.identifier.id) || + operand.effect === Effect.Capture) { + operand.effect = Effect.Capture; + } + else { + operand.effect = Effect.Read; + } + } + (_b = (_a = fn.env.logger) === null || _a === void 0 ? void 0 : _a.debugLogIRs) === null || _b === void 0 ? void 0 : _b.call(_a, { + kind: 'hir', + name: 'AnalyseFunction (inner)', + value: fn, + }); +} + +function collectMaybeMemoDependencies(value, maybeDeps, optional) { + var _a; + switch (value.kind) { + case 'LoadGlobal': { + return { + root: { + kind: 'Global', + identifierName: value.binding.name, + }, + path: [], + loc: value.loc, + }; + } + case 'PropertyLoad': { + const object = maybeDeps.get(value.object.identifier.id); + if (object != null) { + return { + root: object.root, + path: [ + ...object.path, + { property: value.property, optional, loc: value.loc }, + ], + loc: value.loc, + }; + } + break; + } + case 'LoadLocal': + case 'LoadContext': { + const source = maybeDeps.get(value.place.identifier.id); + if (source != null) { + return source; + } + else if (value.place.identifier.name != null && + value.place.identifier.name.kind === 'named') { + return { + root: { + kind: 'NamedLocal', + value: Object.assign({}, value.place), + constant: false, + }, + path: [], + loc: value.place.loc, + }; + } + break; + } + case 'StoreLocal': { + const lvalue = value.lvalue.place.identifier; + const rvalue = value.value.identifier.id; + const aliased = maybeDeps.get(rvalue); + if (aliased != null && ((_a = lvalue.name) === null || _a === void 0 ? void 0 : _a.kind) !== 'named') { + maybeDeps.set(lvalue.id, aliased); + return aliased; + } + break; + } + } + return null; +} +function collectTemporaries(instr, env, sidemap) { + const { value, lvalue } = instr; + switch (value.kind) { + case 'FunctionExpression': { + sidemap.functions.set(instr.lvalue.identifier.id, instr); + break; + } + case 'LoadGlobal': { + const global = env.getGlobalDeclaration(value.binding, value.loc); + const hookKind = global !== null ? getHookKindForType(env, global) : null; + const lvalId = instr.lvalue.identifier.id; + if (hookKind === 'useMemo' || hookKind === 'useCallback') { + sidemap.manualMemos.set(lvalId, { + kind: hookKind, + loadInstr: instr, + }); + } + else if (value.binding.name === 'React') { + sidemap.react.add(lvalId); + } + break; + } + case 'PropertyLoad': { + if (sidemap.react.has(value.object.identifier.id)) { + const property = value.property; + if (property === 'useMemo' || property === 'useCallback') { + sidemap.manualMemos.set(instr.lvalue.identifier.id, { + kind: property, + loadInstr: instr, + }); + } + } + break; + } + case 'ArrayExpression': { + if (value.elements.every(e => e.kind === 'Identifier')) { + sidemap.maybeDepsLists.set(instr.lvalue.identifier.id, { + loc: value.loc, + deps: value.elements, + }); + } + break; + } + } + const maybeDep = collectMaybeMemoDependencies(value, sidemap.maybeDeps, sidemap.optionals.has(lvalue.identifier.id)); + if (maybeDep != null) { + sidemap.maybeDeps.set(lvalue.identifier.id, maybeDep); + } +} +function makeManualMemoizationMarkers(fnExpr, env, depsList, depsLoc, memoDecl, manualMemoId) { + return [ + { + id: makeInstructionId(0), + lvalue: createTemporaryPlace(env, fnExpr.loc), + value: { + kind: 'StartMemoize', + manualMemoId, + deps: depsList, + depsLoc, + loc: fnExpr.loc, + }, + effects: null, + loc: fnExpr.loc, + }, + { + id: makeInstructionId(0), + lvalue: createTemporaryPlace(env, fnExpr.loc), + value: { + kind: 'FinishMemoize', + manualMemoId, + decl: Object.assign({}, memoDecl), + loc: fnExpr.loc, + }, + effects: null, + loc: fnExpr.loc, + }, + ]; +} +function getManualMemoizationReplacement(fn, loc, kind) { + if (kind === 'useMemo') { + return { + kind: 'CallExpression', + callee: fn, + args: [], + loc, + }; + } + else { + return { + kind: 'LoadLocal', + place: { + kind: 'Identifier', + identifier: fn.identifier, + effect: Effect.Unknown, + reactive: false, + loc, + }, + loc, + }; + } +} +function extractManualMemoizationArgs(instr, kind, sidemap, env) { + const [fnPlace, depsListPlace] = instr.value.args; + if (fnPlace == null || fnPlace.kind !== 'Identifier') { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: `Expected a callback function to be passed to ${kind}`, + description: kind === 'useCallback' + ? 'The first argument to useCallback() must be a function to cache' + : 'The first argument to useMemo() must be a function that calculates a result to cache', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: instr.value.loc, + message: kind === 'useCallback' + ? `Expected a callback function` + : `Expected a memoization function`, + })); + return null; + } + if (depsListPlace == null) { + return { + fnPlace, + depsList: null, + depsLoc: null, + }; + } + const maybeDepsList = depsListPlace.kind === 'Identifier' + ? sidemap.maybeDepsLists.get(depsListPlace.identifier.id) + : null; + if (maybeDepsList == null) { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: `Expected the dependency list for ${kind} to be an array literal`, + description: `Expected the dependency list for ${kind} to be an array literal`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc: (depsListPlace === null || depsListPlace === void 0 ? void 0 : depsListPlace.kind) === 'Identifier' ? depsListPlace.loc : instr.loc, + message: `Expected the dependency list for ${kind} to be an array literal`, + })); + return null; + } + const depsList = []; + for (const dep of maybeDepsList.deps) { + const maybeDep = sidemap.maybeDeps.get(dep.identifier.id); + if (maybeDep == null) { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: `Expected the dependency list to be an array of simple expressions (e.g. \`x\`, \`x.y.z\`, \`x?.y?.z\`)`, + description: `Expected the dependency list to be an array of simple expressions (e.g. \`x\`, \`x.y.z\`, \`x?.y?.z\`)`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc: dep.loc, + message: `Expected the dependency list to be an array of simple expressions (e.g. \`x\`, \`x.y.z\`, \`x?.y?.z\`)`, + })); + } + else { + depsList.push(maybeDep); + } + } + return { + fnPlace, + depsList, + depsLoc: maybeDepsList.loc, + }; +} +function dropManualMemoization(func) { + const isValidationEnabled = func.env.config.validatePreserveExistingMemoizationGuarantees || + func.env.config.validateNoSetStateInRender || + func.env.config.enablePreserveExistingMemoizationGuarantees; + const optionals = findOptionalPlaces$1(func); + const sidemap = { + functions: new Map(), + manualMemos: new Map(), + react: new Set(), + maybeDeps: new Map(), + maybeDepsLists: new Map(), + optionals, + }; + let nextManualMemoId = 0; + const queuedInserts = new Map(); + for (const [_, block] of func.body.blocks) { + for (let i = 0; i < block.instructions.length; i++) { + const instr = block.instructions[i]; + if (instr.value.kind === 'CallExpression' || + instr.value.kind === 'MethodCall') { + const id = instr.value.kind === 'CallExpression' + ? instr.value.callee.identifier.id + : instr.value.property.identifier.id; + const manualMemo = sidemap.manualMemos.get(id); + if (manualMemo != null) { + const memoDetails = extractManualMemoizationArgs(instr, manualMemo.kind, sidemap, func.env); + if (memoDetails == null) { + continue; + } + const { fnPlace, depsList, depsLoc } = memoDetails; + instr.value = getManualMemoizationReplacement(fnPlace, instr.value.loc, manualMemo.kind); + if (isValidationEnabled) { + if (!sidemap.functions.has(fnPlace.identifier.id)) { + func.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: `Expected the first argument to be an inline function expression`, + description: `Expected the first argument to be an inline function expression`, + suggestions: [], + }).withDetails({ + kind: 'error', + loc: fnPlace.loc, + message: `Expected the first argument to be an inline function expression`, + })); + continue; + } + const memoDecl = manualMemo.kind === 'useMemo' + ? instr.lvalue + : { + kind: 'Identifier', + identifier: fnPlace.identifier, + effect: Effect.Unknown, + reactive: false, + loc: fnPlace.loc, + }; + const [startMarker, finishMarker] = makeManualMemoizationMarkers(fnPlace, func.env, depsList, depsLoc, memoDecl, nextManualMemoId++); + queuedInserts.set(manualMemo.loadInstr.id, startMarker); + queuedInserts.set(instr.id, finishMarker); + } + } + } + else { + collectTemporaries(instr, func.env, sidemap); + } + } + } + if (queuedInserts.size > 0) { + let hasChanges = false; + for (const [_, block] of func.body.blocks) { + let nextInstructions = null; + for (let i = 0; i < block.instructions.length; i++) { + const instr = block.instructions[i]; + const insertInstr = queuedInserts.get(instr.id); + if (insertInstr != null) { + nextInstructions = nextInstructions !== null && nextInstructions !== void 0 ? nextInstructions : block.instructions.slice(0, i); + nextInstructions.push(instr); + nextInstructions.push(insertInstr); + } + else if (nextInstructions != null) { + nextInstructions.push(instr); + } + } + if (nextInstructions !== null) { + block.instructions = nextInstructions; + hasChanges = true; + } + } + if (hasChanges) { + markInstructionIds(func.body); + } + } +} +function findOptionalPlaces$1(fn) { + const optionals = new Set(); + for (const [, block] of fn.body.blocks) { + if (block.terminal.kind === 'optional' && block.terminal.optional) { + const optionalTerminal = block.terminal; + let testBlock = fn.body.blocks.get(block.terminal.test); + loop: while (true) { + const terminal = testBlock.terminal; + switch (terminal.kind) { + case 'branch': { + if (terminal.fallthrough === optionalTerminal.fallthrough) { + const consequent = fn.body.blocks.get(terminal.consequent); + const last = consequent.instructions.at(-1); + if (last !== undefined && last.value.kind === 'StoreLocal') { + optionals.add(last.value.value.identifier.id); + } + break loop; + } + else { + testBlock = fn.body.blocks.get(terminal.fallthrough); + } + break; + } + case 'optional': + case 'logical': + case 'sequence': + case 'ternary': { + testBlock = fn.body.blocks.get(terminal.fallthrough); + break; + } + case 'maybe-throw': { + testBlock = fn.body.blocks.get(terminal.continuation); + break; + } + default: { + CompilerError.invariant(false, { + reason: `Unexpected terminal in optional`, + message: `Unexpected ${terminal.kind} in optional`, + loc: terminal.loc, + }); + } + } + } + } + } + return optionals; +} + +function createControlDominators(fn, isControlVariable) { + const postDominators = computePostDominatorTree(fn, { + includeThrowsAsExitNode: false, + }); + const postDominatorFrontierCache = new Map(); + function isControlledBlock(id) { + let controlBlocks = postDominatorFrontierCache.get(id); + if (controlBlocks === undefined) { + controlBlocks = postDominatorFrontier(fn, postDominators, id); + postDominatorFrontierCache.set(id, controlBlocks); + } + for (const blockId of controlBlocks) { + const controlBlock = fn.body.blocks.get(blockId); + switch (controlBlock.terminal.kind) { + case 'if': + case 'branch': { + if (isControlVariable(controlBlock.terminal.test)) { + return true; + } + break; + } + case 'switch': { + if (isControlVariable(controlBlock.terminal.test)) { + return true; + } + for (const case_ of controlBlock.terminal.cases) { + if (case_.test !== null && isControlVariable(case_.test)) { + return true; + } + } + break; + } + } + } + return false; + } + return isControlledBlock; +} +function postDominatorFrontier(fn, postDominators, targetId) { + const visited = new Set(); + const frontier = new Set(); + const targetPostDominators = postDominatorsOf(fn, postDominators, targetId); + for (const blockId of [...targetPostDominators, targetId]) { + if (visited.has(blockId)) { + continue; + } + visited.add(blockId); + const block = fn.body.blocks.get(blockId); + for (const pred of block.preds) { + if (!targetPostDominators.has(pred)) { + frontier.add(pred); + } + } + } + return frontier; +} +function postDominatorsOf(fn, postDominators, targetId) { + var _a; + const result = new Set(); + const visited = new Set(); + const queue = [targetId]; + while (queue.length) { + const currentId = queue.shift(); + if (visited.has(currentId)) { + continue; + } + visited.add(currentId); + const current = fn.body.blocks.get(currentId); + for (const pred of current.preds) { + const predPostDominator = (_a = postDominators.get(pred)) !== null && _a !== void 0 ? _a : pred; + if (predPostDominator === targetId || result.has(predPostDominator)) { + result.add(pred); + } + queue.push(pred); + } + } + return result; +} + +class StableSidemap { + constructor(env) { + this.map = new Map(); + this.env = env; + } + handleInstruction(instr) { + const { value, lvalue } = instr; + switch (value.kind) { + case 'CallExpression': + case 'MethodCall': { + if (evaluatesToStableTypeOrContainer(this.env, instr)) { + if (isStableType(lvalue.identifier)) { + this.map.set(lvalue.identifier.id, { + isStable: true, + }); + } + else { + this.map.set(lvalue.identifier.id, { + isStable: false, + }); + } + } + break; + } + case 'Destructure': + case 'PropertyLoad': { + const source = value.kind === 'Destructure' + ? value.value.identifier.id + : value.object.identifier.id; + const entry = this.map.get(source); + if (entry) { + for (const lvalue of eachInstructionLValue(instr)) { + if (isStableTypeContainer(lvalue.identifier)) { + this.map.set(lvalue.identifier.id, { + isStable: false, + }); + } + else if (isStableType(lvalue.identifier)) { + this.map.set(lvalue.identifier.id, { + isStable: true, + }); + } + } + } + break; + } + case 'StoreLocal': { + const entry = this.map.get(value.value.identifier.id); + if (entry) { + this.map.set(lvalue.identifier.id, entry); + this.map.set(value.lvalue.place.identifier.id, entry); + } + break; + } + case 'LoadLocal': { + const entry = this.map.get(value.place.identifier.id); + if (entry) { + this.map.set(lvalue.identifier.id, entry); + } + break; + } + } + } + isStable(id) { + const entry = this.map.get(id); + return entry != null ? entry.isStable : false; + } +} +function inferReactivePlaces(fn) { + const reactiveIdentifiers = new ReactivityMap(findDisjointMutableValues(fn)); + const stableIdentifierSources = new StableSidemap(fn.env); + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + reactiveIdentifiers.markReactive(place); + } + const isReactiveControlledBlock = createControlDominators(fn, place => reactiveIdentifiers.isReactive(place)); + do { + for (const [, block] of fn.body.blocks) { + let hasReactiveControl = isReactiveControlledBlock(block.id); + for (const phi of block.phis) { + if (reactiveIdentifiers.isReactive(phi.place)) { + continue; + } + let isPhiReactive = false; + for (const [, operand] of phi.operands) { + if (reactiveIdentifiers.isReactive(operand)) { + isPhiReactive = true; + break; + } + } + if (isPhiReactive) { + reactiveIdentifiers.markReactive(phi.place); + } + else { + for (const [pred] of phi.operands) { + if (isReactiveControlledBlock(pred)) { + reactiveIdentifiers.markReactive(phi.place); + break; + } + } + } + } + for (const instruction of block.instructions) { + stableIdentifierSources.handleInstruction(instruction); + const { value } = instruction; + let hasReactiveInput = false; + for (const operand of eachInstructionValueOperand(value)) { + const reactive = reactiveIdentifiers.isReactive(operand); + hasReactiveInput || (hasReactiveInput = reactive); + } + if (value.kind === 'CallExpression' && + (getHookKind(fn.env, value.callee.identifier) != null || + isUseOperator(value.callee.identifier))) { + hasReactiveInput = true; + } + else if (value.kind === 'MethodCall' && + (getHookKind(fn.env, value.property.identifier) != null || + isUseOperator(value.property.identifier))) { + hasReactiveInput = true; + } + if (hasReactiveInput) { + for (const lvalue of eachInstructionLValue(instruction)) { + if (stableIdentifierSources.isStable(lvalue.identifier.id)) { + continue; + } + reactiveIdentifiers.markReactive(lvalue); + } + } + if (hasReactiveInput || hasReactiveControl) { + for (const operand of eachInstructionValueOperand(value)) { + switch (operand.effect) { + case Effect.Capture: + case Effect.Store: + case Effect.ConditionallyMutate: + case Effect.ConditionallyMutateIterator: + case Effect.Mutate: { + if (isMutable(instruction, operand)) { + reactiveIdentifiers.markReactive(operand); + } + break; + } + case Effect.Freeze: + case Effect.Read: { + break; + } + case Effect.Unknown: { + CompilerError.invariant(false, { + reason: 'Unexpected unknown effect', + loc: operand.loc, + }); + } + default: { + assertExhaustive$1(operand.effect, `Unexpected effect kind \`${operand.effect}\``); + } + } + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + reactiveIdentifiers.isReactive(operand); + } + } + } while (reactiveIdentifiers.snapshot()); + function propagateReactivityToInnerFunctions(fn, isOutermost) { + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + if (!isOutermost) { + for (const operand of eachInstructionOperand(instr)) { + reactiveIdentifiers.isReactive(operand); + } + } + if (instr.value.kind === 'ObjectMethod' || + instr.value.kind === 'FunctionExpression') { + propagateReactivityToInnerFunctions(instr.value.loweredFunc.func, false); + } + } + if (!isOutermost) { + for (const operand of eachTerminalOperand(block.terminal)) { + reactiveIdentifiers.isReactive(operand); + } + } + } + } + propagateReactivityToInnerFunctions(fn, true); +} +class ReactivityMap { + constructor(aliasedIdentifiers) { + this.hasChanges = false; + this.reactive = new Set(); + this.aliasedIdentifiers = aliasedIdentifiers; + } + isReactive(place) { + var _a; + const identifier = (_a = this.aliasedIdentifiers.find(place.identifier)) !== null && _a !== void 0 ? _a : place.identifier; + const reactive = this.reactive.has(identifier.id); + if (reactive) { + place.reactive = true; + } + return reactive; + } + markReactive(place) { + var _a; + place.reactive = true; + const identifier = (_a = this.aliasedIdentifiers.find(place.identifier)) !== null && _a !== void 0 ? _a : place.identifier; + if (!this.reactive.has(identifier.id)) { + this.hasChanges = true; + this.reactive.add(identifier.id); + } + } + snapshot() { + const hasChanges = this.hasChanges; + this.hasChanges = false; + return hasChanges; + } +} + +function inlineImmediatelyInvokedFunctionExpressions(fn) { + const functions = new Map(); + const inlinedFunctions = new Set(); + const queue = Array.from(fn.body.blocks.values()); + queue: for (const block of queue) { + if (isStatementBlockKind(block.kind)) { + for (let ii = 0; ii < block.instructions.length; ii++) { + const instr = block.instructions[ii]; + switch (instr.value.kind) { + case 'FunctionExpression': { + if (instr.lvalue.identifier.name === null) { + functions.set(instr.lvalue.identifier.id, instr.value); + } + break; + } + case 'CallExpression': { + if (instr.value.args.length !== 0) { + continue; + } + const body = functions.get(instr.value.callee.identifier.id); + if (body === undefined) { + continue; + } + if (body.loweredFunc.func.params.length > 0 || + body.loweredFunc.func.async || + body.loweredFunc.func.generator) { + continue; + } + inlinedFunctions.add(instr.value.callee.identifier.id); + const continuationBlockId = fn.env.nextBlockId; + const continuationBlock = { + id: continuationBlockId, + instructions: block.instructions.slice(ii + 1), + kind: block.kind, + phis: new Set(), + preds: new Set(), + terminal: block.terminal, + }; + fn.body.blocks.set(continuationBlockId, continuationBlock); + block.instructions.length = ii; + if (hasSingleExitReturnTerminal(body.loweredFunc.func)) { + block.terminal = { + kind: 'goto', + block: body.loweredFunc.func.body.entry, + id: block.terminal.id, + loc: block.terminal.loc, + variant: GotoVariant.Break, + }; + for (const block of body.loweredFunc.func.body.blocks.values()) { + if (block.terminal.kind === 'return') { + block.instructions.push({ + id: makeInstructionId(0), + loc: block.terminal.loc, + lvalue: instr.lvalue, + value: { + kind: 'LoadLocal', + loc: block.terminal.loc, + place: block.terminal.value, + }, + effects: null, + }); + block.terminal = { + kind: 'goto', + block: continuationBlockId, + id: block.terminal.id, + loc: block.terminal.loc, + variant: GotoVariant.Break, + }; + } + } + for (const [id, block] of body.loweredFunc.func.body.blocks) { + block.preds.clear(); + fn.body.blocks.set(id, block); + } + } + else { + const newTerminal = { + block: body.loweredFunc.func.body.entry, + id: makeInstructionId(0), + kind: 'label', + fallthrough: continuationBlockId, + loc: block.terminal.loc, + }; + block.terminal = newTerminal; + const result = instr.lvalue; + declareTemporary(fn.env, block, result); + if (result.identifier.name == null) { + promoteTemporary(result.identifier); + } + for (const [id, block] of body.loweredFunc.func.body.blocks) { + block.preds.clear(); + rewriteBlock(fn.env, block, continuationBlockId, result); + fn.body.blocks.set(id, block); + } + } + queue.push(continuationBlock); + continue queue; + } + default: { + for (const place of eachInstructionValueOperand(instr.value)) { + functions.delete(place.identifier.id); + } + } + } + } + } + } + if (inlinedFunctions.size !== 0) { + for (const block of fn.body.blocks.values()) { + retainWhere(block.instructions, instr => !inlinedFunctions.has(instr.lvalue.identifier.id)); + } + reversePostorderBlocks(fn.body); + markInstructionIds(fn.body); + markPredecessors(fn.body); + mergeConsecutiveBlocks(fn); + } +} +function hasSingleExitReturnTerminal(fn) { + let hasReturn = false; + let exitCount = 0; + for (const [, block] of fn.body.blocks) { + if (block.terminal.kind === 'return' || block.terminal.kind === 'throw') { + hasReturn || (hasReturn = block.terminal.kind === 'return'); + exitCount++; + } + } + return exitCount === 1 && hasReturn; +} +function rewriteBlock(env, block, returnTarget, returnValue) { + const { terminal } = block; + if (terminal.kind !== 'return') { + return; + } + block.instructions.push({ + id: makeInstructionId(0), + loc: terminal.loc, + lvalue: createTemporaryPlace(env, terminal.loc), + value: { + kind: 'StoreLocal', + lvalue: { kind: InstructionKind.Reassign, place: Object.assign({}, returnValue) }, + value: terminal.value, + type: null, + loc: terminal.loc, + }, + effects: null, + }); + block.terminal = { + kind: 'goto', + block: returnTarget, + id: makeInstructionId(0), + variant: GotoVariant.Break, + loc: block.terminal.loc, + }; +} +function declareTemporary(env, block, result) { + block.instructions.push({ + id: makeInstructionId(0), + loc: GeneratedSource, + lvalue: createTemporaryPlace(env, result.loc), + value: { + kind: 'DeclareLocal', + lvalue: { + place: result, + kind: InstructionKind.Let, + }, + type: null, + loc: result.loc, + }, + effects: null, + }); +} + +function alignMethodCallScopes(fn) { + const scopeMapping = new Map(); + const mergedScopes = new DisjointSet(); + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + if (value.kind === 'MethodCall') { + const lvalueScope = lvalue.identifier.scope; + const propertyScope = value.property.identifier.scope; + if (lvalueScope !== null) { + if (propertyScope !== null) { + mergedScopes.union([lvalueScope, propertyScope]); + } + else { + scopeMapping.set(value.property.identifier.id, lvalueScope); + } + } + else if (propertyScope !== null) { + scopeMapping.set(value.property.identifier.id, null); + } + } + else if (value.kind === 'FunctionExpression' || + value.kind === 'ObjectMethod') { + alignMethodCallScopes(value.loweredFunc.func); + } + } + } + mergedScopes.forEach((scope, root) => { + if (scope === root) { + return; + } + root.range.start = makeInstructionId(Math.min(scope.range.start, root.range.start)); + root.range.end = makeInstructionId(Math.max(scope.range.end, root.range.end)); + }); + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const mappedScope = scopeMapping.get(instr.lvalue.identifier.id); + if (mappedScope !== undefined) { + instr.lvalue.identifier.scope = mappedScope; + } + else if (instr.lvalue.identifier.scope !== null) { + const mergedScope = mergedScopes.find(instr.lvalue.identifier.scope); + if (mergedScope != null) { + instr.lvalue.identifier.scope = mergedScope; + } + } + } + } +} + +function alignReactiveScopesToBlockScopesHIR(fn) { + var _a, _b, _c, _d, _e, _f, _g; + const activeBlockFallthroughRanges = []; + const activeScopes = new Set(); + const seen = new Set(); + const valueBlockNodes = new Map(); + const placeScopes = new Map(); + function recordPlace(id, place, node) { + if (place.identifier.scope !== null) { + placeScopes.set(place, place.identifier.scope); + } + const scope = getPlaceScope(id, place); + if (scope == null) { + return; + } + activeScopes.add(scope); + node === null || node === void 0 ? void 0 : node.children.push({ kind: 'scope', scope, id }); + if (seen.has(scope)) { + return; + } + seen.add(scope); + if (node != null && node.valueRange !== null) { + scope.range.start = makeInstructionId(Math.min(node.valueRange.start, scope.range.start)); + scope.range.end = makeInstructionId(Math.max(node.valueRange.end, scope.range.end)); + } + } + for (const [, block] of fn.body.blocks) { + const startingId = (_b = (_a = block.instructions[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : block.terminal.id; + retainWhere_Set(activeScopes, scope => scope.range.end > startingId); + const top = activeBlockFallthroughRanges.at(-1); + if ((top === null || top === void 0 ? void 0 : top.fallthrough) === block.id) { + activeBlockFallthroughRanges.pop(); + for (const scope of activeScopes) { + scope.range.start = makeInstructionId(Math.min(scope.range.start, top.range.start)); + } + } + const { instructions, terminal } = block; + const node = (_c = valueBlockNodes.get(block.id)) !== null && _c !== void 0 ? _c : null; + for (const instr of instructions) { + for (const lvalue of eachInstructionLValue(instr)) { + recordPlace(instr.id, lvalue, node); + } + for (const operand of eachInstructionValueOperand(instr.value)) { + recordPlace(instr.id, operand, node); + } + } + for (const operand of eachTerminalOperand(terminal)) { + recordPlace(terminal.id, operand, node); + } + const fallthrough = terminalFallthrough(terminal); + if (fallthrough !== null && terminal.kind !== 'branch') { + const fallthroughBlock = fn.body.blocks.get(fallthrough); + const nextId = (_e = (_d = fallthroughBlock.instructions[0]) === null || _d === void 0 ? void 0 : _d.id) !== null && _e !== void 0 ? _e : fallthroughBlock.terminal.id; + for (const scope of activeScopes) { + if (scope.range.end > terminal.id) { + scope.range.end = makeInstructionId(Math.max(scope.range.end, nextId)); + } + } + activeBlockFallthroughRanges.push({ + fallthrough, + range: { + start: terminal.id, + end: nextId, + }, + }); + CompilerError.invariant(!valueBlockNodes.has(fallthrough), { + reason: 'Expect hir blocks to have unique fallthroughs', + loc: terminal.loc, + }); + if (node != null) { + valueBlockNodes.set(fallthrough, node); + } + } + else if (terminal.kind === 'goto') { + const start = activeBlockFallthroughRanges.find(range => range.fallthrough === terminal.block); + if (start != null && start !== activeBlockFallthroughRanges.at(-1)) { + const fallthroughBlock = fn.body.blocks.get(start.fallthrough); + const firstId = (_g = (_f = fallthroughBlock.instructions[0]) === null || _f === void 0 ? void 0 : _f.id) !== null && _g !== void 0 ? _g : fallthroughBlock.terminal.id; + for (const scope of activeScopes) { + if (scope.range.end <= terminal.id) { + continue; + } + scope.range.start = makeInstructionId(Math.min(start.range.start, scope.range.start)); + scope.range.end = makeInstructionId(Math.max(firstId, scope.range.end)); + } + } + } + mapTerminalSuccessors(terminal, successor => { + var _a, _b; + if (valueBlockNodes.has(successor)) { + return successor; + } + const successorBlock = fn.body.blocks.get(successor); + if (successorBlock.kind === 'block' || successorBlock.kind === 'catch') ; + else if (node == null || + terminal.kind === 'ternary' || + terminal.kind === 'logical' || + terminal.kind === 'optional') { + let valueRange; + if (node == null) { + CompilerError.invariant(fallthrough !== null, { + reason: `Expected a fallthrough for value block`, + loc: terminal.loc, + }); + const fallthroughBlock = fn.body.blocks.get(fallthrough); + const nextId = (_b = (_a = fallthroughBlock.instructions[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : fallthroughBlock.terminal.id; + valueRange = { + start: terminal.id, + end: nextId, + }; + } + else { + valueRange = node.valueRange; + } + const childNode = { + kind: 'node', + id: terminal.id, + children: [], + valueRange, + }; + node === null || node === void 0 ? void 0 : node.children.push(childNode); + valueBlockNodes.set(successor, childNode); + } + else { + valueBlockNodes.set(successor, node); + } + return successor; + }); + } +} + +function flattenReactiveLoopsHIR(fn) { + const activeLoops = Array(); + for (const [, block] of fn.body.blocks) { + retainWhere(activeLoops, id => id !== block.id); + const { terminal } = block; + switch (terminal.kind) { + case 'do-while': + case 'for': + case 'for-in': + case 'for-of': + case 'while': { + activeLoops.push(terminal.fallthrough); + break; + } + case 'scope': { + if (activeLoops.length !== 0) { + block.terminal = { + kind: 'pruned-scope', + block: terminal.block, + fallthrough: terminal.fallthrough, + id: terminal.id, + loc: terminal.loc, + scope: terminal.scope, + }; + } + break; + } + case 'branch': + case 'goto': + case 'if': + case 'label': + case 'logical': + case 'maybe-throw': + case 'optional': + case 'pruned-scope': + case 'return': + case 'sequence': + case 'switch': + case 'ternary': + case 'throw': + case 'try': + case 'unreachable': + case 'unsupported': { + break; + } + default: { + assertExhaustive$1(terminal, `Unexpected terminal kind \`${terminal.kind}\``); + } + } + } +} + +function flattenScopesWithHooksOrUseHIR(fn) { + const activeScopes = []; + const prune = []; + for (const [, block] of fn.body.blocks) { + retainWhere(activeScopes, current => current.fallthrough !== block.id); + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'MethodCall': + case 'CallExpression': { + const callee = value.kind === 'MethodCall' ? value.property : value.callee; + if (getHookKind(fn.env, callee.identifier) != null || + isUseOperator(callee.identifier)) { + prune.push(...activeScopes.map(entry => entry.block)); + activeScopes.length = 0; + } + } + } + } + if (block.terminal.kind === 'scope') { + activeScopes.push({ + block: block.id, + fallthrough: block.terminal.fallthrough, + }); + } + } + for (const id of prune) { + const block = fn.body.blocks.get(id); + const terminal = block.terminal; + CompilerError.invariant(terminal.kind === 'scope', { + reason: `Expected block to have a scope terminal`, + description: `Expected block bb${block.id} to end in a scope terminal`, + loc: terminal.loc, + }); + const body = fn.body.blocks.get(terminal.block); + if (body.instructions.length === 1 && + body.terminal.kind === 'goto' && + body.terminal.block === terminal.fallthrough) { + block.terminal = { + kind: 'label', + block: terminal.block, + fallthrough: terminal.fallthrough, + id: terminal.id, + loc: terminal.loc, + }; + continue; + } + block.terminal = { + kind: 'pruned-scope', + block: terminal.block, + fallthrough: terminal.fallthrough, + id: terminal.id, + loc: terminal.loc, + scope: terminal.scope, + }; + } +} + +function pruneAlwaysInvalidatingScopes(fn) { + visitReactiveFunction(fn, new Transform(), false); +} +class Transform extends ReactiveFunctionTransform { + constructor() { + super(...arguments); + this.alwaysInvalidatingValues = new Set(); + this.unmemoizedValues = new Set(); + } + transformInstruction(instruction, withinScope) { + this.visitInstruction(instruction, withinScope); + const { lvalue, value } = instruction; + switch (value.kind) { + case 'ArrayExpression': + case 'ObjectExpression': + case 'JsxExpression': + case 'JsxFragment': + case 'NewExpression': { + if (lvalue !== null) { + this.alwaysInvalidatingValues.add(lvalue.identifier); + if (!withinScope) { + this.unmemoizedValues.add(lvalue.identifier); + } + } + break; + } + case 'StoreLocal': { + if (this.alwaysInvalidatingValues.has(value.value.identifier)) { + this.alwaysInvalidatingValues.add(value.lvalue.place.identifier); + } + if (this.unmemoizedValues.has(value.value.identifier)) { + this.unmemoizedValues.add(value.lvalue.place.identifier); + } + break; + } + case 'LoadLocal': { + if (lvalue !== null && + this.alwaysInvalidatingValues.has(value.place.identifier)) { + this.alwaysInvalidatingValues.add(lvalue.identifier); + } + if (lvalue !== null && + this.unmemoizedValues.has(value.place.identifier)) { + this.unmemoizedValues.add(lvalue.identifier); + } + break; + } + } + return { kind: 'keep' }; + } + transformScope(scopeBlock, _withinScope) { + this.visitScope(scopeBlock, true); + for (const dep of scopeBlock.scope.dependencies) { + if (this.unmemoizedValues.has(dep.identifier)) { + for (const [_, decl] of scopeBlock.scope.declarations) { + if (this.alwaysInvalidatingValues.has(decl.identifier)) { + this.unmemoizedValues.add(decl.identifier); + } + } + for (const identifier of scopeBlock.scope.reassignments) { + if (this.alwaysInvalidatingValues.has(identifier)) { + this.unmemoizedValues.add(identifier); + } + } + return { + kind: 'replace', + value: { + kind: 'pruned-scope', + scope: scopeBlock.scope, + instructions: scopeBlock.instructions, + }, + }; + } + } + return { kind: 'keep' }; + } +} + +function isPrimitiveBinaryOp(op) { + switch (op) { + case '+': + case '-': + case '/': + case '%': + case '*': + case '**': + case '&': + case '|': + case '>>': + case '<<': + case '^': + case '>': + case '<': + case '>=': + case '<=': + case '|>': + return true; + default: + return false; + } +} +function inferTypes(func) { + const unifier = new Unifier(func.env); + for (const e of generate(func)) { + unifier.unify(e.left, e.right); + } + apply(func, unifier); +} +function apply(func, unifier) { + for (const [_, block] of func.body.blocks) { + for (const phi of block.phis) { + phi.place.identifier.type = unifier.get(phi.place.identifier.type); + } + for (const instr of block.instructions) { + for (const operand of eachInstructionLValue(instr)) { + operand.identifier.type = unifier.get(operand.identifier.type); + } + for (const place of eachInstructionOperand(instr)) { + place.identifier.type = unifier.get(place.identifier.type); + } + const { lvalue, value } = instr; + lvalue.identifier.type = unifier.get(lvalue.identifier.type); + if (value.kind === 'FunctionExpression' || + value.kind === 'ObjectMethod') { + apply(value.loweredFunc.func, unifier); + } + } + } + const returns = func.returns.identifier; + returns.type = unifier.get(returns.type); +} +function equation(left, right) { + return { + left, + right, + }; +} +function* generate(func) { + if (func.fnType === 'Component') { + const [props, ref] = func.params; + if (props && props.kind === 'Identifier') { + yield equation(props.identifier.type, { + kind: 'Object', + shapeId: BuiltInPropsId, + }); + } + if (ref && ref.kind === 'Identifier') { + yield equation(ref.identifier.type, { + kind: 'Object', + shapeId: BuiltInUseRefId, + }); + } + } + const names = new Map(); + const returnTypes = []; + for (const [_, block] of func.body.blocks) { + for (const phi of block.phis) { + yield equation(phi.place.identifier.type, { + kind: 'Phi', + operands: [...phi.operands.values()].map(id => id.identifier.type), + }); + } + for (const instr of block.instructions) { + yield* generateInstructionTypes(func.env, names, instr); + } + const terminal = block.terminal; + if (terminal.kind === 'return') { + returnTypes.push(terminal.value.identifier.type); + } + } + if (returnTypes.length > 1) { + yield equation(func.returns.identifier.type, { + kind: 'Phi', + operands: returnTypes, + }); + } + else if (returnTypes.length === 1) { + yield equation(func.returns.identifier.type, returnTypes[0]); + } +} +function setName(names, id, name) { + var _a; + if (((_a = name.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named') { + names.set(id, name.name.value); + } +} +function getName(names, id) { + var _a; + return (_a = names.get(id)) !== null && _a !== void 0 ? _a : ''; +} +function* generateInstructionTypes(env, names, instr) { + const { lvalue, value } = instr; + const left = lvalue.identifier.type; + switch (value.kind) { + case 'TemplateLiteral': + case 'JSXText': + case 'Primitive': { + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'UnaryExpression': { + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'LoadLocal': { + setName(names, lvalue.identifier.id, value.place.identifier); + yield equation(left, value.place.identifier.type); + break; + } + case 'DeclareContext': + case 'LoadContext': { + break; + } + case 'StoreContext': { + if (value.lvalue.kind === InstructionKind.Const) { + yield equation(value.lvalue.place.identifier.type, value.value.identifier.type); + } + break; + } + case 'StoreLocal': { + yield equation(left, value.value.identifier.type); + yield equation(value.lvalue.place.identifier.type, value.value.identifier.type); + break; + } + case 'StoreGlobal': { + yield equation(left, value.value.identifier.type); + break; + } + case 'BinaryExpression': { + if (isPrimitiveBinaryOp(value.operator)) { + yield equation(value.left.identifier.type, { kind: 'Primitive' }); + yield equation(value.right.identifier.type, { kind: 'Primitive' }); + } + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + yield equation(value.value.identifier.type, { kind: 'Primitive' }); + yield equation(value.lvalue.identifier.type, { kind: 'Primitive' }); + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'LoadGlobal': { + const globalType = env.getGlobalDeclaration(value.binding, value.loc); + if (globalType) { + yield equation(left, globalType); + } + break; + } + case 'CallExpression': { + const returnType = makeType(); + let shapeId = null; + if (env.config.enableTreatSetIdentifiersAsStateSetters) { + const name = getName(names, value.callee.identifier.id); + if (name.startsWith('set')) { + shapeId = BuiltInSetStateId; + } + } + yield equation(value.callee.identifier.type, { + kind: 'Function', + shapeId, + return: returnType, + isConstructor: false, + }); + yield equation(left, returnType); + break; + } + case 'TaggedTemplateExpression': { + const returnType = makeType(); + yield equation(value.tag.identifier.type, { + kind: 'Function', + shapeId: null, + return: returnType, + isConstructor: false, + }); + yield equation(left, returnType); + break; + } + case 'ObjectExpression': { + for (const property of value.properties) { + if (property.kind === 'ObjectProperty' && + property.key.kind === 'computed') { + yield equation(property.key.name.identifier.type, { + kind: 'Primitive', + }); + } + } + yield equation(left, { kind: 'Object', shapeId: BuiltInObjectId }); + break; + } + case 'ArrayExpression': { + yield equation(left, { kind: 'Object', shapeId: BuiltInArrayId }); + break; + } + case 'PropertyLoad': { + yield equation(left, { + kind: 'Property', + objectType: value.object.identifier.type, + objectName: getName(names, value.object.identifier.id), + propertyName: { + kind: 'literal', + value: value.property, + }, + }); + break; + } + case 'ComputedLoad': { + yield equation(left, { + kind: 'Property', + objectType: value.object.identifier.type, + objectName: getName(names, value.object.identifier.id), + propertyName: { + kind: 'computed', + value: value.property.identifier.type, + }, + }); + break; + } + case 'MethodCall': { + const returnType = makeType(); + yield equation(value.property.identifier.type, { + kind: 'Function', + return: returnType, + shapeId: null, + isConstructor: false, + }); + yield equation(left, returnType); + break; + } + case 'Destructure': { + const pattern = value.lvalue.pattern; + if (pattern.kind === 'ArrayPattern') { + for (let i = 0; i < pattern.items.length; i++) { + const item = pattern.items[i]; + if (item.kind === 'Identifier') { + const propertyName = String(i); + yield equation(item.identifier.type, { + kind: 'Property', + objectType: value.value.identifier.type, + objectName: getName(names, value.value.identifier.id), + propertyName: { + kind: 'literal', + value: makePropertyLiteral(propertyName), + }, + }); + } + else if (item.kind === 'Spread') { + yield equation(item.place.identifier.type, { + kind: 'Object', + shapeId: BuiltInArrayId, + }); + } + else { + continue; + } + } + } + else { + for (const property of pattern.properties) { + if (property.kind === 'ObjectProperty') { + if (property.key.kind === 'identifier' || + property.key.kind === 'string') { + yield equation(property.place.identifier.type, { + kind: 'Property', + objectType: value.value.identifier.type, + objectName: getName(names, value.value.identifier.id), + propertyName: { + kind: 'literal', + value: makePropertyLiteral(property.key.name), + }, + }); + } + } + } + } + break; + } + case 'TypeCastExpression': { + yield equation(left, value.value.identifier.type); + break; + } + case 'PropertyDelete': + case 'ComputedDelete': { + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'FunctionExpression': { + yield* generate(value.loweredFunc.func); + yield equation(left, { + kind: 'Function', + shapeId: BuiltInFunctionId, + return: value.loweredFunc.func.returns.identifier.type, + isConstructor: false, + }); + break; + } + case 'NextPropertyOf': { + yield equation(left, { kind: 'Primitive' }); + break; + } + case 'ObjectMethod': { + yield* generate(value.loweredFunc.func); + yield equation(left, { kind: 'ObjectMethod' }); + break; + } + case 'JsxExpression': + case 'JsxFragment': { + if (env.config.enableTreatRefLikeIdentifiersAsRefs) { + if (value.kind === 'JsxExpression') { + for (const prop of value.props) { + if (prop.kind === 'JsxAttribute' && prop.name === 'ref') { + yield equation(prop.place.identifier.type, { + kind: 'Object', + shapeId: BuiltInUseRefId, + }); + } + } + } + } + yield equation(left, { kind: 'Object', shapeId: BuiltInJsxId }); + break; + } + case 'NewExpression': { + const returnType = makeType(); + yield equation(value.callee.identifier.type, { + kind: 'Function', + return: returnType, + shapeId: null, + isConstructor: true, + }); + yield equation(left, returnType); + break; + } + case 'PropertyStore': { + yield equation(makeType(), { + kind: 'Property', + objectType: value.object.identifier.type, + objectName: getName(names, value.object.identifier.id), + propertyName: { + kind: 'literal', + value: value.property, + }, + }); + break; + } + case 'DeclareLocal': + case 'RegExpLiteral': + case 'MetaProperty': + case 'ComputedStore': + case 'Await': + case 'GetIterator': + case 'IteratorNext': + case 'UnsupportedNode': + case 'Debugger': + case 'FinishMemoize': + case 'StartMemoize': { + break; + } + default: + assertExhaustive$1(value, `Unhandled instruction value kind: ${value.kind}`); + } +} +class Unifier { + constructor(env) { + this.substitutions = new Map(); + this.env = env; + } + unify(tA, tB) { + if (tB.kind === 'Property') { + if (this.env.config.enableTreatRefLikeIdentifiersAsRefs && + isRefLikeName(tB)) { + this.unify(tB.objectType, { + kind: 'Object', + shapeId: BuiltInUseRefId, + }); + this.unify(tA, { + kind: 'Object', + shapeId: BuiltInRefValueId, + }); + return; + } + const objectType = this.get(tB.objectType); + const propertyType = tB.propertyName.kind === 'literal' + ? this.env.getPropertyType(objectType, tB.propertyName.value) + : this.env.getFallthroughPropertyType(objectType, tB.propertyName.value); + if (propertyType !== null) { + this.unify(tA, propertyType); + } + return; + } + if (typeEquals(tA, tB)) { + return; + } + if (tA.kind === 'Type') { + this.bindVariableTo(tA, tB); + return; + } + if (tB.kind === 'Type') { + this.bindVariableTo(tB, tA); + return; + } + if (tB.kind === 'Function' && + tA.kind === 'Function' && + tA.isConstructor === tB.isConstructor) { + this.unify(tA.return, tB.return); + return; + } + } + bindVariableTo(v, type) { + if (type.kind === 'Poly') { + return; + } + if (this.substitutions.has(v.id)) { + this.unify(this.substitutions.get(v.id), type); + return; + } + if (type.kind === 'Type' && this.substitutions.has(type.id)) { + this.unify(v, this.substitutions.get(type.id)); + return; + } + if (type.kind === 'Phi') { + CompilerError.invariant(type.operands.length > 0, { + reason: 'there should be at least one operand', + loc: GeneratedSource, + }); + let candidateType = null; + for (const operand of type.operands) { + const resolved = this.get(operand); + if (candidateType === null) { + candidateType = resolved; + } + else if (!typeEquals(resolved, candidateType)) { + const unionType = tryUnionTypes(resolved, candidateType); + if (unionType === null) { + candidateType = null; + break; + } + else { + candidateType = unionType; + } + } + } + if (candidateType !== null) { + this.unify(v, candidateType); + return; + } + } + if (this.occursCheck(v, type)) { + const resolvedType = this.tryResolveType(v, type); + if (resolvedType !== null) { + this.substitutions.set(v.id, resolvedType); + return; + } + throw new Error('cycle detected'); + } + this.substitutions.set(v.id, type); + } + tryResolveType(v, type) { + switch (type.kind) { + case 'Phi': { + const operands = []; + for (const operand of type.operands) { + if (operand.kind === 'Type' && operand.id === v.id) { + continue; + } + const resolved = this.tryResolveType(v, operand); + if (resolved === null) { + return null; + } + operands.push(resolved); + } + return { kind: 'Phi', operands }; + } + case 'Type': { + const substitution = this.get(type); + if (substitution !== type) { + const resolved = this.tryResolveType(v, substitution); + if (resolved !== null) { + this.substitutions.set(type.id, resolved); + } + return resolved; + } + return type; + } + case 'Property': { + const objectType = this.tryResolveType(v, this.get(type.objectType)); + if (objectType === null) { + return null; + } + return { + kind: 'Property', + objectName: type.objectName, + objectType, + propertyName: type.propertyName, + }; + } + case 'Function': { + const returnType = this.tryResolveType(v, this.get(type.return)); + if (returnType === null) { + return null; + } + return { + kind: 'Function', + return: returnType, + shapeId: type.shapeId, + isConstructor: type.isConstructor, + }; + } + case 'ObjectMethod': + case 'Object': + case 'Primitive': + case 'Poly': { + return type; + } + default: { + assertExhaustive$1(type, `Unexpected type kind '${type.kind}'`); + } + } + } + occursCheck(v, type) { + if (typeEquals(v, type)) + return true; + if (type.kind === 'Type' && this.substitutions.has(type.id)) { + return this.occursCheck(v, this.substitutions.get(type.id)); + } + if (type.kind === 'Phi') { + return type.operands.some(o => this.occursCheck(v, o)); + } + if (type.kind === 'Function') { + return this.occursCheck(v, type.return); + } + return false; + } + get(type) { + if (type.kind === 'Type') { + if (this.substitutions.has(type.id)) { + return this.get(this.substitutions.get(type.id)); + } + } + if (type.kind === 'Phi') { + return { kind: 'Phi', operands: type.operands.map(o => this.get(o)) }; + } + if (type.kind === 'Function') { + return { + kind: 'Function', + isConstructor: type.isConstructor, + shapeId: type.shapeId, + return: this.get(type.return), + }; + } + return type; + } +} +const RefLikeNameRE = /^(?:[a-zA-Z$_][a-zA-Z$_0-9]*)Ref$|^ref$/; +function isRefLikeName(t) { + return (t.propertyName.kind === 'literal' && + RefLikeNameRE.test(t.objectName) && + t.propertyName.value === 'current'); +} +function tryUnionTypes(ty1, ty2) { + let readonlyType; + let otherType; + if (ty1.kind === 'Object' && ty1.shapeId === BuiltInMixedReadonlyId) { + readonlyType = ty1; + otherType = ty2; + } + else if (ty2.kind === 'Object' && ty2.shapeId === BuiltInMixedReadonlyId) { + readonlyType = ty2; + otherType = ty1; + } + else { + return null; + } + if (otherType.kind === 'Primitive') { + return readonlyType; + } + else if (otherType.kind === 'Object' && + otherType.shapeId === BuiltInArrayId) { + return otherType; + } + return null; +} + +function validateContextVariableLValues(fn) { + const identifierKinds = new Map(); + validateContextVariableLValuesImpl(fn, identifierKinds, fn.env); +} +function validateContextVariableLValuesImpl(fn, identifierKinds, env) { + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'DeclareContext': + case 'StoreContext': { + visit(identifierKinds, value.lvalue.place, 'context', env); + break; + } + case 'LoadContext': { + visit(identifierKinds, value.place, 'context', env); + break; + } + case 'StoreLocal': + case 'DeclareLocal': { + visit(identifierKinds, value.lvalue.place, 'local', env); + break; + } + case 'LoadLocal': { + visit(identifierKinds, value.place, 'local', env); + break; + } + case 'PostfixUpdate': + case 'PrefixUpdate': { + visit(identifierKinds, value.lvalue, 'local', env); + break; + } + case 'Destructure': { + for (const lvalue of eachPatternOperand(value.lvalue.pattern)) { + visit(identifierKinds, lvalue, 'destructure', env); + } + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + validateContextVariableLValuesImpl(value.loweredFunc.func, identifierKinds, env); + break; + } + default: { + for (const _ of eachInstructionValueLValue(value)) { + fn.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Todo, + reason: 'ValidateContextVariableLValues: unhandled instruction variant', + description: `Handle '${value.kind} lvalues`, + }).withDetails({ + kind: 'error', + loc: value.loc, + message: null, + })); + } + } + } + } + } +} +function visit(identifiers, place, kind, env) { + const prev = identifiers.get(place.identifier.id); + if (prev !== undefined) { + const wasContext = prev.kind === 'context'; + const isContext = kind === 'context'; + if (wasContext !== isContext) { + if (prev.kind === 'destructure' || kind === 'destructure') { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Todo, + reason: `Support destructuring of context variables`, + description: null, + }).withDetails({ + kind: 'error', + loc: kind === 'destructure' ? place.loc : prev.place.loc, + message: null, + })); + return; + } + CompilerError.invariant(false, { + reason: 'Expected all references to a variable to be consistently local or context references', + description: `Identifier ${printPlace(place)} is referenced as a ${kind} variable, but was previously referenced as a ${prev.kind} variable`, + message: `this is ${prev.kind}`, + loc: place.loc, + }); + } + } + identifiers.set(place.identifier.id, { place, kind }); +} + +function computeUnconditionalBlocks(fn) { + const unconditionalBlocks = new Set(); + const dominators = computePostDominatorTree(fn, { + includeThrowsAsExitNode: false, + }); + const exit = dominators.exit; + let current = fn.body.entry; + while (current !== null && current !== exit) { + CompilerError.invariant(!unconditionalBlocks.has(current), { + reason: 'Internal error: non-terminating loop in ComputeUnconditionalBlocks', + loc: GeneratedSource, + }); + unconditionalBlocks.add(current); + current = dominators.get(current); + } + return unconditionalBlocks; +} + +var Kind; +(function (Kind) { + Kind["Error"] = "Error"; + Kind["KnownHook"] = "KnownHook"; + Kind["PotentialHook"] = "PotentialHook"; + Kind["Global"] = "Global"; + Kind["Local"] = "Local"; +})(Kind || (Kind = {})); +function joinKinds(a, b) { + if (a === Kind.Error || b === Kind.Error) { + return Kind.Error; + } + else if (a === Kind.KnownHook || b === Kind.KnownHook) { + return Kind.KnownHook; + } + else if (a === Kind.PotentialHook || b === Kind.PotentialHook) { + return Kind.PotentialHook; + } + else if (a === Kind.Global || b === Kind.Global) { + return Kind.Global; + } + else { + return Kind.Local; + } +} +function validateHooksUsage(fn) { + const unconditionalBlocks = computeUnconditionalBlocks(fn); + const errorsByPlace = new Map(); + function trackError(loc, errorDetail) { + if (typeof loc === 'symbol') { + fn.env.recordError(errorDetail); + } + else { + errorsByPlace.set(loc, errorDetail); + } + } + function recordConditionalHookError(place) { + setKind(place, Kind.Error); + const reason = 'Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)'; + const previousError = typeof place.loc !== 'symbol' ? errorsByPlace.get(place.loc) : undefined; + if (previousError === undefined || previousError.reason !== reason) { + trackError(place.loc, new CompilerErrorDetail({ + category: ErrorCategory.Hooks, + description: null, + reason, + loc: place.loc, + suggestions: null, + })); + } + } + function recordInvalidHookUsageError(place) { + const previousError = typeof place.loc !== 'symbol' ? errorsByPlace.get(place.loc) : undefined; + if (previousError === undefined) { + trackError(place.loc, new CompilerErrorDetail({ + category: ErrorCategory.Hooks, + description: null, + reason: 'Hooks may not be referenced as normal values, they must be called. See https://react.dev/reference/rules/react-calls-components-and-hooks#never-pass-around-hooks-as-regular-values', + loc: place.loc, + suggestions: null, + })); + } + } + function recordDynamicHookUsageError(place) { + const previousError = typeof place.loc !== 'symbol' ? errorsByPlace.get(place.loc) : undefined; + if (previousError === undefined) { + trackError(place.loc, new CompilerErrorDetail({ + category: ErrorCategory.Hooks, + description: null, + reason: 'Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks', + loc: place.loc, + suggestions: null, + })); + } + } + const valueKinds = new Map(); + function getKindForPlace(place) { + const knownKind = valueKinds.get(place.identifier.id); + if (place.identifier.name !== null && + isHookName$2(place.identifier.name.value)) { + return joinKinds(knownKind !== null && knownKind !== void 0 ? knownKind : Kind.Local, Kind.PotentialHook); + } + else { + return knownKind !== null && knownKind !== void 0 ? knownKind : Kind.Local; + } + } + function visitPlace(place) { + const kind = valueKinds.get(place.identifier.id); + if (kind === Kind.KnownHook) { + recordInvalidHookUsageError(place); + } + } + function setKind(place, kind) { + valueKinds.set(place.identifier.id, kind); + } + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + const kind = getKindForPlace(place); + setKind(place, kind); + } + for (const [, block] of fn.body.blocks) { + for (const phi of block.phis) { + let kind = phi.place.identifier.name !== null && + isHookName$2(phi.place.identifier.name.value) + ? Kind.PotentialHook + : Kind.Local; + for (const [, operand] of phi.operands) { + const operandKind = valueKinds.get(operand.identifier.id); + if (operandKind !== undefined) { + kind = joinKinds(kind, operandKind); + } + } + valueKinds.set(phi.place.identifier.id, kind); + } + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'LoadGlobal': { + if (getHookKind(fn.env, instr.lvalue.identifier) != null) { + setKind(instr.lvalue, Kind.KnownHook); + } + else { + setKind(instr.lvalue, Kind.Global); + } + break; + } + case 'LoadContext': + case 'LoadLocal': { + visitPlace(instr.value.place); + const kind = getKindForPlace(instr.value.place); + setKind(instr.lvalue, kind); + break; + } + case 'StoreLocal': + case 'StoreContext': { + visitPlace(instr.value.value); + const kind = joinKinds(getKindForPlace(instr.value.value), getKindForPlace(instr.value.lvalue.place)); + setKind(instr.value.lvalue.place, kind); + setKind(instr.lvalue, kind); + break; + } + case 'ComputedLoad': { + visitPlace(instr.value.object); + const kind = getKindForPlace(instr.value.object); + setKind(instr.lvalue, joinKinds(getKindForPlace(instr.lvalue), kind)); + break; + } + case 'PropertyLoad': { + const objectKind = getKindForPlace(instr.value.object); + const isHookProperty = typeof instr.value.property === 'string' && + isHookName$2(instr.value.property); + let kind; + switch (objectKind) { + case Kind.Error: { + kind = Kind.Error; + break; + } + case Kind.KnownHook: { + kind = isHookProperty ? Kind.KnownHook : Kind.Local; + break; + } + case Kind.PotentialHook: { + kind = Kind.PotentialHook; + break; + } + case Kind.Global: { + kind = isHookProperty ? Kind.KnownHook : Kind.Global; + break; + } + case Kind.Local: { + kind = isHookProperty ? Kind.PotentialHook : Kind.Local; + break; + } + default: { + assertExhaustive$1(objectKind, `Unexpected kind \`${objectKind}\``); + } + } + setKind(instr.lvalue, kind); + break; + } + case 'CallExpression': { + const calleeKind = getKindForPlace(instr.value.callee); + const isHookCallee = calleeKind === Kind.KnownHook || calleeKind === Kind.PotentialHook; + if (isHookCallee && !unconditionalBlocks.has(block.id)) { + recordConditionalHookError(instr.value.callee); + } + else if (calleeKind === Kind.PotentialHook) { + recordDynamicHookUsageError(instr.value.callee); + } + for (const operand of eachInstructionOperand(instr)) { + if (operand === instr.value.callee) { + continue; + } + visitPlace(operand); + } + break; + } + case 'MethodCall': { + const calleeKind = getKindForPlace(instr.value.property); + const isHookCallee = calleeKind === Kind.KnownHook || calleeKind === Kind.PotentialHook; + if (isHookCallee && !unconditionalBlocks.has(block.id)) { + recordConditionalHookError(instr.value.property); + } + else if (calleeKind === Kind.PotentialHook) { + recordDynamicHookUsageError(instr.value.property); + } + for (const operand of eachInstructionOperand(instr)) { + if (operand === instr.value.property) { + continue; + } + visitPlace(operand); + } + break; + } + case 'Destructure': { + visitPlace(instr.value.value); + const objectKind = getKindForPlace(instr.value.value); + for (const lvalue of eachInstructionLValue(instr)) { + const isHookProperty = lvalue.identifier.name !== null && + isHookName$2(lvalue.identifier.name.value); + let kind; + switch (objectKind) { + case Kind.Error: { + kind = Kind.Error; + break; + } + case Kind.KnownHook: { + kind = Kind.KnownHook; + break; + } + case Kind.PotentialHook: { + kind = Kind.PotentialHook; + break; + } + case Kind.Global: { + kind = isHookProperty ? Kind.KnownHook : Kind.Global; + break; + } + case Kind.Local: { + kind = isHookProperty ? Kind.PotentialHook : Kind.Local; + break; + } + default: { + assertExhaustive$1(objectKind, `Unexpected kind \`${objectKind}\``); + } + } + setKind(lvalue, kind); + } + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + visitFunctionExpression(fn.env, instr.value.loweredFunc.func); + break; + } + default: { + for (const operand of eachInstructionOperand(instr)) { + visitPlace(operand); + } + for (const lvalue of eachInstructionLValue(instr)) { + const kind = getKindForPlace(lvalue); + setKind(lvalue, kind); + } + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + visitPlace(operand); + } + } + for (const [, error] of errorsByPlace) { + fn.env.recordError(error); + } +} +function visitFunctionExpression(env, fn) { + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'ObjectMethod': + case 'FunctionExpression': { + visitFunctionExpression(env, instr.value.loweredFunc.func); + break; + } + case 'MethodCall': + case 'CallExpression': { + const callee = instr.value.kind === 'CallExpression' + ? instr.value.callee + : instr.value.property; + const hookKind = getHookKind(fn.env, callee.identifier); + if (hookKind != null) { + env.recordError(new CompilerErrorDetail({ + category: ErrorCategory.Hooks, + reason: 'Hooks must be called at the top level in the body of a function component or custom hook, and may not be called within function expressions. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)', + loc: callee.loc, + description: `Cannot call ${hookKind === 'Custom' ? 'hook' : hookKind} within a function expression`, + suggestions: null, + })); + } + break; + } + } + } + } +} + +function validateNoCapitalizedCalls(fn) { + var _a; + const envConfig = fn.env.config; + const ALLOW_LIST = new Set([ + ...DEFAULT_GLOBALS.keys(), + ...((_a = envConfig.validateNoCapitalizedCalls) !== null && _a !== void 0 ? _a : []), + ]); + const isAllowed = (name) => { + return ALLOW_LIST.has(name); + }; + const capitalLoadGlobals = new Map(); + const capitalizedProperties = new Map(); + const reason = 'Capitalized functions are reserved for components, which must be invoked with JSX. If this is a component, render it with JSX. Otherwise, ensure that it has no hook calls and rename it to begin with a lowercase letter. Alternatively, if you know for a fact that this function is not a component, you can allowlist it via the compiler config'; + for (const [, block] of fn.body.blocks) { + for (const { lvalue, value } of block.instructions) { + switch (value.kind) { + case 'LoadGlobal': { + if (value.binding.name != '' && + /^[A-Z]/.test(value.binding.name) && + !(value.binding.name.toUpperCase() === value.binding.name) && + !isAllowed(value.binding.name)) { + capitalLoadGlobals.set(lvalue.identifier.id, value.binding.name); + } + break; + } + case 'CallExpression': { + const calleeIdentifier = value.callee.identifier.id; + const calleeName = capitalLoadGlobals.get(calleeIdentifier); + if (calleeName != null) { + fn.env.recordError(new CompilerErrorDetail({ + category: ErrorCategory.CapitalizedCalls, + reason, + description: `${calleeName} may be a component`, + loc: value.loc, + suggestions: null, + })); + continue; + } + break; + } + case 'PropertyLoad': { + if (typeof value.property === 'string' && + /^[A-Z]/.test(value.property)) { + capitalizedProperties.set(lvalue.identifier.id, value.property); + } + break; + } + case 'MethodCall': { + const propertyIdentifier = value.property.identifier.id; + const propertyName = capitalizedProperties.get(propertyIdentifier); + if (propertyName != null) { + fn.env.recordError(new CompilerErrorDetail({ + category: ErrorCategory.CapitalizedCalls, + reason, + description: `${propertyName} may be a component`, + loc: value.loc, + suggestions: null, + })); + } + break; + } + } + } + } +} + +var _Env_changed, _Env_data, _Env_temporaries; +function makeRefId(id) { + CompilerError.invariant(id >= 0 && Number.isInteger(id), { + reason: 'Expected identifier id to be a non-negative integer', + loc: GeneratedSource, + }); + return id; +} +let _refId = 0; +function nextRefId() { + return makeRefId(_refId++); +} +class Env { + constructor() { + _Env_changed.set(this, false); + _Env_data.set(this, new Map()); + _Env_temporaries.set(this, new Map()); + } + lookup(place) { + var _a; + return (_a = __classPrivateFieldGet(this, _Env_temporaries, "f").get(place.identifier.id)) !== null && _a !== void 0 ? _a : place; + } + define(place, value) { + __classPrivateFieldGet(this, _Env_temporaries, "f").set(place.identifier.id, value); + } + resetChanged() { + __classPrivateFieldSet(this, _Env_changed, false, "f"); + } + hasChanged() { + return __classPrivateFieldGet(this, _Env_changed, "f"); + } + get(key) { + var _a, _b; + const operandId = (_b = (_a = __classPrivateFieldGet(this, _Env_temporaries, "f").get(key)) === null || _a === void 0 ? void 0 : _a.identifier.id) !== null && _b !== void 0 ? _b : key; + return __classPrivateFieldGet(this, _Env_data, "f").get(operandId); + } + set(key, value) { + var _a, _b; + const operandId = (_b = (_a = __classPrivateFieldGet(this, _Env_temporaries, "f").get(key)) === null || _a === void 0 ? void 0 : _a.identifier.id) !== null && _b !== void 0 ? _b : key; + const cur = __classPrivateFieldGet(this, _Env_data, "f").get(operandId); + const widenedValue = joinRefAccessTypes(value, cur !== null && cur !== void 0 ? cur : { kind: 'None' }); + if (!(cur == null && widenedValue.kind === 'None') && + (cur == null || !tyEqual(cur, widenedValue))) { + __classPrivateFieldSet(this, _Env_changed, true, "f"); + } + __classPrivateFieldGet(this, _Env_data, "f").set(operandId, widenedValue); + return this; + } +} +_Env_changed = new WeakMap(), _Env_data = new WeakMap(), _Env_temporaries = new WeakMap(); +function validateNoRefAccessInRender(fn) { + const env = new Env(); + collectTemporariesSidemap$1(fn, env); + const errors = new CompilerError(); + validateNoRefAccessInRenderImpl(fn, env, errors); + for (const detail of errors.details) { + fn.env.recordError(detail); + } +} +function collectTemporariesSidemap$1(fn, env) { + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'LoadLocal': { + const temp = env.lookup(value.place); + if (temp != null) { + env.define(lvalue, temp); + } + break; + } + case 'StoreLocal': { + const temp = env.lookup(value.value); + if (temp != null) { + env.define(lvalue, temp); + env.define(value.lvalue.place, temp); + } + break; + } + case 'PropertyLoad': { + if (isUseRefType(value.object.identifier) && + value.property === 'current') { + continue; + } + const temp = env.lookup(value.object); + if (temp != null) { + env.define(lvalue, temp); + } + break; + } + } + } + } +} +function refTypeOfType(place) { + if (isRefValueType(place.identifier)) { + return { kind: 'RefValue' }; + } + else if (isUseRefType(place.identifier)) { + return { kind: 'Ref', refId: nextRefId() }; + } + else { + return { kind: 'None' }; + } +} +function tyEqual(a, b) { + if (a.kind !== b.kind) { + return false; + } + switch (a.kind) { + case 'None': + return true; + case 'Ref': + return true; + case 'Nullable': + return true; + case 'Guard': + CompilerError.invariant(b.kind === 'Guard', { + reason: 'Expected ref value', + loc: GeneratedSource, + }); + return a.refId === b.refId; + case 'RefValue': + CompilerError.invariant(b.kind === 'RefValue', { + reason: 'Expected ref value', + loc: GeneratedSource, + }); + return a.loc == b.loc; + case 'Structure': { + CompilerError.invariant(b.kind === 'Structure', { + reason: 'Expected structure', + loc: GeneratedSource, + }); + const fnTypesEqual = (a.fn === null && b.fn === null) || + (a.fn !== null && + b.fn !== null && + a.fn.readRefEffect === b.fn.readRefEffect && + tyEqual(a.fn.returnType, b.fn.returnType)); + return (fnTypesEqual && + (a.value === b.value || + (a.value !== null && b.value !== null && tyEqual(a.value, b.value)))); + } + } +} +function joinRefAccessTypes(...types) { + function joinRefAccessRefTypes(a, b) { + if (a.kind === 'RefValue') { + if (b.kind === 'RefValue' && a.refId === b.refId) { + return a; + } + return { kind: 'RefValue' }; + } + else if (b.kind === 'RefValue') { + return b; + } + else if (a.kind === 'Ref' || b.kind === 'Ref') { + if (a.kind === 'Ref' && b.kind === 'Ref' && a.refId === b.refId) { + return a; + } + return { kind: 'Ref', refId: nextRefId() }; + } + else { + CompilerError.invariant(a.kind === 'Structure' && b.kind === 'Structure', { + reason: 'Expected structure', + loc: GeneratedSource, + }); + const fn = a.fn === null + ? b.fn + : b.fn === null + ? a.fn + : { + readRefEffect: a.fn.readRefEffect || b.fn.readRefEffect, + returnType: joinRefAccessTypes(a.fn.returnType, b.fn.returnType), + }; + const value = a.value === null + ? b.value + : b.value === null + ? a.value + : joinRefAccessRefTypes(a.value, b.value); + return { + kind: 'Structure', + fn, + value, + }; + } + } + return types.reduce((a, b) => { + if (a.kind === 'None') { + return b; + } + else if (b.kind === 'None') { + return a; + } + else if (a.kind === 'Guard') { + if (b.kind === 'Guard' && a.refId === b.refId) { + return a; + } + else if (b.kind === 'Nullable' || b.kind === 'Guard') { + return { kind: 'None' }; + } + else { + return b; + } + } + else if (b.kind === 'Guard') { + if (a.kind === 'Nullable') { + return { kind: 'None' }; + } + else { + return b; + } + } + else if (a.kind === 'Nullable') { + return b; + } + else if (b.kind === 'Nullable') { + return a; + } + else { + return joinRefAccessRefTypes(a, b); + } + }, { kind: 'None' }); +} +function validateNoRefAccessInRenderImpl(fn, env, errors) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + let returnValues = []; + let place; + for (const param of fn.params) { + if (param.kind === 'Identifier') { + place = param; + } + else { + place = param.place; + } + const type = refTypeOfType(place); + env.set(place.identifier.id, type); + } + const interpolatedAsJsx = new Set(); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { value } = instr; + if (value.kind === 'JsxExpression' || value.kind === 'JsxFragment') { + if (value.children != null) { + for (const child of value.children) { + interpolatedAsJsx.add(child.identifier.id); + } + } + } + } + } + for (let i = 0; (i == 0 || env.hasChanged()) && i < 10; i++) { + env.resetChanged(); + returnValues = []; + const safeBlocks = []; + for (const [, block] of fn.body.blocks) { + retainWhere(safeBlocks, entry => entry.block !== block.id); + for (const phi of block.phis) { + env.set(phi.place.identifier.id, joinRefAccessTypes(...Array(...phi.operands.values()).map(operand => { var _a; return (_a = env.get(operand.identifier.id)) !== null && _a !== void 0 ? _a : { kind: 'None' }; }))); + } + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'JsxExpression': + case 'JsxFragment': { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoDirectRefValueAccess(errors, operand, env); + } + break; + } + case 'ComputedLoad': + case 'PropertyLoad': { + if (instr.value.kind === 'ComputedLoad') { + validateNoDirectRefValueAccess(errors, instr.value.property, env); + } + const objType = env.get(instr.value.object.identifier.id); + let lookupType = null; + if ((objType === null || objType === void 0 ? void 0 : objType.kind) === 'Structure') { + lookupType = objType.value; + } + else if ((objType === null || objType === void 0 ? void 0 : objType.kind) === 'Ref') { + lookupType = { + kind: 'RefValue', + loc: instr.loc, + refId: objType.refId, + }; + } + env.set(instr.lvalue.identifier.id, lookupType !== null && lookupType !== void 0 ? lookupType : refTypeOfType(instr.lvalue)); + break; + } + case 'TypeCastExpression': { + env.set(instr.lvalue.identifier.id, (_a = env.get(instr.value.value.identifier.id)) !== null && _a !== void 0 ? _a : refTypeOfType(instr.lvalue)); + break; + } + case 'LoadContext': + case 'LoadLocal': { + env.set(instr.lvalue.identifier.id, (_b = env.get(instr.value.place.identifier.id)) !== null && _b !== void 0 ? _b : refTypeOfType(instr.lvalue)); + break; + } + case 'StoreContext': + case 'StoreLocal': { + env.set(instr.value.lvalue.place.identifier.id, (_c = env.get(instr.value.value.identifier.id)) !== null && _c !== void 0 ? _c : refTypeOfType(instr.value.lvalue.place)); + env.set(instr.lvalue.identifier.id, (_d = env.get(instr.value.value.identifier.id)) !== null && _d !== void 0 ? _d : refTypeOfType(instr.lvalue)); + break; + } + case 'Destructure': { + const objType = env.get(instr.value.value.identifier.id); + let lookupType = null; + if ((objType === null || objType === void 0 ? void 0 : objType.kind) === 'Structure') { + lookupType = objType.value; + } + env.set(instr.lvalue.identifier.id, lookupType !== null && lookupType !== void 0 ? lookupType : refTypeOfType(instr.lvalue)); + for (const lval of eachPatternOperand(instr.value.lvalue.pattern)) { + env.set(lval.identifier.id, lookupType !== null && lookupType !== void 0 ? lookupType : refTypeOfType(lval)); + } + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + let returnType = { kind: 'None' }; + let readRefEffect = false; + const innerErrors = new CompilerError(); + const result = validateNoRefAccessInRenderImpl(instr.value.loweredFunc.func, env, innerErrors); + if (!innerErrors.hasAnyErrors()) { + returnType = result; + } + else { + readRefEffect = true; + } + env.set(instr.lvalue.identifier.id, { + kind: 'Structure', + fn: { + readRefEffect, + returnType, + }, + value: null, + }); + break; + } + case 'MethodCall': + case 'CallExpression': { + const callee = instr.value.kind === 'CallExpression' + ? instr.value.callee + : instr.value.property; + const hookKind = getHookKindForType(fn.env, callee.identifier.type); + let returnType = { kind: 'None' }; + const fnType = env.get(callee.identifier.id); + let didError = false; + if ((fnType === null || fnType === void 0 ? void 0 : fnType.kind) === 'Structure' && fnType.fn !== null) { + returnType = fnType.fn.returnType; + if (fnType.fn.readRefEffect) { + didError = true; + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: callee.loc, + message: `This function accesses a ref value`, + })); + } + } + if (!didError) { + const isRefLValue = isUseRefType(instr.lvalue.identifier); + if (isRefLValue || + (hookKind != null && + hookKind !== 'useState' && + hookKind !== 'useReducer')) { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoDirectRefValueAccess(errors, operand, env); + } + } + else if (interpolatedAsJsx.has(instr.lvalue.identifier.id)) { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoRefValueAccess(errors, env, operand); + } + } + else if (hookKind == null && instr.effects != null) { + const visitedEffects = new Set(); + for (const effect of instr.effects) { + let place = null; + let validation = 'none'; + switch (effect.kind) { + case 'Freeze': { + place = effect.value; + validation = 'direct-ref'; + break; + } + case 'Mutate': + case 'MutateTransitive': + case 'MutateConditionally': + case 'MutateTransitiveConditionally': { + place = effect.value; + validation = 'ref-passed'; + break; + } + case 'Render': { + place = effect.place; + validation = 'ref-passed'; + break; + } + case 'Capture': + case 'Alias': + case 'MaybeAlias': + case 'Assign': + case 'CreateFrom': { + place = effect.from; + validation = 'ref-passed'; + break; + } + case 'ImmutableCapture': { + place = effect.from; + const isFrozen = instr.effects.some(e => e.kind === 'Freeze' && + e.value.identifier.id === effect.from.identifier.id); + validation = isFrozen ? 'direct-ref' : 'ref-passed'; + break; + } + } + if (place !== null && validation !== 'none') { + const key = `${place.identifier.id}:${validation}`; + if (!visitedEffects.has(key)) { + visitedEffects.add(key); + if (validation === 'direct-ref') { + validateNoDirectRefValueAccess(errors, place, env); + } + else { + validateNoRefPassedToFunction(errors, env, place, place.loc); + } + } + } + } + } + else { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoRefPassedToFunction(errors, env, operand, operand.loc); + } + } + } + env.set(instr.lvalue.identifier.id, returnType); + break; + } + case 'ObjectExpression': + case 'ArrayExpression': { + const types = []; + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoDirectRefValueAccess(errors, operand, env); + types.push((_e = env.get(operand.identifier.id)) !== null && _e !== void 0 ? _e : { kind: 'None' }); + } + const value = joinRefAccessTypes(...types); + if (value.kind === 'None' || + value.kind === 'Guard' || + value.kind === 'Nullable') { + env.set(instr.lvalue.identifier.id, { kind: 'None' }); + } + else { + env.set(instr.lvalue.identifier.id, { + kind: 'Structure', + value, + fn: null, + }); + } + break; + } + case 'PropertyDelete': + case 'PropertyStore': + case 'ComputedDelete': + case 'ComputedStore': { + const target = env.get(instr.value.object.identifier.id); + let safe = null; + if (instr.value.kind === 'PropertyStore' && + target != null && + target.kind === 'Ref') { + safe = safeBlocks.find(entry => entry.ref === target.refId); + } + if (safe != null) { + retainWhere(safeBlocks, entry => entry !== safe); + } + else { + validateNoRefUpdate(errors, env, instr.value.object, instr.loc); + } + if (instr.value.kind === 'ComputedDelete' || + instr.value.kind === 'ComputedStore') { + validateNoRefValueAccess(errors, env, instr.value.property); + } + if (instr.value.kind === 'ComputedStore' || + instr.value.kind === 'PropertyStore') { + validateNoDirectRefValueAccess(errors, instr.value.value, env); + const type = env.get(instr.value.value.identifier.id); + if (type != null && type.kind === 'Structure') { + let objectType = type; + if (target != null) { + objectType = joinRefAccessTypes(objectType, target); + } + env.set(instr.value.object.identifier.id, objectType); + } + } + break; + } + case 'StartMemoize': + case 'FinishMemoize': + break; + case 'LoadGlobal': { + if (instr.value.binding.name === 'undefined') { + env.set(instr.lvalue.identifier.id, { kind: 'Nullable' }); + } + break; + } + case 'Primitive': { + if (instr.value.value == null) { + env.set(instr.lvalue.identifier.id, { kind: 'Nullable' }); + } + break; + } + case 'UnaryExpression': { + if (instr.value.operator === '!') { + const value = env.get(instr.value.value.identifier.id); + const refId = (value === null || value === void 0 ? void 0 : value.kind) === 'RefValue' && value.refId != null + ? value.refId + : null; + if (refId !== null) { + env.set(instr.lvalue.identifier.id, { kind: 'Guard', refId }); + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }) + .withDetails({ + kind: 'error', + loc: instr.value.value.loc, + message: `Cannot access ref value during render`, + }) + .withDetails({ + kind: 'hint', + message: 'To initialize a ref only once, check that the ref is null with the pattern `if (ref.current == null) { ref.current = ... }`', + })); + break; + } + } + validateNoRefValueAccess(errors, env, instr.value.value); + break; + } + case 'BinaryExpression': { + const left = env.get(instr.value.left.identifier.id); + const right = env.get(instr.value.right.identifier.id); + let nullish = false; + let refId = null; + if ((left === null || left === void 0 ? void 0 : left.kind) === 'RefValue' && left.refId != null) { + refId = left.refId; + } + else if ((right === null || right === void 0 ? void 0 : right.kind) === 'RefValue' && right.refId != null) { + refId = right.refId; + } + if ((left === null || left === void 0 ? void 0 : left.kind) === 'Nullable') { + nullish = true; + } + else if ((right === null || right === void 0 ? void 0 : right.kind) === 'Nullable') { + nullish = true; + } + if (refId !== null && nullish) { + env.set(instr.lvalue.identifier.id, { kind: 'Guard', refId }); + } + else { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoRefValueAccess(errors, env, operand); + } + } + break; + } + default: { + for (const operand of eachInstructionValueOperand(instr.value)) { + validateNoRefValueAccess(errors, env, operand); + } + break; + } + } + for (const operand of eachInstructionOperand(instr)) { + guardCheck(errors, operand, env); + } + if (isUseRefType(instr.lvalue.identifier) && + ((_f = env.get(instr.lvalue.identifier.id)) === null || _f === void 0 ? void 0 : _f.kind) !== 'Ref') { + env.set(instr.lvalue.identifier.id, joinRefAccessTypes((_g = env.get(instr.lvalue.identifier.id)) !== null && _g !== void 0 ? _g : { kind: 'None' }, { kind: 'Ref', refId: nextRefId() })); + } + if (isRefValueType(instr.lvalue.identifier) && + ((_h = env.get(instr.lvalue.identifier.id)) === null || _h === void 0 ? void 0 : _h.kind) !== 'RefValue') { + env.set(instr.lvalue.identifier.id, joinRefAccessTypes((_j = env.get(instr.lvalue.identifier.id)) !== null && _j !== void 0 ? _j : { kind: 'None' }, { kind: 'RefValue', loc: instr.loc })); + } + } + if (block.terminal.kind === 'if') { + const test = env.get(block.terminal.test.identifier.id); + if ((test === null || test === void 0 ? void 0 : test.kind) === 'Guard' && + safeBlocks.find(entry => entry.ref === test.refId) == null) { + safeBlocks.push({ block: block.terminal.fallthrough, ref: test.refId }); + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + if (block.terminal.kind !== 'return') { + validateNoRefValueAccess(errors, env, operand); + if (block.terminal.kind !== 'if') { + guardCheck(errors, operand, env); + } + } + else { + validateNoDirectRefValueAccess(errors, operand, env); + guardCheck(errors, operand, env); + returnValues.push(env.get(operand.identifier.id)); + } + } + } + if (errors.hasAnyErrors()) { + return { kind: 'None' }; + } + } + CompilerError.invariant(!env.hasChanged(), { + reason: 'Ref type environment did not converge', + loc: GeneratedSource, + }); + return joinRefAccessTypes(...returnValues.filter((env) => env !== undefined)); +} +function destructure(type) { + if ((type === null || type === void 0 ? void 0 : type.kind) === 'Structure' && type.value !== null) { + return destructure(type.value); + } + return type; +} +function guardCheck(errors, operand, env) { + var _a; + if (((_a = env.get(operand.identifier.id)) === null || _a === void 0 ? void 0 : _a.kind) === 'Guard') { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: operand.loc, + message: `Cannot access ref value during render`, + })); + } +} +function validateNoRefValueAccess(errors, env, operand) { + var _a; + const type = destructure(env.get(operand.identifier.id)); + if ((type === null || type === void 0 ? void 0 : type.kind) === 'RefValue' || + ((type === null || type === void 0 ? void 0 : type.kind) === 'Structure' && ((_a = type.fn) === null || _a === void 0 ? void 0 : _a.readRefEffect))) { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: (type.kind === 'RefValue' && type.loc) || operand.loc, + message: `Cannot access ref value during render`, + })); + } +} +function validateNoRefPassedToFunction(errors, env, operand, loc) { + var _a; + const type = destructure(env.get(operand.identifier.id)); + if ((type === null || type === void 0 ? void 0 : type.kind) === 'Ref' || + (type === null || type === void 0 ? void 0 : type.kind) === 'RefValue' || + ((type === null || type === void 0 ? void 0 : type.kind) === 'Structure' && ((_a = type.fn) === null || _a === void 0 ? void 0 : _a.readRefEffect))) { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: (type.kind === 'RefValue' && type.loc) || loc, + message: `Passing a ref to a function may read its value during render`, + })); + } +} +function validateNoRefUpdate(errors, env, operand, loc) { + const type = destructure(env.get(operand.identifier.id)); + if ((type === null || type === void 0 ? void 0 : type.kind) === 'Ref' || (type === null || type === void 0 ? void 0 : type.kind) === 'RefValue') { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: (type.kind === 'RefValue' && type.loc) || loc, + message: `Cannot update ref during render`, + })); + } +} +function validateNoDirectRefValueAccess(errors, operand, env) { + var _a; + const type = destructure(env.get(operand.identifier.id)); + if ((type === null || type === void 0 ? void 0 : type.kind) === 'RefValue') { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.Refs, + reason: 'Cannot access refs during render', + description: ERROR_DESCRIPTION, + }).withDetails({ + kind: 'error', + loc: (_a = type.loc) !== null && _a !== void 0 ? _a : operand.loc, + message: `Cannot access ref value during render`, + })); + } +} +const ERROR_DESCRIPTION = 'React refs are values that are not needed for rendering. Refs should only be accessed ' + + 'outside of render, such as in event handlers or effects. ' + + 'Accessing a ref value (the `current` property) during render can cause your component ' + + 'not to update as expected (https://react.dev/reference/react/useRef)'; + +function validateNoSetStateInRender(fn) { + const unconditionalSetStateFunctions = new Set(); + const errors = validateNoSetStateInRenderImpl(fn, unconditionalSetStateFunctions); + for (const detail of errors.details) { + fn.env.recordError(detail); + } +} +function validateNoSetStateInRenderImpl(fn, unconditionalSetStateFunctions) { + const unconditionalBlocks = computeUnconditionalBlocks(fn); + let activeManualMemoId = null; + const errors = new CompilerError(); + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'LoadLocal': { + if (unconditionalSetStateFunctions.has(instr.value.place.identifier.id)) { + unconditionalSetStateFunctions.add(instr.lvalue.identifier.id); + } + break; + } + case 'StoreLocal': { + if (unconditionalSetStateFunctions.has(instr.value.value.identifier.id)) { + unconditionalSetStateFunctions.add(instr.value.lvalue.place.identifier.id); + unconditionalSetStateFunctions.add(instr.lvalue.identifier.id); + } + break; + } + case 'ObjectMethod': + case 'FunctionExpression': { + if ([...eachInstructionValueOperand(instr.value)].some(operand => isSetStateType(operand.identifier) || + unconditionalSetStateFunctions.has(operand.identifier.id)) && + validateNoSetStateInRenderImpl(instr.value.loweredFunc.func, unconditionalSetStateFunctions).hasAnyErrors()) { + unconditionalSetStateFunctions.add(instr.lvalue.identifier.id); + } + break; + } + case 'StartMemoize': { + CompilerError.invariant(activeManualMemoId === null, { + reason: 'Unexpected nested StartMemoize instructions', + loc: instr.value.loc, + }); + activeManualMemoId = instr.value.manualMemoId; + break; + } + case 'FinishMemoize': { + CompilerError.invariant(activeManualMemoId === instr.value.manualMemoId, { + reason: 'Expected FinishMemoize to align with previous StartMemoize instruction', + loc: instr.value.loc, + }); + activeManualMemoId = null; + break; + } + case 'CallExpression': { + const callee = instr.value.callee; + if (isSetStateType(callee.identifier) || + unconditionalSetStateFunctions.has(callee.identifier.id)) { + if (activeManualMemoId !== null) { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.RenderSetState, + reason: 'Calling setState from useMemo may trigger an infinite loop', + description: 'Each time the memo callback is evaluated it will change state. This can cause a memoization dependency to change, running the memo function again and causing an infinite loop. Instead of setting state in useMemo(), prefer deriving the value during render. (https://react.dev/reference/react/useState)', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: callee.loc, + message: 'Found setState() within useMemo()', + })); + } + else if (unconditionalBlocks.has(block.id)) { + const enableUseKeyedState = fn.env.config.enableUseKeyedState; + if (enableUseKeyedState) { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.RenderSetState, + reason: 'Cannot call setState during render', + description: 'Calling setState during render may trigger an infinite loop.\n' + + '* To reset state when other state/props change, use `const [state, setState] = useKeyedState(initialState, key)` to reset `state` when `key` changes.\n' + + '* To derive data from other state/props, compute the derived data during render without using state', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: callee.loc, + message: 'Found setState() in render', + })); + } + else { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.RenderSetState, + reason: 'Cannot call setState during render', + description: 'Calling setState during render may trigger an infinite loop.\n' + + '* To reset state when other state/props change, store the previous value in state and update conditionally: https://react.dev/reference/react/useState#storing-information-from-previous-renders\n' + + '* To derive data from other state/props, compute the derived data during render without using state', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: callee.loc, + message: 'Found setState() in render', + })); + } + } + } + break; + } + } + } + } + return errors; +} + +function validatePreservedManualMemoization(fn) { + const state = { + env: fn.env, + manualMemoState: null, + }; + visitReactiveFunction(fn, new Visitor(), state); +} +function prettyPrintScopeDependency(val) { + var _a; + let rootStr; + if (((_a = val.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named') { + rootStr = val.identifier.name.value; + } + else { + rootStr = '[unnamed]'; + } + return `${rootStr}${val.path.map(v => `${v.optional ? '?.' : '.'}${v.property}`).join('')}`; +} +var CompareDependencyResult; +(function (CompareDependencyResult) { + CompareDependencyResult[CompareDependencyResult["Ok"] = 0] = "Ok"; + CompareDependencyResult[CompareDependencyResult["RootDifference"] = 1] = "RootDifference"; + CompareDependencyResult[CompareDependencyResult["PathDifference"] = 2] = "PathDifference"; + CompareDependencyResult[CompareDependencyResult["Subpath"] = 3] = "Subpath"; + CompareDependencyResult[CompareDependencyResult["RefAccessDifference"] = 4] = "RefAccessDifference"; +})(CompareDependencyResult || (CompareDependencyResult = {})); +function merge$1(a, b) { + return Math.max(a, b); +} +function getCompareDependencyResultDescription(result) { + switch (result) { + case CompareDependencyResult.Ok: + return 'Dependencies equal'; + case CompareDependencyResult.RootDifference: + case CompareDependencyResult.PathDifference: + return 'Inferred different dependency than source'; + case CompareDependencyResult.RefAccessDifference: + return 'Differences in ref.current access'; + case CompareDependencyResult.Subpath: + return 'Inferred less specific property than source'; + } +} +function compareDeps(inferred, source) { + const rootsEqual = (inferred.root.kind === 'Global' && + source.root.kind === 'Global' && + inferred.root.identifierName === source.root.identifierName) || + (inferred.root.kind === 'NamedLocal' && + source.root.kind === 'NamedLocal' && + inferred.root.value.identifier.id === source.root.value.identifier.id); + if (!rootsEqual) { + return CompareDependencyResult.RootDifference; + } + let isSubpath = true; + for (let i = 0; i < Math.min(inferred.path.length, source.path.length); i++) { + if (inferred.path[i].property !== source.path[i].property) { + isSubpath = false; + break; + } + else if (inferred.path[i].optional !== source.path[i].optional) { + return CompareDependencyResult.PathDifference; + } + } + if (isSubpath && + (source.path.length === inferred.path.length || + (inferred.path.length >= source.path.length && + !inferred.path.some(token => token.property === 'current')))) { + return CompareDependencyResult.Ok; + } + else { + if (isSubpath) { + if (source.path.some(token => token.property === 'current') || + inferred.path.some(token => token.property === 'current')) { + return CompareDependencyResult.RefAccessDifference; + } + else { + return CompareDependencyResult.Subpath; + } + } + else { + return CompareDependencyResult.PathDifference; + } + } +} +function validateInferredDep(dep, temporaries, declsWithinMemoBlock, validDepsInMemoBlock, env, memoLocation) { + var _a; + let normalizedDep; + const maybeNormalizedRoot = temporaries.get(dep.identifier.id); + if (maybeNormalizedRoot != null) { + normalizedDep = { + root: maybeNormalizedRoot.root, + path: [...maybeNormalizedRoot.path, ...dep.path], + loc: maybeNormalizedRoot.loc, + }; + } + else { + CompilerError.invariant(((_a = dep.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named', { + reason: 'ValidatePreservedManualMemoization: expected scope dependency to be named', + loc: GeneratedSource, + }); + normalizedDep = { + root: { + kind: 'NamedLocal', + value: { + kind: 'Identifier', + identifier: dep.identifier, + loc: GeneratedSource, + effect: Effect.Read, + reactive: false, + }, + constant: false, + }, + path: [...dep.path], + loc: GeneratedSource, + }; + } + for (const decl of declsWithinMemoBlock) { + if (normalizedDep.root.kind === 'NamedLocal' && + decl === normalizedDep.root.value.identifier.declarationId) { + return; + } + } + let errorDiagnostic = null; + for (const originalDep of validDepsInMemoBlock) { + const compareResult = compareDeps(normalizedDep, originalDep); + if (compareResult === CompareDependencyResult.Ok) { + return; + } + else { + errorDiagnostic = merge$1(errorDiagnostic !== null && errorDiagnostic !== void 0 ? errorDiagnostic : compareResult, compareResult); + } + } + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.PreserveManualMemo, + reason: 'Existing memoization could not be preserved', + description: [ + 'React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. ', + 'The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected. ', + (dep.identifier.name != null && dep.identifier.name.kind === 'named') + ? `The inferred dependency was \`${prettyPrintScopeDependency(dep)}\`, but the source dependencies were [${validDepsInMemoBlock + .map(dep => printManualMemoDependency$1(dep, true)) + .join(', ')}]. ${errorDiagnostic + ? getCompareDependencyResultDescription(errorDiagnostic) + : 'Inferred dependency not present in source'}` + : '', + ] + .join('') + .trim(), + suggestions: null, + }).withDetails({ + kind: 'error', + loc: memoLocation, + message: 'Could not preserve existing manual memoization', + })); +} +class Visitor extends ReactiveFunctionVisitor { + constructor() { + super(...arguments); + this.scopes = new Set(); + this.prunedScopes = new Set(); + this.temporaries = new Map(); + } + recordDepsInValue(value, state) { + var _a, _b; + switch (value.kind) { + case 'SequenceExpression': { + for (const instr of value.instructions) { + this.visitInstruction(instr, state); + } + this.recordDepsInValue(value.value, state); + break; + } + case 'OptionalExpression': { + this.recordDepsInValue(value.value, state); + break; + } + case 'ConditionalExpression': { + this.recordDepsInValue(value.test, state); + this.recordDepsInValue(value.consequent, state); + this.recordDepsInValue(value.alternate, state); + break; + } + case 'LogicalExpression': { + this.recordDepsInValue(value.left, state); + this.recordDepsInValue(value.right, state); + break; + } + default: { + collectMaybeMemoDependencies(value, this.temporaries, false); + if (value.kind === 'StoreLocal' || + value.kind === 'StoreContext' || + value.kind === 'Destructure') { + for (const storeTarget of eachInstructionValueLValue(value)) { + (_a = state.manualMemoState) === null || _a === void 0 ? void 0 : _a.decls.add(storeTarget.identifier.declarationId); + if (((_b = storeTarget.identifier.name) === null || _b === void 0 ? void 0 : _b.kind) === 'named') { + this.temporaries.set(storeTarget.identifier.id, { + root: { + kind: 'NamedLocal', + value: storeTarget, + constant: false, + }, + path: [], + loc: storeTarget.loc, + }); + } + } + } + break; + } + } + } + recordTemporaries(instr, state) { + var _a; + const temporaries = this.temporaries; + const { lvalue, value } = instr; + const lvalId = lvalue === null || lvalue === void 0 ? void 0 : lvalue.identifier.id; + if (lvalId != null && temporaries.has(lvalId)) { + return; + } + const isNamedLocal = ((_a = lvalue === null || lvalue === void 0 ? void 0 : lvalue.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) === 'named'; + if (lvalue !== null && isNamedLocal && state.manualMemoState != null) { + state.manualMemoState.decls.add(lvalue.identifier.declarationId); + } + this.recordDepsInValue(value, state); + if (lvalue != null) { + temporaries.set(lvalue.identifier.id, { + root: { + kind: 'NamedLocal', + value: Object.assign({}, lvalue), + constant: false, + }, + path: [], + loc: lvalue.loc, + }); + } + } + visitScope(scopeBlock, state) { + this.traverseScope(scopeBlock, state); + if (state.manualMemoState != null && + state.manualMemoState.depsFromSource != null) { + for (const dep of scopeBlock.scope.dependencies) { + validateInferredDep(dep, this.temporaries, state.manualMemoState.decls, state.manualMemoState.depsFromSource, state.env, state.manualMemoState.loc); + } + } + this.scopes.add(scopeBlock.scope.id); + for (const id of scopeBlock.scope.merged) { + this.scopes.add(id); + } + } + visitPrunedScope(scopeBlock, state) { + this.traversePrunedScope(scopeBlock, state); + this.prunedScopes.add(scopeBlock.scope.id); + } + visitInstruction(instruction, state) { + var _a, _b; + this.recordTemporaries(instruction, state); + const value = instruction.value; + if (value.kind === 'StoreLocal' && + value.lvalue.kind === 'Reassign' && + state.manualMemoState != null) { + const ids = getOrInsertDefault(state.manualMemoState.reassignments, value.lvalue.place.identifier.declarationId, new Set()); + ids.add(value.value.identifier); + } + if (value.kind === 'LoadLocal' && + value.place.identifier.scope != null && + instruction.lvalue != null && + instruction.lvalue.identifier.scope == null && + state.manualMemoState != null) { + const ids = getOrInsertDefault(state.manualMemoState.reassignments, instruction.lvalue.identifier.declarationId, new Set()); + ids.add(value.place.identifier); + } + if (value.kind === 'StartMemoize') { + CompilerError.invariant(state.manualMemoState == null, { + reason: 'Unexpected nested StartMemoize instructions', + description: `Bad manual memoization ids: ${(_a = state.manualMemoState) === null || _a === void 0 ? void 0 : _a.manualMemoId}, ${value.manualMemoId}`, + loc: value.loc, + }); + if (value.hasInvalidDeps === true) { + return; + } + let depsFromSource = null; + if (value.deps != null) { + depsFromSource = value.deps; + } + state.manualMemoState = { + loc: instruction.loc, + decls: new Set(), + depsFromSource, + manualMemoId: value.manualMemoId, + reassignments: new Map(), + }; + for (const { identifier, loc } of eachInstructionValueOperand(value)) { + if (identifier.scope != null && + !this.scopes.has(identifier.scope.id) && + !this.prunedScopes.has(identifier.scope.id)) { + state.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.PreserveManualMemo, + reason: 'Existing memoization could not be preserved', + description: [ + 'React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. ', + 'This dependency may be mutated later, which could cause the value to change unexpectedly', + ].join(''), + }).withDetails({ + kind: 'error', + loc, + message: 'This dependency may be modified later', + })); + } + } + } + if (value.kind === 'FinishMemoize') { + if (state.manualMemoState == null) { + return; + } + CompilerError.invariant(state.manualMemoState.manualMemoId === value.manualMemoId, { + reason: 'Unexpected mismatch between StartMemoize and FinishMemoize', + description: `Encountered StartMemoize id=${state.manualMemoState.manualMemoId} followed by FinishMemoize id=${value.manualMemoId}`, + loc: value.loc, + }); + const reassignments = state.manualMemoState.reassignments; + state.manualMemoState = null; + if (!value.pruned) { + for (const { identifier, loc } of eachInstructionValueOperand(value)) { + let decls; + if (identifier.scope == null) { + decls = (_b = reassignments.get(identifier.declarationId)) !== null && _b !== void 0 ? _b : [identifier]; + } + else { + decls = [identifier]; + } + for (const identifier of decls) { + if (isUnmemoized(identifier, this.scopes)) { + state.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.PreserveManualMemo, + reason: 'Existing memoization could not be preserved', + description: [ + 'React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. This value was memoized in source but not in compilation output', + '', + ] + .join('') + .trim(), + }).withDetails({ + kind: 'error', + loc, + message: 'Could not preserve existing memoization', + })); + } + } + } + } + } + } +} +function isUnmemoized(operand, scopes) { + return operand.scope != null && !scopes.has(operand.scope.id); +} + +const IMPORTANT_INSTRUMENTED_TYPES = new Set([ + 'ArrowFunctionExpression', + 'AssignmentPattern', + 'ObjectMethod', + 'ExpressionStatement', + 'BreakStatement', + 'ContinueStatement', + 'ReturnStatement', + 'ThrowStatement', + 'TryStatement', + 'VariableDeclarator', + 'IfStatement', + 'ForStatement', + 'ForInStatement', + 'ForOfStatement', + 'WhileStatement', + 'DoWhileStatement', + 'SwitchStatement', + 'SwitchCase', + 'WithStatement', + 'FunctionDeclaration', + 'FunctionExpression', + 'LabeledStatement', + 'ConditionalExpression', + 'LogicalExpression', + 'VariableDeclaration', + 'Identifier', +]); +function isManualMemoization(node) { + if (libExports$1.isCallExpression(node)) { + const callee = node.callee; + if (libExports$1.isIdentifier(callee)) { + return callee.name === 'useMemo' || callee.name === 'useCallback'; + } + if (libExports$1.isMemberExpression(callee) && + libExports$1.isIdentifier(callee.property) && + libExports$1.isIdentifier(callee.object)) { + return (callee.object.name === 'React' && + (callee.property.name === 'useMemo' || + callee.property.name === 'useCallback')); + } + } + return false; +} +function locationKey(loc) { + return `${loc.start.line}:${loc.start.column}-${loc.end.line}:${loc.end.column}`; +} +function validateSourceLocations(func, generatedAst, env) { + const importantOriginalLocations = new Map(); + func.traverse({ + enter(path) { + const node = path.node; + if (!IMPORTANT_INSTRUMENTED_TYPES.has(node.type)) { + return; + } + if (isManualMemoization(node)) { + return; + } + if (libExports$1.isReturnStatement(node) && node.argument != null) { + const parentBody = path.parentPath; + const parentFunc = parentBody === null || parentBody === void 0 ? void 0 : parentBody.parentPath; + if ((parentBody === null || parentBody === void 0 ? void 0 : parentBody.isBlockStatement()) && + (parentFunc === null || parentFunc === void 0 ? void 0 : parentFunc.isArrowFunctionExpression()) && + parentBody.node.body.length === 1 && + parentBody.node.directives.length === 0) { + return; + } + } + if (node.loc) { + const key = locationKey(node.loc); + const existing = importantOriginalLocations.get(key); + if (existing) { + existing.nodeTypes.add(node.type); + } + else { + importantOriginalLocations.set(key, { + loc: node.loc, + nodeTypes: new Set([node.type]), + }); + } + } + }, + }); + const generatedLocations = new Map(); + function collectGeneratedLocations(node) { + if (node.loc) { + const key = locationKey(node.loc); + const nodeTypes = generatedLocations.get(key); + if (nodeTypes) { + nodeTypes.add(node.type); + } + else { + generatedLocations.set(key, new Set([node.type])); + } + } + const keys = libExports$1.VISITOR_KEYS[node.type]; + if (!keys) { + return; + } + for (const key of keys) { + const value = node[key]; + if (Array.isArray(value)) { + for (const item of value) { + if (libExports$1.isNode(item)) { + collectGeneratedLocations(item); + } + } + } + else if (libExports$1.isNode(value)) { + collectGeneratedLocations(value); + } + } + } + collectGeneratedLocations(generatedAst.body); + for (const outlined of generatedAst.outlined) { + collectGeneratedLocations(outlined.fn.body); + } + const strictNodeTypes = new Set([ + 'VariableDeclaration', + 'VariableDeclarator', + 'Identifier', + ]); + const reportMissingLocation = (loc, nodeType) => { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Todo, + reason: 'Important source location missing in generated code', + description: `Source location for ${nodeType} is missing in the generated output. This can cause coverage instrumentation ` + + `to fail to track this code properly, resulting in inaccurate coverage reports.`, + }).withDetails({ + kind: 'error', + loc, + message: null, + })); + }; + const reportWrongNodeType = (loc, expectedType, actualTypes) => { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Todo, + reason: 'Important source location has wrong node type in generated code', + description: `Source location for ${expectedType} exists in the generated output but with wrong node type(s): ${Array.from(actualTypes).join(', ')}. ` + + `This can cause coverage instrumentation to fail to track this code properly, resulting in inaccurate coverage reports.`, + }).withDetails({ + kind: 'error', + loc, + message: null, + })); + }; + for (const [key, { loc, nodeTypes }] of importantOriginalLocations) { + const generatedNodeTypes = generatedLocations.get(key); + if (!generatedNodeTypes) { + reportMissingLocation(loc, Array.from(nodeTypes).join(', ')); + } + else { + for (const nodeType of nodeTypes) { + if (strictNodeTypes.has(nodeType) && + !generatedNodeTypes.has(nodeType)) { + const hasValidNodeType = Array.from(generatedNodeTypes).some(genType => nodeTypes.has(genType)); + if (hasValidNodeType) { + reportMissingLocation(loc, nodeType); + } + else { + reportWrongNodeType(loc, nodeType, generatedNodeTypes); + } + } + } + } + } +} + +function validateUseMemo(fn) { + const voidMemoErrors = new CompilerError(); + const useMemos = new Set(); + const react = new Set(); + const functions = new Map(); + const unusedUseMemos = new Map(); + for (const [, block] of fn.body.blocks) { + for (const { lvalue, value } of block.instructions) { + if (unusedUseMemos.size !== 0) { + for (const operand of eachInstructionValueOperand(value)) { + unusedUseMemos.delete(operand.identifier.id); + } + } + switch (value.kind) { + case 'LoadGlobal': { + if (value.binding.name === 'useMemo') { + useMemos.add(lvalue.identifier.id); + } + else if (value.binding.name === 'React') { + react.add(lvalue.identifier.id); + } + break; + } + case 'PropertyLoad': { + if (react.has(value.object.identifier.id)) { + if (value.property === 'useMemo') { + useMemos.add(lvalue.identifier.id); + } + } + break; + } + case 'FunctionExpression': { + functions.set(lvalue.identifier.id, value); + break; + } + case 'MethodCall': + case 'CallExpression': { + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + const isUseMemo = useMemos.has(callee.identifier.id); + if (!isUseMemo || value.args.length === 0) { + continue; + } + const [arg] = value.args; + if (arg.kind !== 'Identifier') { + continue; + } + const body = functions.get(arg.identifier.id); + if (body === undefined) { + continue; + } + if (body.loweredFunc.func.params.length > 0) { + const firstParam = body.loweredFunc.func.params[0]; + const loc = firstParam.kind === 'Identifier' + ? firstParam.loc + : firstParam.place.loc; + fn.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: 'useMemo() callbacks may not accept parameters', + description: 'useMemo() callbacks are called by React to cache calculations across re-renders. They should not take parameters. Instead, directly reference the props, state, or local variables needed for the computation', + suggestions: null, + }).withDetails({ + kind: 'error', + loc, + message: 'Callbacks with parameters are not supported', + })); + } + if (body.loweredFunc.func.async || body.loweredFunc.func.generator) { + fn.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: 'useMemo() callbacks may not be async or generator functions', + description: 'useMemo() callbacks are called once and must synchronously return a value', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: body.loc, + message: 'Async and generator functions are not supported', + })); + } + validateNoContextVariableAssignment(body.loweredFunc.func, fn.env); + if (fn.env.config.validateNoVoidUseMemo) { + if (!hasNonVoidReturn(body.loweredFunc.func)) { + voidMemoErrors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.VoidUseMemo, + reason: 'useMemo() callbacks must return a value', + description: `This useMemo() callback doesn't return a value. useMemo() is for computing and caching values, not for arbitrary side effects`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc: body.loc, + message: 'useMemo() callbacks must return a value', + })); + } + else { + unusedUseMemos.set(lvalue.identifier.id, callee.loc); + } + } + break; + } + } + } + if (unusedUseMemos.size !== 0) { + for (const operand of eachTerminalOperand(block.terminal)) { + unusedUseMemos.delete(operand.identifier.id); + } + } + } + if (unusedUseMemos.size !== 0) { + for (const loc of unusedUseMemos.values()) { + voidMemoErrors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.VoidUseMemo, + reason: 'useMemo() result is unused', + description: `This useMemo() value is unused. useMemo() is for computing and caching values, not for arbitrary side effects`, + suggestions: null, + }).withDetails({ + kind: 'error', + loc, + message: 'useMemo() result is unused', + })); + } + } + fn.env.logErrors(voidMemoErrors.asResult()); +} +function validateNoContextVariableAssignment(fn, env) { + const context = new Set(fn.context.map(place => place.identifier.id)); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const value = instr.value; + switch (value.kind) { + case 'StoreContext': { + if (context.has(value.lvalue.place.identifier.id)) { + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.UseMemo, + reason: 'useMemo() callbacks may not reassign variables declared outside of the callback', + description: 'useMemo() callbacks must be pure functions and cannot reassign variables defined outside of the callback function', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: value.lvalue.place.loc, + message: 'Cannot reassign variable', + })); + } + break; + } + } + } + } +} +function hasNonVoidReturn(func) { + for (const [, block] of func.body.blocks) { + if (block.terminal.kind === 'return') { + if (block.terminal.returnVariant === 'Explicit' || + block.terminal.returnVariant === 'Implicit') { + return true; + } + } + } + return false; +} + +function validateLocalsNotReassignedAfterRender(fn) { + const contextVariables = new Set(); + const reassignment = getContextReassignment(fn, contextVariables, false, false, fn.env); + if (reassignment !== null) { + const variable = reassignment.identifier.name != null && + reassignment.identifier.name.kind === 'named' + ? `\`${reassignment.identifier.name.value}\`` + : 'variable'; + fn.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'Cannot reassign variable after render completes', + description: `Reassigning ${variable} after render has completed can cause inconsistent behavior on subsequent renders. Consider using state instead`, + }).withDetails({ + kind: 'error', + loc: reassignment.loc, + message: `Cannot reassign ${variable} after render completes`, + })); + } +} +function getContextReassignment(fn, contextVariables, isFunctionExpression, isAsync, env) { + const reassigningFunctions = new Map(); + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'FunctionExpression': + case 'ObjectMethod': { + let reassignment = getContextReassignment(value.loweredFunc.func, contextVariables, true, isAsync || value.loweredFunc.func.async, env); + if (reassignment === null) { + for (const operand of eachInstructionValueOperand(value)) { + const reassignmentFromOperand = reassigningFunctions.get(operand.identifier.id); + if (reassignmentFromOperand !== undefined) { + reassignment = reassignmentFromOperand; + break; + } + } + } + if (reassignment !== null) { + if (isAsync || value.loweredFunc.func.async) { + const variable = reassignment.identifier.name !== null && + reassignment.identifier.name.kind === 'named' + ? `\`${reassignment.identifier.name.value}\`` + : 'variable'; + env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'Cannot reassign variable in async function', + description: 'Reassigning a variable in an async function can cause inconsistent behavior on subsequent renders. Consider using state instead', + }).withDetails({ + kind: 'error', + loc: reassignment.loc, + message: `Cannot reassign ${variable}`, + })); + return null; + } + reassigningFunctions.set(lvalue.identifier.id, reassignment); + } + break; + } + case 'StoreLocal': { + const reassignment = reassigningFunctions.get(value.value.identifier.id); + if (reassignment !== undefined) { + reassigningFunctions.set(value.lvalue.place.identifier.id, reassignment); + reassigningFunctions.set(lvalue.identifier.id, reassignment); + } + break; + } + case 'LoadLocal': { + const reassignment = reassigningFunctions.get(value.place.identifier.id); + if (reassignment !== undefined) { + reassigningFunctions.set(lvalue.identifier.id, reassignment); + } + break; + } + case 'DeclareContext': { + if (!isFunctionExpression) { + contextVariables.add(value.lvalue.place.identifier.id); + } + break; + } + case 'StoreContext': { + if (isFunctionExpression) { + if (contextVariables.has(value.lvalue.place.identifier.id)) { + return value.lvalue.place; + } + } + else { + contextVariables.add(value.lvalue.place.identifier.id); + } + const reassignment = reassigningFunctions.get(value.value.identifier.id); + if (reassignment !== undefined) { + reassigningFunctions.set(value.lvalue.place.identifier.id, reassignment); + reassigningFunctions.set(lvalue.identifier.id, reassignment); + } + break; + } + default: { + let operands = eachInstructionValueOperand(value); + if (value.kind === 'CallExpression') { + const signature = getFunctionCallSignature(fn.env, value.callee.identifier.type); + if (signature === null || signature === void 0 ? void 0 : signature.noAlias) { + operands = [value.callee]; + } + } + else if (value.kind === 'MethodCall') { + const signature = getFunctionCallSignature(fn.env, value.property.identifier.type); + if (signature === null || signature === void 0 ? void 0 : signature.noAlias) { + operands = [value.receiver, value.property]; + } + } + else if (value.kind === 'TaggedTemplateExpression') { + const signature = getFunctionCallSignature(fn.env, value.tag.identifier.type); + if (signature === null || signature === void 0 ? void 0 : signature.noAlias) { + operands = [value.tag]; + } + } + for (const operand of operands) { + CompilerError.invariant(operand.effect !== Effect.Unknown, { + reason: `Expected effects to be inferred prior to ValidateLocalsNotReassignedAfterRender`, + loc: operand.loc, + }); + const reassignment = reassigningFunctions.get(operand.identifier.id); + if (reassignment !== undefined) { + if (operand.effect === Effect.Freeze) { + return reassignment; + } + else { + for (const lval of eachInstructionLValue(instr)) { + reassigningFunctions.set(lval.identifier.id, reassignment); + } + } + } + } + break; + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + const reassignment = reassigningFunctions.get(operand.identifier.id); + if (reassignment !== undefined) { + return reassignment; + } + } + } + return null; +} + +function outlineFunctions(fn, fbtOperands) { + var _a; + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + const { value, lvalue } = instr; + if (value.kind === 'FunctionExpression' || + value.kind === 'ObjectMethod') { + outlineFunctions(value.loweredFunc.func, fbtOperands); + } + if (value.kind === 'FunctionExpression' && + value.loweredFunc.func.context.length === 0 && + value.loweredFunc.func.id === null && + !fbtOperands.has(lvalue.identifier.id)) { + const loweredFunc = value.loweredFunc.func; + const id = fn.env.generateGloballyUniqueIdentifierName((_a = loweredFunc.id) !== null && _a !== void 0 ? _a : loweredFunc.nameHint); + loweredFunc.id = id.value; + fn.env.outlineFunction(loweredFunc, null); + instr.value = { + kind: 'LoadGlobal', + binding: { + kind: 'Global', + name: id.value, + }, + loc: value.loc, + }; + } + } + } +} + +function validateNoSetStateInEffects(fn, env) { + const setStateFunctions = new Map(); + const errors = new CompilerError(); + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'LoadLocal': { + if (setStateFunctions.has(instr.value.place.identifier.id)) { + setStateFunctions.set(instr.lvalue.identifier.id, instr.value.place); + } + break; + } + case 'StoreLocal': { + if (setStateFunctions.has(instr.value.value.identifier.id)) { + setStateFunctions.set(instr.value.lvalue.place.identifier.id, instr.value.value); + setStateFunctions.set(instr.lvalue.identifier.id, instr.value.value); + } + break; + } + case 'FunctionExpression': { + if ([...eachInstructionValueOperand(instr.value)].some(operand => isSetStateType(operand.identifier) || + setStateFunctions.has(operand.identifier.id))) { + const callee = getSetStateCall(instr.value.loweredFunc.func, setStateFunctions, env); + if (callee !== null) { + setStateFunctions.set(instr.lvalue.identifier.id, callee); + } + } + break; + } + case 'MethodCall': + case 'CallExpression': { + const callee = instr.value.kind === 'MethodCall' + ? instr.value.property + : instr.value.callee; + if (isUseEffectEventType(callee.identifier)) { + const arg = instr.value.args[0]; + if (arg !== undefined && arg.kind === 'Identifier') { + const setState = setStateFunctions.get(arg.identifier.id); + if (setState !== undefined) { + setStateFunctions.set(instr.lvalue.identifier.id, setState); + } + } + } + else if (isUseEffectHookType(callee.identifier) || + isUseLayoutEffectHookType(callee.identifier) || + isUseInsertionEffectHookType(callee.identifier)) { + const arg = instr.value.args[0]; + if (arg !== undefined && arg.kind === 'Identifier') { + const setState = setStateFunctions.get(arg.identifier.id); + if (setState !== undefined) { + const enableVerbose = env.config.enableVerboseNoSetStateInEffect; + if (enableVerbose) { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.EffectSetState, + reason: 'Calling setState synchronously within an effect can trigger cascading renders', + description: 'Effects are intended to synchronize state between React and external systems. ' + + 'Calling setState synchronously causes cascading renders that hurt performance.\n\n' + + 'This pattern may indicate one of several issues:\n\n' + + '**1. Non-local derived data**: If the value being set could be computed from props/state ' + + 'but requires data from a parent component, consider restructuring state ownership so the ' + + 'derivation can happen during render in the component that owns the relevant state.\n\n' + + "**2. Derived event pattern**: If you're detecting when a prop changes (e.g., `isPlaying` " + + 'transitioning from false to true), this often indicates the parent should provide an event ' + + 'callback (like `onPlay`) instead of just the current state. Request access to the original event.\n\n' + + "**3. Force update / external sync**: If you're forcing a re-render to sync with an external " + + 'data source (mutable values outside React), use `useSyncExternalStore` to properly subscribe ' + + 'to external state changes.\n\n' + + 'See: https://react.dev/learn/you-might-not-need-an-effect', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: setState.loc, + message: 'Avoid calling setState() directly within an effect', + })); + } + else { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.EffectSetState, + reason: 'Calling setState synchronously within an effect can trigger cascading renders', + description: 'Effects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. ' + + 'In general, the body of an effect should do one or both of the following:\n' + + '* Update external systems with the latest state from React.\n' + + '* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\n' + + 'Calling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. ' + + '(https://react.dev/learn/you-might-not-need-an-effect)', + suggestions: null, + }).withDetails({ + kind: 'error', + loc: setState.loc, + message: 'Avoid calling setState() directly within an effect', + })); + } + } + } + } + break; + } + } + } + } + return errors.asResult(); +} +function getSetStateCall(fn, setStateFunctions, env) { + const enableAllowSetStateFromRefsInEffects = env.config.enableAllowSetStateFromRefsInEffects; + const refDerivedValues = new Set(); + const isDerivedFromRef = (place) => { + return (refDerivedValues.has(place.identifier.id) || + isUseRefType(place.identifier) || + isRefValueType(place.identifier)); + }; + const isRefControlledBlock = enableAllowSetStateFromRefsInEffects + ? createControlDominators(fn, place => isDerivedFromRef(place)) + : () => false; + for (const [, block] of fn.body.blocks) { + if (enableAllowSetStateFromRefsInEffects) { + for (const phi of block.phis) { + if (isDerivedFromRef(phi.place)) { + continue; + } + let isPhiDerivedFromRef = false; + for (const [, operand] of phi.operands) { + if (isDerivedFromRef(operand)) { + isPhiDerivedFromRef = true; + break; + } + } + if (isPhiDerivedFromRef) { + refDerivedValues.add(phi.place.identifier.id); + } + else { + for (const [pred] of phi.operands) { + if (isRefControlledBlock(pred)) { + refDerivedValues.add(phi.place.identifier.id); + break; + } + } + } + } + } + for (const instr of block.instructions) { + if (enableAllowSetStateFromRefsInEffects) { + const hasRefOperand = Iterable_some(eachInstructionValueOperand(instr.value), isDerivedFromRef); + if (hasRefOperand) { + for (const lvalue of eachInstructionLValue(instr)) { + refDerivedValues.add(lvalue.identifier.id); + } + for (const operand of eachInstructionValueOperand(instr.value)) { + switch (operand.effect) { + case Effect.Capture: + case Effect.Store: + case Effect.ConditionallyMutate: + case Effect.ConditionallyMutateIterator: + case Effect.Mutate: { + if (isMutable(instr, operand)) { + refDerivedValues.add(operand.identifier.id); + } + break; + } + case Effect.Freeze: + case Effect.Read: { + break; + } + case Effect.Unknown: { + CompilerError.invariant(false, { + reason: 'Unexpected unknown effect', + loc: operand.loc, + }); + } + default: { + assertExhaustive$1(operand.effect, `Unexpected effect kind \`${operand.effect}\``); + } + } + } + } + if (instr.value.kind === 'PropertyLoad' && + instr.value.property === 'current' && + (isUseRefType(instr.value.object.identifier) || + isRefValueType(instr.value.object.identifier))) { + refDerivedValues.add(instr.lvalue.identifier.id); + } + } + switch (instr.value.kind) { + case 'LoadLocal': { + if (setStateFunctions.has(instr.value.place.identifier.id)) { + setStateFunctions.set(instr.lvalue.identifier.id, instr.value.place); + } + break; + } + case 'StoreLocal': { + if (setStateFunctions.has(instr.value.value.identifier.id)) { + setStateFunctions.set(instr.value.lvalue.place.identifier.id, instr.value.value); + setStateFunctions.set(instr.lvalue.identifier.id, instr.value.value); + } + break; + } + case 'CallExpression': { + const callee = instr.value.callee; + if (isSetStateType(callee.identifier) || + setStateFunctions.has(callee.identifier.id)) { + if (enableAllowSetStateFromRefsInEffects) { + const arg = instr.value.args.at(0); + if (arg !== undefined && + arg.kind === 'Identifier' && + refDerivedValues.has(arg.identifier.id)) { + return null; + } + else if (isRefControlledBlock(block.id)) { + continue; + } + } + return callee; + } + } + } + } + } + return null; +} + +function validateNoJSXInTryStatement(fn) { + const activeTryBlocks = []; + const errors = new CompilerError(); + for (const [, block] of fn.body.blocks) { + retainWhere(activeTryBlocks, id => id !== block.id); + if (activeTryBlocks.length !== 0) { + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'JsxExpression': + case 'JsxFragment': { + errors.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.ErrorBoundaries, + reason: 'Avoid constructing JSX within try/catch', + description: `React does not immediately render components when JSX is rendered, so any errors from this component will not be caught by the try/catch. To catch errors in rendering a given component, wrap that component in an error boundary. (https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)`, + }).withDetails({ + kind: 'error', + loc: value.loc, + message: 'Avoid constructing JSX within try/catch', + })); + break; + } + } + } + } + if (block.terminal.kind === 'try') { + activeTryBlocks.push(block.terminal.handler); + } + } + return errors.asResult(); +} + +function collectHoistablePropertyLoads(fn, temporaries, hoistableFromOptionals) { + const registry = new PropertyPathRegistry(); + const knownImmutableIdentifiers = new Set(); + if (fn.fnType === 'Component' || fn.fnType === 'Hook') { + for (const p of fn.params) { + if (p.kind === 'Identifier') { + knownImmutableIdentifiers.add(p.identifier.id); + } + } + } + return collectHoistablePropertyLoadsImpl(fn, { + temporaries, + knownImmutableIdentifiers, + hoistableFromOptionals, + registry, + nestedFnImmutableContext: null, + assumedInvokedFns: getAssumedInvokedFunctions(fn), + }); +} +function collectHoistablePropertyLoadsImpl(fn, context) { + const nodes = collectNonNullsInBlocks(fn, context); + propagateNonNull(fn, nodes, context.registry); + return nodes; +} +function keyByScopeId(fn, source) { + const keyedByScopeId = new Map(); + for (const [_, block] of fn.body.blocks) { + if (block.terminal.kind === 'scope') { + keyedByScopeId.set(block.terminal.scope.id, source.get(block.terminal.block)); + } + } + return keyedByScopeId; +} +class PropertyPathRegistry { + constructor() { + this.roots = new Map(); + } + getOrCreateIdentifier(identifier, reactive, loc) { + let rootNode = this.roots.get(identifier.id); + if (rootNode === undefined) { + rootNode = { + root: identifier.id, + properties: new Map(), + optionalProperties: new Map(), + fullPath: { + identifier, + reactive, + path: [], + loc, + }, + hasOptional: false, + parent: null, + }; + this.roots.set(identifier.id, rootNode); + } + else { + CompilerError.invariant(reactive === rootNode.fullPath.reactive, { + reason: '[HoistablePropertyLoads] Found inconsistencies in `reactive` flag when deduping identifier reads within the same scope', + loc: identifier.loc, + }); + } + return rootNode; + } + static getOrCreatePropertyEntry(parent, entry) { + const map = entry.optional ? parent.optionalProperties : parent.properties; + let child = map.get(entry.property); + if (child == null) { + child = { + properties: new Map(), + optionalProperties: new Map(), + parent: parent, + fullPath: { + identifier: parent.fullPath.identifier, + reactive: parent.fullPath.reactive, + path: parent.fullPath.path.concat(entry), + loc: entry.loc, + }, + hasOptional: parent.hasOptional || entry.optional, + }; + map.set(entry.property, child); + } + return child; + } + getOrCreateProperty(n) { + let currNode = this.getOrCreateIdentifier(n.identifier, n.reactive, n.loc); + if (n.path.length === 0) { + return currNode; + } + for (let i = 0; i < n.path.length - 1; i++) { + currNode = PropertyPathRegistry.getOrCreatePropertyEntry(currNode, n.path[i]); + } + return PropertyPathRegistry.getOrCreatePropertyEntry(currNode, n.path.at(-1)); + } +} +function getMaybeNonNullInInstruction(value, context) { + var _a, _b, _c; + let path = null; + if (value.kind === 'PropertyLoad') { + path = (_a = context.temporaries.get(value.object.identifier.id)) !== null && _a !== void 0 ? _a : { + identifier: value.object.identifier, + reactive: value.object.reactive, + path: [], + loc: value.loc, + }; + } + else if (value.kind === 'Destructure') { + path = (_b = context.temporaries.get(value.value.identifier.id)) !== null && _b !== void 0 ? _b : null; + } + else if (value.kind === 'ComputedLoad') { + path = (_c = context.temporaries.get(value.object.identifier.id)) !== null && _c !== void 0 ? _c : null; + } + return path != null ? context.registry.getOrCreateProperty(path) : null; +} +function isImmutableAtInstr(identifier, instr, context) { + if (context.nestedFnImmutableContext != null) { + return context.nestedFnImmutableContext.has(identifier.id); + } + else { + const mutableAtInstr = identifier.mutableRange.end > identifier.mutableRange.start + 1 && + identifier.scope != null && + inRange({ + id: instr, + }, identifier.scope.range); + return (!mutableAtInstr || context.knownImmutableIdentifiers.has(identifier.id)); + } +} +function collectNonNullsInBlocks(fn, context) { + var _a; + const knownNonNullIdentifiers = new Set(); + if (fn.fnType === 'Component' && + fn.params.length > 0 && + fn.params[0].kind === 'Identifier') { + const identifier = fn.params[0].identifier; + knownNonNullIdentifiers.add(context.registry.getOrCreateIdentifier(identifier, true, fn.params[0].loc)); + } + const nodes = new Map(); + for (const [_, block] of fn.body.blocks) { + const assumedNonNullObjects = new Set(knownNonNullIdentifiers); + const maybeOptionalChain = context.hoistableFromOptionals.get(block.id); + if (maybeOptionalChain != null) { + assumedNonNullObjects.add(context.registry.getOrCreateProperty(maybeOptionalChain)); + } + for (const instr of block.instructions) { + const maybeNonNull = getMaybeNonNullInInstruction(instr.value, context); + if (maybeNonNull != null && + isImmutableAtInstr(maybeNonNull.fullPath.identifier, instr.id, context)) { + assumedNonNullObjects.add(maybeNonNull); + } + if (instr.value.kind === 'FunctionExpression') { + const innerFn = instr.value.loweredFunc; + if (context.assumedInvokedFns.has(innerFn)) { + const innerHoistableMap = collectHoistablePropertyLoadsImpl(innerFn.func, Object.assign(Object.assign({}, context), { nestedFnImmutableContext: (_a = context.nestedFnImmutableContext) !== null && _a !== void 0 ? _a : new Set(innerFn.func.context + .filter(place => isImmutableAtInstr(place.identifier, instr.id, context)) + .map(place => place.identifier.id)) })); + const innerHoistables = assertNonNull(innerHoistableMap.get(innerFn.func.body.entry)); + for (const entry of innerHoistables.assumedNonNullObjects) { + assumedNonNullObjects.add(entry); + } + } + } + else if (fn.env.config.enablePreserveExistingMemoizationGuarantees && + instr.value.kind === 'StartMemoize' && + instr.value.deps != null) { + for (const dep of instr.value.deps) { + if (dep.root.kind === 'NamedLocal') { + if (!isImmutableAtInstr(dep.root.value.identifier, instr.id, context)) { + continue; + } + for (let i = 0; i < dep.path.length; i++) { + const pathEntry = dep.path[i]; + if (pathEntry.optional) { + break; + } + const depNode = context.registry.getOrCreateProperty({ + identifier: dep.root.value.identifier, + path: dep.path.slice(0, i), + reactive: dep.root.value.reactive, + loc: dep.loc, + }); + assumedNonNullObjects.add(depNode); + } + } + } + } + } + nodes.set(block.id, { + block, + assumedNonNullObjects, + }); + } + return nodes; +} +function propagateNonNull(fn, nodes, registry) { + const blockSuccessors = new Map(); + const terminalPreds = new Set(); + for (const [blockId, block] of fn.body.blocks) { + for (const pred of block.preds) { + getOrInsertDefault(blockSuccessors, pred, new Set()).add(blockId); + } + if (block.terminal.kind === 'throw' || block.terminal.kind === 'return') { + terminalPreds.add(blockId); + } + } + function recursivelyPropagateNonNull(nodeId, direction, traversalState) { + var _a; + if (traversalState.has(nodeId)) { + return false; + } + traversalState.set(nodeId, 'active'); + const node = nodes.get(nodeId); + if (node == null) { + CompilerError.invariant(false, { + reason: `Bad node ${nodeId}, kind: ${direction}`, + loc: GeneratedSource, + }); + } + const neighbors = Array.from(direction === 'backward' + ? ((_a = blockSuccessors.get(nodeId)) !== null && _a !== void 0 ? _a : []) + : node.block.preds); + let changed = false; + for (const pred of neighbors) { + if (!traversalState.has(pred)) { + const neighborChanged = recursivelyPropagateNonNull(pred, direction, traversalState); + changed || (changed = neighborChanged); + } + } + const neighborAccesses = Set_intersect(Array.from(neighbors) + .filter(n => traversalState.get(n) === 'done') + .map(n => assertNonNull(nodes.get(n)).assumedNonNullObjects)); + const prevObjects = assertNonNull(nodes.get(nodeId)).assumedNonNullObjects; + const mergedObjects = Set_union(prevObjects, neighborAccesses); + reduceMaybeOptionalChains(mergedObjects, registry); + assertNonNull(nodes.get(nodeId)).assumedNonNullObjects = mergedObjects; + traversalState.set(nodeId, 'done'); + changed || (changed = !Set_equal(prevObjects, mergedObjects)); + return changed; + } + const traversalState = new Map(); + const reversedBlocks = [...fn.body.blocks]; + reversedBlocks.reverse(); + let changed; + let i = 0; + do { + CompilerError.invariant(i++ < 100, { + reason: '[CollectHoistablePropertyLoads] fixed point iteration did not terminate after 100 loops', + loc: GeneratedSource, + }); + changed = false; + for (const [blockId] of fn.body.blocks) { + const forwardChanged = recursivelyPropagateNonNull(blockId, 'forward', traversalState); + changed || (changed = forwardChanged); + } + traversalState.clear(); + for (const [blockId] of reversedBlocks) { + const backwardChanged = recursivelyPropagateNonNull(blockId, 'backward', traversalState); + changed || (changed = backwardChanged); + } + traversalState.clear(); + } while (changed); +} +function assertNonNull(value, source) { + CompilerError.invariant(value != null, { + reason: 'Unexpected null', + description: source != null ? `(from ${source})` : null, + loc: GeneratedSource, + }); + return value; +} +function reduceMaybeOptionalChains(nodes, registry) { + let optionalChainNodes = Set_filter(nodes, n => n.hasOptional); + if (optionalChainNodes.size === 0) { + return; + } + let changed; + do { + changed = false; + for (const original of optionalChainNodes) { + let { identifier, path: origPath, reactive, loc: origLoc, } = original.fullPath; + let currNode = registry.getOrCreateIdentifier(identifier, reactive, origLoc); + for (let i = 0; i < origPath.length; i++) { + const entry = origPath[i]; + const nextEntry = entry.optional && nodes.has(currNode) + ? { property: entry.property, optional: false, loc: entry.loc } + : entry; + currNode = PropertyPathRegistry.getOrCreatePropertyEntry(currNode, nextEntry); + } + if (currNode !== original) { + changed = true; + optionalChainNodes.delete(original); + optionalChainNodes.add(currNode); + nodes.delete(original); + nodes.add(currNode); + } + } + } while (changed); +} +function getAssumedInvokedFunctions(fn, temporaries = new Map()) { + var _a; + const hoistableFunctions = new Set(); + for (const block of fn.body.blocks.values()) { + for (const { lvalue, value } of block.instructions) { + if (value.kind === 'FunctionExpression') { + temporaries.set(lvalue.identifier.id, { + fn: value.loweredFunc, + mayInvoke: new Set(), + }); + } + else if (value.kind === 'StoreLocal') { + const lvalue = value.lvalue.place.identifier; + const maybeLoweredFunc = temporaries.get(value.value.identifier.id); + if (maybeLoweredFunc != null) { + temporaries.set(lvalue.id, maybeLoweredFunc); + } + } + else if (value.kind === 'LoadLocal') { + const maybeLoweredFunc = temporaries.get(value.place.identifier.id); + if (maybeLoweredFunc != null) { + temporaries.set(lvalue.identifier.id, maybeLoweredFunc); + } + } + } + } + for (const block of fn.body.blocks.values()) { + for (const { lvalue, value } of block.instructions) { + if (value.kind === 'CallExpression') { + const callee = value.callee; + const maybeHook = getHookKind(fn.env, callee.identifier); + const maybeLoweredFunc = temporaries.get(callee.identifier.id); + if (maybeLoweredFunc != null) { + hoistableFunctions.add(maybeLoweredFunc.fn); + } + else if (maybeHook != null) { + for (const arg of value.args) { + if (arg.kind === 'Identifier') { + const maybeLoweredFunc = temporaries.get(arg.identifier.id); + if (maybeLoweredFunc != null) { + hoistableFunctions.add(maybeLoweredFunc.fn); + } + } + } + } + } + else if (value.kind === 'JsxExpression') { + for (const attr of value.props) { + if (attr.kind === 'JsxSpreadAttribute') { + continue; + } + const maybeLoweredFunc = temporaries.get(attr.place.identifier.id); + if (maybeLoweredFunc != null) { + hoistableFunctions.add(maybeLoweredFunc.fn); + } + } + for (const child of (_a = value.children) !== null && _a !== void 0 ? _a : []) { + const maybeLoweredFunc = temporaries.get(child.identifier.id); + if (maybeLoweredFunc != null) { + hoistableFunctions.add(maybeLoweredFunc.fn); + } + } + } + else if (value.kind === 'FunctionExpression') { + const loweredFunc = value.loweredFunc.func; + const lambdasCalled = getAssumedInvokedFunctions(loweredFunc, temporaries); + const maybeLoweredFunc = temporaries.get(lvalue.identifier.id); + if (maybeLoweredFunc != null) { + for (const called of lambdasCalled) { + maybeLoweredFunc.mayInvoke.add(called); + } + } + } + } + if (block.terminal.kind === 'return') { + const maybeLoweredFunc = temporaries.get(block.terminal.value.identifier.id); + if (maybeLoweredFunc != null) { + hoistableFunctions.add(maybeLoweredFunc.fn); + } + } + } + for (const [_, { fn, mayInvoke }] of temporaries) { + if (hoistableFunctions.has(fn)) { + for (const called of mayInvoke) { + hoistableFunctions.add(called); + } + } + } + return hoistableFunctions; +} + +var _a, _ReactiveScopeDependencyTreeHIR_hoistableObjects, _ReactiveScopeDependencyTreeHIR_deps, _ReactiveScopeDependencyTreeHIR_getOrCreateRoot, _ReactiveScopeDependencyTreeHIR_debugImpl; +class ReactiveScopeDependencyTreeHIR { + constructor(hoistableObjects) { + var _b; + _ReactiveScopeDependencyTreeHIR_hoistableObjects.set(this, new Map()); + _ReactiveScopeDependencyTreeHIR_deps.set(this, new Map()); + for (const { path, identifier, reactive, loc } of hoistableObjects) { + let currNode = __classPrivateFieldGet(_a, _a, "m", _ReactiveScopeDependencyTreeHIR_getOrCreateRoot).call(_a, identifier, reactive, __classPrivateFieldGet(this, _ReactiveScopeDependencyTreeHIR_hoistableObjects, "f"), path.length > 0 && path[0].optional ? 'Optional' : 'NonNull', loc); + for (let i = 0; i < path.length; i++) { + const prevAccessType = (_b = currNode.properties.get(path[i].property)) === null || _b === void 0 ? void 0 : _b.accessType; + const accessType = i + 1 < path.length && path[i + 1].optional ? 'Optional' : 'NonNull'; + CompilerError.invariant(prevAccessType == null || prevAccessType === accessType, { + reason: 'Conflicting access types', + loc: GeneratedSource, + }); + let nextNode = currNode.properties.get(path[i].property); + if (nextNode == null) { + nextNode = { + properties: new Map(), + accessType, + loc: path[i].loc, + }; + currNode.properties.set(path[i].property, nextNode); + } + currNode = nextNode; + } + } + } + addDependency(dep) { + const { identifier, reactive, path, loc } = dep; + let depCursor = __classPrivateFieldGet(_a, _a, "m", _ReactiveScopeDependencyTreeHIR_getOrCreateRoot).call(_a, identifier, reactive, __classPrivateFieldGet(this, _ReactiveScopeDependencyTreeHIR_deps, "f"), PropertyAccessType.UnconditionalAccess, loc); + let hoistableCursor = __classPrivateFieldGet(this, _ReactiveScopeDependencyTreeHIR_hoistableObjects, "f").get(identifier); + for (const entry of path) { + let nextHoistableCursor; + let nextDepCursor; + if (entry.optional) { + if (hoistableCursor != null) { + nextHoistableCursor = hoistableCursor === null || hoistableCursor === void 0 ? void 0 : hoistableCursor.properties.get(entry.property); + } + let accessType; + if (hoistableCursor != null && + hoistableCursor.accessType === 'NonNull') { + accessType = PropertyAccessType.UnconditionalAccess; + } + else { + accessType = PropertyAccessType.OptionalAccess; + } + nextDepCursor = makeOrMergeProperty(depCursor, entry.property, accessType, entry.loc); + } + else if (hoistableCursor != null && + hoistableCursor.accessType === 'NonNull') { + nextHoistableCursor = hoistableCursor.properties.get(entry.property); + nextDepCursor = makeOrMergeProperty(depCursor, entry.property, PropertyAccessType.UnconditionalAccess, entry.loc); + } + else { + break; + } + depCursor = nextDepCursor; + hoistableCursor = nextHoistableCursor; + } + depCursor.accessType = merge(depCursor.accessType, PropertyAccessType.OptionalDependency); + } + deriveMinimalDependencies() { + const results = new Set(); + for (const [rootId, rootNode] of __classPrivateFieldGet(this, _ReactiveScopeDependencyTreeHIR_deps, "f").entries()) { + collectMinimalDependenciesInSubtree(rootNode, rootNode.reactive, rootId, [], results); + } + return results; + } + printDeps(includeAccesses) { + let res = []; + for (const [rootId, rootNode] of __classPrivateFieldGet(this, _ReactiveScopeDependencyTreeHIR_deps, "f").entries()) { + const rootResults = printSubtree(rootNode, includeAccesses).map(result => `${printIdentifier(rootId)}.${result}`); + res.push(rootResults); + } + return res.flat().join('\n'); + } + static debug(roots) { + const buf = [`tree() [`]; + for (const [rootId, rootNode] of roots) { + buf.push(`${printIdentifier(rootId)} (${rootNode.accessType}):`); + __classPrivateFieldGet(this, _a, "m", _ReactiveScopeDependencyTreeHIR_debugImpl).call(this, buf, rootNode, 1); + } + buf.push(']'); + return buf.length > 2 ? buf.join('\n') : buf.join(''); + } +} +_a = ReactiveScopeDependencyTreeHIR, _ReactiveScopeDependencyTreeHIR_hoistableObjects = new WeakMap(), _ReactiveScopeDependencyTreeHIR_deps = new WeakMap(), _ReactiveScopeDependencyTreeHIR_getOrCreateRoot = function _ReactiveScopeDependencyTreeHIR_getOrCreateRoot(identifier, reactive, roots, defaultAccessType, loc) { + let rootNode = roots.get(identifier); + if (rootNode === undefined) { + rootNode = { + properties: new Map(), + reactive, + accessType: defaultAccessType, + loc, + }; + roots.set(identifier, rootNode); + } + else { + CompilerError.invariant(reactive === rootNode.reactive, { + reason: '[DeriveMinimalDependenciesHIR] Conflicting reactive root flag', + description: `Identifier ${printIdentifier(identifier)}`, + loc: GeneratedSource, + }); + } + return rootNode; +}, _ReactiveScopeDependencyTreeHIR_debugImpl = function _ReactiveScopeDependencyTreeHIR_debugImpl(buf, node, depth = 0) { + for (const [property, childNode] of node.properties) { + buf.push(`${' '.repeat(depth)}.${property} (${childNode.accessType}):`); + __classPrivateFieldGet(this, _a, "m", _ReactiveScopeDependencyTreeHIR_debugImpl).call(this, buf, childNode, depth + 1); + } +}; +var PropertyAccessType; +(function (PropertyAccessType) { + PropertyAccessType["OptionalAccess"] = "OptionalAccess"; + PropertyAccessType["UnconditionalAccess"] = "UnconditionalAccess"; + PropertyAccessType["OptionalDependency"] = "OptionalDependency"; + PropertyAccessType["UnconditionalDependency"] = "UnconditionalDependency"; +})(PropertyAccessType || (PropertyAccessType = {})); +function isOptional(access) { + return (access === PropertyAccessType.OptionalAccess || + access === PropertyAccessType.OptionalDependency); +} +function isDependency(access) { + return (access === PropertyAccessType.OptionalDependency || + access === PropertyAccessType.UnconditionalDependency); +} +function merge(access1, access2) { + const resultIsUnconditional = !(isOptional(access1) && isOptional(access2)); + const resultIsDependency = isDependency(access1) || isDependency(access2); + if (resultIsUnconditional) { + if (resultIsDependency) { + return PropertyAccessType.UnconditionalDependency; + } + else { + return PropertyAccessType.UnconditionalAccess; + } + } + else { + if (resultIsDependency) { + return PropertyAccessType.OptionalDependency; + } + else { + return PropertyAccessType.OptionalAccess; + } + } +} +function collectMinimalDependenciesInSubtree(node, reactive, rootIdentifier, path, results) { + if (isDependency(node.accessType)) { + results.add({ identifier: rootIdentifier, reactive, path, loc: node.loc }); + } + else { + for (const [childName, childNode] of node.properties) { + collectMinimalDependenciesInSubtree(childNode, reactive, rootIdentifier, [ + ...path, + { + property: childName, + optional: isOptional(childNode.accessType), + loc: childNode.loc, + }, + ], results); + } + } +} +function printSubtree(node, includeAccesses) { + const results = []; + for (const [propertyName, propertyNode] of node.properties) { + if (includeAccesses || isDependency(propertyNode.accessType)) { + results.push(`${propertyName} (${propertyNode.accessType})`); + } + const propertyResults = printSubtree(propertyNode, includeAccesses); + results.push(...propertyResults.map(result => `${propertyName}.${result}`)); + } + return results; +} +function makeOrMergeProperty(node, property, accessType, loc) { + let child = node.properties.get(property); + if (child == null) { + child = { + properties: new Map(), + accessType, + loc, + }; + node.properties.set(property, child); + } + else { + child.accessType = merge(child.accessType, accessType); + } + return child; +} + +function collectOptionalChainSidemap(fn) { + const context = { + currFn: fn, + blocks: fn.body.blocks, + seenOptionals: new Set(), + processedInstrsInOptional: new Set(), + temporariesReadInOptional: new Map(), + hoistableObjects: new Map(), + }; + traverseFunction(fn, context); + return { + temporariesReadInOptional: context.temporariesReadInOptional, + processedInstrsInOptional: context.processedInstrsInOptional, + hoistableObjects: context.hoistableObjects, + }; +} +function traverseFunction(fn, context) { + for (const [_, block] of fn.body.blocks) { + for (const instr of block.instructions) { + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + traverseFunction(instr.value.loweredFunc.func, Object.assign(Object.assign({}, context), { currFn: instr.value.loweredFunc.func, blocks: instr.value.loweredFunc.func.body.blocks })); + } + } + if (block.terminal.kind === 'optional' && + !context.seenOptionals.has(block.id)) { + traverseOptionalBlock(block, context, null); + } + } +} +function matchOptionalTestBlock(terminal, blocks) { + const consequentBlock = assertNonNull(blocks.get(terminal.consequent)); + if (consequentBlock.instructions.length === 2 && + consequentBlock.instructions[0].value.kind === 'PropertyLoad' && + consequentBlock.instructions[1].value.kind === 'StoreLocal') { + const propertyLoad = consequentBlock + .instructions[0]; + const storeLocal = consequentBlock.instructions[1].value; + const storeLocalInstr = consequentBlock.instructions[1]; + CompilerError.invariant(propertyLoad.value.object.identifier.id === terminal.test.identifier.id, { + reason: '[OptionalChainDeps] Inconsistent optional chaining property load', + description: `Test=${printIdentifier(terminal.test.identifier)} PropertyLoad base=${printIdentifier(propertyLoad.value.object.identifier)}`, + loc: propertyLoad.loc, + }); + CompilerError.invariant(storeLocal.value.identifier.id === propertyLoad.lvalue.identifier.id, { + reason: '[OptionalChainDeps] Unexpected storeLocal', + loc: propertyLoad.loc, + }); + if (consequentBlock.terminal.kind !== 'goto' || + consequentBlock.terminal.variant !== GotoVariant.Break) { + return null; + } + const alternate = assertNonNull(blocks.get(terminal.alternate)); + CompilerError.invariant(alternate.instructions.length === 2 && + alternate.instructions[0].value.kind === 'Primitive' && + alternate.instructions[1].value.kind === 'StoreLocal', { + reason: 'Unexpected alternate structure', + loc: terminal.loc, + }); + return { + consequentId: storeLocal.lvalue.place.identifier.id, + property: propertyLoad.value.property, + propertyId: propertyLoad.lvalue.identifier.id, + storeLocalInstr, + consequentGoto: consequentBlock.terminal.block, + propertyLoadLoc: propertyLoad.loc, + }; + } + return null; +} +function traverseOptionalBlock(optional, context, outerAlternate) { + context.seenOptionals.add(optional.id); + const maybeTest = context.blocks.get(optional.terminal.test); + let test; + let baseObject; + if (maybeTest.terminal.kind === 'branch') { + CompilerError.invariant(optional.terminal.optional, { + reason: '[OptionalChainDeps] Expect base case to be always optional', + loc: optional.terminal.loc, + }); + if (maybeTest.instructions.length === 0 || + maybeTest.instructions[0].value.kind !== 'LoadLocal') { + return null; + } + const path = []; + for (let i = 1; i < maybeTest.instructions.length; i++) { + const instrVal = maybeTest.instructions[i].value; + const prevInstr = maybeTest.instructions[i - 1]; + if (instrVal.kind === 'PropertyLoad' && + instrVal.object.identifier.id === prevInstr.lvalue.identifier.id) { + path.push({ + property: instrVal.property, + optional: false, + loc: instrVal.loc, + }); + } + else { + return null; + } + } + CompilerError.invariant(maybeTest.terminal.test.identifier.id === + maybeTest.instructions.at(-1).lvalue.identifier.id, { + reason: '[OptionalChainDeps] Unexpected test expression', + loc: maybeTest.terminal.loc, + }); + baseObject = { + identifier: maybeTest.instructions[0].value.place.identifier, + reactive: maybeTest.instructions[0].value.place.reactive, + path, + loc: maybeTest.instructions[0].value.place.loc, + }; + test = maybeTest.terminal; + } + else if (maybeTest.terminal.kind === 'optional') { + const testBlock = context.blocks.get(maybeTest.terminal.fallthrough); + if (testBlock.terminal.kind !== 'branch') { + return null; + } + const innerOptional = traverseOptionalBlock(maybeTest, context, testBlock.terminal.alternate); + if (innerOptional == null) { + return null; + } + if (testBlock.terminal.test.identifier.id !== innerOptional) { + return null; + } + if (!optional.terminal.optional) { + context.hoistableObjects.set(optional.id, assertNonNull(context.temporariesReadInOptional.get(innerOptional))); + } + baseObject = assertNonNull(context.temporariesReadInOptional.get(innerOptional)); + test = testBlock.terminal; + } + else { + return null; + } + if (test.alternate === outerAlternate) { + CompilerError.invariant(optional.instructions.length === 0, { + reason: '[OptionalChainDeps] Unexpected instructions an inner optional block. ' + + 'This indicates that the compiler may be incorrectly concatenating two unrelated optional chains', + loc: optional.terminal.loc, + }); + } + const matchConsequentResult = matchOptionalTestBlock(test, context.blocks); + if (!matchConsequentResult) { + return null; + } + CompilerError.invariant(matchConsequentResult.consequentGoto === optional.terminal.fallthrough, { + reason: '[OptionalChainDeps] Unexpected optional goto-fallthrough', + description: `${matchConsequentResult.consequentGoto} != ${optional.terminal.fallthrough}`, + loc: optional.terminal.loc, + }); + const load = { + identifier: baseObject.identifier, + reactive: baseObject.reactive, + path: [ + ...baseObject.path, + { + property: matchConsequentResult.property, + optional: optional.terminal.optional, + loc: matchConsequentResult.propertyLoadLoc, + }, + ], + loc: matchConsequentResult.propertyLoadLoc, + }; + context.processedInstrsInOptional.add(matchConsequentResult.storeLocalInstr); + context.processedInstrsInOptional.add(test); + context.temporariesReadInOptional.set(matchConsequentResult.consequentId, load); + context.temporariesReadInOptional.set(matchConsequentResult.propertyId, load); + return matchConsequentResult.consequentId; +} + +var _DependencyCollectionContext_instances, _DependencyCollectionContext_declarations, _DependencyCollectionContext_reassignments, _DependencyCollectionContext_scopes, _DependencyCollectionContext_dependencies, _DependencyCollectionContext_temporaries, _DependencyCollectionContext_temporariesUsedOutsideScope, _DependencyCollectionContext_processedInstrsInOptional, _DependencyCollectionContext_innerFnContext, _DependencyCollectionContext_checkValidDependency, _DependencyCollectionContext_isScopeActive; +function propagateScopeDependenciesHIR(fn) { + const usedOutsideDeclaringScope = findTemporariesUsedOutsideDeclaringScope(fn); + const temporaries = collectTemporariesSidemap(fn, usedOutsideDeclaringScope); + const { temporariesReadInOptional, processedInstrsInOptional, hoistableObjects, } = collectOptionalChainSidemap(fn); + const hoistablePropertyLoads = keyByScopeId(fn, collectHoistablePropertyLoads(fn, temporaries, hoistableObjects)); + const scopeDeps = collectDependencies$1(fn, usedOutsideDeclaringScope, new Map([...temporaries, ...temporariesReadInOptional]), processedInstrsInOptional); + for (const [scope, deps] of scopeDeps) { + if (deps.length === 0) { + continue; + } + const hoistables = hoistablePropertyLoads.get(scope.id); + CompilerError.invariant(hoistables != null, { + reason: '[PropagateScopeDependencies] Scope not found in tracked blocks', + loc: GeneratedSource, + }); + const tree = new ReactiveScopeDependencyTreeHIR([...hoistables.assumedNonNullObjects].map(o => o.fullPath)); + for (const dep of deps) { + tree.addDependency(Object.assign({}, dep)); + } + const candidates = tree.deriveMinimalDependencies(); + for (const candidateDep of candidates) { + if (!Iterable_some(scope.dependencies, existingDep => existingDep.identifier.declarationId === + candidateDep.identifier.declarationId && + areEqualPaths(existingDep.path, candidateDep.path))) + scope.dependencies.add(candidateDep); + } + } +} +function findTemporariesUsedOutsideDeclaringScope(fn) { + const declarations = new Map(); + const prunedScopes = new Set(); + const scopeTraversal = new ScopeBlockTraversal(); + const usedOutsideDeclaringScope = new Set(); + function handlePlace(place) { + const declaringScope = declarations.get(place.identifier.declarationId); + if (declaringScope != null && + !scopeTraversal.isScopeActive(declaringScope) && + !prunedScopes.has(declaringScope)) { + usedOutsideDeclaringScope.add(place.identifier.declarationId); + } + } + function handleInstruction(instr) { + const scope = scopeTraversal.currentScope; + if (scope == null || prunedScopes.has(scope)) { + return; + } + switch (instr.value.kind) { + case 'LoadLocal': + case 'LoadContext': + case 'PropertyLoad': { + declarations.set(instr.lvalue.identifier.declarationId, scope); + break; + } + } + } + for (const [blockId, block] of fn.body.blocks) { + scopeTraversal.recordScopes(block); + const scopeStartInfo = scopeTraversal.blockInfos.get(blockId); + if ((scopeStartInfo === null || scopeStartInfo === void 0 ? void 0 : scopeStartInfo.kind) === 'begin' && scopeStartInfo.pruned) { + prunedScopes.add(scopeStartInfo.scope.id); + } + for (const instr of block.instructions) { + for (const place of eachInstructionOperand(instr)) { + handlePlace(place); + } + handleInstruction(instr); + } + for (const place of eachTerminalOperand(block.terminal)) { + handlePlace(place); + } + } + return usedOutsideDeclaringScope; +} +function collectTemporariesSidemap(fn, usedOutsideDeclaringScope) { + const temporaries = new Map(); + collectTemporariesSidemapImpl(fn, usedOutsideDeclaringScope, temporaries, null); + return temporaries; +} +function isLoadContextMutable(instrValue, id) { + if (instrValue.kind === 'LoadContext') { + return (instrValue.place.identifier.scope != null && + id >= instrValue.place.identifier.scope.range.end); + } + return false; +} +function collectTemporariesSidemapImpl(fn, usedOutsideDeclaringScope, temporaries, innerFnContext) { + for (const [_, block] of fn.body.blocks) { + for (const { value, lvalue, id: origInstrId } of block.instructions) { + const instrId = innerFnContext != null ? innerFnContext.instrId : origInstrId; + const usedOutside = usedOutsideDeclaringScope.has(lvalue.identifier.declarationId); + if (value.kind === 'PropertyLoad' && !usedOutside) { + if (innerFnContext == null || + temporaries.has(value.object.identifier.id)) { + const property = getProperty(value.object, value.property, false, value.loc, temporaries); + temporaries.set(lvalue.identifier.id, property); + } + } + else if ((value.kind === 'LoadLocal' || isLoadContextMutable(value, instrId)) && + lvalue.identifier.name == null && + value.place.identifier.name !== null && + !usedOutside) { + if (innerFnContext == null || + fn.context.some(context => context.identifier.id === value.place.identifier.id)) { + temporaries.set(lvalue.identifier.id, { + identifier: value.place.identifier, + reactive: value.place.reactive, + path: [], + loc: value.loc, + }); + } + } + else if (value.kind === 'FunctionExpression' || + value.kind === 'ObjectMethod') { + collectTemporariesSidemapImpl(value.loweredFunc.func, usedOutsideDeclaringScope, temporaries, innerFnContext !== null && innerFnContext !== void 0 ? innerFnContext : { instrId }); + } + } + } +} +function getProperty(object, propertyName, optional, loc, temporaries) { + const resolvedDependency = temporaries.get(object.identifier.id); + let property; + if (resolvedDependency == null) { + property = { + identifier: object.identifier, + reactive: object.reactive, + path: [{ property: propertyName, optional, loc }], + loc, + }; + } + else { + property = { + identifier: resolvedDependency.identifier, + reactive: resolvedDependency.reactive, + path: [ + ...resolvedDependency.path, + { property: propertyName, optional, loc }, + ], + loc, + }; + } + return property; +} +class DependencyCollectionContext { + constructor(temporariesUsedOutsideScope, temporaries, processedInstrsInOptional) { + _DependencyCollectionContext_instances.add(this); + _DependencyCollectionContext_declarations.set(this, new Map()); + _DependencyCollectionContext_reassignments.set(this, new Map()); + _DependencyCollectionContext_scopes.set(this, empty()); + _DependencyCollectionContext_dependencies.set(this, empty()); + this.deps = new Map(); + _DependencyCollectionContext_temporaries.set(this, void 0); + _DependencyCollectionContext_temporariesUsedOutsideScope.set(this, void 0); + _DependencyCollectionContext_processedInstrsInOptional.set(this, void 0); + _DependencyCollectionContext_innerFnContext.set(this, null); + __classPrivateFieldSet(this, _DependencyCollectionContext_temporariesUsedOutsideScope, temporariesUsedOutsideScope, "f"); + __classPrivateFieldSet(this, _DependencyCollectionContext_temporaries, temporaries, "f"); + __classPrivateFieldSet(this, _DependencyCollectionContext_processedInstrsInOptional, processedInstrsInOptional, "f"); + } + enterScope(scope) { + __classPrivateFieldSet(this, _DependencyCollectionContext_dependencies, __classPrivateFieldGet(this, _DependencyCollectionContext_dependencies, "f").push([]), "f"); + __classPrivateFieldSet(this, _DependencyCollectionContext_scopes, __classPrivateFieldGet(this, _DependencyCollectionContext_scopes, "f").push(scope), "f"); + } + exitScope(scope, pruned) { + var _a; + const scopedDependencies = __classPrivateFieldGet(this, _DependencyCollectionContext_dependencies, "f").value; + CompilerError.invariant(scopedDependencies != null, { + reason: '[PropagateScopeDeps]: Unexpected scope mismatch', + loc: scope.loc, + }); + __classPrivateFieldSet(this, _DependencyCollectionContext_scopes, __classPrivateFieldGet(this, _DependencyCollectionContext_scopes, "f").pop(), "f"); + __classPrivateFieldSet(this, _DependencyCollectionContext_dependencies, __classPrivateFieldGet(this, _DependencyCollectionContext_dependencies, "f").pop(), "f"); + for (const dep of scopedDependencies) { + if (__classPrivateFieldGet(this, _DependencyCollectionContext_instances, "m", _DependencyCollectionContext_checkValidDependency).call(this, dep)) { + (_a = __classPrivateFieldGet(this, _DependencyCollectionContext_dependencies, "f").value) === null || _a === void 0 ? void 0 : _a.push(dep); + } + } + if (!pruned) { + this.deps.set(scope, scopedDependencies); + } + } + isUsedOutsideDeclaringScope(place) { + return __classPrivateFieldGet(this, _DependencyCollectionContext_temporariesUsedOutsideScope, "f").has(place.identifier.declarationId); + } + declare(identifier, decl) { + if (__classPrivateFieldGet(this, _DependencyCollectionContext_innerFnContext, "f") != null) + return; + if (!__classPrivateFieldGet(this, _DependencyCollectionContext_declarations, "f").has(identifier.declarationId)) { + __classPrivateFieldGet(this, _DependencyCollectionContext_declarations, "f").set(identifier.declarationId, decl); + } + __classPrivateFieldGet(this, _DependencyCollectionContext_reassignments, "f").set(identifier, decl); + } + hasDeclared(identifier) { + return __classPrivateFieldGet(this, _DependencyCollectionContext_declarations, "f").has(identifier.declarationId); + } + get currentScope() { + return __classPrivateFieldGet(this, _DependencyCollectionContext_scopes, "f"); + } + visitOperand(place) { + var _a; + this.visitDependency((_a = __classPrivateFieldGet(this, _DependencyCollectionContext_temporaries, "f").get(place.identifier.id)) !== null && _a !== void 0 ? _a : { + identifier: place.identifier, + reactive: place.reactive, + path: [], + loc: place.loc, + }); + } + visitProperty(object, property, optional, loc) { + const nextDependency = getProperty(object, property, optional, loc, __classPrivateFieldGet(this, _DependencyCollectionContext_temporaries, "f")); + this.visitDependency(nextDependency); + } + visitDependency(maybeDependency) { + var _a; + const originalDeclaration = __classPrivateFieldGet(this, _DependencyCollectionContext_declarations, "f").get(maybeDependency.identifier.declarationId); + if (originalDeclaration !== undefined && + originalDeclaration.scope.value !== null) { + originalDeclaration.scope.each(scope => { + if (!__classPrivateFieldGet(this, _DependencyCollectionContext_instances, "m", _DependencyCollectionContext_isScopeActive).call(this, scope) && + !Iterable_some(scope.declarations.values(), decl => decl.identifier.declarationId === + maybeDependency.identifier.declarationId)) { + scope.declarations.set(maybeDependency.identifier.id, { + identifier: maybeDependency.identifier, + scope: originalDeclaration.scope.value, + }); + } + }); + } + if (isUseRefType(maybeDependency.identifier) && + ((_a = maybeDependency.path.at(0)) === null || _a === void 0 ? void 0 : _a.property) === 'current') { + maybeDependency = { + identifier: maybeDependency.identifier, + reactive: maybeDependency.reactive, + path: [], + loc: maybeDependency.loc, + }; + } + if (__classPrivateFieldGet(this, _DependencyCollectionContext_instances, "m", _DependencyCollectionContext_checkValidDependency).call(this, maybeDependency)) { + __classPrivateFieldGet(this, _DependencyCollectionContext_dependencies, "f").value.push(maybeDependency); + } + } + visitReassignment(place) { + const currentScope = this.currentScope.value; + if (currentScope != null && + !Iterable_some(currentScope.reassignments, identifier => identifier.declarationId === place.identifier.declarationId) && + __classPrivateFieldGet(this, _DependencyCollectionContext_instances, "m", _DependencyCollectionContext_checkValidDependency).call(this, { + identifier: place.identifier, + reactive: place.reactive, + path: [], + loc: place.loc, + })) { + currentScope.reassignments.add(place.identifier); + } + } + enterInnerFn(innerFn, cb) { + var _a; + const prevContext = __classPrivateFieldGet(this, _DependencyCollectionContext_innerFnContext, "f"); + __classPrivateFieldSet(this, _DependencyCollectionContext_innerFnContext, (_a = __classPrivateFieldGet(this, _DependencyCollectionContext_innerFnContext, "f")) !== null && _a !== void 0 ? _a : { outerInstrId: innerFn.id }, "f"); + const result = cb(); + __classPrivateFieldSet(this, _DependencyCollectionContext_innerFnContext, prevContext, "f"); + return result; + } + isDeferredDependency(instr) { + return (__classPrivateFieldGet(this, _DependencyCollectionContext_processedInstrsInOptional, "f").has(instr.value) || + (instr.kind === HIRValue.Instruction && + __classPrivateFieldGet(this, _DependencyCollectionContext_temporaries, "f").has(instr.value.lvalue.identifier.id))); + } +} +_DependencyCollectionContext_declarations = new WeakMap(), _DependencyCollectionContext_reassignments = new WeakMap(), _DependencyCollectionContext_scopes = new WeakMap(), _DependencyCollectionContext_dependencies = new WeakMap(), _DependencyCollectionContext_temporaries = new WeakMap(), _DependencyCollectionContext_temporariesUsedOutsideScope = new WeakMap(), _DependencyCollectionContext_processedInstrsInOptional = new WeakMap(), _DependencyCollectionContext_innerFnContext = new WeakMap(), _DependencyCollectionContext_instances = new WeakSet(), _DependencyCollectionContext_checkValidDependency = function _DependencyCollectionContext_checkValidDependency(maybeDependency) { + var _a; + if (isRefValueType(maybeDependency.identifier)) { + return false; + } + if (isObjectMethodType(maybeDependency.identifier)) { + return false; + } + const identifier = maybeDependency.identifier; + const currentDeclaration = (_a = __classPrivateFieldGet(this, _DependencyCollectionContext_reassignments, "f").get(identifier)) !== null && _a !== void 0 ? _a : __classPrivateFieldGet(this, _DependencyCollectionContext_declarations, "f").get(identifier.declarationId); + const currentScope = this.currentScope.value; + return (currentScope != null && + currentDeclaration !== undefined && + currentDeclaration.id < currentScope.range.start); +}, _DependencyCollectionContext_isScopeActive = function _DependencyCollectionContext_isScopeActive(scope) { + if (__classPrivateFieldGet(this, _DependencyCollectionContext_scopes, "f") === null) { + return false; + } + return __classPrivateFieldGet(this, _DependencyCollectionContext_scopes, "f").find(state => state === scope); +}; +var HIRValue; +(function (HIRValue) { + HIRValue[HIRValue["Instruction"] = 1] = "Instruction"; + HIRValue[HIRValue["Terminal"] = 2] = "Terminal"; +})(HIRValue || (HIRValue = {})); +function handleInstruction(instr, context) { + const { id, value, lvalue } = instr; + context.declare(lvalue.identifier, { + id, + scope: context.currentScope, + }); + if (context.isDeferredDependency({ kind: HIRValue.Instruction, value: instr })) { + return; + } + if (value.kind === 'PropertyLoad') { + context.visitProperty(value.object, value.property, false, value.loc); + } + else if (value.kind === 'StoreLocal') { + context.visitOperand(value.value); + if (value.lvalue.kind === InstructionKind.Reassign) { + context.visitReassignment(value.lvalue.place); + } + context.declare(value.lvalue.place.identifier, { + id, + scope: context.currentScope, + }); + } + else if (value.kind === 'DeclareLocal' || value.kind === 'DeclareContext') { + if (convertHoistedLValueKind(value.lvalue.kind) === null) { + context.declare(value.lvalue.place.identifier, { + id, + scope: context.currentScope, + }); + } + } + else if (value.kind === 'Destructure') { + context.visitOperand(value.value); + for (const place of eachPatternOperand(value.lvalue.pattern)) { + if (value.lvalue.kind === InstructionKind.Reassign) { + context.visitReassignment(place); + } + context.declare(place.identifier, { + id, + scope: context.currentScope, + }); + } + } + else if (value.kind === 'StoreContext') { + if (!context.hasDeclared(value.lvalue.place.identifier) || + value.lvalue.kind !== InstructionKind.Reassign) { + context.declare(value.lvalue.place.identifier, { + id, + scope: context.currentScope, + }); + } + for (const operand of eachInstructionValueOperand(value)) { + context.visitOperand(operand); + } + } + else { + for (const operand of eachInstructionValueOperand(value)) { + context.visitOperand(operand); + } + } +} +function collectDependencies$1(fn, usedOutsideDeclaringScope, temporaries, processedInstrsInOptional) { + const context = new DependencyCollectionContext(usedOutsideDeclaringScope, temporaries, processedInstrsInOptional); + for (const param of fn.params) { + if (param.kind === 'Identifier') { + context.declare(param.identifier, { + id: makeInstructionId(0), + scope: empty(), + }); + } + else { + context.declare(param.place.identifier, { + id: makeInstructionId(0), + scope: empty(), + }); + } + } + const scopeTraversal = new ScopeBlockTraversal(); + const handleFunction = (fn) => { + for (const [blockId, block] of fn.body.blocks) { + scopeTraversal.recordScopes(block); + const scopeBlockInfo = scopeTraversal.blockInfos.get(blockId); + if ((scopeBlockInfo === null || scopeBlockInfo === void 0 ? void 0 : scopeBlockInfo.kind) === 'begin') { + context.enterScope(scopeBlockInfo.scope); + } + else if ((scopeBlockInfo === null || scopeBlockInfo === void 0 ? void 0 : scopeBlockInfo.kind) === 'end') { + context.exitScope(scopeBlockInfo.scope, scopeBlockInfo.pruned); + } + for (const phi of block.phis) { + for (const operand of phi.operands) { + const maybeOptionalChain = temporaries.get(operand[1].identifier.id); + if (maybeOptionalChain) { + context.visitDependency(maybeOptionalChain); + } + } + } + for (const instr of block.instructions) { + if (instr.value.kind === 'FunctionExpression' || + instr.value.kind === 'ObjectMethod') { + context.declare(instr.lvalue.identifier, { + id: instr.id, + scope: context.currentScope, + }); + const innerFn = instr.value.loweredFunc.func; + context.enterInnerFn(instr, () => { + handleFunction(innerFn); + }); + } + else { + handleInstruction(instr, context); + } + } + if (!context.isDeferredDependency({ + kind: HIRValue.Terminal, + value: block.terminal, + })) { + for (const place of eachTerminalOperand(block.terminal)) { + context.visitOperand(place); + } + } + } + }; + handleFunction(fn); + return context.deps; +} + +function outlineJSX(fn) { + const outlinedFns = []; + outlineJsxImpl(fn, outlinedFns); + for (const outlinedFn of outlinedFns) { + fn.env.outlineFunction(outlinedFn, 'Component'); + } +} +function outlineJsxImpl(fn, outlinedFns) { + const globals = new Map(); + function processAndOutlineJSX(state, rewriteInstr) { + if (state.jsx.length <= 1) { + return; + } + const result = process$1(fn, [...state.jsx].sort((a, b) => a.id - b.id), globals); + if (result) { + outlinedFns.push(result.fn); + rewriteInstr.set(state.jsx.at(0).id, result.instrs); + } + } + for (const [, block] of fn.body.blocks) { + const rewriteInstr = new Map(); + let state = { + jsx: [], + children: new Set(), + }; + for (let i = block.instructions.length - 1; i >= 0; i--) { + const instr = block.instructions[i]; + const { value, lvalue } = instr; + switch (value.kind) { + case 'LoadGlobal': { + globals.set(lvalue.identifier.id, instr); + break; + } + case 'FunctionExpression': { + outlineJsxImpl(value.loweredFunc.func, outlinedFns); + break; + } + case 'JsxExpression': { + if (!state.children.has(lvalue.identifier.id)) { + processAndOutlineJSX(state, rewriteInstr); + state = { + jsx: [], + children: new Set(), + }; + } + state.jsx.push(instr); + if (value.children) { + for (const child of value.children) { + state.children.add(child.identifier.id); + } + } + break; + } + case 'ArrayExpression': + case 'Await': + case 'BinaryExpression': + case 'CallExpression': + case 'ComputedDelete': + case 'ComputedLoad': + case 'ComputedStore': + case 'Debugger': + case 'DeclareContext': + case 'DeclareLocal': + case 'Destructure': + case 'FinishMemoize': + case 'GetIterator': + case 'IteratorNext': + case 'JSXText': + case 'JsxFragment': + case 'LoadContext': + case 'LoadLocal': + case 'MetaProperty': + case 'MethodCall': + case 'NewExpression': + case 'NextPropertyOf': + case 'ObjectExpression': + case 'ObjectMethod': + case 'PostfixUpdate': + case 'PrefixUpdate': + case 'Primitive': + case 'PropertyDelete': + case 'PropertyLoad': + case 'PropertyStore': + case 'RegExpLiteral': + case 'StartMemoize': + case 'StoreContext': + case 'StoreGlobal': + case 'StoreLocal': + case 'TaggedTemplateExpression': + case 'TemplateLiteral': + case 'TypeCastExpression': + case 'UnsupportedNode': + case 'UnaryExpression': { + break; + } + default: { + assertExhaustive$1(value, `Unexpected instruction: ${value}`); + } + } + } + processAndOutlineJSX(state, rewriteInstr); + if (rewriteInstr.size > 0) { + const newInstrs = []; + for (let i = 0; i < block.instructions.length; i++) { + const id = i + 1; + if (rewriteInstr.has(id)) { + const instrs = rewriteInstr.get(id); + newInstrs.push(...instrs); + } + else { + newInstrs.push(block.instructions[i]); + } + } + block.instructions = newInstrs; + } + deadCodeElimination(fn); + } +} +function process$1(fn, jsx, globals) { + if (fn.fnType === 'Component') { + return null; + } + const props = collectProps(fn.env, jsx); + if (!props) + return null; + const outlinedTag = fn.env.generateGloballyUniqueIdentifierName(null).value; + const newInstrs = emitOutlinedJsx(fn.env, jsx, props, outlinedTag); + if (!newInstrs) + return null; + const outlinedFn = emitOutlinedFn(fn.env, jsx, props, globals); + if (!outlinedFn) + return null; + outlinedFn.id = outlinedTag; + return { instrs: newInstrs, fn: outlinedFn }; +} +function collectProps(env, instructions) { + let id = 1; + function generateName(oldName) { + let newName = oldName; + while (seen.has(newName)) { + newName = `${oldName}${id++}`; + } + seen.add(newName); + env.programContext.addNewReference(newName); + return newName; + } + const attributes = []; + const jsxIds = new Set(instructions.map(i => i.lvalue.identifier.id)); + const seen = new Set(); + for (const instr of instructions) { + const { value } = instr; + for (const at of value.props) { + if (at.kind === 'JsxSpreadAttribute') { + return null; + } + if (at.kind === 'JsxAttribute') { + const newName = generateName(at.name); + attributes.push({ + originalName: at.name, + newName, + place: at.place, + }); + } + } + if (value.children) { + for (const child of value.children) { + if (jsxIds.has(child.identifier.id)) { + continue; + } + promoteTemporary(child.identifier); + const newName = generateName('t'); + attributes.push({ + originalName: child.identifier.name.value, + newName: newName, + place: child, + }); + } + } + } + return attributes; +} +function emitOutlinedJsx(env, instructions, outlinedProps, outlinedTag) { + const props = outlinedProps.map(p => ({ + kind: 'JsxAttribute', + name: p.newName, + place: p.place, + })); + const loadJsx = { + id: makeInstructionId(0), + loc: GeneratedSource, + lvalue: createTemporaryPlace(env, GeneratedSource), + value: { + kind: 'LoadGlobal', + binding: { + kind: 'ModuleLocal', + name: outlinedTag, + }, + loc: GeneratedSource, + }, + effects: null, + }; + promoteTemporaryJsxTag(loadJsx.lvalue.identifier); + const jsxExpr = { + id: makeInstructionId(0), + loc: GeneratedSource, + lvalue: instructions.at(-1).lvalue, + value: { + kind: 'JsxExpression', + tag: Object.assign({}, loadJsx.lvalue), + props, + children: null, + loc: GeneratedSource, + openingLoc: GeneratedSource, + closingLoc: GeneratedSource, + }, + effects: null, + }; + return [loadJsx, jsxExpr]; +} +function emitOutlinedFn(env, jsx, oldProps, globals) { + const instructions = []; + const oldToNewProps = createOldToNewPropsMapping(env, oldProps); + const propsObj = createTemporaryPlace(env, GeneratedSource); + promoteTemporary(propsObj.identifier); + const destructurePropsInstr = emitDestructureProps(env, propsObj, oldToNewProps); + instructions.push(destructurePropsInstr); + const updatedJsxInstructions = emitUpdatedJsx(jsx, oldToNewProps); + const loadGlobalInstrs = emitLoadGlobals(jsx, globals); + if (!loadGlobalInstrs) { + return null; + } + instructions.push(...loadGlobalInstrs); + instructions.push(...updatedJsxInstructions); + const block = { + kind: 'block', + id: makeBlockId(0), + instructions, + terminal: { + id: makeInstructionId(0), + kind: 'return', + returnVariant: 'Explicit', + loc: GeneratedSource, + value: instructions.at(-1).lvalue, + effects: null, + }, + preds: new Set(), + phis: new Set(), + }; + const fn = { + loc: GeneratedSource, + id: null, + nameHint: null, + fnType: 'Other', + env, + params: [propsObj], + returnTypeAnnotation: null, + returns: createTemporaryPlace(env, GeneratedSource), + context: [], + body: { + entry: block.id, + blocks: new Map([[block.id, block]]), + }, + generator: false, + async: false, + directives: [], + aliasingEffects: [], + }; + return fn; +} +function emitLoadGlobals(jsx, globals) { + const instructions = []; + for (const { value } of jsx) { + if (value.tag.kind === 'Identifier') { + const loadGlobalInstr = globals.get(value.tag.identifier.id); + if (!loadGlobalInstr) { + return null; + } + instructions.push(loadGlobalInstr); + } + } + return instructions; +} +function emitUpdatedJsx(jsx, oldToNewProps) { + const newInstrs = []; + const jsxIds = new Set(jsx.map(i => i.lvalue.identifier.id)); + for (const instr of jsx) { + const { value } = instr; + const newProps = []; + for (const prop of value.props) { + invariant(prop.kind === 'JsxAttribute', `Expected only attributes but found ${prop.kind}`); + if (prop.name === 'key') { + continue; + } + const newProp = oldToNewProps.get(prop.place.identifier.id); + invariant(newProp !== undefined, `Expected a new property for ${printIdentifier(prop.place.identifier)}`); + newProps.push({ + kind: 'JsxAttribute', + name: newProp.originalName, + place: newProp.place, + }); + } + let newChildren = null; + if (value.children) { + newChildren = []; + for (const child of value.children) { + if (jsxIds.has(child.identifier.id)) { + newChildren.push(Object.assign({}, child)); + continue; + } + const newChild = oldToNewProps.get(child.identifier.id); + invariant(newChild !== undefined, `Expected a new prop for ${printIdentifier(child.identifier)}`); + newChildren.push(Object.assign({}, newChild.place)); + } + } + newInstrs.push(Object.assign(Object.assign({}, instr), { value: Object.assign(Object.assign({}, value), { props: newProps, children: newChildren }) })); + } + return newInstrs; +} +function createOldToNewPropsMapping(env, oldProps) { + const oldToNewProps = new Map(); + for (const oldProp of oldProps) { + if (oldProp.originalName === 'key') { + continue; + } + const newProp = Object.assign(Object.assign({}, oldProp), { place: createTemporaryPlace(env, GeneratedSource) }); + newProp.place.identifier.name = makeIdentifierName(oldProp.newName); + oldToNewProps.set(oldProp.place.identifier.id, newProp); + } + return oldToNewProps; +} +function emitDestructureProps(env, propsObj, oldToNewProps) { + const properties = []; + for (const [_, prop] of oldToNewProps) { + properties.push({ + kind: 'ObjectProperty', + key: { + kind: 'string', + name: prop.newName, + }, + type: 'property', + place: prop.place, + }); + } + const destructurePropsInstr = { + id: makeInstructionId(0), + lvalue: createTemporaryPlace(env, GeneratedSource), + loc: GeneratedSource, + value: { + kind: 'Destructure', + lvalue: { + pattern: { + kind: 'ObjectPattern', + properties, + loc: GeneratedSource, + }, + kind: InstructionKind.Let, + }, + loc: GeneratedSource, + value: propsObj, + }, + effects: null, + }; + return destructurePropsInstr; +} + +function optimizePropsMethodCalls(fn) { + for (const [, block] of fn.body.blocks) { + for (let i = 0; i < block.instructions.length; i++) { + const instr = block.instructions[i]; + if (instr.value.kind === 'MethodCall' && + isPropsType(instr.value.receiver.identifier)) { + instr.value = { + kind: 'CallExpression', + callee: instr.value.property, + args: instr.value.args, + loc: instr.value.loc, + }; + } + } + } +} + +function validateStaticComponents(fn) { + const error = new CompilerError(); + const knownDynamicComponents = new Map(); + for (const block of fn.body.blocks.values()) { + phis: for (const phi of block.phis) { + for (const operand of phi.operands.values()) { + const loc = knownDynamicComponents.get(operand.identifier.id); + if (loc != null) { + knownDynamicComponents.set(phi.place.identifier.id, loc); + continue phis; + } + } + } + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'FunctionExpression': + case 'NewExpression': + case 'MethodCall': + case 'CallExpression': { + knownDynamicComponents.set(lvalue.identifier.id, value.loc); + break; + } + case 'LoadLocal': { + const loc = knownDynamicComponents.get(value.place.identifier.id); + if (loc != null) { + knownDynamicComponents.set(lvalue.identifier.id, loc); + } + break; + } + case 'StoreLocal': { + const loc = knownDynamicComponents.get(value.value.identifier.id); + if (loc != null) { + knownDynamicComponents.set(lvalue.identifier.id, loc); + knownDynamicComponents.set(value.lvalue.place.identifier.id, loc); + } + break; + } + case 'JsxExpression': { + if (value.tag.kind === 'Identifier') { + const location = knownDynamicComponents.get(value.tag.identifier.id); + if (location != null) { + error.pushDiagnostic(CompilerDiagnostic.create({ + category: ErrorCategory.StaticComponents, + reason: 'Cannot create components during render', + description: `Components created during render will reset their state each time they are created. Declare components outside of render`, + }) + .withDetails({ + kind: 'error', + loc: value.tag.loc, + message: 'This component is created during render', + }) + .withDetails({ + kind: 'error', + loc: location, + message: 'The component is created during render here', + })); + } + } + } + } + } + } + return error.asResult(); +} + +function validateNoFreezingKnownMutableFunctions(fn) { + const contextMutationEffects = new Map(); + function visitOperand(operand) { + if (operand.effect === Effect.Freeze) { + const effect = contextMutationEffects.get(operand.identifier.id); + if (effect != null) { + const place = effect.value; + const variable = place != null && + place.identifier.name != null && + place.identifier.name.kind === 'named' + ? `\`${place.identifier.name.value}\`` + : 'a local variable'; + fn.env.recordError(CompilerDiagnostic.create({ + category: ErrorCategory.Immutability, + reason: 'Cannot modify local variables after render completes', + description: `This argument is a function which may reassign or mutate ${variable} after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead`, + }) + .withDetails({ + kind: 'error', + loc: operand.loc, + message: `This function may (indirectly) reassign or modify ${variable} after render`, + }) + .withDetails({ + kind: 'error', + loc: effect.value.loc, + message: `This modifies ${variable}`, + })); + } + } + } + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'LoadLocal': { + const effect = contextMutationEffects.get(value.place.identifier.id); + if (effect != null) { + contextMutationEffects.set(lvalue.identifier.id, effect); + } + break; + } + case 'StoreLocal': { + const effect = contextMutationEffects.get(value.value.identifier.id); + if (effect != null) { + contextMutationEffects.set(lvalue.identifier.id, effect); + contextMutationEffects.set(value.lvalue.place.identifier.id, effect); + } + break; + } + case 'FunctionExpression': { + if (value.loweredFunc.func.aliasingEffects != null) { + const context = new Set(value.loweredFunc.func.context.map(p => p.identifier.id)); + effects: for (const effect of value.loweredFunc.func + .aliasingEffects) { + switch (effect.kind) { + case 'Mutate': + case 'MutateTransitive': { + const knownMutation = contextMutationEffects.get(effect.value.identifier.id); + if (knownMutation != null) { + contextMutationEffects.set(lvalue.identifier.id, knownMutation); + } + else if (context.has(effect.value.identifier.id) && + !isRefOrRefLikeMutableType(effect.value.identifier.type)) { + contextMutationEffects.set(lvalue.identifier.id, effect); + break effects; + } + break; + } + case 'MutateConditionally': + case 'MutateTransitiveConditionally': { + const knownMutation = contextMutationEffects.get(effect.value.identifier.id); + if (knownMutation != null) { + contextMutationEffects.set(lvalue.identifier.id, knownMutation); + } + break; + } + } + } + } + break; + } + default: { + for (const operand of eachInstructionValueOperand(value)) { + visitOperand(operand); + } + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + visitOperand(operand); + } + } +} + +function validateNoDerivedComputationsInEffects(fn) { + const candidateDependencies = new Map(); + const functions = new Map(); + const locals = new Map(); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + if (value.kind === 'LoadLocal') { + locals.set(lvalue.identifier.id, value.place.identifier.id); + } + else if (value.kind === 'ArrayExpression') { + candidateDependencies.set(lvalue.identifier.id, value); + } + else if (value.kind === 'FunctionExpression') { + functions.set(lvalue.identifier.id, value); + } + else if (value.kind === 'CallExpression' || + value.kind === 'MethodCall') { + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + if (isUseEffectHookType(callee.identifier) && + value.args.length === 2 && + value.args[0].kind === 'Identifier' && + value.args[1].kind === 'Identifier') { + const effectFunction = functions.get(value.args[0].identifier.id); + const deps = candidateDependencies.get(value.args[1].identifier.id); + if (effectFunction != null && + deps != null && + deps.elements.length !== 0 && + deps.elements.every(element => element.kind === 'Identifier')) { + const dependencies = deps.elements.map(dep => { + var _a; + CompilerError.invariant(dep.kind === 'Identifier', { + reason: `Dependency is checked as a place above`, + loc: value.loc, + }); + return (_a = locals.get(dep.identifier.id)) !== null && _a !== void 0 ? _a : dep.identifier.id; + }); + validateEffect$1(effectFunction.loweredFunc.func, dependencies, fn.env); + } + } + } + } + } +} +function validateEffect$1(effectFunction, effectDeps, env) { + for (const operand of effectFunction.context) { + if (isSetStateType(operand.identifier)) { + continue; + } + else if (effectDeps.find(dep => dep === operand.identifier.id) != null) { + continue; + } + else { + return; + } + } + for (const dep of effectDeps) { + if (effectFunction.context.find(operand => operand.identifier.id === dep) == + null) { + return; + } + } + const seenBlocks = new Set(); + const values = new Map(); + for (const dep of effectDeps) { + values.set(dep, [dep]); + } + const setStateLocations = []; + for (const block of effectFunction.body.blocks.values()) { + for (const pred of block.preds) { + if (!seenBlocks.has(pred)) { + return; + } + } + for (const phi of block.phis) { + const aggregateDeps = new Set(); + for (const operand of phi.operands.values()) { + const deps = values.get(operand.identifier.id); + if (deps != null) { + for (const dep of deps) { + aggregateDeps.add(dep); + } + } + } + if (aggregateDeps.size !== 0) { + values.set(phi.place.identifier.id, Array.from(aggregateDeps)); + } + } + for (const instr of block.instructions) { + switch (instr.value.kind) { + case 'Primitive': + case 'JSXText': + case 'LoadGlobal': { + break; + } + case 'LoadLocal': { + const deps = values.get(instr.value.place.identifier.id); + if (deps != null) { + values.set(instr.lvalue.identifier.id, deps); + } + break; + } + case 'ComputedLoad': + case 'PropertyLoad': + case 'BinaryExpression': + case 'TemplateLiteral': + case 'CallExpression': + case 'MethodCall': { + const aggregateDeps = new Set(); + for (const operand of eachInstructionValueOperand(instr.value)) { + const deps = values.get(operand.identifier.id); + if (deps != null) { + for (const dep of deps) { + aggregateDeps.add(dep); + } + } + } + if (aggregateDeps.size !== 0) { + values.set(instr.lvalue.identifier.id, Array.from(aggregateDeps)); + } + if (instr.value.kind === 'CallExpression' && + isSetStateType(instr.value.callee.identifier) && + instr.value.args.length === 1 && + instr.value.args[0].kind === 'Identifier') { + const deps = values.get(instr.value.args[0].identifier.id); + if (deps != null && new Set(deps).size === effectDeps.length) { + setStateLocations.push(instr.value.callee.loc); + } + else { + return; + } + } + break; + } + default: { + return; + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + if (values.has(operand.identifier.id)) { + return; + } + } + seenBlocks.add(block.id); + } + for (const loc of setStateLocations) { + env.recordError(new CompilerErrorDetail({ + category: ErrorCategory.EffectDerivationsOfState, + reason: 'Values derived from props and state should be calculated during render, not in an effect. (https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state)', + description: null, + loc, + suggestions: null, + })); + } +} + +const MAX_FIXPOINT_ITERATIONS = 100; +class DerivationCache { + constructor() { + this.hasChanges = false; + this.cache = new Map(); + this.previousCache = null; + } + takeSnapshot() { + this.previousCache = new Map(); + for (const [key, value] of this.cache.entries()) { + this.previousCache.set(key, { + place: value.place, + sourcesIds: new Set(value.sourcesIds), + typeOfValue: value.typeOfValue, + isStateSource: value.isStateSource, + }); + } + } + checkForChanges() { + if (this.previousCache === null) { + this.hasChanges = true; + return; + } + for (const [key, value] of this.cache.entries()) { + const previousValue = this.previousCache.get(key); + if (previousValue === undefined || + !this.isDerivationEqual(previousValue, value)) { + this.hasChanges = true; + return; + } + } + if (this.cache.size !== this.previousCache.size) { + this.hasChanges = true; + return; + } + this.hasChanges = false; + } + snapshot() { + const hasChanges = this.hasChanges; + this.hasChanges = false; + return hasChanges; + } + addDerivationEntry(derivedVar, sourcesIds, typeOfValue, isStateSource) { + var _a; + let finalIsSource = isStateSource; + if (!finalIsSource) { + for (const sourceId of sourcesIds) { + const sourceMetadata = this.cache.get(sourceId); + if ((sourceMetadata === null || sourceMetadata === void 0 ? void 0 : sourceMetadata.isStateSource) && + ((_a = sourceMetadata.place.identifier.name) === null || _a === void 0 ? void 0 : _a.kind) !== 'named') { + finalIsSource = true; + break; + } + } + } + this.cache.set(derivedVar.identifier.id, { + place: derivedVar, + sourcesIds: sourcesIds, + typeOfValue: typeOfValue !== null && typeOfValue !== void 0 ? typeOfValue : 'ignored', + isStateSource: finalIsSource, + }); + } + isDerivationEqual(a, b) { + if (a.typeOfValue !== b.typeOfValue) { + return false; + } + if (a.sourcesIds.size !== b.sourcesIds.size) { + return false; + } + for (const id of a.sourcesIds) { + if (!b.sourcesIds.has(id)) { + return false; + } + } + return true; + } +} +function isNamedIdentifier(place) { + return (place.identifier.name !== null && place.identifier.name.kind === 'named'); +} +function validateNoDerivedComputationsInEffects_exp(fn) { + const functions = new Map(); + const candidateDependencies = new Map(); + const derivationCache = new DerivationCache(); + const errors = new CompilerError(); + const effectsCache = new Map(); + const setStateLoads = new Map(); + const setStateUsages = new Map(); + const context = { + functions, + candidateDependencies, + errors, + derivationCache, + effectsCache, + setStateLoads, + setStateUsages, + }; + if (fn.fnType === 'Hook') { + for (const param of fn.params) { + if (param.kind === 'Identifier') { + context.derivationCache.cache.set(param.identifier.id, { + place: param, + sourcesIds: new Set(), + typeOfValue: 'fromProps', + isStateSource: true, + }); + } + } + } + else if (fn.fnType === 'Component') { + const props = fn.params[0]; + if (props != null && props.kind === 'Identifier') { + context.derivationCache.cache.set(props.identifier.id, { + place: props, + sourcesIds: new Set(), + typeOfValue: 'fromProps', + isStateSource: true, + }); + } + } + let iterationCount = 0; + do { + context.derivationCache.takeSnapshot(); + for (const block of fn.body.blocks.values()) { + recordPhiDerivations(block, context); + for (const instr of block.instructions) { + recordInstructionDerivations(instr, context); + } + } + context.derivationCache.checkForChanges(); + iterationCount++; + CompilerError.invariant(iterationCount < MAX_FIXPOINT_ITERATIONS, { + reason: '[ValidateNoDerivedComputationsInEffects] Fixpoint iteration failed to converge.', + description: `Fixpoint iteration exceeded ${MAX_FIXPOINT_ITERATIONS} iterations while tracking derivations. This suggests a cyclic dependency in the derivation cache.`, + loc: fn.loc, + }); + } while (context.derivationCache.snapshot()); + for (const [, effect] of effectsCache) { + validateEffect(effect.effect, effect.dependencies, context); + } + return errors.asResult(); +} +function recordPhiDerivations(block, context) { + for (const phi of block.phis) { + let typeOfValue = 'ignored'; + let sourcesIds = new Set(); + for (const operand of phi.operands.values()) { + const operandMetadata = context.derivationCache.cache.get(operand.identifier.id); + if (operandMetadata === undefined) { + continue; + } + typeOfValue = joinValue(typeOfValue, operandMetadata.typeOfValue); + sourcesIds.add(operand.identifier.id); + } + if (typeOfValue !== 'ignored') { + context.derivationCache.addDerivationEntry(phi.place, sourcesIds, typeOfValue, false); + } + } +} +function joinValue(lvalueType, valueType) { + if (lvalueType === 'ignored') + return valueType; + if (valueType === 'ignored') + return lvalueType; + if (lvalueType === valueType) + return lvalueType; + return 'fromPropsAndState'; +} +function getRootSetState(key, loads, visited = new Set()) { + if (visited.has(key)) { + return null; + } + visited.add(key); + const parentId = loads.get(key); + if (parentId === undefined) { + return null; + } + if (parentId === null) { + return key; + } + return getRootSetState(parentId, loads, visited); +} +function maybeRecordSetState(instr, loads, usages) { + for (const operand of eachInstructionLValue(instr)) { + if (instr.value.kind === 'LoadLocal' && + loads.has(instr.value.place.identifier.id)) { + loads.set(operand.identifier.id, instr.value.place.identifier.id); + } + else { + if (isSetStateType(operand.identifier)) { + loads.set(operand.identifier.id, null); + } + } + const rootSetState = getRootSetState(operand.identifier.id, loads); + if (rootSetState !== null && usages.get(rootSetState) === undefined) { + usages.set(rootSetState, new Set([operand.loc])); + } + } +} +function recordInstructionDerivations(instr, context, isFirstPass) { + var _a; + maybeRecordSetState(instr, context.setStateLoads, context.setStateUsages); + let typeOfValue = 'ignored'; + let isSource = false; + const sources = new Set(); + const { lvalue, value } = instr; + if (value.kind === 'FunctionExpression') { + context.functions.set(lvalue.identifier.id, value); + for (const [, block] of value.loweredFunc.func.body.blocks) { + recordPhiDerivations(block, context); + for (const instr of block.instructions) { + recordInstructionDerivations(instr, context); + } + } + } + else if (value.kind === 'CallExpression' || value.kind === 'MethodCall') { + const callee = value.kind === 'CallExpression' ? value.callee : value.property; + if (isUseEffectHookType(callee.identifier) && + value.args.length === 2 && + value.args[0].kind === 'Identifier' && + value.args[1].kind === 'Identifier') { + const effectFunction = context.functions.get(value.args[0].identifier.id); + const deps = context.candidateDependencies.get(value.args[1].identifier.id); + if (effectFunction != null && deps != null) { + context.effectsCache.set(value.args[0].identifier.id, { + effect: effectFunction.loweredFunc.func, + dependencies: deps, + }); + } + } + else if (isUseStateType(lvalue.identifier)) { + typeOfValue = 'fromState'; + context.derivationCache.addDerivationEntry(lvalue, new Set(), typeOfValue, true); + return; + } + } + else if (value.kind === 'ArrayExpression') { + context.candidateDependencies.set(lvalue.identifier.id, value); + } + for (const operand of eachInstructionOperand(instr)) { + if (context.setStateLoads.has(operand.identifier.id)) { + const rootSetStateId = getRootSetState(operand.identifier.id, context.setStateLoads); + if (rootSetStateId !== null) { + (_a = context.setStateUsages.get(rootSetStateId)) === null || _a === void 0 ? void 0 : _a.add(operand.loc); + } + } + const operandMetadata = context.derivationCache.cache.get(operand.identifier.id); + if (operandMetadata === undefined) { + continue; + } + typeOfValue = joinValue(typeOfValue, operandMetadata.typeOfValue); + sources.add(operand.identifier.id); + } + if (typeOfValue === 'ignored') { + return; + } + for (const lvalue of eachInstructionLValue(instr)) { + context.derivationCache.addDerivationEntry(lvalue, sources, typeOfValue, isSource); + } + if (value.kind === 'FunctionExpression') { + return; + } + for (const operand of eachInstructionOperand(instr)) { + switch (operand.effect) { + case Effect.Capture: + case Effect.Store: + case Effect.ConditionallyMutate: + case Effect.ConditionallyMutateIterator: + case Effect.Mutate: { + if (isMutable(instr, operand)) { + if (context.derivationCache.cache.has(operand.identifier.id)) { + const operandMetadata = context.derivationCache.cache.get(operand.identifier.id); + if (operandMetadata !== undefined) { + operandMetadata.typeOfValue = joinValue(typeOfValue, operandMetadata.typeOfValue); + } + } + else { + context.derivationCache.addDerivationEntry(operand, sources, typeOfValue, false); + } + } + break; + } + case Effect.Freeze: + case Effect.Read: { + break; + } + case Effect.Unknown: { + CompilerError.invariant(false, { + reason: 'Unexpected unknown effect', + loc: operand.loc, + }); + } + default: { + assertExhaustive$1(operand.effect, `Unexpected effect kind \`${operand.effect}\``); + } + } + } +} +function buildTreeNode(sourceId, context, visited = new Set()) { + const sourceMetadata = context.derivationCache.cache.get(sourceId); + if (!sourceMetadata) { + return []; + } + if (sourceMetadata.isStateSource && isNamedIdentifier(sourceMetadata.place)) { + return [ + { + name: sourceMetadata.place.identifier.name.value, + typeOfValue: sourceMetadata.typeOfValue, + isSource: sourceMetadata.isStateSource, + children: [], + }, + ]; + } + const children = []; + const namedSiblings = new Set(); + for (const childId of sourceMetadata.sourcesIds) { + CompilerError.invariant(childId !== sourceId, { + reason: 'Unexpected self-reference: a value should not have itself as a source', + loc: sourceMetadata.place.loc, + }); + const childNodes = buildTreeNode(childId, context, new Set([ + ...visited, + ...(isNamedIdentifier(sourceMetadata.place) + ? [sourceMetadata.place.identifier.name.value] + : []), + ])); + if (childNodes) { + for (const childNode of childNodes) { + if (!namedSiblings.has(childNode.name)) { + children.push(childNode); + namedSiblings.add(childNode.name); + } + } + } + } + if (isNamedIdentifier(sourceMetadata.place) && + !visited.has(sourceMetadata.place.identifier.name.value)) { + return [ + { + name: sourceMetadata.place.identifier.name.value, + typeOfValue: sourceMetadata.typeOfValue, + isSource: sourceMetadata.isStateSource, + children: children, + }, + ]; + } + return children; +} +function renderTree(node, indent = '', isLast = true, propsSet, stateSet) { + const prefix = indent + (isLast ? '└── ' : '├── '); + const childIndent = indent + (isLast ? ' ' : '│ '); + let result = `${prefix}${node.name}`; + if (node.isSource) { + let typeLabel; + if (node.typeOfValue === 'fromProps') { + propsSet.add(node.name); + typeLabel = 'Prop'; + } + else if (node.typeOfValue === 'fromState') { + stateSet.add(node.name); + typeLabel = 'State'; + } + else { + propsSet.add(node.name); + stateSet.add(node.name); + typeLabel = 'Prop and State'; + } + result += ` (${typeLabel})`; + } + if (node.children.length > 0) { + result += '\n'; + node.children.forEach((child, index) => { + const isLastChild = index === node.children.length - 1; + result += renderTree(child, childIndent, isLastChild, propsSet, stateSet); + if (index < node.children.length - 1) { + result += '\n'; + } + }); + } + return result; +} +function getFnLocalDeps(fn) { + if (!fn) { + return undefined; + } + const deps = new Set(); + for (const [, block] of fn.loweredFunc.func.body.blocks) { + for (const instr of block.instructions) { + if (instr.value.kind === 'LoadLocal') { + deps.add(instr.value.place.identifier.id); + } + } + } + return deps; +} +function validateEffect(effectFunction, dependencies, context) { + var _a; + const seenBlocks = new Set(); + const effectDerivedSetStateCalls = []; + const effectSetStateUsages = new Map(); + for (const dep of dependencies.elements) { + if (dep.kind === 'Identifier') { + const root = getRootSetState(dep.identifier.id, context.setStateLoads); + if (root !== null) { + effectSetStateUsages.set(root, new Set([dep.loc])); + } + } + } + let cleanUpFunctionDeps; + const globals = new Set(); + for (const block of effectFunction.body.blocks.values()) { + if (block.terminal.kind === 'return' && + block.terminal.returnVariant === 'Explicit') { + cleanUpFunctionDeps = getFnLocalDeps(context.functions.get(block.terminal.value.identifier.id)); + } + for (const pred of block.preds) { + if (!seenBlocks.has(pred)) { + return; + } + } + for (const instr of block.instructions) { + if (isUseRefType(instr.lvalue.identifier)) { + return; + } + maybeRecordSetState(instr, context.setStateLoads, effectSetStateUsages); + for (const operand of eachInstructionOperand(instr)) { + if (context.setStateLoads.has(operand.identifier.id)) { + const rootSetStateId = getRootSetState(operand.identifier.id, context.setStateLoads); + if (rootSetStateId !== null) { + (_a = effectSetStateUsages.get(rootSetStateId)) === null || _a === void 0 ? void 0 : _a.add(operand.loc); + } + } + } + if (instr.value.kind === 'CallExpression' && + isSetStateType(instr.value.callee.identifier) && + instr.value.args.length === 1 && + instr.value.args[0].kind === 'Identifier') { + const calleeMetadata = context.derivationCache.cache.get(instr.value.callee.identifier.id); + if ((calleeMetadata === null || calleeMetadata === void 0 ? void 0 : calleeMetadata.typeOfValue) != 'fromState') { + continue; + } + const argMetadata = context.derivationCache.cache.get(instr.value.args[0].identifier.id); + if (argMetadata !== undefined) { + effectDerivedSetStateCalls.push({ + value: instr.value, + id: instr.value.callee.identifier.id, + sourceIds: argMetadata.sourcesIds, + typeOfValue: argMetadata.typeOfValue, + }); + } + } + else if (instr.value.kind === 'CallExpression') { + const calleeMetadata = context.derivationCache.cache.get(instr.value.callee.identifier.id); + if (calleeMetadata !== undefined && + (calleeMetadata.typeOfValue === 'fromProps' || + calleeMetadata.typeOfValue === 'fromPropsAndState')) { + return; + } + if (globals.has(instr.value.callee.identifier.id)) { + return; + } + } + else if (instr.value.kind === 'LoadGlobal') { + globals.add(instr.lvalue.identifier.id); + for (const operand of eachInstructionOperand(instr)) { + globals.add(operand.identifier.id); + } + } + } + seenBlocks.add(block.id); + } + for (const derivedSetStateCall of effectDerivedSetStateCalls) { + const rootSetStateCall = getRootSetState(derivedSetStateCall.id, context.setStateLoads); + if (rootSetStateCall !== null && + effectSetStateUsages.has(rootSetStateCall) && + context.setStateUsages.has(rootSetStateCall) && + effectSetStateUsages.get(rootSetStateCall).size === + context.setStateUsages.get(rootSetStateCall).size - 1) { + const propsSet = new Set(); + const stateSet = new Set(); + const rootNodesMap = new Map(); + for (const id of derivedSetStateCall.sourceIds) { + const nodes = buildTreeNode(id, context); + for (const node of nodes) { + if (!rootNodesMap.has(node.name)) { + rootNodesMap.set(node.name, node); + } + } + } + const rootNodes = Array.from(rootNodesMap.values()); + const trees = rootNodes.map((node, index) => renderTree(node, '', index === rootNodes.length - 1, propsSet, stateSet)); + for (const dep of derivedSetStateCall.sourceIds) { + if (cleanUpFunctionDeps !== undefined && cleanUpFunctionDeps.has(dep)) { + return; + } + } + const propsArr = Array.from(propsSet); + const stateArr = Array.from(stateSet); + let rootSources = ''; + if (propsArr.length > 0) { + rootSources += `Props: [${propsArr.join(', ')}]`; + } + if (stateArr.length > 0) { + if (rootSources) + rootSources += '\n'; + rootSources += `State: [${stateArr.join(', ')}]`; + } + const description = `Using an effect triggers an additional render which can hurt performance and user experience, potentially briefly showing stale values to the user + +This setState call is setting a derived value that depends on the following reactive sources: + +${rootSources} + +Data Flow Tree: +${trees.join('\n')} + +See: https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state`; + context.errors.pushDiagnostic(CompilerDiagnostic.create({ + description: description, + category: ErrorCategory.EffectDerivationsOfState, + reason: 'You might not need an effect. Derive values in render, not effects.', + }).withDetails({ + kind: 'error', + loc: derivedSetStateCall.value.callee.loc, + message: 'This should be computed during render, not in an effect', + })); + } + } +} + +function nameAnonymousFunctions(fn) { + if (fn.id == null) { + return; + } + const parentName = fn.id; + const functions = nameAnonymousFunctionsImpl(fn); + function visit(node, prefix) { + var _a, _b; + if (node.generatedName != null && node.fn.nameHint == null) { + const name = `${prefix}${node.generatedName}]`; + node.fn.nameHint = name; + node.fn.loweredFunc.func.nameHint = name; + } + const nextPrefix = `${prefix}${(_b = (_a = node.generatedName) !== null && _a !== void 0 ? _a : node.fn.name) !== null && _b !== void 0 ? _b : ''} > `; + for (const inner of node.inner) { + visit(inner, nextPrefix); + } + } + for (const node of functions) { + visit(node, `${parentName}[`); + } +} +function nameAnonymousFunctionsImpl(fn) { + var _a, _b; + const functions = new Map(); + const names = new Map(); + const nodes = []; + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'LoadGlobal': { + names.set(lvalue.identifier.id, value.binding.name); + break; + } + case 'LoadContext': + case 'LoadLocal': { + const name = value.place.identifier.name; + if (name != null && name.kind === 'named') { + names.set(lvalue.identifier.id, name.value); + } + const func = functions.get(value.place.identifier.id); + if (func != null) { + functions.set(lvalue.identifier.id, func); + } + break; + } + case 'PropertyLoad': { + const objectName = names.get(value.object.identifier.id); + if (objectName != null) { + names.set(lvalue.identifier.id, `${objectName}.${String(value.property)}`); + } + break; + } + case 'FunctionExpression': { + const inner = nameAnonymousFunctionsImpl(value.loweredFunc.func); + const node = { + fn: value, + generatedName: null, + inner, + }; + nodes.push(node); + if (value.name == null) { + functions.set(lvalue.identifier.id, node); + } + break; + } + case 'StoreContext': + case 'StoreLocal': { + const node = functions.get(value.value.identifier.id); + const variableName = value.lvalue.place.identifier.name; + if (node != null && + node.generatedName == null && + variableName != null && + variableName.kind === 'named') { + node.generatedName = variableName.value; + functions.delete(value.value.identifier.id); + } + break; + } + case 'CallExpression': + case 'MethodCall': { + const callee = value.kind === 'MethodCall' ? value.property : value.callee; + const hookKind = getHookKind(fn.env, callee.identifier); + let calleeName = null; + if (hookKind != null && hookKind !== 'Custom') { + calleeName = hookKind; + } + else { + calleeName = (_a = names.get(callee.identifier.id)) !== null && _a !== void 0 ? _a : '(anonymous)'; + } + let fnArgCount = 0; + for (const arg of value.args) { + if (arg.kind === 'Identifier' && functions.has(arg.identifier.id)) { + fnArgCount++; + } + } + for (let i = 0; i < value.args.length; i++) { + const arg = value.args[i]; + if (arg.kind === 'Spread') { + continue; + } + const node = functions.get(arg.identifier.id); + if (node != null && node.generatedName == null) { + const generatedName = fnArgCount > 1 ? `${calleeName}(arg${i})` : `${calleeName}()`; + node.generatedName = generatedName; + functions.delete(arg.identifier.id); + } + } + break; + } + case 'JsxExpression': { + for (const attr of value.props) { + if (attr.kind === 'JsxSpreadAttribute') { + continue; + } + const node = functions.get(attr.place.identifier.id); + if (node != null && node.generatedName == null) { + const elementName = value.tag.kind === 'BuiltinTag' + ? value.tag.name + : ((_b = names.get(value.tag.identifier.id)) !== null && _b !== void 0 ? _b : null); + const propName = elementName == null + ? attr.name + : `<${elementName}>.${attr.name}`; + node.generatedName = `${propName}`; + functions.delete(attr.place.identifier.id); + } + } + break; + } + } + } + } + return nodes; +} + +function optimizeForSSR(fn) { + const inlinedState = new Map(); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'Destructure': { + if (inlinedState.has(value.value.identifier.id) && + value.lvalue.pattern.kind === 'ArrayPattern' && + value.lvalue.pattern.items.length >= 1 && + value.lvalue.pattern.items[0].kind === 'Identifier') { + continue; + } + break; + } + case 'MethodCall': + case 'CallExpression': { + const calleee = value.kind === 'CallExpression' ? value.callee : value.property; + const hookKind = getHookKind(fn.env, calleee.identifier); + switch (hookKind) { + case 'useReducer': { + if (value.args.length === 2 && + value.args[1].kind === 'Identifier') { + const arg = value.args[1]; + const replace = { + kind: 'LoadLocal', + place: arg, + loc: arg.loc, + }; + inlinedState.set(instr.lvalue.identifier.id, replace); + } + else if (value.args.length === 3 && + value.args[1].kind === 'Identifier' && + value.args[2].kind === 'Identifier') { + const arg = value.args[1]; + const initializer = value.args[2]; + const replace = { + kind: 'CallExpression', + callee: initializer, + args: [arg], + loc: value.loc, + }; + inlinedState.set(instr.lvalue.identifier.id, replace); + } + break; + } + case 'useState': { + if (value.args.length === 1 && + value.args[0].kind === 'Identifier') { + const arg = value.args[0]; + if (isPrimitiveType(arg.identifier) || + isPlainObjectType(arg.identifier) || + isArrayType(arg.identifier)) { + const replace = { + kind: 'LoadLocal', + place: arg, + loc: arg.loc, + }; + inlinedState.set(instr.lvalue.identifier.id, replace); + } + } + break; + } + } + } + } + if (inlinedState.size !== 0) { + for (const operand of eachInstructionValueOperand(value)) { + inlinedState.delete(operand.identifier.id); + } + } + } + if (inlinedState.size !== 0) { + for (const operand of eachTerminalOperand(block.terminal)) { + inlinedState.delete(operand.identifier.id); + } + } + } + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + const { value } = instr; + switch (value.kind) { + case 'FunctionExpression': { + if (hasKnownNonRenderCall(value.loweredFunc.func)) { + instr.value = { + kind: 'Primitive', + value: undefined, + loc: value.loc, + }; + } + break; + } + case 'JsxExpression': { + if (value.tag.kind === 'BuiltinTag' && + value.tag.name.indexOf('-') === -1) { + const tag = value.tag.name; + retainWhere(value.props, prop => { + return (prop.kind === 'JsxSpreadAttribute' || + (!isKnownEventHandler(tag, prop.name) && prop.name !== 'ref')); + }); + } + break; + } + case 'Destructure': { + if (inlinedState.has(value.value.identifier.id)) { + CompilerError.invariant(value.lvalue.pattern.kind === 'ArrayPattern' && + value.lvalue.pattern.items.length >= 1 && + value.lvalue.pattern.items[0].kind === 'Identifier', { + reason: 'Expected a valid destructuring pattern for inlined state', + message: 'Expected a valid destructuring pattern', + loc: value.loc, + }); + const store = { + kind: 'StoreLocal', + loc: value.loc, + type: null, + lvalue: { + kind: value.lvalue.kind, + place: value.lvalue.pattern.items[0], + }, + value: value.value, + }; + instr.value = store; + } + break; + } + case 'MethodCall': + case 'CallExpression': { + const calleee = value.kind === 'CallExpression' ? value.callee : value.property; + const hookKind = getHookKind(fn.env, calleee.identifier); + switch (hookKind) { + case 'useEffectEvent': { + if (value.args.length === 1 && + value.args[0].kind === 'Identifier') { + const load = { + kind: 'LoadLocal', + place: value.args[0], + loc: value.loc, + }; + instr.value = load; + } + break; + } + case 'useEffect': + case 'useLayoutEffect': + case 'useInsertionEffect': { + instr.value = { + kind: 'Primitive', + value: undefined, + loc: value.loc, + }; + break; + } + case 'useReducer': + case 'useState': { + const replace = inlinedState.get(instr.lvalue.identifier.id); + if (replace != null) { + instr.value = replace; + } + break; + } + } + } + } + } + } +} +function hasKnownNonRenderCall(fn) { + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + if (instr.value.kind === 'CallExpression' && + (isSetStateType(instr.value.callee.identifier) || + isStartTransitionType(instr.value.callee.identifier))) { + return true; + } + } + } + return false; +} +const EVENT_HANDLER_PATTERN = /^on[A-Z]/; +function isKnownEventHandler(_tag, prop) { + return EVENT_HANDLER_PATTERN.test(prop); +} + +function validateExhaustiveDependencies(fn) { + const env = fn.env; + const reactive = collectReactiveIdentifiersHIR(fn); + const temporaries = new Map(); + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + temporaries.set(place.identifier.id, { + kind: 'Local', + identifier: place.identifier, + path: [], + context: false, + loc: place.loc, + }); + } + let startMemo = null; + function onStartMemoize(value, dependencies, locals) { + CompilerError.invariant(startMemo == null, { + reason: 'Unexpected nested memo calls', + loc: value.loc, + }); + startMemo = value; + dependencies.clear(); + locals.clear(); + } + function onFinishMemoize(value, dependencies, locals) { + var _a; + CompilerError.invariant(startMemo != null && startMemo.manualMemoId === value.manualMemoId, { + reason: 'Found FinishMemoize without corresponding StartMemoize', + loc: value.loc, + }); + if (env.config.validateExhaustiveMemoizationDependencies) { + visitCandidateDependency(value.decl, temporaries, dependencies, locals); + const inferred = Array.from(dependencies); + const diagnostic = validateDependencies(inferred, (_a = startMemo.deps) !== null && _a !== void 0 ? _a : [], reactive, startMemo.depsLoc, ErrorCategory.MemoDependencies, 'all'); + if (diagnostic != null) { + fn.env.recordError(diagnostic); + startMemo.hasInvalidDeps = true; + } + } + dependencies.clear(); + locals.clear(); + startMemo = null; + } + collectDependencies(fn, temporaries, { + onStartMemoize, + onFinishMemoize, + onEffect: (inferred, manual, manualMemoLoc) => { + if (env.config.validateExhaustiveEffectDependencies === 'off') { + return; + } + const manualDeps = []; + for (const dep of manual) { + if (dep.kind === 'Local') { + manualDeps.push({ + root: { + kind: 'NamedLocal', + constant: false, + value: { + effect: Effect.Read, + identifier: dep.identifier, + kind: 'Identifier', + loc: dep.loc, + reactive: reactive.has(dep.identifier.id), + }, + }, + path: dep.path, + loc: dep.loc, + }); + } + else { + manualDeps.push({ + root: { + kind: 'Global', + identifierName: dep.binding.name, + }, + path: [], + loc: GeneratedSource, + }); + } + } + const effectReportMode = typeof env.config.validateExhaustiveEffectDependencies === 'string' + ? env.config.validateExhaustiveEffectDependencies + : 'all'; + const diagnostic = validateDependencies(Array.from(inferred), manualDeps, reactive, manualMemoLoc, ErrorCategory.EffectExhaustiveDependencies, effectReportMode); + if (diagnostic != null) { + fn.env.recordError(diagnostic); + } + }, + }, false); +} +function validateDependencies(inferred, manualDependencies, reactive, manualMemoLoc, category, exhaustiveDepsReportMode) { + var _a, _b, _c, _d; + inferred.sort((a, b) => { + var _a, _b; + if (a.kind === 'Global' && b.kind == 'Global') { + return a.binding.name.localeCompare(b.binding.name); + } + else if (a.kind == 'Local' && b.kind == 'Local') { + CompilerError.invariant(a.identifier.name != null && + a.identifier.name.kind === 'named' && + b.identifier.name != null && + b.identifier.name.kind === 'named', { + reason: 'Expected dependencies to be named variables', + loc: a.loc, + }); + if (a.identifier.id !== b.identifier.id) { + return a.identifier.name.value.localeCompare(b.identifier.name.value); + } + if (a.path.length !== b.path.length) { + return a.path.length - b.path.length; + } + for (let i = 0; i < a.path.length; i++) { + const aProperty = a.path[i]; + const bProperty = b.path[i]; + const aOptional = aProperty.optional ? 0 : 1; + const bOptional = bProperty.optional ? 0 : 1; + if (aOptional !== bOptional) { + return aOptional - bOptional; + } + else if (aProperty.property !== bProperty.property) { + return String(aProperty.property).localeCompare(String(bProperty.property)); + } + } + return 0; + } + else { + const aName = a.kind === 'Global' ? a.binding.name : (_a = a.identifier.name) === null || _a === void 0 ? void 0 : _a.value; + const bName = b.kind === 'Global' ? b.binding.name : (_b = b.identifier.name) === null || _b === void 0 ? void 0 : _b.value; + if (aName != null && bName != null) { + return aName.localeCompare(bName); + } + return 0; + } + }); + retainWhere(inferred, (dep, ix) => { + const match = inferred.findIndex(prevDep => { + return (isEqualTemporary(prevDep, dep) || + (prevDep.kind === 'Local' && + dep.kind === 'Local' && + prevDep.identifier.id === dep.identifier.id && + isSubPath(prevDep.path, dep.path))); + }); + return match === -1 || match >= ix; + }); + const matched = new Set(); + const missing = []; + const extra = []; + for (const inferredDependency of inferred) { + if (inferredDependency.kind === 'Global') { + for (const manualDependency of manualDependencies) { + if (manualDependency.root.kind === 'Global' && + manualDependency.root.identifierName === + inferredDependency.binding.name) { + matched.add(manualDependency); + extra.push(manualDependency); + } + } + continue; + } + CompilerError.invariant(inferredDependency.kind === 'Local', { + reason: 'Unexpected function dependency', + loc: inferredDependency.loc, + }); + if (isEffectEventFunctionType(inferredDependency.identifier)) { + continue; + } + let hasMatchingManualDependency = false; + for (const manualDependency of manualDependencies) { + if (manualDependency.root.kind === 'NamedLocal' && + manualDependency.root.value.identifier.id === + inferredDependency.identifier.id && + (areEqualPaths(manualDependency.path, inferredDependency.path) || + isSubPathIgnoringOptionals(manualDependency.path, inferredDependency.path))) { + hasMatchingManualDependency = true; + matched.add(manualDependency); + } + } + if (hasMatchingManualDependency || + isOptionalDependency(inferredDependency, reactive)) { + continue; + } + missing.push(inferredDependency); + } + for (const dep of manualDependencies) { + if (matched.has(dep)) { + continue; + } + if (dep.root.kind === 'NamedLocal' && dep.root.constant) { + CompilerError.invariant(!dep.root.value.reactive && isPrimitiveType(dep.root.value.identifier), { + reason: 'Expected constant-folded dependency to be non-reactive', + loc: dep.root.value.loc, + }); + continue; + } + extra.push(dep); + } + const filteredMissing = exhaustiveDepsReportMode === 'extra-only' ? [] : missing; + const filteredExtra = exhaustiveDepsReportMode === 'missing-only' ? [] : extra; + if (filteredMissing.length !== 0 || filteredExtra.length !== 0) { + let suggestion = null; + if (manualMemoLoc != null && + typeof manualMemoLoc !== 'symbol' && + manualMemoLoc.start.index != null && + manualMemoLoc.end.index != null) { + suggestion = { + description: 'Update dependencies', + range: [manualMemoLoc.start.index, manualMemoLoc.end.index], + op: CompilerSuggestionOperation.Replace, + text: `[${inferred + .filter(dep => dep.kind === 'Local' && + !isOptionalDependency(dep, reactive) && + !isEffectEventFunctionType(dep.identifier)) + .map(printInferredDependency) + .join(', ')}]`, + }; + } + const diagnostic = createDiagnostic(category, filteredMissing, filteredExtra, suggestion); + for (const dep of filteredMissing) { + let reactiveStableValueHint = ''; + if (isStableType(dep.identifier)) { + reactiveStableValueHint = + '. Refs, setState functions, and other "stable" values generally do not need to be added ' + + 'as dependencies, but this variable may change over time to point to different values'; + } + diagnostic.withDetails({ + kind: 'error', + message: `Missing dependency \`${printInferredDependency(dep)}\`${reactiveStableValueHint}`, + loc: dep.loc, + }); + } + for (const dep of filteredExtra) { + if (dep.root.kind === 'Global') { + diagnostic.withDetails({ + kind: 'error', + message: `Unnecessary dependency \`${printManualMemoDependency(dep)}\`. ` + + 'Values declared outside of a component/hook should not be listed as ' + + 'dependencies as the component will not re-render if they change', + loc: (_a = dep.loc) !== null && _a !== void 0 ? _a : manualMemoLoc, + }); + } + else { + const root = dep.root.value; + const matchingInferred = inferred.find((inferredDep) => { + return (inferredDep.kind === 'Local' && + inferredDep.identifier.id === root.identifier.id && + isSubPathIgnoringOptionals(inferredDep.path, dep.path)); + }); + if (matchingInferred != null && + isEffectEventFunctionType(matchingInferred.identifier)) { + diagnostic.withDetails({ + kind: 'error', + message: `Functions returned from \`useEffectEvent\` must not be included in the dependency array. ` + + `Remove \`${printManualMemoDependency(dep)}\` from the dependencies.`, + loc: (_b = dep.loc) !== null && _b !== void 0 ? _b : manualMemoLoc, + }); + } + else if (matchingInferred != null && + !isOptionalDependency(matchingInferred, reactive)) { + diagnostic.withDetails({ + kind: 'error', + message: `Overly precise dependency \`${printManualMemoDependency(dep)}\`, ` + + `use \`${printInferredDependency(matchingInferred)}\` instead`, + loc: (_c = dep.loc) !== null && _c !== void 0 ? _c : manualMemoLoc, + }); + } + else { + diagnostic.withDetails({ + kind: 'error', + message: `Unnecessary dependency \`${printManualMemoDependency(dep)}\``, + loc: (_d = dep.loc) !== null && _d !== void 0 ? _d : manualMemoLoc, + }); + } + } + } + if (suggestion != null) { + diagnostic.withDetails({ + kind: 'hint', + message: `Inferred dependencies: \`${suggestion.text}\``, + }); + } + return diagnostic; + } + return null; +} +function addDependency(dep, dependencies, locals) { + if (dep.kind === 'Aggregate') { + for (const x of dep.dependencies) { + addDependency(x, dependencies, locals); + } + } + else if (dep.kind === 'Global') { + dependencies.add(dep); + } + else if (!locals.has(dep.identifier.id)) { + dependencies.add(dep); + } +} +function visitCandidateDependency(place, temporaries, dependencies, locals) { + const dep = temporaries.get(place.identifier.id); + if (dep != null) { + addDependency(dep, dependencies, locals); + } +} +function collectDependencies(fn, temporaries, callbacks, isFunctionExpression) { + var _a, _b; + const optionals = findOptionalPlaces(fn); + const locals = new Set(); + if (isFunctionExpression) { + for (const param of fn.params) { + const place = param.kind === 'Identifier' ? param : param.place; + locals.add(place.identifier.id); + } + } + const dependencies = new Set(); + function visit(place) { + visitCandidateDependency(place, temporaries, dependencies, locals); + } + for (const block of fn.body.blocks.values()) { + for (const phi of block.phis) { + const deps = []; + for (const operand of phi.operands.values()) { + const dep = temporaries.get(operand.identifier.id); + if (dep == null) { + continue; + } + if (dep.kind === 'Aggregate') { + deps.push(...dep.dependencies); + } + else { + deps.push(dep); + } + } + if (deps.length === 0) { + continue; + } + else if (deps.length === 1) { + temporaries.set(phi.place.identifier.id, deps[0]); + } + else { + temporaries.set(phi.place.identifier.id, { + kind: 'Aggregate', + dependencies: new Set(deps), + }); + } + } + for (const instr of block.instructions) { + const { lvalue, value } = instr; + switch (value.kind) { + case 'LoadGlobal': { + temporaries.set(lvalue.identifier.id, { + kind: 'Global', + binding: value.binding, + }); + break; + } + case 'LoadContext': + case 'LoadLocal': { + const temp = temporaries.get(value.place.identifier.id); + if (temp != null) { + if (temp.kind === 'Local') { + const local = Object.assign(Object.assign({}, temp), { loc: value.place.loc }); + temporaries.set(lvalue.identifier.id, local); + } + else { + temporaries.set(lvalue.identifier.id, temp); + } + if (locals.has(value.place.identifier.id)) { + locals.add(lvalue.identifier.id); + } + } + break; + } + case 'DeclareLocal': { + const local = { + kind: 'Local', + identifier: value.lvalue.place.identifier, + path: [], + context: false, + loc: value.lvalue.place.loc, + }; + temporaries.set(value.lvalue.place.identifier.id, local); + locals.add(value.lvalue.place.identifier.id); + break; + } + case 'StoreLocal': { + if (value.lvalue.place.identifier.name == null) { + const temp = temporaries.get(value.value.identifier.id); + if (temp != null) { + temporaries.set(value.lvalue.place.identifier.id, temp); + } + break; + } + visit(value.value); + if (value.lvalue.kind !== InstructionKind.Reassign) { + const local = { + kind: 'Local', + identifier: value.lvalue.place.identifier, + path: [], + context: false, + loc: value.lvalue.place.loc, + }; + temporaries.set(value.lvalue.place.identifier.id, local); + locals.add(value.lvalue.place.identifier.id); + } + break; + } + case 'DeclareContext': { + const local = { + kind: 'Local', + identifier: value.lvalue.place.identifier, + path: [], + context: true, + loc: value.lvalue.place.loc, + }; + temporaries.set(value.lvalue.place.identifier.id, local); + break; + } + case 'StoreContext': { + visit(value.value); + if (value.lvalue.kind !== InstructionKind.Reassign) { + const local = { + kind: 'Local', + identifier: value.lvalue.place.identifier, + path: [], + context: true, + loc: value.lvalue.place.loc, + }; + temporaries.set(value.lvalue.place.identifier.id, local); + locals.add(value.lvalue.place.identifier.id); + } + break; + } + case 'Destructure': { + visit(value.value); + if (value.lvalue.kind !== InstructionKind.Reassign) { + for (const lvalue of eachInstructionValueLValue(value)) { + const local = { + kind: 'Local', + identifier: lvalue.identifier, + path: [], + context: false, + loc: lvalue.loc, + }; + temporaries.set(lvalue.identifier.id, local); + locals.add(lvalue.identifier.id); + } + } + break; + } + case 'PropertyLoad': { + if (typeof value.property === 'number' || + (isUseRefType(value.object.identifier) && + value.property === 'current')) { + visit(value.object); + break; + } + const object = temporaries.get(value.object.identifier.id); + if (object != null && object.kind === 'Local') { + const optional = (_a = optionals.get(value.object.identifier.id)) !== null && _a !== void 0 ? _a : false; + const local = { + kind: 'Local', + identifier: object.identifier, + context: object.context, + path: [ + ...object.path, + { + optional, + property: value.property, + loc: value.loc, + }, + ], + loc: value.loc, + }; + temporaries.set(lvalue.identifier.id, local); + } + break; + } + case 'FunctionExpression': + case 'ObjectMethod': { + const functionDeps = collectDependencies(value.loweredFunc.func, temporaries, null, true); + temporaries.set(lvalue.identifier.id, functionDeps); + addDependency(functionDeps, dependencies, locals); + break; + } + case 'StartMemoize': { + const onStartMemoize = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onStartMemoize; + if (onStartMemoize != null) { + onStartMemoize(value, dependencies, locals); + } + break; + } + case 'FinishMemoize': { + const onFinishMemoize = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onFinishMemoize; + if (onFinishMemoize != null) { + onFinishMemoize(value, dependencies, locals); + } + break; + } + case 'ArrayExpression': { + const arrayDeps = new Set(); + for (const item of value.elements) { + if (item.kind === 'Hole') { + continue; + } + const place = item.kind === 'Identifier' ? item : item.place; + visitCandidateDependency(place, temporaries, arrayDeps, new Set()); + visit(place); + } + temporaries.set(lvalue.identifier.id, { + kind: 'Aggregate', + dependencies: arrayDeps, + loc: value.loc, + }); + break; + } + case 'CallExpression': + case 'MethodCall': { + const receiver = value.kind === 'CallExpression' ? value.callee : value.property; + const onEffect = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onEffect; + if (onEffect != null && isEffectHook(receiver.identifier)) { + const [fn, deps] = value.args; + if ((fn === null || fn === void 0 ? void 0 : fn.kind) === 'Identifier' && (deps === null || deps === void 0 ? void 0 : deps.kind) === 'Identifier') { + const fnDeps = temporaries.get(fn.identifier.id); + const manualDeps = temporaries.get(deps.identifier.id); + if ((fnDeps === null || fnDeps === void 0 ? void 0 : fnDeps.kind) === 'Aggregate' && + (manualDeps === null || manualDeps === void 0 ? void 0 : manualDeps.kind) === 'Aggregate') { + onEffect(fnDeps.dependencies, manualDeps.dependencies, (_b = manualDeps.loc) !== null && _b !== void 0 ? _b : null); + } + } + } + for (const operand of eachInstructionValueOperand(value)) { + if (value.kind === 'MethodCall' && + operand.identifier.id === value.property.identifier.id) { + continue; + } + visit(operand); + } + break; + } + default: { + for (const operand of eachInstructionValueOperand(value)) { + visit(operand); + } + for (const lvalue of eachInstructionLValue(instr)) { + locals.add(lvalue.identifier.id); + } + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + if (optionals.has(operand.identifier.id)) { + continue; + } + visit(operand); + } + } + return { kind: 'Aggregate', dependencies }; +} +function printInferredDependency(dep) { + switch (dep.kind) { + case 'Global': { + return dep.binding.name; + } + case 'Local': { + CompilerError.invariant(dep.identifier.name != null && dep.identifier.name.kind === 'named', { + reason: 'Expected dependencies to be named variables', + loc: dep.loc, + }); + return `${dep.identifier.name.value}${dep.path.map(p => (p.optional ? '?' : '') + '.' + p.property).join('')}`; + } + } +} +function printManualMemoDependency(dep) { + let identifierName; + if (dep.root.kind === 'Global') { + identifierName = dep.root.identifierName; + } + else { + const name = dep.root.value.identifier.name; + CompilerError.invariant(name != null && name.kind === 'named', { + reason: 'Expected manual dependencies to be named variables', + loc: dep.root.value.loc, + }); + identifierName = name.value; + } + return `${identifierName}${dep.path.map(p => (p.optional ? '?' : '') + '.' + p.property).join('')}`; +} +function isEqualTemporary(a, b) { + switch (a.kind) { + case 'Aggregate': { + return false; + } + case 'Global': { + return b.kind === 'Global' && a.binding.name === b.binding.name; + } + case 'Local': { + return (b.kind === 'Local' && + a.identifier.id === b.identifier.id && + areEqualPaths(a.path, b.path)); + } + } +} +function collectReactiveIdentifiersHIR(fn) { + const reactive = new Set(); + for (const block of fn.body.blocks.values()) { + for (const instr of block.instructions) { + for (const lvalue of eachInstructionLValue(instr)) { + if (lvalue.reactive) { + reactive.add(lvalue.identifier.id); + } + } + for (const operand of eachInstructionValueOperand(instr.value)) { + if (operand.reactive) { + reactive.add(operand.identifier.id); + } + } + } + for (const operand of eachTerminalOperand(block.terminal)) { + if (operand.reactive) { + reactive.add(operand.identifier.id); + } + } + } + return reactive; +} +function findOptionalPlaces(fn) { + const optionals = new Map(); + const visited = new Set(); + for (const [, block] of fn.body.blocks) { + if (visited.has(block.id)) { + continue; + } + if (block.terminal.kind === 'optional') { + visited.add(block.id); + const optionalTerminal = block.terminal; + let testBlock = fn.body.blocks.get(block.terminal.test); + const queue = [block.terminal.optional]; + loop: while (true) { + visited.add(testBlock.id); + const terminal = testBlock.terminal; + switch (terminal.kind) { + case 'branch': { + const isOptional = queue.pop(); + CompilerError.invariant(isOptional !== undefined, { + reason: 'Expected an optional value for each optional test condition', + loc: terminal.test.loc, + }); + if (isOptional != null) { + optionals.set(terminal.test.identifier.id, isOptional); + } + if (terminal.fallthrough === optionalTerminal.fallthrough) { + const consequent = fn.body.blocks.get(terminal.consequent); + const last = consequent.instructions.at(-1); + if (last !== undefined && last.value.kind === 'StoreLocal') { + if (isOptional != null) { + optionals.set(last.value.value.identifier.id, isOptional); + } + } + break loop; + } + else { + testBlock = fn.body.blocks.get(terminal.fallthrough); + } + break; + } + case 'optional': { + queue.push(terminal.optional); + testBlock = fn.body.blocks.get(terminal.test); + break; + } + case 'logical': + case 'ternary': { + queue.push(null); + testBlock = fn.body.blocks.get(terminal.test); + break; + } + case 'sequence': { + testBlock = fn.body.blocks.get(terminal.block); + break; + } + case 'maybe-throw': { + testBlock = fn.body.blocks.get(terminal.continuation); + break; + } + default: { + CompilerError.invariant(false, { + reason: `Unexpected terminal in optional`, + message: `Unexpected ${terminal.kind} in optional`, + loc: terminal.loc, + }); + } + } + } + CompilerError.invariant(queue.length === 0, { + reason: 'Expected a matching number of conditional blocks and branch points', + loc: block.terminal.loc, + }); + } + } + return optionals; +} +function isOptionalDependency(inferredDependency, reactive) { + return (!reactive.has(inferredDependency.identifier.id) && + (isStableType(inferredDependency.identifier) || + isPrimitiveType(inferredDependency.identifier))); +} +function createDiagnostic(category, missing, extra, suggestion) { + let reason; + let description; + function joinMissingExtraDetail(missingString, extraString, joinStr) { + return [ + missing.length !== 0 ? missingString : null, + extra.length !== 0 ? extraString : null, + ] + .filter(Boolean) + .join(joinStr); + } + switch (category) { + case ErrorCategory.MemoDependencies: { + reason = `Found ${joinMissingExtraDetail('missing', 'extra', '/')} memoization dependencies`; + description = joinMissingExtraDetail('Missing dependencies can cause a value to update less often than it should, resulting in stale UI', 'Extra dependencies can cause a value to update more often than it should, resulting in performance' + + ' problems such as excessive renders or effects firing too often', '. '); + break; + } + case ErrorCategory.EffectExhaustiveDependencies: { + reason = `Found ${joinMissingExtraDetail('missing', 'extra', '/')} effect dependencies`; + description = joinMissingExtraDetail('Missing dependencies can cause an effect to fire less often than it should', 'Extra dependencies can cause an effect to fire more often than it should, resulting' + + ' in performance problems such as excessive renders and side effects', '. '); + break; + } + default: { + CompilerError.invariant(false, { + reason: `Unexpected error category: ${category}`, + loc: GeneratedSource, + }); + } + } + return CompilerDiagnostic.create({ + category, + reason, + description, + suggestions: suggestion != null ? [suggestion] : null, + }); +} +function isEffectHook(identifier) { + return (isUseEffectHookType(identifier) || + isUseLayoutEffectHookType(identifier) || + isUseInsertionEffectHookType(identifier)); +} + +function run(func, config, fnType, mode, programContext, logger, filename, code) { + var _a, _b; + const contextIdentifiers = findContextIdentifiers(func); + const env = new Environment(func.scope, fnType, mode, config, contextIdentifiers, func, logger, filename, code, programContext); + (_b = (_a = env.logger) === null || _a === void 0 ? void 0 : _a.debugLogIRs) === null || _b === void 0 ? void 0 : _b.call(_a, { + kind: 'debug', + name: 'EnvironmentConfig', + value: prettyFormat(env.config), + }); + return runWithEnvironment(func, env); +} +function runWithEnvironment(func, env) { + const log = (value) => { + var _a, _b; + (_b = (_a = env.logger) === null || _a === void 0 ? void 0 : _a.debugLogIRs) === null || _b === void 0 ? void 0 : _b.call(_a, value); + }; + const hir = lower(func, env); + log({ kind: 'hir', name: 'HIR', value: hir }); + pruneMaybeThrows(hir); + log({ kind: 'hir', name: 'PruneMaybeThrows', value: hir }); + validateContextVariableLValues(hir); + validateUseMemo(hir); + if (env.enableDropManualMemoization) { + dropManualMemoization(hir); + log({ kind: 'hir', name: 'DropManualMemoization', value: hir }); + } + inlineImmediatelyInvokedFunctionExpressions(hir); + log({ + kind: 'hir', + name: 'InlineImmediatelyInvokedFunctionExpressions', + value: hir, + }); + mergeConsecutiveBlocks(hir); + log({ kind: 'hir', name: 'MergeConsecutiveBlocks', value: hir }); + assertConsistentIdentifiers(hir); + assertTerminalSuccessorsExist(hir); + enterSSA(hir); + log({ kind: 'hir', name: 'SSA', value: hir }); + eliminateRedundantPhi(hir); + log({ kind: 'hir', name: 'EliminateRedundantPhi', value: hir }); + assertConsistentIdentifiers(hir); + constantPropagation(hir); + log({ kind: 'hir', name: 'ConstantPropagation', value: hir }); + inferTypes(hir); + log({ kind: 'hir', name: 'InferTypes', value: hir }); + if (env.enableValidations) { + if (env.config.validateHooksUsage) { + validateHooksUsage(hir); + } + if (env.config.validateNoCapitalizedCalls) { + validateNoCapitalizedCalls(hir); + } + } + optimizePropsMethodCalls(hir); + log({ kind: 'hir', name: 'OptimizePropsMethodCalls', value: hir }); + analyseFunctions(hir); + log({ kind: 'hir', name: 'AnalyseFunctions', value: hir }); + inferMutationAliasingEffects(hir); + log({ kind: 'hir', name: 'InferMutationAliasingEffects', value: hir }); + if (env.outputMode === 'ssr') { + optimizeForSSR(hir); + log({ kind: 'hir', name: 'OptimizeForSSR', value: hir }); + } + deadCodeElimination(hir); + log({ kind: 'hir', name: 'DeadCodeElimination', value: hir }); + pruneMaybeThrows(hir); + log({ kind: 'hir', name: 'PruneMaybeThrows', value: hir }); + inferMutationAliasingRanges(hir, { + isFunctionExpression: false, + }); + log({ kind: 'hir', name: 'InferMutationAliasingRanges', value: hir }); + if (env.enableValidations) { + validateLocalsNotReassignedAfterRender(hir); + if (env.config.assertValidMutableRanges) { + assertValidMutableRanges(hir); + } + if (env.config.validateRefAccessDuringRender) { + validateNoRefAccessInRender(hir); + } + if (env.config.validateNoSetStateInRender) { + validateNoSetStateInRender(hir); + } + if (env.config.validateNoDerivedComputationsInEffects_exp && + env.outputMode === 'lint') { + env.logErrors(validateNoDerivedComputationsInEffects_exp(hir)); + } + else if (env.config.validateNoDerivedComputationsInEffects) { + validateNoDerivedComputationsInEffects(hir); + } + if (env.config.validateNoSetStateInEffects && env.outputMode === 'lint') { + env.logErrors(validateNoSetStateInEffects(hir, env)); + } + if (env.config.validateNoJSXInTryStatements && env.outputMode === 'lint') { + env.logErrors(validateNoJSXInTryStatement(hir)); + } + validateNoFreezingKnownMutableFunctions(hir); + } + inferReactivePlaces(hir); + log({ kind: 'hir', name: 'InferReactivePlaces', value: hir }); + if (env.enableValidations) { + if (env.config.validateExhaustiveMemoizationDependencies || + env.config.validateExhaustiveEffectDependencies) { + validateExhaustiveDependencies(hir); + } + } + rewriteInstructionKindsBasedOnReassignment(hir); + log({ + kind: 'hir', + name: 'RewriteInstructionKindsBasedOnReassignment', + value: hir, + }); + if (env.enableValidations && + env.config.validateStaticComponents && + env.outputMode === 'lint') { + env.logErrors(validateStaticComponents(hir)); + } + if (env.enableMemoization) { + inferReactiveScopeVariables(hir); + log({ kind: 'hir', name: 'InferReactiveScopeVariables', value: hir }); + } + const fbtOperands = memoizeFbtAndMacroOperandsInSameScope(hir); + log({ + kind: 'hir', + name: 'MemoizeFbtAndMacroOperandsInSameScope', + value: hir, + }); + if (env.config.enableJsxOutlining) { + outlineJSX(hir); + } + if (env.config.enableNameAnonymousFunctions) { + nameAnonymousFunctions(hir); + log({ + kind: 'hir', + name: 'NameAnonymousFunctions', + value: hir, + }); + } + if (env.config.enableFunctionOutlining) { + outlineFunctions(hir, fbtOperands); + log({ kind: 'hir', name: 'OutlineFunctions', value: hir }); + } + alignMethodCallScopes(hir); + log({ + kind: 'hir', + name: 'AlignMethodCallScopes', + value: hir, + }); + alignObjectMethodScopes(hir); + log({ + kind: 'hir', + name: 'AlignObjectMethodScopes', + value: hir, + }); + pruneUnusedLabelsHIR(hir); + log({ + kind: 'hir', + name: 'PruneUnusedLabelsHIR', + value: hir, + }); + alignReactiveScopesToBlockScopesHIR(hir); + log({ + kind: 'hir', + name: 'AlignReactiveScopesToBlockScopesHIR', + value: hir, + }); + mergeOverlappingReactiveScopesHIR(hir); + log({ + kind: 'hir', + name: 'MergeOverlappingReactiveScopesHIR', + value: hir, + }); + assertValidBlockNesting(hir); + buildReactiveScopeTerminalsHIR(hir); + log({ + kind: 'hir', + name: 'BuildReactiveScopeTerminalsHIR', + value: hir, + }); + assertValidBlockNesting(hir); + flattenReactiveLoopsHIR(hir); + log({ + kind: 'hir', + name: 'FlattenReactiveLoopsHIR', + value: hir, + }); + flattenScopesWithHooksOrUseHIR(hir); + log({ + kind: 'hir', + name: 'FlattenScopesWithHooksOrUseHIR', + value: hir, + }); + assertTerminalSuccessorsExist(hir); + assertTerminalPredsExist(hir); + propagateScopeDependenciesHIR(hir); + log({ + kind: 'hir', + name: 'PropagateScopeDependenciesHIR', + value: hir, + }); + const reactiveFunction = buildReactiveFunction(hir); + log({ + kind: 'reactive', + name: 'BuildReactiveFunction', + value: reactiveFunction, + }); + assertWellFormedBreakTargets(reactiveFunction); + pruneUnusedLabels(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneUnusedLabels', + value: reactiveFunction, + }); + assertScopeInstructionsWithinScopes(reactiveFunction); + pruneNonEscapingScopes(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneNonEscapingScopes', + value: reactiveFunction, + }); + pruneNonReactiveDependencies(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneNonReactiveDependencies', + value: reactiveFunction, + }); + pruneUnusedScopes(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneUnusedScopes', + value: reactiveFunction, + }); + mergeReactiveScopesThatInvalidateTogether(reactiveFunction); + log({ + kind: 'reactive', + name: 'MergeReactiveScopesThatInvalidateTogether', + value: reactiveFunction, + }); + pruneAlwaysInvalidatingScopes(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneAlwaysInvalidatingScopes', + value: reactiveFunction, + }); + propagateEarlyReturns(reactiveFunction); + log({ + kind: 'reactive', + name: 'PropagateEarlyReturns', + value: reactiveFunction, + }); + pruneUnusedLValues(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneUnusedLValues', + value: reactiveFunction, + }); + promoteUsedTemporaries(reactiveFunction); + log({ + kind: 'reactive', + name: 'PromoteUsedTemporaries', + value: reactiveFunction, + }); + extractScopeDeclarationsFromDestructuring(reactiveFunction); + log({ + kind: 'reactive', + name: 'ExtractScopeDeclarationsFromDestructuring', + value: reactiveFunction, + }); + stabilizeBlockIds(reactiveFunction); + log({ + kind: 'reactive', + name: 'StabilizeBlockIds', + value: reactiveFunction, + }); + const uniqueIdentifiers = renameVariables(reactiveFunction); + log({ + kind: 'reactive', + name: 'RenameVariables', + value: reactiveFunction, + }); + pruneHoistedContexts(reactiveFunction); + log({ + kind: 'reactive', + name: 'PruneHoistedContexts', + value: reactiveFunction, + }); + if (env.config.enablePreserveExistingMemoizationGuarantees || + env.config.validatePreserveExistingMemoizationGuarantees) { + validatePreservedManualMemoization(reactiveFunction); + } + const ast = codegenFunction(reactiveFunction, { + uniqueIdentifiers, + fbtOperands, + }); + log({ kind: 'ast', name: 'Codegen', value: ast }); + for (const outlined of ast.outlined) { + log({ kind: 'ast', name: 'Codegen (outlined)', value: outlined.fn }); + } + if (env.config.validateSourceLocations) { + validateSourceLocations(func, ast, env); + } + if (env.config.throwUnknownException__testonly) { + throw new Error('unexpected error'); + } + if (env.hasErrors()) { + return Err(env.aggregateErrors()); + } + return Ok(ast); +} +function compileFn(func, config, fnType, mode, programContext, logger, filename, code) { + return run(func, config, fnType, mode, programContext, logger, filename, code); +} + +function filterSuppressionsThatAffectFunction(suppressionRanges, fn) { + const suppressionsInScope = []; + const fnNode = fn.node; + for (const suppressionRange of suppressionRanges) { + if (suppressionRange.disableComment.start == null || + fnNode.start == null || + fnNode.end == null) { + continue; + } + if (suppressionRange.disableComment.start > fnNode.start && + (suppressionRange.enableComment === null || + (suppressionRange.enableComment.end != null && + suppressionRange.enableComment.end < fnNode.end))) { + suppressionsInScope.push(suppressionRange); + } + if (suppressionRange.disableComment.start < fnNode.start && + (suppressionRange.enableComment === null || + (suppressionRange.enableComment.end != null && + suppressionRange.enableComment.end > fnNode.end))) { + suppressionsInScope.push(suppressionRange); + } + } + return suppressionsInScope; +} +function findProgramSuppressions(programComments, ruleNames, flowSuppressions) { + const suppressionRanges = []; + let disableComment = null; + let enableComment = null; + let source = null; + let disableNextLinePattern = null; + let disablePattern = null; + let enablePattern = null; + if (ruleNames != null && ruleNames.length !== 0) { + const rulePattern = `(${ruleNames.join('|')})`; + disableNextLinePattern = new RegExp(`eslint-disable-next-line ${rulePattern}`); + disablePattern = new RegExp(`eslint-disable ${rulePattern}`); + enablePattern = new RegExp(`eslint-enable ${rulePattern}`); + } + const flowSuppressionPattern = new RegExp('\\$(FlowFixMe\\w*|FlowExpectedError|FlowIssue)\\[react\\-rule'); + for (const comment of programComments) { + if (comment.start == null || comment.end == null) { + continue; + } + if (disableComment == null && + disableNextLinePattern != null && + disableNextLinePattern.test(comment.value)) { + disableComment = comment; + enableComment = comment; + source = 'Eslint'; + } + if (flowSuppressions && + disableComment == null && + flowSuppressionPattern.test(comment.value)) { + disableComment = comment; + enableComment = comment; + source = 'Flow'; + } + if (disablePattern != null && disablePattern.test(comment.value)) { + disableComment = comment; + source = 'Eslint'; + } + if (enablePattern != null && + enablePattern.test(comment.value) && + source === 'Eslint') { + enableComment = comment; + } + if (disableComment != null && source != null) { + suppressionRanges.push({ + disableComment: disableComment, + enableComment: enableComment, + source, + }); + disableComment = null; + enableComment = null; + source = null; + } + } + return suppressionRanges; +} +function suppressionsToCompilerError(suppressionRanges) { + var _a; + CompilerError.invariant(suppressionRanges.length !== 0, { + reason: `Expected at least suppression comment source range`, + loc: GeneratedSource, + }); + const error = new CompilerError(); + for (const suppressionRange of suppressionRanges) { + if (suppressionRange.disableComment.start == null || + suppressionRange.disableComment.end == null) { + continue; + } + let reason, suggestion; + switch (suppressionRange.source) { + case 'Eslint': + reason = + 'React Compiler has skipped optimizing this component because one or more React ESLint rules were disabled'; + suggestion = + 'Remove the ESLint suppression and address the React error'; + break; + case 'Flow': + reason = + 'React Compiler has skipped optimizing this component because one or more React rule violations were reported by Flow'; + suggestion = 'Remove the Flow suppression and address the React error'; + break; + default: + assertExhaustive$1(suppressionRange.source, 'Unhandled suppression source'); + } + error.pushDiagnostic(CompilerDiagnostic.create({ + reason: reason, + description: `React Compiler only works when your components follow all the rules of React, disabling them may result in unexpected or incorrect behavior. Found suppression \`${suppressionRange.disableComment.value.trim()}\``, + category: ErrorCategory.Suppression, + suggestions: [ + { + description: suggestion, + range: [ + suppressionRange.disableComment.start, + suppressionRange.disableComment.end, + ], + op: CompilerSuggestionOperation.Remove, + }, + ], + }).withDetails({ + kind: 'error', + loc: (_a = suppressionRange.disableComment.loc) !== null && _a !== void 0 ? _a : null, + message: 'Found React rule suppression', + })); + } + return error; +} + +const OPT_IN_DIRECTIVES = new Set(['use forget', 'use memo']); +const OPT_OUT_DIRECTIVES = new Set(['use no forget', 'use no memo']); +const DYNAMIC_GATING_DIRECTIVE = new RegExp('^use memo if\\(([^\\)]*)\\)$'); +function tryFindDirectiveEnablingMemoization(directives, opts) { + var _a, _b; + const optIn = directives.find(directive => OPT_IN_DIRECTIVES.has(directive.value.value)); + if (optIn != null) { + return Ok(optIn); + } + const dynamicGating = findDirectivesDynamicGating(directives, opts); + if (dynamicGating.isOk()) { + return Ok((_b = (_a = dynamicGating.unwrap()) === null || _a === void 0 ? void 0 : _a.directive) !== null && _b !== void 0 ? _b : null); + } + else { + return Err(dynamicGating.unwrapErr()); + } +} +function findDirectiveDisablingMemoization(directives, { customOptOutDirectives }) { + var _a, _b; + if (customOptOutDirectives != null) { + return ((_a = directives.find(directive => customOptOutDirectives.indexOf(directive.value.value) !== -1)) !== null && _a !== void 0 ? _a : null); + } + return ((_b = directives.find(directive => OPT_OUT_DIRECTIVES.has(directive.value.value))) !== null && _b !== void 0 ? _b : null); +} +function findDirectivesDynamicGating(directives, opts) { + var _a, _b; + if (opts.dynamicGating === null) { + return Ok(null); + } + const errors = new CompilerError(); + const result = []; + for (const directive of directives) { + const maybeMatch = DYNAMIC_GATING_DIRECTIVE.exec(directive.value.value); + if (maybeMatch != null && maybeMatch[1] != null) { + if (libExports$1.isValidIdentifier(maybeMatch[1])) { + result.push({ directive, match: maybeMatch[1] }); + } + else { + errors.push({ + reason: `Dynamic gating directive is not a valid JavaScript identifier`, + description: `Found '${directive.value.value}'`, + category: ErrorCategory.Gating, + loc: (_a = directive.loc) !== null && _a !== void 0 ? _a : null, + suggestions: null, + }); + } + } + } + if (errors.hasAnyErrors()) { + return Err(errors); + } + else if (result.length > 1) { + const error = new CompilerError(); + error.push({ + reason: `Multiple dynamic gating directives found`, + description: `Expected a single directive but found [${result + .map(r => r.directive.value.value) + .join(', ')}]`, + category: ErrorCategory.Gating, + loc: (_b = result[0].directive.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + }); + return Err(error); + } + else if (result.length === 1) { + return Ok({ + gating: { + source: opts.dynamicGating.source, + importSpecifierName: result[0].match, + }, + directive: result[0].directive, + }); + } + else { + return Ok(null); + } +} +function isError(err) { + return !(err instanceof CompilerError) || err.hasErrors(); +} +function isConfigError(err) { + if (err instanceof CompilerError) { + return err.details.some(detail => detail.category === ErrorCategory.Config); + } + return false; +} +function logError(err, context, fnLoc) { + var _a, _b; + if (context.opts.logger) { + if (err instanceof CompilerError) { + for (const detail of err.details) { + context.opts.logger.logEvent(context.filename, { + kind: 'CompileError', + fnLoc, + detail, + }); + } + } + else { + let stringifiedError; + if (err instanceof Error) { + stringifiedError = (_a = err.stack) !== null && _a !== void 0 ? _a : err.message; + } + else { + stringifiedError = (_b = err === null || err === void 0 ? void 0 : err.toString()) !== null && _b !== void 0 ? _b : '[ null ]'; + } + context.opts.logger.logEvent(context.filename, { + kind: 'PipelineError', + fnLoc, + data: stringifiedError, + }); + } + } +} +function handleError(err, context, fnLoc) { + logError(err, context, fnLoc); + if (context.opts.panicThreshold === 'all_errors' || + (context.opts.panicThreshold === 'critical_errors' && isError(err)) || + isConfigError(err)) { + throw err; + } +} +function createNewFunctionNode(originalFn, compiledFn) { + var _a, _b, _c; + let transformedFn; + switch (originalFn.node.type) { + case 'FunctionDeclaration': { + const fn = { + type: 'FunctionDeclaration', + id: compiledFn.id, + loc: (_a = originalFn.node.loc) !== null && _a !== void 0 ? _a : null, + async: compiledFn.async, + generator: compiledFn.generator, + params: compiledFn.params, + body: compiledFn.body, + }; + transformedFn = fn; + break; + } + case 'ArrowFunctionExpression': { + const fn = { + type: 'ArrowFunctionExpression', + loc: (_b = originalFn.node.loc) !== null && _b !== void 0 ? _b : null, + async: compiledFn.async, + generator: compiledFn.generator, + params: compiledFn.params, + expression: originalFn.node.expression, + body: compiledFn.body, + }; + transformedFn = fn; + break; + } + case 'FunctionExpression': { + const fn = { + type: 'FunctionExpression', + id: compiledFn.id, + loc: (_c = originalFn.node.loc) !== null && _c !== void 0 ? _c : null, + async: compiledFn.async, + generator: compiledFn.generator, + params: compiledFn.params, + body: compiledFn.body, + }; + transformedFn = fn; + break; + } + default: { + assertExhaustive$1(originalFn.node, `Creating unhandled function: ${originalFn.node}`); + } + } + return transformedFn; +} +function insertNewOutlinedFunctionNode(program, originalFn, compiledFn) { + var _a, _b, _c; + switch (originalFn.type) { + case 'FunctionDeclaration': { + return originalFn.insertAfter(createNewFunctionNode(originalFn, compiledFn))[0]; + } + case 'ArrowFunctionExpression': + case 'FunctionExpression': { + const fn = { + type: 'FunctionDeclaration', + id: compiledFn.id, + loc: (_a = originalFn.node.loc) !== null && _a !== void 0 ? _a : null, + async: compiledFn.async, + generator: compiledFn.generator, + params: compiledFn.params, + body: compiledFn.body, + }; + const insertedFuncDecl = program.pushContainer('body', [fn])[0]; + CompilerError.invariant(insertedFuncDecl.isFunctionDeclaration(), { + reason: 'Expected inserted function declaration', + description: `Got: ${insertedFuncDecl}`, + loc: (_c = (_b = insertedFuncDecl.node) === null || _b === void 0 ? void 0 : _b.loc) !== null && _c !== void 0 ? _c : GeneratedSource, + }); + return insertedFuncDecl; + } + default: { + assertExhaustive$1(originalFn, `Inserting unhandled function: ${originalFn}`); + } + } +} +const DEFAULT_ESLINT_SUPPRESSIONS = [ + 'react-hooks/exhaustive-deps', + 'react-hooks/rules-of-hooks', +]; +function isFilePartOfSources(sources, filename) { + if (typeof sources === 'function') { + return sources(filename); + } + for (const prefix of sources) { + if (filename.indexOf(prefix) !== -1) { + return true; + } + } + return false; +} +function compileProgram(program, pass) { + var _a, _b; + if (shouldSkipCompilation(program, pass)) { + return; + } + const restrictedImportsErr = validateRestrictedImports(program, pass.opts.environment); + if (restrictedImportsErr) { + handleError(restrictedImportsErr, pass, null); + return; + } + const suppressions = findProgramSuppressions(pass.comments, pass.opts.environment.validateExhaustiveMemoizationDependencies && + pass.opts.environment.validateHooksUsage + ? null + : ((_a = pass.opts.eslintSuppressionRules) !== null && _a !== void 0 ? _a : DEFAULT_ESLINT_SUPPRESSIONS), pass.opts.flowSuppressions); + const programContext = new ProgramContext({ + program: program, + opts: pass.opts, + filename: pass.filename, + code: pass.code, + suppressions, + hasModuleScopeOptOut: findDirectiveDisablingMemoization(program.node.directives, pass.opts) != + null, + }); + const queue = findFunctionsToCompile(program, pass, programContext); + const compiledFns = []; + const outputMode = (_b = pass.opts.outputMode) !== null && _b !== void 0 ? _b : (pass.opts.noEmit ? 'lint' : 'client'); + while (queue.length !== 0) { + const current = queue.shift(); + const compiled = processFn(current.fn, current.fnType, programContext, outputMode); + if (compiled != null) { + for (const outlined of compiled.outlined) { + CompilerError.invariant(outlined.fn.outlined.length === 0, { + reason: 'Unexpected nested outlined functions', + loc: outlined.fn.loc, + }); + const fn = insertNewOutlinedFunctionNode(program, current.fn, outlined.fn); + fn.skip(); + programContext.alreadyCompiled.add(fn.node); + if (outlined.type !== null) { + queue.push({ + kind: 'outlined', + fn, + fnType: outlined.type, + }); + } + } + compiledFns.push({ + kind: current.kind, + originalFn: current.fn, + compiledFn: compiled, + }); + } + } + if (programContext.hasModuleScopeOptOut) { + if (compiledFns.length > 0) { + const error = new CompilerError(); + error.pushErrorDetail(new CompilerErrorDetail({ + reason: 'Unexpected compiled functions when module scope opt-out is present', + category: ErrorCategory.Invariant, + loc: null, + })); + handleError(error, programContext, null); + } + return; + } + applyCompiledFunctions(program, compiledFns, pass, programContext); +} +function findFunctionsToCompile(program, pass, programContext) { + var _a; + const queue = []; + const traverseFunction = (fn, pass) => { + if (pass.opts.compilationMode === 'all' && + fn.scope.getProgramParent() !== fn.scope.parent) { + return; + } + const fnType = getReactFunctionType(fn, pass); + if (fnType === null || programContext.alreadyCompiled.has(fn.node)) { + return; + } + programContext.alreadyCompiled.add(fn.node); + fn.skip(); + queue.push({ kind: 'original', fn, fnType }); + }; + program.traverse({ + ClassDeclaration(node) { + node.skip(); + }, + ClassExpression(node) { + node.skip(); + }, + FunctionDeclaration: traverseFunction, + FunctionExpression: traverseFunction, + ArrowFunctionExpression: traverseFunction, + }, Object.assign(Object.assign({}, pass), { opts: Object.assign(Object.assign({}, pass.opts), pass.opts), filename: (_a = pass.filename) !== null && _a !== void 0 ? _a : null })); + return queue; +} +function processFn(fn, fnType, programContext, outputMode) { + var _a, _b, _c, _d, _e, _f, _g, _h; + let directives; + if (fn.node.body.type !== 'BlockStatement') { + directives = { + optIn: null, + optOut: null, + }; + } + else { + const optIn = tryFindDirectiveEnablingMemoization(fn.node.body.directives, programContext.opts); + if (optIn.isErr()) { + handleError(optIn.unwrapErr(), programContext, (_a = fn.node.loc) !== null && _a !== void 0 ? _a : null); + return null; + } + directives = { + optIn: optIn.unwrapOr(null), + optOut: findDirectiveDisablingMemoization(fn.node.body.directives, programContext.opts), + }; + } + let compiledFn; + const compileResult = tryCompileFunction(fn, fnType, programContext, outputMode); + if (compileResult.kind === 'error') { + if (directives.optOut != null) { + logError(compileResult.error, programContext, (_b = fn.node.loc) !== null && _b !== void 0 ? _b : null); + } + else { + handleError(compileResult.error, programContext, (_c = fn.node.loc) !== null && _c !== void 0 ? _c : null); + } + return null; + } + else { + compiledFn = compileResult.compiledFn; + } + if (programContext.opts.ignoreUseNoForget === false && + directives.optOut != null) { + programContext.logEvent({ + kind: 'CompileSkip', + fnLoc: (_d = fn.node.body.loc) !== null && _d !== void 0 ? _d : null, + reason: `Skipped due to '${directives.optOut.value}' directive.`, + loc: (_e = directives.optOut.loc) !== null && _e !== void 0 ? _e : null, + }); + return null; + } + programContext.logEvent({ + kind: 'CompileSuccess', + fnLoc: (_f = fn.node.loc) !== null && _f !== void 0 ? _f : null, + fnName: (_h = (_g = compiledFn.id) === null || _g === void 0 ? void 0 : _g.name) !== null && _h !== void 0 ? _h : null, + memoSlots: compiledFn.memoSlotsUsed, + memoBlocks: compiledFn.memoBlocks, + memoValues: compiledFn.memoValues, + prunedMemoBlocks: compiledFn.prunedMemoBlocks, + prunedMemoValues: compiledFn.prunedMemoValues, + }); + if (programContext.hasModuleScopeOptOut) { + return null; + } + else if (programContext.opts.outputMode === 'lint') { + return null; + } + else if (programContext.opts.compilationMode === 'annotation' && + directives.optIn == null) { + return null; + } + else { + return compiledFn; + } +} +function tryCompileFunction(fn, fnType, programContext, outputMode) { + var _a; + const suppressionsInFunction = filterSuppressionsThatAffectFunction(programContext.suppressions, fn); + if (suppressionsInFunction.length > 0) { + return { + kind: 'error', + error: suppressionsToCompilerError(suppressionsInFunction), + }; + } + try { + const result = compileFn(fn, programContext.opts.environment, fnType, outputMode, programContext, programContext.opts.logger, programContext.filename, programContext.code); + if (result.isOk()) { + return { kind: 'compile', compiledFn: result.unwrap() }; + } + else { + return { kind: 'error', error: result.unwrapErr() }; + } + } + catch (err) { + if (err instanceof CompilerError && + err.details.every(detail => detail.category !== ErrorCategory.Invariant)) { + programContext.logEvent({ + kind: 'CompileUnexpectedThrow', + fnLoc: (_a = fn.node.loc) !== null && _a !== void 0 ? _a : null, + data: err.toString(), + }); + } + return { kind: 'error', error: err }; + } +} +function applyCompiledFunctions(program, compiledFns, pass, programContext) { + var _a, _b; + let referencedBeforeDeclared = null; + for (const result of compiledFns) { + const { kind, originalFn, compiledFn } = result; + const transformedFn = createNewFunctionNode(originalFn, compiledFn); + programContext.alreadyCompiled.add(transformedFn); + let dynamicGating = null; + if (originalFn.node.body.type === 'BlockStatement') { + const result = findDirectivesDynamicGating(originalFn.node.body.directives, pass.opts); + if (result.isOk()) { + dynamicGating = (_b = (_a = result.unwrap()) === null || _a === void 0 ? void 0 : _a.gating) !== null && _b !== void 0 ? _b : null; + } + } + const functionGating = dynamicGating !== null && dynamicGating !== void 0 ? dynamicGating : pass.opts.gating; + if (kind === 'original' && functionGating != null) { + referencedBeforeDeclared !== null && referencedBeforeDeclared !== void 0 ? referencedBeforeDeclared : (referencedBeforeDeclared = getFunctionReferencedBeforeDeclarationAtTopLevel(program, compiledFns)); + insertGatedFunctionDeclaration(originalFn, transformedFn, programContext, functionGating, referencedBeforeDeclared.has(result)); + } + else { + originalFn.replaceWith(transformedFn); + } + } + if (compiledFns.length > 0) { + addImportsToProgram(program, programContext); + } +} +function shouldSkipCompilation(program, pass) { + if (pass.opts.sources) { + if (pass.filename === null) { + const error = new CompilerError(); + error.pushErrorDetail(new CompilerErrorDetail({ + reason: `Expected a filename but found none.`, + description: "When the 'sources' config options is specified, the React compiler will only compile files with a name", + category: ErrorCategory.Config, + loc: null, + })); + handleError(error, pass, null); + return true; + } + if (!isFilePartOfSources(pass.opts.sources, pass.filename)) { + return true; + } + } + if (hasMemoCacheFunctionImport(program, getReactCompilerRuntimeModule(pass.opts.target))) { + return true; + } + return false; +} +function getReactFunctionType(fn, pass) { + var _a, _b; + if (fn.node.body.type === 'BlockStatement') { + const optInDirectives = tryFindDirectiveEnablingMemoization(fn.node.body.directives, pass.opts); + if (optInDirectives.unwrapOr(null) != null) { + return (_a = getComponentOrHookLike(fn)) !== null && _a !== void 0 ? _a : 'Other'; + } + } + let componentSyntaxType = null; + if (fn.isFunctionDeclaration()) { + if (isComponentDeclaration(fn.node)) { + componentSyntaxType = 'Component'; + } + else if (isHookDeclaration(fn.node)) { + componentSyntaxType = 'Hook'; + } + } + switch (pass.opts.compilationMode) { + case 'annotation': { + return null; + } + case 'infer': { + return componentSyntaxType !== null && componentSyntaxType !== void 0 ? componentSyntaxType : getComponentOrHookLike(fn); + } + case 'syntax': { + return componentSyntaxType; + } + case 'all': { + return (_b = getComponentOrHookLike(fn)) !== null && _b !== void 0 ? _b : 'Other'; + } + default: { + assertExhaustive$1(pass.opts.compilationMode, `Unexpected compilationMode \`${pass.opts.compilationMode}\``); + } + } +} +function hasMemoCacheFunctionImport(program, moduleName) { + let hasUseMemoCache = false; + program.traverse({ + ImportSpecifier(path) { + const imported = path.get('imported'); + let importedName = null; + if (imported.isIdentifier()) { + importedName = imported.node.name; + } + else if (imported.isStringLiteral()) { + importedName = imported.node.value; + } + if (importedName === 'c' && + path.parentPath.isImportDeclaration() && + path.parentPath.get('source').node.value === moduleName) { + hasUseMemoCache = true; + } + }, + }); + return hasUseMemoCache; +} +function isHookName$1(s) { + return /^use[A-Z0-9]/.test(s); +} +function isHook$1(path) { + if (path.isIdentifier()) { + return isHookName$1(path.node.name); + } + else if (path.isMemberExpression() && + !path.node.computed && + isHook$1(path.get('property'))) { + const obj = path.get('object').node; + const isPascalCaseNameSpace = /^[A-Z].*/; + return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name); + } + else { + return false; + } +} +function isComponentName$1(path) { + return path.isIdentifier() && /^[A-Z]/.test(path.node.name); +} +function isReactAPI(path, functionName) { + const node = path.node; + return ((node.type === 'Identifier' && node.name === functionName) || + (node.type === 'MemberExpression' && + node.object.type === 'Identifier' && + node.object.name === 'React' && + node.property.type === 'Identifier' && + node.property.name === functionName)); +} +function isForwardRefCallback$1(path) { + return !!(path.parentPath.isCallExpression() && + path.parentPath.get('callee').isExpression() && + isReactAPI(path.parentPath.get('callee'), 'forwardRef')); +} +function isMemoCallback$1(path) { + return (path.parentPath.isCallExpression() && + path.parentPath.get('callee').isExpression() && + isReactAPI(path.parentPath.get('callee'), 'memo')); +} +function isValidPropsAnnotation(annot) { + if (annot == null) { + return true; + } + else if (annot.type === 'TSTypeAnnotation') { + switch (annot.typeAnnotation.type) { + case 'TSArrayType': + case 'TSBigIntKeyword': + case 'TSBooleanKeyword': + case 'TSConstructorType': + case 'TSFunctionType': + case 'TSLiteralType': + case 'TSNeverKeyword': + case 'TSNumberKeyword': + case 'TSStringKeyword': + case 'TSSymbolKeyword': + case 'TSTupleType': + return false; + } + return true; + } + else if (annot.type === 'TypeAnnotation') { + switch (annot.typeAnnotation.type) { + case 'ArrayTypeAnnotation': + case 'BooleanLiteralTypeAnnotation': + case 'BooleanTypeAnnotation': + case 'EmptyTypeAnnotation': + case 'FunctionTypeAnnotation': + case 'NumberLiteralTypeAnnotation': + case 'NumberTypeAnnotation': + case 'StringLiteralTypeAnnotation': + case 'StringTypeAnnotation': + case 'SymbolTypeAnnotation': + case 'ThisTypeAnnotation': + case 'TupleTypeAnnotation': + return false; + } + return true; + } + else if (annot.type === 'Noop') { + return true; + } + else { + assertExhaustive$1(annot, `Unexpected annotation node \`${annot}\``); + } +} +function isValidComponentParams(params) { + if (params.length === 0) { + return true; + } + else if (params.length > 0 && params.length <= 2) { + if (!isValidPropsAnnotation(params[0].node.typeAnnotation)) { + return false; + } + if (params.length === 1) { + return !params[0].isRestElement(); + } + else if (params[1].isIdentifier()) { + const { name } = params[1].node; + return name.includes('ref') || name.includes('Ref'); + } + else { + return false; + } + } + return false; +} +function getComponentOrHookLike(node) { + const functionName = getFunctionName$1(node); + if (functionName !== null && isComponentName$1(functionName)) { + let isComponent = callsHooksOrCreatesJsx(node) && + isValidComponentParams(node.get('params')) && + !returnsNonNode(node); + return isComponent ? 'Component' : null; + } + else if (functionName !== null && isHook$1(functionName)) { + return callsHooksOrCreatesJsx(node) ? 'Hook' : null; + } + if (node.isFunctionExpression() || node.isArrowFunctionExpression()) { + if (isForwardRefCallback$1(node) || isMemoCallback$1(node)) { + return callsHooksOrCreatesJsx(node) ? 'Component' : null; + } + } + return null; +} +function skipNestedFunctions(node) { + return (fn) => { + if (fn.node !== node.node) { + fn.skip(); + } + }; +} +function callsHooksOrCreatesJsx(node) { + let invokesHooks = false; + let createsJsx = false; + node.traverse({ + JSX() { + createsJsx = true; + }, + CallExpression(call) { + const callee = call.get('callee'); + if (callee.isExpression() && isHook$1(callee)) { + invokesHooks = true; + } + }, + ArrowFunctionExpression: skipNestedFunctions(node), + FunctionExpression: skipNestedFunctions(node), + FunctionDeclaration: skipNestedFunctions(node), + }); + return invokesHooks || createsJsx; +} +function isNonNode(node) { + if (!node) { + return true; + } + switch (node.type) { + case 'ObjectExpression': + case 'ArrowFunctionExpression': + case 'FunctionExpression': + case 'BigIntLiteral': + case 'ClassExpression': + case 'NewExpression': + return true; + } + return false; +} +function returnsNonNode(node) { + let returnsNonNode = false; + if (node.type === 'ArrowFunctionExpression' && + node.node.body.type !== 'BlockStatement') { + returnsNonNode = isNonNode(node.node.body); + } + node.traverse({ + ReturnStatement(ret) { + returnsNonNode = isNonNode(ret.node.argument); + }, + ArrowFunctionExpression: skipNestedFunctions(node), + FunctionExpression: skipNestedFunctions(node), + FunctionDeclaration: skipNestedFunctions(node), + ObjectMethod: node => node.skip(), + }); + return returnsNonNode; +} +function getFunctionName$1(path) { + if (path.isFunctionDeclaration()) { + const id = path.get('id'); + if (id.isIdentifier()) { + return id; + } + return null; + } + let id = null; + const parent = path.parentPath; + if (parent.isVariableDeclarator() && parent.get('init').node === path.node) { + id = parent.get('id'); + } + else if (parent.isAssignmentExpression() && + parent.get('right').node === path.node && + parent.get('operator') === '=') { + id = parent.get('left'); + } + else if (parent.isProperty() && + parent.get('value').node === path.node && + !parent.get('computed') && + parent.get('key').isLVal()) { + id = parent.get('key'); + } + else if (parent.isAssignmentPattern() && + parent.get('right').node === path.node && + !parent.get('computed')) { + id = parent.get('left'); + } + if (id !== null && (id.isIdentifier() || id.isMemberExpression())) { + return id; + } + else { + return null; + } +} +function getFunctionReferencedBeforeDeclarationAtTopLevel(program, fns) { + const fnNames = new Map(fns + .map(fn => [ + getFunctionName$1(fn.originalFn), + fn, + ]) + .filter((entry) => !!entry[0] && entry[0].isIdentifier()) + .map(entry => [entry[0].node.name, { id: entry[0].node, fn: entry[1] }])); + const referencedBeforeDeclaration = new Set(); + program.traverse({ + TypeAnnotation(path) { + path.skip(); + }, + TSTypeAnnotation(path) { + path.skip(); + }, + TypeAlias(path) { + path.skip(); + }, + TSTypeAliasDeclaration(path) { + path.skip(); + }, + Identifier(id) { + const fn = fnNames.get(id.node.name); + if (!fn) { + return; + } + if (id.node === fn.id) { + fnNames.delete(id.node.name); + return; + } + const scope = id.scope.getFunctionParent(); + if (scope === null && id.isReferencedIdentifier()) { + referencedBeforeDeclaration.add(fn.fn); + } + }, + }); + return referencedBeforeDeclaration; +} +function getReactCompilerRuntimeModule(target) { + if (target === '19') { + return 'react/compiler-runtime'; + } + else if (target === '17' || target === '18') { + return 'react-compiler-runtime'; + } + else { + CompilerError.invariant(target != null && + target.kind === 'donotuse_meta_internal' && + typeof target.runtimeModule === 'string', { + reason: 'Expected target to already be validated', + loc: GeneratedSource, + }); + return target.runtimeModule; + } +} + +function validateRestrictedImports(path, { validateBlocklistedImports }) { + if (validateBlocklistedImports == null || + validateBlocklistedImports.length === 0) { + return null; + } + const error = new CompilerError(); + const restrictedImports = new Set(validateBlocklistedImports); + path.traverse({ + ImportDeclaration(importDeclPath) { + var _a; + if (restrictedImports.has(importDeclPath.node.source.value)) { + error.push({ + category: ErrorCategory.Todo, + reason: 'Bailing out due to blocklisted import', + description: `Import from module ${importDeclPath.node.source.value}`, + loc: (_a = importDeclPath.node.loc) !== null && _a !== void 0 ? _a : null, + }); + } + }, + }); + if (error.hasAnyErrors()) { + return error; + } + else { + return null; + } +} +class ProgramContext { + constructor({ program, suppressions, opts, filename, code, hasModuleScopeOptOut, }) { + this.alreadyCompiled = new (WeakSet !== null && WeakSet !== void 0 ? WeakSet : Set)(); + this.knownReferencedNames = new Set(); + this.imports = new Map(); + this.scope = program.scope; + this.opts = opts; + this.filename = filename; + this.code = code; + this.reactRuntimeModule = getReactCompilerRuntimeModule(opts.target); + this.suppressions = suppressions; + this.hasModuleScopeOptOut = hasModuleScopeOptOut; + } + isHookName(name) { + return isHookName$2(name); + } + hasReference(name) { + return (this.knownReferencedNames.has(name) || + this.scope.hasBinding(name) || + this.scope.hasGlobal(name) || + this.scope.hasReference(name)); + } + newUid(name) { + let uid; + if (this.isHookName(name)) { + uid = name; + let i = 0; + while (this.hasReference(uid)) { + this.knownReferencedNames.add(uid); + uid = `${name}_${i++}`; + } + } + else if (!this.hasReference(name)) { + uid = name; + } + else { + uid = this.scope.generateUid(name); + } + this.knownReferencedNames.add(uid); + return uid; + } + addMemoCacheImport() { + return this.addImportSpecifier({ + source: this.reactRuntimeModule, + importSpecifierName: 'c', + }, '_c'); + } + addImportSpecifier({ source: module, importSpecifierName: specifier }, nameHint) { + var _a; + const maybeBinding = (_a = this.imports.get(module)) === null || _a === void 0 ? void 0 : _a.get(specifier); + if (maybeBinding != null) { + return Object.assign({}, maybeBinding); + } + const binding = { + kind: 'ImportSpecifier', + name: this.newUid(nameHint !== null && nameHint !== void 0 ? nameHint : specifier), + module, + imported: specifier, + }; + getOrInsertWith(this.imports, module, () => new Map()).set(specifier, Object.assign({}, binding)); + return binding; + } + addNewReference(name) { + this.knownReferencedNames.add(name); + } + assertGlobalBinding(name, localScope) { + var _a, _b; + const scope = localScope !== null && localScope !== void 0 ? localScope : this.scope; + if (!scope.hasReference(name) && !scope.hasBinding(name)) { + return Ok(undefined); + } + const error = new CompilerError(); + error.push({ + category: ErrorCategory.Todo, + reason: 'Encountered conflicting global in generated program', + description: `Conflict from local binding ${name}`, + loc: (_b = (_a = scope.getBinding(name)) === null || _a === void 0 ? void 0 : _a.path.node.loc) !== null && _b !== void 0 ? _b : null, + suggestions: null, + }); + return Err(error); + } + logEvent(event) { + if (this.opts.logger != null) { + this.opts.logger.logEvent(this.filename, event); + } + } +} +function getExistingImports(program) { + const existingImports = new Map(); + program.traverse({ + ImportDeclaration(path) { + if (isNonNamespacedImport(path)) { + existingImports.set(path.node.source.value, path); + } + }, + }); + return existingImports; +} +function addImportsToProgram(path, programContext) { + const existingImports = getExistingImports(path); + const stmts = []; + const sortedModules = [...programContext.imports.entries()].sort(([a], [b]) => a.localeCompare(b)); + for (const [moduleName, importsMap] of sortedModules) { + for (const [specifierName, loweredImport] of importsMap) { + CompilerError.invariant(path.scope.getBinding(loweredImport.name) == null, { + reason: 'Encountered conflicting import specifiers in generated program', + description: `Conflict from import ${loweredImport.module}:(${loweredImport.imported} as ${loweredImport.name})`, + loc: GeneratedSource, + }); + CompilerError.invariant(loweredImport.module === moduleName && + loweredImport.imported === specifierName, { + reason: 'Found inconsistent import specifier. This is an internal bug.', + description: `Expected import ${moduleName}:${specifierName} but found ${loweredImport.module}:${loweredImport.imported}`, + loc: GeneratedSource, + }); + } + const sortedImport = [ + ...importsMap.values(), + ].sort(({ imported: a }, { imported: b }) => a.localeCompare(b)); + const importSpecifiers = sortedImport.map(specifier => { + return libExports$1.importSpecifier(libExports$1.identifier(specifier.name), libExports$1.identifier(specifier.imported)); + }); + const maybeExistingImports = existingImports.get(moduleName); + if (maybeExistingImports != null) { + maybeExistingImports.pushContainer('specifiers', importSpecifiers); + } + else { + if (path.node.sourceType === 'module') { + stmts.push(libExports$1.importDeclaration(importSpecifiers, libExports$1.stringLiteral(moduleName))); + } + else { + stmts.push(libExports$1.variableDeclaration('const', [ + libExports$1.variableDeclarator(libExports$1.objectPattern(sortedImport.map(specifier => { + return libExports$1.objectProperty(libExports$1.identifier(specifier.imported), libExports$1.identifier(specifier.name)); + })), libExports$1.callExpression(libExports$1.identifier('require'), [ + libExports$1.stringLiteral(moduleName), + ])), + ])); + } + } + } + path.unshiftContainer('body', stmts); +} +function isNonNamespacedImport(importDeclPath) { + return (importDeclPath + .get('specifiers') + .every(specifier => specifier.isImportSpecifier()) && + importDeclPath.node.importKind !== 'type' && + importDeclPath.node.importKind !== 'typeof'); +} + +v4.z.enum([ + 'all_errors', + 'critical_errors', + 'none', +]); +const DynamicGatingOptionsSchema = v4.z.object({ + source: v4.z.string(), +}); +const CustomOptOutDirectiveSchema = v4.z + .nullable(v4.z.array(v4.z.string())) + .default(null); +const CompilerReactTargetSchema = v4.z.union([ + v4.z.literal('17'), + v4.z.literal('18'), + v4.z.literal('19'), + v4.z.object({ + kind: v4.z.literal('donotuse_meta_internal'), + runtimeModule: v4.z.string().default('react'), + }), +]); +v4.z.enum([ + 'infer', + 'syntax', + 'annotation', + 'all', +]); +v4.z.enum([ + 'ssr', + 'client', + 'lint', +]); +const defaultOptions = { + compilationMode: 'infer', + panicThreshold: 'none', + environment: parseEnvironmentConfig({}).unwrap(), + logger: null, + gating: null, + noEmit: false, + outputMode: null, + dynamicGating: null, + eslintSuppressionRules: null, + flowSuppressions: true, + ignoreUseNoForget: false, + sources: filename => { + return filename.indexOf('node_modules') === -1; + }, + enableReanimatedCheck: true, + customOptOutDirectives: null, + target: '19', +}; +function parsePluginOptions(obj) { + if (obj == null || typeof obj !== 'object') { + return defaultOptions; + } + const parsedOptions = Object.create(null); + for (let [key, value] of Object.entries(obj)) { + if (typeof value === 'string') { + value = value.toLowerCase(); + } + if (isCompilerFlag(key)) { + switch (key) { + case 'environment': { + const environmentResult = parseEnvironmentConfig(value); + if (environmentResult.isErr()) { + CompilerError.throwInvalidConfig({ + reason: 'Error in validating environment config. This is an advanced setting and not meant to be used directly', + description: environmentResult.unwrapErr().toString(), + suggestions: null, + loc: null, + }); + } + parsedOptions[key] = environmentResult.unwrap(); + break; + } + case 'target': { + parsedOptions[key] = parseTargetConfig(value); + break; + } + case 'gating': { + if (value == null) { + parsedOptions[key] = null; + } + else { + parsedOptions[key] = tryParseExternalFunction(value); + } + break; + } + case 'dynamicGating': { + if (value == null) { + parsedOptions[key] = null; + } + else { + const result = DynamicGatingOptionsSchema.safeParse(value); + if (result.success) { + parsedOptions[key] = result.data; + } + else { + CompilerError.throwInvalidConfig({ + reason: 'Could not parse dynamic gating. Update React Compiler config to fix the error', + description: `${v4$1.fromZodError(result.error)}`, + loc: null, + suggestions: null, + }); + } + } + break; + } + case 'customOptOutDirectives': { + const result = CustomOptOutDirectiveSchema.safeParse(value); + if (result.success) { + parsedOptions[key] = result.data; + } + else { + CompilerError.throwInvalidConfig({ + reason: 'Could not parse custom opt out directives. Update React Compiler config to fix the error', + description: `${v4$1.fromZodError(result.error)}`, + loc: null, + suggestions: null, + }); + } + break; + } + default: { + parsedOptions[key] = value; + } + } + } + } + return Object.assign(Object.assign({}, defaultOptions), parsedOptions); +} +function parseTargetConfig(value) { + const parsed = CompilerReactTargetSchema.safeParse(value); + if (parsed.success) { + return parsed.data; + } + else { + CompilerError.throwInvalidConfig({ + reason: 'Not a valid target', + description: `${v4$1.fromZodError(parsed.error)}`, + suggestions: null, + loc: null, + }); + } +} +function isCompilerFlag(s) { + return hasOwnProperty$1(defaultOptions, s); +} + +function hasModule(name) { + if (typeof require === 'undefined') { + return false; + } + try { + return !!require.resolve(name); + } + catch (error) { + if (error.code === 'MODULE_NOT_FOUND' && + error.message.indexOf(name) !== -1) { + return false; + } + throw error; + } +} +function pipelineUsesReanimatedPlugin(plugins) { + if (Array.isArray(plugins)) { + for (const plugin of plugins) { + if (hasOwnProperty$1(plugin, 'key')) { + const key = plugin.key; + if (typeof key === 'string' && + key.indexOf('react-native-reanimated') !== -1) { + return true; + } + } + } + } + return hasModule('react-native-reanimated'); +} +function injectReanimatedFlag(options) { + return Object.assign(Object.assign({}, options), { environment: Object.assign(Object.assign({}, options.environment), { enableCustomTypeDefinitionForReanimated: true }) }); +} + +const ENABLE_REACT_COMPILER_TIMINGS = process.env['ENABLE_REACT_COMPILER_TIMINGS'] === '1'; +function BabelPluginReactCompiler(_babel) { + return { + name: 'react-forget', + visitor: { + Program: { + enter(prog, pass) { + var _a, _b, _c; + try { + const filename = (_a = pass.filename) !== null && _a !== void 0 ? _a : 'unknown'; + if (ENABLE_REACT_COMPILER_TIMINGS === true) { + performance.mark(`${filename}:start`, { + detail: 'BabelPlugin:Program:start', + }); + } + let opts = parsePluginOptions(pass.opts); + const isDev = (typeof false !== 'undefined' && false === true) || + process.env['NODE_ENV'] === 'development'; + if (opts.enableReanimatedCheck === true && + pipelineUsesReanimatedPlugin(pass.file.opts.plugins)) { + opts = injectReanimatedFlag(opts); + } + if (opts.environment.enableResetCacheOnSourceFileChanges !== false && + isDev) { + opts = Object.assign(Object.assign({}, opts), { environment: Object.assign(Object.assign({}, opts.environment), { enableResetCacheOnSourceFileChanges: true }) }); + } + compileProgram(prog, { + opts, + filename: (_b = pass.filename) !== null && _b !== void 0 ? _b : null, + comments: (_c = pass.file.ast.comments) !== null && _c !== void 0 ? _c : [], + code: pass.file.code, + }); + if (ENABLE_REACT_COMPILER_TIMINGS === true) { + performance.mark(`${filename}:end`, { + detail: 'BabelPlugin:Program:end', + }); + } + } + catch (e) { + if (e instanceof CompilerError) { + throw e.withPrintedMessage(pass.file.code, { eslint: false }); + } + throw e; + } + }, + exit(_, pass) { + var _a; + if (ENABLE_REACT_COMPILER_TIMINGS === true) { + const filename = (_a = pass.filename) !== null && _a !== void 0 ? _a : 'unknown'; + const measurement = performance.measure(filename, { + start: `${filename}:start`, + end: `${filename}:end`, + detail: 'BabelPlugin:Program', + }); + if ('logger' in pass.opts && pass.opts.logger != null) { + const logger = pass.opts.logger; + logger.logEvent(filename, { + kind: 'Timing', + measurement, + }); + } + } + }, + }, + }, + }; +} + +// ----------------------------------------------------------------------------- +// Land or remove (zero effort) +// +// Flags that can likely be deleted or landed without consequences +// ----------------------------------------------------------------------------- + + +// ----------------------------------------------------------------------------- +// eslint-plugin-react-hooks +// ----------------------------------------------------------------------------- +const eprh_enableUseKeyedStateCompilerLint = false; +const eprh_enableVerboseNoSetStateInEffectCompilerLint = false; +const eprh_enableExhaustiveEffectDependenciesCompilerLint = 'off'; + +var _LRUCache_values, _LRUCache_headIdx; +const COMPONENT_NAME_PATTERN = /^[A-Z]/; +const HOOK_NAME_PATTERN = /^use[A-Z0-9]/; +function mayContainReactCode(sourceCode) { + const ast = sourceCode.ast; + for (const node of ast.body) { + if (checkTopLevelNode(node)) { + return true; + } + } + return false; +} +function checkTopLevelNode(node) { + if (node.type === 'ComponentDeclaration' || node.type === 'HookDeclaration') { + return true; + } + if (node.type === 'ExportNamedDeclaration') { + const decl = node.declaration; + if (decl != null) { + return checkTopLevelNode(decl); + } + return false; + } + if (node.type === 'ExportDefaultDeclaration') { + const decl = node.declaration; + if (decl.type === 'FunctionExpression' || + decl.type === 'ArrowFunctionExpression' || + (decl.type === 'FunctionDeclaration' && + decl.id == null)) { + return true; + } + return checkTopLevelNode(decl); + } + if (node.type === 'FunctionDeclaration') { + if ('__componentDeclaration' in node || '__hookDeclaration' in node) { + return true; + } + const id = node.id; + if (id != null) { + const name = id.name; + if (COMPONENT_NAME_PATTERN.test(name) || HOOK_NAME_PATTERN.test(name)) { + return true; + } + } + } + if (node.type === 'VariableDeclaration') { + for (const decl of node.declarations) { + if (decl.id.type === 'Identifier') { + const init = decl.init; + if (init != null && + (init.type === 'ArrowFunctionExpression' || + init.type === 'FunctionExpression')) { + const name = decl.id.name; + if (COMPONENT_NAME_PATTERN.test(name) || + HOOK_NAME_PATTERN.test(name)) { + return true; + } + } + } + } + } + return false; +} +const COMPILER_OPTIONS = { + outputMode: 'lint', + panicThreshold: 'none', + flowSuppressions: false, + environment: { + validateRefAccessDuringRender: true, + validateNoSetStateInRender: true, + validateNoSetStateInEffects: true, + validateNoJSXInTryStatements: true, + validateNoImpureFunctionsInRender: true, + validateStaticComponents: true, + validateNoFreezingKnownMutableFunctions: true, + validateNoVoidUseMemo: true, + validateNoCapitalizedCalls: [], + validateHooksUsage: true, + validateNoDerivedComputationsInEffects: true, + enableUseKeyedState: eprh_enableUseKeyedStateCompilerLint, + enableVerboseNoSetStateInEffect: eprh_enableVerboseNoSetStateInEffectCompilerLint, + validateExhaustiveEffectDependencies: eprh_enableExhaustiveEffectDependenciesCompilerLint, + }, +}; +const FLOW_SUPPRESSION_REGEX = /\$FlowFixMe\[([^\]]*)\]/g; +function getFlowSuppressions(sourceCode) { + const comments = sourceCode.getAllComments(); + const results = []; + for (const commentNode of comments) { + const matches = commentNode.value.matchAll(FLOW_SUPPRESSION_REGEX); + for (const match of matches) { + if (match.index != null && commentNode.loc != null) { + const code = match[1]; + results.push({ + line: commentNode.loc.end.line, + code, + }); + } + } + } + return results; +} +function runReactCompilerImpl({ sourceCode, filename, userOpts, }) { + var _a, _b; + const options = parsePluginOptions(Object.assign(Object.assign(Object.assign({}, COMPILER_OPTIONS), userOpts), { environment: Object.assign(Object.assign({}, COMPILER_OPTIONS.environment), userOpts.environment) })); + const results = { + sourceCode: sourceCode.text, + filename, + userOpts, + flowSuppressions: [], + events: [], + }; + const userLogger = options.logger; + options.logger = { + logEvent: (eventFilename, event) => { + userLogger === null || userLogger === void 0 ? void 0 : userLogger.logEvent(eventFilename, event); + results.events.push(event); + }, + }; + try { + options.environment = validateEnvironmentConfig((_a = options.environment) !== null && _a !== void 0 ? _a : {}); + } + catch (err) { + (_b = options.logger) === null || _b === void 0 ? void 0 : _b.logEvent(filename, err); + } + let babelAST = null; + if (filename.endsWith('.tsx') || filename.endsWith('.ts')) { + try { + babelAST = BabelParser.parse(sourceCode.text, { + sourceFilename: filename, + sourceType: 'unambiguous', + plugins: ['typescript', 'jsx'], + }); + } + catch (_c) { + } + } + else { + try { + babelAST = HermesParser.parse(sourceCode.text, { + babel: true, + enableExperimentalComponentSyntax: true, + sourceFilename: filename, + sourceType: 'module', + }); + } + catch (_d) { + } + } + if (babelAST != null) { + results.flowSuppressions = getFlowSuppressions(sourceCode); + try { + core$1.transformFromAstSync(babelAST, sourceCode.text, { + filename, + highlightCode: false, + retainLines: true, + plugins: [[BabelPluginReactCompiler, options]], + sourceType: 'module', + configFile: false, + babelrc: false, + }); + } + catch (err) { + } + } + return results; +} +const SENTINEL = Symbol(); +class LRUCache { + constructor(size) { + _LRUCache_values.set(this, void 0); + _LRUCache_headIdx.set(this, 0); + __classPrivateFieldSet(this, _LRUCache_values, new Array(size).fill(SENTINEL), "f"); + } + get(key) { + const idx = __classPrivateFieldGet(this, _LRUCache_values, "f").findIndex(entry => entry[0] === key); + if (idx === __classPrivateFieldGet(this, _LRUCache_headIdx, "f")) { + return __classPrivateFieldGet(this, _LRUCache_values, "f")[__classPrivateFieldGet(this, _LRUCache_headIdx, "f")][1]; + } + else if (idx < 0) { + return null; + } + const entry = __classPrivateFieldGet(this, _LRUCache_values, "f")[idx]; + const len = __classPrivateFieldGet(this, _LRUCache_values, "f").length; + for (let i = 0; i < Math.min(idx, len - 1); i++) { + __classPrivateFieldGet(this, _LRUCache_values, "f")[(__classPrivateFieldGet(this, _LRUCache_headIdx, "f") + i + 1) % len] = + __classPrivateFieldGet(this, _LRUCache_values, "f")[(__classPrivateFieldGet(this, _LRUCache_headIdx, "f") + i) % len]; + } + __classPrivateFieldGet(this, _LRUCache_values, "f")[__classPrivateFieldGet(this, _LRUCache_headIdx, "f")] = entry; + return entry[1]; + } + push(key, value) { + __classPrivateFieldSet(this, _LRUCache_headIdx, (__classPrivateFieldGet(this, _LRUCache_headIdx, "f") - 1 + __classPrivateFieldGet(this, _LRUCache_values, "f").length) % __classPrivateFieldGet(this, _LRUCache_values, "f").length, "f"); + __classPrivateFieldGet(this, _LRUCache_values, "f")[__classPrivateFieldGet(this, _LRUCache_headIdx, "f")] = [key, value]; + } +} +_LRUCache_values = new WeakMap(), _LRUCache_headIdx = new WeakMap(); +const cache = new LRUCache(10); +function runReactCompiler({ sourceCode, filename, userOpts, }) { + const entry = cache.get(filename); + if (entry != null && + entry.sourceCode === sourceCode.text && + util.isDeepStrictEqual(entry.userOpts, userOpts)) { + return entry; + } + if (!mayContainReactCode(sourceCode)) { + const emptyResult = { + sourceCode: sourceCode.text, + filename, + userOpts, + flowSuppressions: [], + events: [], + }; + if (entry != null) { + Object.assign(entry, emptyResult); + } + else { + cache.push(filename, emptyResult); + } + return Object.assign({}, emptyResult); + } + const runEntry = runReactCompilerImpl({ + sourceCode, + filename, + userOpts, + }); + if (entry != null) { + Object.assign(entry, runEntry); + } + else { + cache.push(filename, runEntry); + } + return Object.assign({}, runEntry); +} + +function assertExhaustive(_, errorMsg) { + throw new Error(errorMsg); +} +function makeSuggestions(detail) { + const suggest = []; + if (Array.isArray(detail.suggestions)) { + for (const suggestion of detail.suggestions) { + switch (suggestion.op) { + case CompilerSuggestionOperation.InsertBefore: + suggest.push({ + desc: suggestion.description, + fix(fixer) { + return fixer.insertTextBeforeRange(suggestion.range, suggestion.text); + }, + }); + break; + case CompilerSuggestionOperation.InsertAfter: + suggest.push({ + desc: suggestion.description, + fix(fixer) { + return fixer.insertTextAfterRange(suggestion.range, suggestion.text); + }, + }); + break; + case CompilerSuggestionOperation.Replace: + suggest.push({ + desc: suggestion.description, + fix(fixer) { + return fixer.replaceTextRange(suggestion.range, suggestion.text); + }, + }); + break; + case CompilerSuggestionOperation.Remove: + suggest.push({ + desc: suggestion.description, + fix(fixer) { + return fixer.removeRange(suggestion.range); + }, + }); + break; + default: + assertExhaustive(suggestion, 'Unhandled suggestion operation'); + } + } + } + return suggest; +} +function getReactCompilerResult(context) { + var _a, _b, _c; + const sourceCode = (_a = context.sourceCode) !== null && _a !== void 0 ? _a : context.getSourceCode(); + const filename = (_b = context.filename) !== null && _b !== void 0 ? _b : context.getFilename(); + const userOpts = (_c = context.options[0]) !== null && _c !== void 0 ? _c : {}; + const results = runReactCompiler({ + sourceCode, + filename, + userOpts, + }); + return results; +} +function hasFlowSuppression(program, nodeLoc, suppressions) { + for (const commentNode of program.flowSuppressions) { + if (suppressions.includes(commentNode.code) && + commentNode.line === nodeLoc.start.line - 1) { + return true; + } + } + return false; +} +function makeRule(rule) { + const create = (context) => { + const result = getReactCompilerResult(context); + for (const event of result.events) { + if (event.kind === 'CompileError') { + const detail = event.detail; + if (detail.category === rule.category) { + const loc = detail.primaryLocation(); + if (loc == null || typeof loc === 'symbol') { + continue; + } + if (hasFlowSuppression(result, loc, [ + 'react-rule-hook', + 'react-rule-unsafe-ref', + ])) { + continue; + } + context.report({ + message: detail.printErrorMessage(result.sourceCode, { + eslint: true, + }), + loc, + suggest: makeSuggestions(detail.options), + }); + } + } + } + return {}; + }; + return { + meta: { + type: 'problem', + docs: { + description: rule.description, + recommended: rule.preset === LintRulePreset.Recommended, + url: `https://react.dev/reference/eslint-plugin-react-hooks/lints/${rule.name}`, + }, + fixable: 'code', + hasSuggestions: true, + schema: [{ type: 'object', additionalProperties: true }], + }, + create, + }; +} +const allRules = LintRules.reduce((acc, rule) => { + acc[rule.name] = { rule: makeRule(rule), severity: rule.severity }; + return acc; +}, {}); +const recommendedRules = LintRules.filter(rule => rule.preset === LintRulePreset.Recommended).reduce((acc, rule) => { + acc[rule.name] = { rule: makeRule(rule), severity: rule.severity }; + return acc; +}, {}); +const recommendedLatestRules = LintRules.filter(rule => rule.preset === LintRulePreset.Recommended || + rule.preset === LintRulePreset.RecommendedLatest).reduce((acc, rule) => { + acc[rule.name] = { rule: makeRule(rule), severity: rule.severity }; + return acc; +}, {}); +function mapErrorSeverityToESlint(severity) { + switch (severity) { + case ErrorSeverity.Error: { + return 'error'; + } + case ErrorSeverity.Warning: { + return 'warn'; + } + case ErrorSeverity.Hint: + case ErrorSeverity.Off: { + return 'off'; + } + default: { + assertExhaustive(severity, `Unhandled severity: ${severity}`); + } + } +} + +var assert_1; +var hasRequiredAssert; +function requireAssert() { + if (hasRequiredAssert) return assert_1; + hasRequiredAssert = 1; + function assert(cond) { + if (!cond) { + throw new Error('Assertion violated.'); + } + } + assert_1 = assert; + return assert_1; +} + +var codePathSegment; +var hasRequiredCodePathSegment; +function requireCodePathSegment() { + if (hasRequiredCodePathSegment) return codePathSegment; + hasRequiredCodePathSegment = 1; + + //------------------------------------------------------------------------------ + // Requirements + //------------------------------------------------------------------------------ + + //------------------------------------------------------------------------------ + // Helpers + //------------------------------------------------------------------------------ + + /** + * Checks whether or not a given segment is reachable. + * @param {CodePathSegment} segment A segment to check. + * @returns {boolean} `true` if the segment is reachable. + */ + function isReachable(segment) { + return segment.reachable; + } + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * A code path segment. + */ + class CodePathSegment { + /** + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * This array includes unreachable segments. + * @param {boolean} reachable A flag which shows this is reachable. + */ + constructor(id, allPrevSegments, reachable) { + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * An array of the next segments. + * @type {CodePathSegment[]} + */ + this.nextSegments = []; + + /** + * An array of the previous segments. + * @type {CodePathSegment[]} + */ + this.prevSegments = allPrevSegments.filter(isReachable); + + /** + * An array of the next segments. + * This array includes unreachable segments. + * @type {CodePathSegment[]} + */ + this.allNextSegments = []; + + /** + * An array of the previous segments. + * This array includes unreachable segments. + * @type {CodePathSegment[]} + */ + this.allPrevSegments = allPrevSegments; + + /** + * A flag which shows this is reachable. + * @type {boolean} + */ + this.reachable = reachable; + + // Internal data. + Object.defineProperty(this, 'internal', { + value: { + used: false, + loopedPrevSegments: [] + } + }); + } + + /** + * Checks a given previous segment is coming from the end of a loop. + * @param {CodePathSegment} segment A previous segment to check. + * @returns {boolean} `true` if the segment is coming from the end of a loop. + */ + isLoopedPrevSegment(segment) { + return this.internal.loopedPrevSegments.includes(segment); + } + + /** + * Creates the root segment. + * @param {string} id An identifier. + * @returns {CodePathSegment} The created segment. + */ + static newRoot(id) { + return new CodePathSegment(id, [], true); + } + + /** + * Creates a segment that follows given segments. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newNext(id, allPrevSegments) { + return new CodePathSegment(id, CodePathSegment.flattenUnusedSegments(allPrevSegments), allPrevSegments.some(isReachable)); + } + + /** + * Creates an unreachable segment that follows given segments. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newUnreachable(id, allPrevSegments) { + const segment = new CodePathSegment(id, CodePathSegment.flattenUnusedSegments(allPrevSegments), false); + + /* + * In `if (a) return a; foo();` case, the unreachable segment preceded by + * the return statement is not used but must not be remove. + */ + CodePathSegment.markUsed(segment); + return segment; + } + + /** + * Creates a segment that follows given segments. + * This factory method does not connect with `allPrevSegments`. + * But this inherits `reachable` flag. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newDisconnected(id, allPrevSegments) { + return new CodePathSegment(id, [], allPrevSegments.some(isReachable)); + } + + /** + * Makes a given segment being used. + * + * And this function registers the segment into the previous segments as a next. + * @param {CodePathSegment} segment A segment to mark. + * @returns {void} + */ + static markUsed(segment) { + if (segment.internal.used) { + return; + } + segment.internal.used = true; + let i; + if (segment.reachable) { + for (i = 0; i < segment.allPrevSegments.length; ++i) { + const prevSegment = segment.allPrevSegments[i]; + prevSegment.allNextSegments.push(segment); + prevSegment.nextSegments.push(segment); + } + } else { + for (i = 0; i < segment.allPrevSegments.length; ++i) { + segment.allPrevSegments[i].allNextSegments.push(segment); + } + } + } + + /** + * Marks a previous segment as looped. + * @param {CodePathSegment} segment A segment. + * @param {CodePathSegment} prevSegment A previous segment to mark. + * @returns {void} + */ + static markPrevSegmentAsLooped(segment, prevSegment) { + segment.internal.loopedPrevSegments.push(prevSegment); + } + + /** + * Replaces unused segments with the previous segments of each unused segment. + * @param {CodePathSegment[]} segments An array of segments to replace. + * @returns {CodePathSegment[]} The replaced array. + */ + static flattenUnusedSegments(segments) { + const done = Object.create(null); + const retv = []; + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + // Ignores duplicated. + if (done[segment.id]) { + continue; + } + + // Use previous segments if unused. + if (!segment.internal.used) { + for (let j = 0; j < segment.allPrevSegments.length; ++j) { + const prevSegment = segment.allPrevSegments[j]; + if (!done[prevSegment.id]) { + done[prevSegment.id] = true; + retv.push(prevSegment); + } + } + } else { + done[segment.id] = true; + retv.push(segment); + } + } + return retv; + } + } + codePathSegment = CodePathSegment; + return codePathSegment; +} + +var forkContext; +var hasRequiredForkContext; +function requireForkContext() { + if (hasRequiredForkContext) return forkContext; + hasRequiredForkContext = 1; + + //------------------------------------------------------------------------------ + // Requirements + //------------------------------------------------------------------------------ + + // eslint-disable-next-line + const assert = requireAssert(); + // eslint-disable-next-line + const CodePathSegment = requireCodePathSegment(); + + //------------------------------------------------------------------------------ + // Helpers + //------------------------------------------------------------------------------ + + /** + * Gets whether or not a given segment is reachable. + * @param {CodePathSegment} segment A segment to get. + * @returns {boolean} `true` if the segment is reachable. + */ + function isReachable(segment) { + return segment.reachable; + } + + /** + * Creates new segments from the specific range of `context.segmentsList`. + * + * When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and + * `end` is `-1`, this creates `[g, h]`. This `g` is from `a`, `c`, and `e`. + * This `h` is from `b`, `d`, and `f`. + * @param {ForkContext} context An instance. + * @param {number} begin The first index of the previous segments. + * @param {number} end The last index of the previous segments. + * @param {Function} create A factory function of new segments. + * @returns {CodePathSegment[]} New segments. + */ + function makeSegments(context, begin, end, create) { + const list = context.segmentsList; + const normalizedBegin = begin >= 0 ? begin : list.length + begin; + const normalizedEnd = end >= 0 ? end : list.length + end; + const segments = []; + for (let i = 0; i < context.count; ++i) { + const allPrevSegments = []; + for (let j = normalizedBegin; j <= normalizedEnd; ++j) { + allPrevSegments.push(list[j][i]); + } + segments.push(create(context.idGenerator.next(), allPrevSegments)); + } + return segments; + } + + /** + * `segments` becomes doubly in a `finally` block. Then if a code path exits by a + * control statement (such as `break`, `continue`) from the `finally` block, the + * destination's segments may be half of the source segments. In that case, this + * merges segments. + * @param {ForkContext} context An instance. + * @param {CodePathSegment[]} segments Segments to merge. + * @returns {CodePathSegment[]} The merged segments. + */ + function mergeExtraSegments(context, segments) { + let currentSegments = segments; + while (currentSegments.length > context.count) { + const merged = []; + for (let i = 0, length = currentSegments.length / 2 | 0; i < length; ++i) { + merged.push(CodePathSegment.newNext(context.idGenerator.next(), [currentSegments[i], currentSegments[i + length]])); + } + currentSegments = merged; + } + return currentSegments; + } + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * A class to manage forking. + */ + class ForkContext { + /** + * @param {IdGenerator} idGenerator An identifier generator for segments. + * @param {ForkContext|null} upper An upper fork context. + * @param {number} count A number of parallel segments. + */ + constructor(idGenerator, upper, count) { + this.idGenerator = idGenerator; + this.upper = upper; + this.count = count; + this.segmentsList = []; + } + + /** + * The head segments. + * @type {CodePathSegment[]} + */ + get head() { + const list = this.segmentsList; + return list.length === 0 ? [] : list[list.length - 1]; + } + + /** + * A flag which shows empty. + * @type {boolean} + */ + get empty() { + return this.segmentsList.length === 0; + } + + /** + * A flag which shows reachable. + * @type {boolean} + */ + get reachable() { + const segments = this.head; + return segments.length > 0 && segments.some(isReachable); + } + + /** + * Creates new segments from this context. + * @param {number} begin The first index of previous segments. + * @param {number} end The last index of previous segments. + * @returns {CodePathSegment[]} New segments. + */ + makeNext(begin, end) { + return makeSegments(this, begin, end, CodePathSegment.newNext); + } + + /** + * Creates new segments from this context. + * The new segments is always unreachable. + * @param {number} begin The first index of previous segments. + * @param {number} end The last index of previous segments. + * @returns {CodePathSegment[]} New segments. + */ + makeUnreachable(begin, end) { + return makeSegments(this, begin, end, CodePathSegment.newUnreachable); + } + + /** + * Creates new segments from this context. + * The new segments don't have connections for previous segments. + * But these inherit the reachable flag from this context. + * @param {number} begin The first index of previous segments. + * @param {number} end The last index of previous segments. + * @returns {CodePathSegment[]} New segments. + */ + makeDisconnected(begin, end) { + return makeSegments(this, begin, end, CodePathSegment.newDisconnected); + } + + /** + * Adds segments into this context. + * The added segments become the head. + * @param {CodePathSegment[]} segments Segments to add. + * @returns {void} + */ + add(segments) { + assert(segments.length >= this.count, segments.length + " >= " + this.count); + this.segmentsList.push(mergeExtraSegments(this, segments)); + } + + /** + * Replaces the head segments with given segments. + * The current head segments are removed. + * @param {CodePathSegment[]} segments Segments to add. + * @returns {void} + */ + replaceHead(segments) { + assert(segments.length >= this.count, segments.length + " >= " + this.count); + this.segmentsList.splice(-1, 1, mergeExtraSegments(this, segments)); + } + + /** + * Adds all segments of a given fork context into this context. + * @param {ForkContext} context A fork context to add. + * @returns {void} + */ + addAll(context) { + assert(context.count === this.count); + const source = context.segmentsList; + for (let i = 0; i < source.length; ++i) { + this.segmentsList.push(source[i]); + } + } + + /** + * Clears all segments in this context. + * @returns {void} + */ + clear() { + this.segmentsList = []; + } + + /** + * Creates the root fork context. + * @param {IdGenerator} idGenerator An identifier generator for segments. + * @returns {ForkContext} New fork context. + */ + static newRoot(idGenerator) { + const context = new ForkContext(idGenerator, null, 1); + context.add([CodePathSegment.newRoot(idGenerator.next())]); + return context; + } + + /** + * Creates an empty fork context preceded by a given context. + * @param {ForkContext} parentContext The parent fork context. + * @param {boolean} forkLeavingPath A flag which shows inside of `finally` block. + * @returns {ForkContext} New fork context. + */ + static newEmpty(parentContext, forkLeavingPath) { + return new ForkContext(parentContext.idGenerator, parentContext, (forkLeavingPath ? 2 : 1) * parentContext.count); + } + } + forkContext = ForkContext; + return forkContext; +} + +var codePathState; +var hasRequiredCodePathState; +function requireCodePathState() { + if (hasRequiredCodePathState) return codePathState; + hasRequiredCodePathState = 1; + + //------------------------------------------------------------------------------ + // Requirements + //------------------------------------------------------------------------------ + + // eslint-disable-next-line + const CodePathSegment = requireCodePathSegment(); + // eslint-disable-next-line + const ForkContext = requireForkContext(); + + //------------------------------------------------------------------------------ + // Helpers + //------------------------------------------------------------------------------ + + /** + * Adds given segments into the `dest` array. + * If the `others` array does not includes the given segments, adds to the `all` + * array as well. + * + * This adds only reachable and used segments. + * @param {CodePathSegment[]} dest A destination array (`returnedSegments` or `thrownSegments`). + * @param {CodePathSegment[]} others Another destination array (`returnedSegments` or `thrownSegments`). + * @param {CodePathSegment[]} all The unified destination array (`finalSegments`). + * @param {CodePathSegment[]} segments Segments to add. + * @returns {void} + */ + function addToReturnedOrThrown(dest, others, all, segments) { + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + dest.push(segment); + if (!others.includes(segment)) { + all.push(segment); + } + } + } + + /** + * Gets a loop-context for a `continue` statement. + * @param {CodePathState} state A state to get. + * @param {string} label The label of a `continue` statement. + * @returns {LoopContext} A loop-context for a `continue` statement. + */ + function getContinueContext(state, label) { + if (!label) { + return state.loopContext; + } + let context = state.loopContext; + while (context) { + if (context.label === label) { + return context; + } + context = context.upper; + } + + /* c8 ignore next */ + return null; + } + + /** + * Gets a context for a `break` statement. + * @param {CodePathState} state A state to get. + * @param {string} label The label of a `break` statement. + * @returns {LoopContext|SwitchContext} A context for a `break` statement. + */ + function getBreakContext(state, label) { + let context = state.breakContext; + while (context) { + if (label ? context.label === label : context.breakable) { + return context; + } + context = context.upper; + } + + /* c8 ignore next */ + return null; + } + + /** + * Gets a context for a `return` statement. + * @param {CodePathState} state A state to get. + * @returns {TryContext|CodePathState} A context for a `return` statement. + */ + function getReturnContext(state) { + let context = state.tryContext; + while (context) { + if (context.hasFinalizer && context.position !== 'finally') { + return context; + } + context = context.upper; + } + return state; + } + + /** + * Gets a context for a `throw` statement. + * @param {CodePathState} state A state to get. + * @returns {TryContext|CodePathState} A context for a `throw` statement. + */ + function getThrowContext(state) { + let context = state.tryContext; + while (context) { + if (context.position === 'try' || context.hasFinalizer && context.position === 'catch') { + return context; + } + context = context.upper; + } + return state; + } + + /** + * Removes a given element from a given array. + * @param {any[]} xs An array to remove the specific element. + * @param {any} x An element to be removed. + * @returns {void} + */ + function remove(xs, x) { + xs.splice(xs.indexOf(x), 1); + } + + /** + * Disconnect given segments. + * + * This is used in a process for switch statements. + * If there is the "default" chunk before other cases, the order is different + * between node's and running's. + * @param {CodePathSegment[]} prevSegments Forward segments to disconnect. + * @param {CodePathSegment[]} nextSegments Backward segments to disconnect. + * @returns {void} + */ + function removeConnection(prevSegments, nextSegments) { + for (let i = 0; i < prevSegments.length; ++i) { + const prevSegment = prevSegments[i]; + const nextSegment = nextSegments[i]; + remove(prevSegment.nextSegments, nextSegment); + remove(prevSegment.allNextSegments, nextSegment); + remove(nextSegment.prevSegments, prevSegment); + remove(nextSegment.allPrevSegments, prevSegment); + } + } + + /** + * Creates looping path. + * @param {CodePathState} state The instance. + * @param {CodePathSegment[]} unflattenedFromSegments Segments which are source. + * @param {CodePathSegment[]} unflattenedToSegments Segments which are destination. + * @returns {void} + */ + function makeLooped(state, unflattenedFromSegments, unflattenedToSegments) { + const fromSegments = CodePathSegment.flattenUnusedSegments(unflattenedFromSegments); + const toSegments = CodePathSegment.flattenUnusedSegments(unflattenedToSegments); + const end = Math.min(fromSegments.length, toSegments.length); + for (let i = 0; i < end; ++i) { + const fromSegment = fromSegments[i]; + const toSegment = toSegments[i]; + if (toSegment.reachable) { + fromSegment.nextSegments.push(toSegment); + } + if (fromSegment.reachable) { + toSegment.prevSegments.push(fromSegment); + } + fromSegment.allNextSegments.push(toSegment); + toSegment.allPrevSegments.push(fromSegment); + if (toSegment.allPrevSegments.length >= 2) { + CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment); + } + state.notifyLooped(fromSegment, toSegment); + } + } + + /** + * Finalizes segments of `test` chunk of a ForStatement. + * + * - Adds `false` paths to paths which are leaving from the loop. + * - Sets `true` paths to paths which go to the body. + * @param {LoopContext} context A loop context to modify. + * @param {ChoiceContext} choiceContext A choice context of this loop. + * @param {CodePathSegment[]} head The current head paths. + * @returns {void} + */ + function finalizeTestSegmentsOfFor(context, choiceContext, head) { + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(head); + choiceContext.falseForkContext.add(head); + choiceContext.qqForkContext.add(head); + } + if (context.test !== true) { + context.brokenForkContext.addAll(choiceContext.falseForkContext); + } + context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1); + } + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * A class which manages state to analyze code paths. + */ + class CodePathState { + /** + * @param {IdGenerator} idGenerator An id generator to generate id for code + * path segments. + * @param {Function} onLooped A callback function to notify looping. + */ + constructor(idGenerator, onLooped) { + this.idGenerator = idGenerator; + this.notifyLooped = onLooped; + this.forkContext = ForkContext.newRoot(idGenerator); + this.choiceContext = null; + this.switchContext = null; + this.tryContext = null; + this.loopContext = null; + this.breakContext = null; + this.chainContext = null; + this.currentSegments = []; + this.initialSegment = this.forkContext.head[0]; + + // returnedSegments and thrownSegments push elements into finalSegments also. + const final = this.finalSegments = []; + const returned = this.returnedForkContext = []; + const thrown = this.thrownForkContext = []; + returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final); + thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final); + } + + /** + * The head segments. + * @type {CodePathSegment[]} + */ + get headSegments() { + return this.forkContext.head; + } + + /** + * The parent forking context. + * This is used for the root of new forks. + * @type {ForkContext} + */ + get parentForkContext() { + const current = this.forkContext; + return current && current.upper; + } + + /** + * Creates and stacks new forking context. + * @param {boolean} forkLeavingPath A flag which shows being in a + * "finally" block. + * @returns {ForkContext} The created context. + */ + pushForkContext(forkLeavingPath) { + this.forkContext = ForkContext.newEmpty(this.forkContext, forkLeavingPath); + return this.forkContext; + } + + /** + * Pops and merges the last forking context. + * @returns {ForkContext} The last context. + */ + popForkContext() { + const lastContext = this.forkContext; + this.forkContext = lastContext.upper; + this.forkContext.replaceHead(lastContext.makeNext(0, -1)); + return lastContext; + } + + /** + * Creates a new path. + * @returns {void} + */ + forkPath() { + this.forkContext.add(this.parentForkContext.makeNext(-1, -1)); + } + + /** + * Creates a bypass path. + * This is used for such as IfStatement which does not have "else" chunk. + * @returns {void} + */ + forkBypassPath() { + this.forkContext.add(this.parentForkContext.head); + } + + //-------------------------------------------------------------------------- + // ConditionalExpression, LogicalExpression, IfStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context for ConditionalExpression, LogicalExpression, AssignmentExpression (logical assignments only), + * IfStatement, WhileStatement, DoWhileStatement, or ForStatement. + * + * LogicalExpressions have cases that it goes different paths between the + * `true` case and the `false` case. + * + * For Example: + * + * if (a || b) { + * foo(); + * } else { + * bar(); + * } + * + * In this case, `b` is evaluated always in the code path of the `else` + * block, but it's not so in the code path of the `if` block. + * So there are 3 paths. + * + * a -> foo(); + * a -> b -> foo(); + * a -> b -> bar(); + * @param {string} kind A kind string. + * If the new context is LogicalExpression's or AssignmentExpression's, this is `"&&"` or `"||"` or `"??"`. + * If it's IfStatement's or ConditionalExpression's, this is `"test"`. + * Otherwise, this is `"loop"`. + * @param {boolean} isForkingAsResult A flag that shows that goes different + * paths between `true` and `false`. + * @returns {void} + */ + pushChoiceContext(kind, isForkingAsResult) { + this.choiceContext = { + upper: this.choiceContext, + kind, + isForkingAsResult, + trueForkContext: ForkContext.newEmpty(this.forkContext), + falseForkContext: ForkContext.newEmpty(this.forkContext), + qqForkContext: ForkContext.newEmpty(this.forkContext), + processed: false + }; + } + + /** + * Pops the last choice context and finalizes it. + * @throws {Error} (Unreachable.) + * @returns {ChoiceContext} The popped context. + */ + popChoiceContext() { + const context = this.choiceContext; + this.choiceContext = context.upper; + const forkContext = this.forkContext; + const headSegments = forkContext.head; + switch (context.kind) { + case '&&': + case '||': + case '??': + /* + * If any result were not transferred from child contexts, + * this sets the head segments to both cases. + * The head segments are the path of the right-hand operand. + */ + if (!context.processed) { + context.trueForkContext.add(headSegments); + context.falseForkContext.add(headSegments); + context.qqForkContext.add(headSegments); + } + + /* + * Transfers results to upper context if this context is in + * test chunk. + */ + if (context.isForkingAsResult) { + const parentContext = this.choiceContext; + parentContext.trueForkContext.addAll(context.trueForkContext); + parentContext.falseForkContext.addAll(context.falseForkContext); + parentContext.qqForkContext.addAll(context.qqForkContext); + parentContext.processed = true; + return context; + } + break; + case 'test': + if (!context.processed) { + /* + * The head segments are the path of the `if` block here. + * Updates the `true` path with the end of the `if` block. + */ + context.trueForkContext.clear(); + context.trueForkContext.add(headSegments); + } else { + /* + * The head segments are the path of the `else` block here. + * Updates the `false` path with the end of the `else` + * block. + */ + context.falseForkContext.clear(); + context.falseForkContext.add(headSegments); + } + break; + case 'loop': + /* + * Loops are addressed in popLoopContext(). + * This is called from popLoopContext(). + */ + return context; + + /* c8 ignore next */ + default: + throw new Error('unreachable'); + } + + // Merges all paths. + const prevForkContext = context.trueForkContext; + prevForkContext.addAll(context.falseForkContext); + forkContext.replaceHead(prevForkContext.makeNext(0, -1)); + return context; + } + + /** + * Makes a code path segment of the right-hand operand of a logical + * expression. + * @throws {Error} (Unreachable.) + * @returns {void} + */ + makeLogicalRight() { + const context = this.choiceContext; + const forkContext = this.forkContext; + if (context.processed) { + /* + * This got segments already from the child choice context. + * Creates the next path from own true/false fork context. + */ + let prevForkContext; + switch (context.kind) { + case '&&': + // if true then go to the right-hand side. + prevForkContext = context.trueForkContext; + break; + case '||': + // if false then go to the right-hand side. + prevForkContext = context.falseForkContext; + break; + case '??': + // Both true/false can short-circuit, so needs the third path to go to the right-hand side. That's qqForkContext. + prevForkContext = context.qqForkContext; + break; + default: + throw new Error('unreachable'); + } + forkContext.replaceHead(prevForkContext.makeNext(0, -1)); + prevForkContext.clear(); + context.processed = false; + } else { + /* + * This did not get segments from the child choice context. + * So addresses the head segments. + * The head segments are the path of the left-hand operand. + */ + switch (context.kind) { + case '&&': + // the false path can short-circuit. + context.falseForkContext.add(forkContext.head); + break; + case '||': + // the true path can short-circuit. + context.trueForkContext.add(forkContext.head); + break; + case '??': + // both can short-circuit. + context.trueForkContext.add(forkContext.head); + context.falseForkContext.add(forkContext.head); + break; + default: + throw new Error('unreachable'); + } + forkContext.replaceHead(forkContext.makeNext(-1, -1)); + } + } + + /** + * Makes a code path segment of the `if` block. + * @returns {void} + */ + makeIfConsequent() { + const context = this.choiceContext; + const forkContext = this.forkContext; + + /* + * If any result were not transferred from child contexts, + * this sets the head segments to both cases. + * The head segments are the path of the test expression. + */ + if (!context.processed) { + context.trueForkContext.add(forkContext.head); + context.falseForkContext.add(forkContext.head); + context.qqForkContext.add(forkContext.head); + } + context.processed = false; + + // Creates new path from the `true` case. + forkContext.replaceHead(context.trueForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment of the `else` block. + * @returns {void} + */ + makeIfAlternate() { + const context = this.choiceContext; + const forkContext = this.forkContext; + + /* + * The head segments are the path of the `if` block. + * Updates the `true` path with the end of the `if` block. + */ + context.trueForkContext.clear(); + context.trueForkContext.add(forkContext.head); + context.processed = true; + + // Creates new path from the `false` case. + forkContext.replaceHead(context.falseForkContext.makeNext(0, -1)); + } + + //-------------------------------------------------------------------------- + // ChainExpression + //-------------------------------------------------------------------------- + + /** + * Push a new `ChainExpression` context to the stack. + * This method is called on entering to each `ChainExpression` node. + * This context is used to count forking in the optional chain then merge them on the exiting from the `ChainExpression` node. + * @returns {void} + */ + pushChainContext() { + this.chainContext = { + upper: this.chainContext, + countChoiceContexts: 0 + }; + } + + /** + * Pop a `ChainExpression` context from the stack. + * This method is called on exiting from each `ChainExpression` node. + * This merges all forks of the last optional chaining. + * @returns {void} + */ + popChainContext() { + const context = this.chainContext; + this.chainContext = context.upper; + + // pop all choice contexts of this. + for (let i = context.countChoiceContexts; i > 0; --i) { + this.popChoiceContext(); + } + } + + /** + * Create a choice context for optional access. + * This method is called on entering to each `(Call|Member)Expression[optional=true]` node. + * This creates a choice context as similar to `LogicalExpression[operator="??"]` node. + * @returns {void} + */ + makeOptionalNode() { + if (this.chainContext) { + this.chainContext.countChoiceContexts += 1; + this.pushChoiceContext('??', false); + } + } + + /** + * Create a fork. + * This method is called on entering to the `arguments|property` property of each `(Call|Member)Expression` node. + * @returns {void} + */ + makeOptionalRight() { + if (this.chainContext) { + this.makeLogicalRight(); + } + } + + //-------------------------------------------------------------------------- + // SwitchStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context object of SwitchStatement and stacks it. + * @param {boolean} hasCase `true` if the switch statement has one or more + * case parts. + * @param {string|null} label The label text. + * @returns {void} + */ + pushSwitchContext(hasCase, label) { + this.switchContext = { + upper: this.switchContext, + hasCase, + defaultSegments: null, + defaultBodySegments: null, + foundDefault: false, + lastIsDefault: false, + countForks: 0 + }; + this.pushBreakContext(true, label); + } + + /** + * Pops the last context of SwitchStatement and finalizes it. + * + * - Disposes all forking stack for `case` and `default`. + * - Creates the next code path segment from `context.brokenForkContext`. + * - If the last `SwitchCase` node is not a `default` part, creates a path + * to the `default` body. + * @returns {void} + */ + popSwitchContext() { + const context = this.switchContext; + this.switchContext = context.upper; + const forkContext = this.forkContext; + const brokenForkContext = this.popBreakContext().brokenForkContext; + if (context.countForks === 0) { + /* + * When there is only one `default` chunk and there is one or more + * `break` statements, even if forks are nothing, it needs to merge + * those. + */ + if (!brokenForkContext.empty) { + brokenForkContext.add(forkContext.makeNext(-1, -1)); + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + return; + } + const lastSegments = forkContext.head; + this.forkBypassPath(); + const lastCaseSegments = forkContext.head; + + /* + * `brokenForkContext` is used to make the next segment. + * It must add the last segment into `brokenForkContext`. + */ + brokenForkContext.add(lastSegments); + + /* + * A path which is failed in all case test should be connected to path + * of `default` chunk. + */ + if (!context.lastIsDefault) { + if (context.defaultBodySegments) { + /* + * Remove a link from `default` label to its chunk. + * It's false route. + */ + removeConnection(context.defaultSegments, context.defaultBodySegments); + makeLooped(this, lastCaseSegments, context.defaultBodySegments); + } else { + /* + * It handles the last case body as broken if `default` chunk + * does not exist. + */ + brokenForkContext.add(lastCaseSegments); + } + } + + // Pops the segment context stack until the entry segment. + for (let i = 0; i < context.countForks; ++i) { + this.forkContext = this.forkContext.upper; + } + + /* + * Creates a path from all brokenForkContext paths. + * This is a path after switch statement. + */ + this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment for a `SwitchCase` node. + * @param {boolean} isEmpty `true` if the body is empty. + * @param {boolean} isDefault `true` if the body is the default case. + * @returns {void} + */ + makeSwitchCaseBody(isEmpty, isDefault) { + const context = this.switchContext; + if (!context.hasCase) { + return; + } + + /* + * Merge forks. + * The parent fork context has two segments. + * Those are from the current case and the body of the previous case. + */ + const parentForkContext = this.forkContext; + const forkContext = this.pushForkContext(); + forkContext.add(parentForkContext.makeNext(0, -1)); + + /* + * Save `default` chunk info. + * If the `default` label is not at the last, we must make a path from + * the last `case` to the `default` chunk. + */ + if (isDefault) { + context.defaultSegments = parentForkContext.head; + if (isEmpty) { + context.foundDefault = true; + } else { + context.defaultBodySegments = forkContext.head; + } + } else { + if (!isEmpty && context.foundDefault) { + context.foundDefault = false; + context.defaultBodySegments = forkContext.head; + } + } + context.lastIsDefault = isDefault; + context.countForks += 1; + } + + //-------------------------------------------------------------------------- + // TryStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context object of TryStatement and stacks it. + * @param {boolean} hasFinalizer `true` if the try statement has a + * `finally` block. + * @returns {void} + */ + pushTryContext(hasFinalizer) { + this.tryContext = { + upper: this.tryContext, + position: 'try', + hasFinalizer, + returnedForkContext: hasFinalizer ? ForkContext.newEmpty(this.forkContext) : null, + thrownForkContext: ForkContext.newEmpty(this.forkContext), + lastOfTryIsReachable: false, + lastOfCatchIsReachable: false + }; + } + + /** + * Pops the last context of TryStatement and finalizes it. + * @returns {void} + */ + popTryContext() { + const context = this.tryContext; + this.tryContext = context.upper; + if (context.position === 'catch') { + // Merges two paths from the `try` block and `catch` block merely. + this.popForkContext(); + return; + } + + /* + * The following process is executed only when there is the `finally` + * block. + */ + + const returned = context.returnedForkContext; + const thrown = context.thrownForkContext; + if (returned.empty && thrown.empty) { + return; + } + + // Separate head to normal paths and leaving paths. + const headSegments = this.forkContext.head; + this.forkContext = this.forkContext.upper; + const normalSegments = headSegments.slice(0, headSegments.length / 2 | 0); + const leavingSegments = headSegments.slice(headSegments.length / 2 | 0); + + // Forwards the leaving path to upper contexts. + if (!returned.empty) { + getReturnContext(this).returnedForkContext.add(leavingSegments); + } + if (!thrown.empty) { + getThrowContext(this).thrownForkContext.add(leavingSegments); + } + + // Sets the normal path as the next. + this.forkContext.replaceHead(normalSegments); + + /* + * If both paths of the `try` block and the `catch` block are + * unreachable, the next path becomes unreachable as well. + */ + if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) { + this.forkContext.makeUnreachable(); + } + } + + /** + * Makes a code path segment for a `catch` block. + * @returns {void} + */ + makeCatchBlock() { + const context = this.tryContext; + const forkContext = this.forkContext; + const thrown = context.thrownForkContext; + + // Update state. + context.position = 'catch'; + context.thrownForkContext = ForkContext.newEmpty(forkContext); + context.lastOfTryIsReachable = forkContext.reachable; + + // Merge thrown paths. + thrown.add(forkContext.head); + const thrownSegments = thrown.makeNext(0, -1); + + // Fork to a bypass and the merged thrown path. + this.pushForkContext(); + this.forkBypassPath(); + this.forkContext.add(thrownSegments); + } + + /** + * Makes a code path segment for a `finally` block. + * + * In the `finally` block, parallel paths are created. The parallel paths + * are used as leaving-paths. The leaving-paths are paths from `return` + * statements and `throw` statements in a `try` block or a `catch` block. + * @returns {void} + */ + makeFinallyBlock() { + const context = this.tryContext; + let forkContext = this.forkContext; + const returned = context.returnedForkContext; + const thrown = context.thrownForkContext; + const headOfLeavingSegments = forkContext.head; + + // Update state. + if (context.position === 'catch') { + // Merges two paths from the `try` block and `catch` block. + this.popForkContext(); + forkContext = this.forkContext; + context.lastOfCatchIsReachable = forkContext.reachable; + } else { + context.lastOfTryIsReachable = forkContext.reachable; + } + context.position = 'finally'; + if (returned.empty && thrown.empty) { + // This path does not leave. + return; + } + + /* + * Create a parallel segment from merging returned and thrown. + * This segment will leave at the end of this finally block. + */ + const segments = forkContext.makeNext(-1, -1); + for (let i = 0; i < forkContext.count; ++i) { + const prevSegsOfLeavingSegment = [headOfLeavingSegments[i]]; + for (let j = 0; j < returned.segmentsList.length; ++j) { + prevSegsOfLeavingSegment.push(returned.segmentsList[j][i]); + } + for (let j = 0; j < thrown.segmentsList.length; ++j) { + prevSegsOfLeavingSegment.push(thrown.segmentsList[j][i]); + } + segments.push(CodePathSegment.newNext(this.idGenerator.next(), prevSegsOfLeavingSegment)); + } + this.pushForkContext(true); + this.forkContext.add(segments); + } + + /** + * Makes a code path segment from the first throwable node to the `catch` + * block or the `finally` block. + * @returns {void} + */ + makeFirstThrowablePathInTryBlock() { + const forkContext = this.forkContext; + if (!forkContext.reachable) { + return; + } + const context = getThrowContext(this); + if (context === this || context.position !== 'try' || !context.thrownForkContext.empty) { + return; + } + context.thrownForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeNext(-1, -1)); + } + + //-------------------------------------------------------------------------- + // Loop Statements + //-------------------------------------------------------------------------- + + /** + * Creates a context object of a loop statement and stacks it. + * @param {string} type The type of the node which was triggered. One of + * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`, + * and `ForStatement`. + * @param {string|null} label A label of the node which was triggered. + * @throws {Error} (Unreachable - unknown type.) + * @returns {void} + */ + pushLoopContext(type, label) { + const forkContext = this.forkContext; + const breakContext = this.pushBreakContext(true, label); + switch (type) { + case 'WhileStatement': + this.pushChoiceContext('loop', false); + this.loopContext = { + upper: this.loopContext, + type, + label, + test: void 0, + continueDestSegments: null, + brokenForkContext: breakContext.brokenForkContext + }; + break; + case 'DoWhileStatement': + this.pushChoiceContext('loop', false); + this.loopContext = { + upper: this.loopContext, + type, + label, + test: void 0, + entrySegments: null, + continueForkContext: ForkContext.newEmpty(forkContext), + brokenForkContext: breakContext.brokenForkContext + }; + break; + case 'ForStatement': + this.pushChoiceContext('loop', false); + this.loopContext = { + upper: this.loopContext, + type, + label, + test: void 0, + endOfInitSegments: null, + testSegments: null, + endOfTestSegments: null, + updateSegments: null, + endOfUpdateSegments: null, + continueDestSegments: null, + brokenForkContext: breakContext.brokenForkContext + }; + break; + case 'ForInStatement': + case 'ForOfStatement': + this.loopContext = { + upper: this.loopContext, + type, + label, + prevSegments: null, + leftSegments: null, + endOfLeftSegments: null, + continueDestSegments: null, + brokenForkContext: breakContext.brokenForkContext + }; + break; + + /* c8 ignore next */ + default: + throw new Error("unknown type: \"" + type + "\""); + } + } + + /** + * Pops the last context of a loop statement and finalizes it. + * @throws {Error} (Unreachable - unknown type.) + * @returns {void} + */ + popLoopContext() { + const context = this.loopContext; + this.loopContext = context.upper; + const forkContext = this.forkContext; + const brokenForkContext = this.popBreakContext().brokenForkContext; + + // Creates a looped path. + switch (context.type) { + case 'WhileStatement': + case 'ForStatement': + this.popChoiceContext(); + makeLooped(this, forkContext.head, context.continueDestSegments); + break; + case 'DoWhileStatement': + { + const choiceContext = this.popChoiceContext(); + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(forkContext.head); + choiceContext.falseForkContext.add(forkContext.head); + } + if (context.test !== true) { + brokenForkContext.addAll(choiceContext.falseForkContext); + } + + // `true` paths go to looping. + const segmentsList = choiceContext.trueForkContext.segmentsList; + for (let i = 0; i < segmentsList.length; ++i) { + makeLooped(this, segmentsList[i], context.entrySegments); + } + break; + } + case 'ForInStatement': + case 'ForOfStatement': + brokenForkContext.add(forkContext.head); + makeLooped(this, forkContext.head, context.leftSegments); + break; + + /* c8 ignore next */ + default: + throw new Error('unreachable'); + } + + // Go next. + if (brokenForkContext.empty) { + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } else { + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + } + + /** + * Makes a code path segment for the test part of a WhileStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeWhileTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + const testSegments = forkContext.makeNext(0, -1); + + // Update state. + context.test = test; + context.continueDestSegments = testSegments; + forkContext.replaceHead(testSegments); + } + + /** + * Makes a code path segment for the body part of a WhileStatement. + * @returns {void} + */ + makeWhileBody() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(forkContext.head); + choiceContext.falseForkContext.add(forkContext.head); + } + + // Update state. + if (context.test !== true) { + context.brokenForkContext.addAll(choiceContext.falseForkContext); + } + forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment for the body part of a DoWhileStatement. + * @returns {void} + */ + makeDoWhileBody() { + const context = this.loopContext; + const forkContext = this.forkContext; + const bodySegments = forkContext.makeNext(-1, -1); + + // Update state. + context.entrySegments = bodySegments; + forkContext.replaceHead(bodySegments); + } + + /** + * Makes a code path segment for the test part of a DoWhileStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeDoWhileTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + context.test = test; + + // Creates paths of `continue` statements. + if (!context.continueForkContext.empty) { + context.continueForkContext.add(forkContext.head); + const testSegments = context.continueForkContext.makeNext(0, -1); + forkContext.replaceHead(testSegments); + } + } + + /** + * Makes a code path segment for the test part of a ForStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeForTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + const endOfInitSegments = forkContext.head; + const testSegments = forkContext.makeNext(-1, -1); + + // Update state. + context.test = test; + context.endOfInitSegments = endOfInitSegments; + context.continueDestSegments = context.testSegments = testSegments; + forkContext.replaceHead(testSegments); + } + + /** + * Makes a code path segment for the update part of a ForStatement. + * @returns {void} + */ + makeForUpdate() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + + // Make the next paths of the test. + if (context.testSegments) { + finalizeTestSegmentsOfFor(context, choiceContext, forkContext.head); + } else { + context.endOfInitSegments = forkContext.head; + } + + // Update state. + const updateSegments = forkContext.makeDisconnected(-1, -1); + context.continueDestSegments = context.updateSegments = updateSegments; + forkContext.replaceHead(updateSegments); + } + + /** + * Makes a code path segment for the body part of a ForStatement. + * @returns {void} + */ + makeForBody() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + + // Update state. + if (context.updateSegments) { + context.endOfUpdateSegments = forkContext.head; + + // `update` -> `test` + if (context.testSegments) { + makeLooped(this, context.endOfUpdateSegments, context.testSegments); + } + } else if (context.testSegments) { + finalizeTestSegmentsOfFor(context, choiceContext, forkContext.head); + } else { + context.endOfInitSegments = forkContext.head; + } + let bodySegments = context.endOfTestSegments; + if (!bodySegments) { + /* + * If there is not the `test` part, the `body` path comes from the + * `init` part and the `update` part. + */ + const prevForkContext = ForkContext.newEmpty(forkContext); + prevForkContext.add(context.endOfInitSegments); + if (context.endOfUpdateSegments) { + prevForkContext.add(context.endOfUpdateSegments); + } + bodySegments = prevForkContext.makeNext(0, -1); + } + context.continueDestSegments = context.continueDestSegments || bodySegments; + forkContext.replaceHead(bodySegments); + } + + /** + * Makes a code path segment for the left part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfLeft() { + const context = this.loopContext; + const forkContext = this.forkContext; + const leftSegments = forkContext.makeDisconnected(-1, -1); + + // Update state. + context.prevSegments = forkContext.head; + context.leftSegments = context.continueDestSegments = leftSegments; + forkContext.replaceHead(leftSegments); + } + + /** + * Makes a code path segment for the right part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfRight() { + const context = this.loopContext; + const forkContext = this.forkContext; + const temp = ForkContext.newEmpty(forkContext); + temp.add(context.prevSegments); + const rightSegments = temp.makeNext(-1, -1); + + // Update state. + context.endOfLeftSegments = forkContext.head; + forkContext.replaceHead(rightSegments); + } + + /** + * Makes a code path segment for the body part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfBody() { + const context = this.loopContext; + const forkContext = this.forkContext; + const temp = ForkContext.newEmpty(forkContext); + temp.add(context.endOfLeftSegments); + const bodySegments = temp.makeNext(-1, -1); + + // Make a path: `right` -> `left`. + makeLooped(this, forkContext.head, context.leftSegments); + + // Update state. + context.brokenForkContext.add(forkContext.head); + forkContext.replaceHead(bodySegments); + } + + //-------------------------------------------------------------------------- + // Control Statements + //-------------------------------------------------------------------------- + + /** + * Creates new context for BreakStatement. + * @param {boolean} breakable The flag to indicate it can break by + * an unlabeled BreakStatement. + * @param {string|null} label The label of this context. + * @returns {Object} The new context. + */ + pushBreakContext(breakable, label) { + this.breakContext = { + upper: this.breakContext, + breakable, + label, + brokenForkContext: ForkContext.newEmpty(this.forkContext) + }; + return this.breakContext; + } + + /** + * Removes the top item of the break context stack. + * @returns {Object} The removed context. + */ + popBreakContext() { + const context = this.breakContext; + const forkContext = this.forkContext; + this.breakContext = context.upper; + + // Process this context here for other than switches and loops. + if (!context.breakable) { + const brokenForkContext = context.brokenForkContext; + if (!brokenForkContext.empty) { + brokenForkContext.add(forkContext.head); + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + } + return context; + } + + /** + * Makes a path for a `break` statement. + * + * It registers the head segment to a context of `break`. + * It makes new unreachable segment, then it set the head with the segment. + * @param {string} label A label of the break statement. + * @returns {void} + */ + makeBreak(label) { + const forkContext = this.forkContext; + if (!forkContext.reachable) { + return; + } + const context = getBreakContext(this, label); + if (context) { + context.brokenForkContext.add(forkContext.head); + } + + /* c8 ignore next */ + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + + /** + * Makes a path for a `continue` statement. + * + * It makes a looping path. + * It makes new unreachable segment, then it set the head with the segment. + * @param {string} label A label of the continue statement. + * @returns {void} + */ + makeContinue(label) { + const forkContext = this.forkContext; + if (!forkContext.reachable) { + return; + } + const context = getContinueContext(this, label); + if (context) { + if (context.continueDestSegments) { + makeLooped(this, forkContext.head, context.continueDestSegments); + + // If the context is a for-in/of loop, this effects a break also. + if (context.type === 'ForInStatement' || context.type === 'ForOfStatement') { + context.brokenForkContext.add(forkContext.head); + } + } else { + context.continueForkContext.add(forkContext.head); + } + } + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + + /** + * Makes a path for a `return` statement. + * + * It registers the head segment to a context of `return`. + * It makes new unreachable segment, then it set the head with the segment. + * @returns {void} + */ + makeReturn() { + const forkContext = this.forkContext; + if (forkContext.reachable) { + getReturnContext(this).returnedForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + } + + /** + * Makes a path for a `throw` statement. + * + * It registers the head segment to a context of `throw`. + * It makes new unreachable segment, then it set the head with the segment. + * @returns {void} + */ + makeThrow() { + const forkContext = this.forkContext; + if (forkContext.reachable) { + getThrowContext(this).thrownForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + } + + /** + * Makes the final path. + * @returns {void} + */ + makeFinal() { + const segments = this.currentSegments; + if (segments.length > 0 && segments[0].reachable) { + this.returnedForkContext.add(segments); + } + } + } + codePathState = CodePathState; + return codePathState; +} + +var idGenerator; +var hasRequiredIdGenerator; +function requireIdGenerator() { + if (hasRequiredIdGenerator) return idGenerator; + hasRequiredIdGenerator = 1; + + /* eslint-disable react-internal/safe-string-coercion */ + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * A generator for unique ids. + */ + class IdGenerator { + /** + * @param {string} prefix Optional. A prefix of generated ids. + */ + constructor(prefix) { + this.prefix = String(prefix); + this.n = 0; + } + + /** + * Generates id. + * @returns {string} A generated id. + */ + next() { + this.n = 1 + this.n | 0; + + /* c8 ignore start */ + if (this.n < 0) { + this.n = 1; + } /* c8 ignore stop */ + + return this.prefix + this.n; + } + } + idGenerator = IdGenerator; + return idGenerator; +} + +var codePath; +var hasRequiredCodePath; +function requireCodePath() { + if (hasRequiredCodePath) return codePath; + hasRequiredCodePath = 1; + + //------------------------------------------------------------------------------ + // Requirements + //------------------------------------------------------------------------------ + + // eslint-disable-next-line + const CodePathState = requireCodePathState(); + // eslint-disable-next-line + const IdGenerator = requireIdGenerator(); + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * A code path. + */ + class CodePath { + /** + * Creates a new instance. + * @param {Object} options Options for the function (see below). + * @param {string} options.id An identifier. + * @param {string} options.origin The type of code path origin. + * @param {CodePath|null} options.upper The code path of the upper function scope. + * @param {Function} options.onLooped A callback function to notify looping. + */ + constructor(_ref) { + let id = _ref.id, + origin = _ref.origin, + upper = _ref.upper, + onLooped = _ref.onLooped; + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * The reason that this code path was started. May be "program", + * "function", "class-field-initializer", or "class-static-block". + * @type {string} + */ + this.origin = origin; + + /** + * The code path of the upper function scope. + * @type {CodePath|null} + */ + this.upper = upper; + + /** + * The code paths of nested function scopes. + * @type {CodePath[]} + */ + this.childCodePaths = []; + + // Initializes internal state. + Object.defineProperty(this, 'internal', { + value: new CodePathState(new IdGenerator(id + "_"), onLooped) + }); + + // Adds this into `childCodePaths` of `upper`. + if (upper) { + upper.childCodePaths.push(this); + } + } + + /** + * Gets the state of a given code path. + * @param {CodePath} codePath A code path to get. + * @returns {CodePathState} The state of the code path. + */ + static getState(codePath) { + return codePath.internal; + } + + /** + * The initial code path segment. + * @type {CodePathSegment} + */ + get initialSegment() { + return this.internal.initialSegment; + } + + /** + * Final code path segments. + * This array is a mix of `returnedSegments` and `thrownSegments`. + * @type {CodePathSegment[]} + */ + get finalSegments() { + return this.internal.finalSegments; + } + + /** + * Final code path segments which is with `return` statements. + * This array contains the last path segment if it's reachable. + * Since the reachable last path returns `undefined`. + * @type {CodePathSegment[]} + */ + get returnedSegments() { + return this.internal.returnedForkContext; + } + + /** + * Final code path segments which is with `throw` statements. + * @type {CodePathSegment[]} + */ + get thrownSegments() { + return this.internal.thrownForkContext; + } + + /** + * Current code path segments. + * @type {CodePathSegment[]} + */ + get currentSegments() { + return this.internal.currentSegments; + } + + /** + * Traverses all segments in this code path. + * + * codePath.traverseSegments(function(segment, controller) { + * // do something. + * }); + * + * This method enumerates segments in order from the head. + * + * The `controller` object has two methods. + * + * - `controller.skip()` - Skip the following segments in this branch. + * - `controller.break()` - Skip all following segments. + * @param {Object} [options] Omittable. + * @param {CodePathSegment} [options.first] The first segment to traverse. + * @param {CodePathSegment} [options.last] The last segment to traverse. + * @param {Function} callback A callback function. + * @returns {void} + */ + traverseSegments(options, callback) { + let resolvedOptions; + let resolvedCallback; + if (typeof options === 'function') { + resolvedCallback = options; + resolvedOptions = {}; + } else { + resolvedOptions = options || {}; + resolvedCallback = callback; + } + const startSegment = resolvedOptions.first || this.internal.initialSegment; + const lastSegment = resolvedOptions.last; + let item = null; + let index = 0; + let end = 0; + let segment = null; + const visited = Object.create(null); + const stack = [[startSegment, 0]]; + let skippedSegment = null; + let broken = false; + const controller = { + skip() { + if (stack.length <= 1) { + broken = true; + } else { + skippedSegment = stack[stack.length - 2][0]; + } + }, + break() { + broken = true; + } + }; + + /** + * Checks a given previous segment has been visited. + * @param {CodePathSegment} prevSegment A previous segment to check. + * @returns {boolean} `true` if the segment has been visited. + */ + function isVisited(prevSegment) { + return visited[prevSegment.id] || segment.isLoopedPrevSegment(prevSegment); + } + while (stack.length > 0) { + item = stack[stack.length - 1]; + segment = item[0]; + index = item[1]; + if (index === 0) { + // Skip if this segment has been visited already. + if (visited[segment.id]) { + stack.pop(); + continue; + } + + // Skip if all previous segments have not been visited. + if (segment !== startSegment && segment.prevSegments.length > 0 && !segment.prevSegments.every(isVisited)) { + stack.pop(); + continue; + } + + // Reset the flag of skipping if all branches have been skipped. + if (skippedSegment && segment.prevSegments.includes(skippedSegment)) { + skippedSegment = null; + } + visited[segment.id] = true; + + // Call the callback when the first time. + if (!skippedSegment) { + resolvedCallback.call(this, segment, controller); + if (segment === lastSegment) { + controller.skip(); + } + if (broken) { + break; + } + } + } + + // Update the stack. + end = segment.nextSegments.length - 1; + if (index < end) { + item[1] += 1; + stack.push([segment.nextSegments[index], 0]); + } else if (index === end) { + item[0] = segment.nextSegments[index]; + item[1] = 0; + } else { + stack.pop(); + } + } + } + } + codePath = CodePath; + return codePath; +} + +var codePathAnalyzer; +var hasRequiredCodePathAnalyzer; +function requireCodePathAnalyzer() { + if (hasRequiredCodePathAnalyzer) return codePathAnalyzer; + hasRequiredCodePathAnalyzer = 1; + + /* eslint-disable react-internal/no-primitive-constructors */ + + //------------------------------------------------------------------------------ + // Requirements + //------------------------------------------------------------------------------ + + // eslint-disable-next-line + const assert = requireAssert(); + // eslint-disable-next-line + const CodePath = requireCodePath(); + // eslint-disable-next-line + const CodePathSegment = requireCodePathSegment(); + // eslint-disable-next-line + const IdGenerator = requireIdGenerator(); + const breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u; + + //------------------------------------------------------------------------------ + // Helpers + //------------------------------------------------------------------------------ + + /** + * Checks whether or not a given node is a `case` node (not `default` node). + * @param {ASTNode} node A `SwitchCase` node to check. + * @returns {boolean} `true` if the node is a `case` node (not `default` node). + */ + function isCaseNode(node) { + return Boolean(node.test); + } + + /** + * Checks if a given node appears as the value of a PropertyDefinition node. + * @param {ASTNode} node THe node to check. + * @returns {boolean} `true` if the node is a PropertyDefinition value, + * false if not. + */ + function isPropertyDefinitionValue(node) { + const parent = node.parent; + return parent && parent.type === 'PropertyDefinition' && parent.value === node; + } + + /** + * Checks whether the given logical operator is taken into account for the code + * path analysis. + * @param {string} operator The operator found in the LogicalExpression node + * @returns {boolean} `true` if the operator is "&&" or "||" or "??" + */ + function isHandledLogicalOperator(operator) { + return operator === '&&' || operator === '||' || operator === '??'; + } + + /** + * Checks whether the given assignment operator is a logical assignment operator. + * Logical assignments are taken into account for the code path analysis + * because of their short-circuiting semantics. + * @param {string} operator The operator found in the AssignmentExpression node + * @returns {boolean} `true` if the operator is "&&=" or "||=" or "??=" + */ + function isLogicalAssignmentOperator(operator) { + return operator === '&&=' || operator === '||=' || operator === '??='; + } + + /** + * Gets the label if the parent node of a given node is a LabeledStatement. + * @param {ASTNode} node A node to get. + * @returns {string|null} The label or `null`. + */ + function getLabel(node) { + if (node.parent.type === 'LabeledStatement') { + return node.parent.label.name; + } + return null; + } + + /** + * Checks whether or not a given logical expression node goes different path + * between the `true` case and the `false` case. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a test of a choice statement. + */ + function isForkingByTrueOrFalse(node) { + const parent = node.parent; + switch (parent.type) { + case 'ConditionalExpression': + case 'IfStatement': + case 'WhileStatement': + case 'DoWhileStatement': + case 'ForStatement': + return parent.test === node; + case 'LogicalExpression': + return isHandledLogicalOperator(parent.operator); + case 'AssignmentExpression': + return isLogicalAssignmentOperator(parent.operator); + default: + return false; + } + } + + /** + * Gets the boolean value of a given literal node. + * + * This is used to detect infinity loops (e.g. `while (true) {}`). + * Statements preceded by an infinity loop are unreachable if the loop didn't + * have any `break` statement. + * @param {ASTNode} node A node to get. + * @returns {boolean|undefined} a boolean value if the node is a Literal node, + * otherwise `undefined`. + */ + function getBooleanValueIfSimpleConstant(node) { + if (node.type === 'Literal') { + return Boolean(node.value); + } + return void 0; + } + + /** + * Checks that a given identifier node is a reference or not. + * + * This is used to detect the first throwable node in a `try` block. + * @param {ASTNode} node An Identifier node to check. + * @returns {boolean} `true` if the node is a reference. + */ + function isIdentifierReference(node) { + const parent = node.parent; + switch (parent.type) { + case 'LabeledStatement': + case 'BreakStatement': + case 'ContinueStatement': + case 'ArrayPattern': + case 'RestElement': + case 'ImportSpecifier': + case 'ImportDefaultSpecifier': + case 'ImportNamespaceSpecifier': + case 'CatchClause': + return false; + case 'FunctionDeclaration': + case 'ComponentDeclaration': + case 'HookDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + case 'ClassDeclaration': + case 'ClassExpression': + case 'VariableDeclarator': + return parent.id !== node; + case 'Property': + case 'PropertyDefinition': + case 'MethodDefinition': + return parent.key !== node || parent.computed || parent.shorthand; + case 'AssignmentPattern': + return parent.key !== node; + default: + return true; + } + } + + /** + * Updates the current segment with the head segment. + * This is similar to local branches and tracking branches of git. + * + * To separate the current and the head is in order to not make useless segments. + * + * In this process, both "onCodePathSegmentStart" and "onCodePathSegmentEnd" + * events are fired. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function forwardCurrentToHead(analyzer, node) { + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + const currentSegments = state.currentSegments; + const headSegments = state.headSegments; + const end = Math.max(currentSegments.length, headSegments.length); + let i, currentSegment, headSegment; + + // Fires leaving events. + for (i = 0; i < end; ++i) { + currentSegment = currentSegments[i]; + headSegment = headSegments[i]; + if (currentSegment !== headSegment && currentSegment) { + if (currentSegment.reachable) { + analyzer.emitter.emit('onCodePathSegmentEnd', currentSegment, node); + } + } + } + + // Update state. + state.currentSegments = headSegments; + + // Fires entering events. + for (i = 0; i < end; ++i) { + currentSegment = currentSegments[i]; + headSegment = headSegments[i]; + if (currentSegment !== headSegment && headSegment) { + CodePathSegment.markUsed(headSegment); + if (headSegment.reachable) { + analyzer.emitter.emit('onCodePathSegmentStart', headSegment, node); + } + } + } + } + + /** + * Updates the current segment with empty. + * This is called at the last of functions or the program. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function leaveFromCurrentSegment(analyzer, node) { + const state = CodePath.getState(analyzer.codePath); + const currentSegments = state.currentSegments; + for (let i = 0; i < currentSegments.length; ++i) { + const currentSegment = currentSegments[i]; + if (currentSegment.reachable) { + analyzer.emitter.emit('onCodePathSegmentEnd', currentSegment, node); + } + } + state.currentSegments = []; + } + + /** + * Updates the code path due to the position of a given node in the parent node + * thereof. + * + * For example, if the node is `parent.consequent`, this creates a fork from the + * current path. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function preprocess(analyzer, node) { + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + const parent = node.parent; + switch (parent.type) { + // The `arguments.length == 0` case is in `postprocess` function. + case 'CallExpression': + if (parent.optional === true && parent.arguments.length >= 1 && parent.arguments[0] === node) { + state.makeOptionalRight(); + } + break; + case 'MemberExpression': + if (parent.optional === true && parent.property === node) { + state.makeOptionalRight(); + } + break; + case 'LogicalExpression': + if (parent.right === node && isHandledLogicalOperator(parent.operator)) { + state.makeLogicalRight(); + } + break; + case 'AssignmentExpression': + if (parent.right === node && isLogicalAssignmentOperator(parent.operator)) { + state.makeLogicalRight(); + } + break; + case 'ConditionalExpression': + case 'IfStatement': + /* + * Fork if this node is at `consequent`/`alternate`. + * `popForkContext()` exists at `IfStatement:exit` and + * `ConditionalExpression:exit`. + */ + if (parent.consequent === node) { + state.makeIfConsequent(); + } else if (parent.alternate === node) { + state.makeIfAlternate(); + } + break; + case 'SwitchCase': + if (parent.consequent[0] === node) { + state.makeSwitchCaseBody(false, !parent.test); + } + break; + case 'TryStatement': + if (parent.handler === node) { + state.makeCatchBlock(); + } else if (parent.finalizer === node) { + state.makeFinallyBlock(); + } + break; + case 'WhileStatement': + if (parent.test === node) { + state.makeWhileTest(getBooleanValueIfSimpleConstant(node)); + } else { + assert(parent.body === node); + state.makeWhileBody(); + } + break; + case 'DoWhileStatement': + if (parent.body === node) { + state.makeDoWhileBody(); + } else { + assert(parent.test === node); + state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node)); + } + break; + case 'ForStatement': + if (parent.test === node) { + state.makeForTest(getBooleanValueIfSimpleConstant(node)); + } else if (parent.update === node) { + state.makeForUpdate(); + } else if (parent.body === node) { + state.makeForBody(); + } + break; + case 'ForInStatement': + case 'ForOfStatement': + if (parent.left === node) { + state.makeForInOfLeft(); + } else if (parent.right === node) { + state.makeForInOfRight(); + } else { + assert(parent.body === node); + state.makeForInOfBody(); + } + break; + case 'AssignmentPattern': + /* + * Fork if this node is at `right`. + * `left` is executed always, so it uses the current path. + * `popForkContext()` exists at `AssignmentPattern:exit`. + */ + if (parent.right === node) { + state.pushForkContext(); + state.forkBypassPath(); + state.forkPath(); + } + break; + } + } + + /** + * Updates the code path due to the type of a given node in entering. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function processCodePathToEnter(analyzer, node) { + let codePath = analyzer.codePath; + let state = codePath && CodePath.getState(codePath); + const parent = node.parent; + + /** + * Creates a new code path and trigger the onCodePathStart event + * based on the currently selected node. + * @param {string} origin The reason the code path was started. + * @returns {void} + */ + function startCodePath(origin) { + if (codePath) { + // Emits onCodePathSegmentStart events if updated. + forwardCurrentToHead(analyzer, node); + } + + // Create the code path of this scope. + codePath = analyzer.codePath = new CodePath({ + id: analyzer.idGenerator.next(), + origin, + upper: codePath, + onLooped: analyzer.onLooped + }); + state = CodePath.getState(codePath); + + // Emits onCodePathStart events. + analyzer.emitter.emit('onCodePathStart', codePath, node); + } + + /* + * Special case: The right side of class field initializer is considered + * to be its own function, so we need to start a new code path in this + * case. + */ + if (isPropertyDefinitionValue(node)) { + startCodePath('class-field-initializer'); + + /* + * Intentional fall through because `node` needs to also be + * processed by the code below. For example, if we have: + * + * class Foo { + * a = () => {} + * } + * + * In this case, we also need start a second code path. + */ + } + switch (node.type) { + case 'Program': + startCodePath('program'); + break; + case 'FunctionDeclaration': + case 'ComponentDeclaration': + case 'HookDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + startCodePath('function'); + break; + case 'StaticBlock': + startCodePath('class-static-block'); + break; + case 'ChainExpression': + state.pushChainContext(); + break; + case 'CallExpression': + if (node.optional === true) { + state.makeOptionalNode(); + } + break; + case 'MemberExpression': + if (node.optional === true) { + state.makeOptionalNode(); + } + break; + case 'LogicalExpression': + if (isHandledLogicalOperator(node.operator)) { + state.pushChoiceContext(node.operator, isForkingByTrueOrFalse(node)); + } + break; + case 'AssignmentExpression': + if (isLogicalAssignmentOperator(node.operator)) { + state.pushChoiceContext(node.operator.slice(0, -1), + // removes `=` from the end + isForkingByTrueOrFalse(node)); + } + break; + case 'ConditionalExpression': + case 'IfStatement': + state.pushChoiceContext('test', false); + break; + case 'SwitchStatement': + state.pushSwitchContext(node.cases.some(isCaseNode), getLabel(node)); + break; + case 'TryStatement': + state.pushTryContext(Boolean(node.finalizer)); + break; + case 'SwitchCase': + /* + * Fork if this node is after the 2st node in `cases`. + * It's similar to `else` blocks. + * The next `test` node is processed in this path. + */ + if (parent.discriminant !== node && parent.cases[0] !== node) { + state.forkPath(); + } + break; + case 'WhileStatement': + case 'DoWhileStatement': + case 'ForStatement': + case 'ForInStatement': + case 'ForOfStatement': + state.pushLoopContext(node.type, getLabel(node)); + break; + case 'LabeledStatement': + if (!breakableTypePattern.test(node.body.type)) { + state.pushBreakContext(false, node.label.name); + } + break; + } + + // Emits onCodePathSegmentStart events if updated. + forwardCurrentToHead(analyzer, node); + } + + /** + * Updates the code path due to the type of a given node in leaving. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function processCodePathToExit(analyzer, node) { + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + let dontForward = false; + switch (node.type) { + case 'ChainExpression': + state.popChainContext(); + break; + case 'IfStatement': + case 'ConditionalExpression': + state.popChoiceContext(); + break; + case 'LogicalExpression': + if (isHandledLogicalOperator(node.operator)) { + state.popChoiceContext(); + } + break; + case 'AssignmentExpression': + if (isLogicalAssignmentOperator(node.operator)) { + state.popChoiceContext(); + } + break; + case 'SwitchStatement': + state.popSwitchContext(); + break; + case 'SwitchCase': + /* + * This is the same as the process at the 1st `consequent` node in + * `preprocess` function. + * Must do if this `consequent` is empty. + */ + if (node.consequent.length === 0) { + state.makeSwitchCaseBody(true, !node.test); + } + if (state.forkContext.reachable) { + dontForward = true; + } + break; + case 'TryStatement': + state.popTryContext(); + break; + case 'BreakStatement': + forwardCurrentToHead(analyzer, node); + state.makeBreak(node.label && node.label.name); + dontForward = true; + break; + case 'ContinueStatement': + forwardCurrentToHead(analyzer, node); + state.makeContinue(node.label && node.label.name); + dontForward = true; + break; + case 'ReturnStatement': + forwardCurrentToHead(analyzer, node); + state.makeReturn(); + dontForward = true; + break; + case 'ThrowStatement': + forwardCurrentToHead(analyzer, node); + state.makeThrow(); + dontForward = true; + break; + case 'Identifier': + if (isIdentifierReference(node)) { + state.makeFirstThrowablePathInTryBlock(); + dontForward = true; + } + break; + case 'CallExpression': + case 'ImportExpression': + case 'MemberExpression': + case 'NewExpression': + case 'YieldExpression': + state.makeFirstThrowablePathInTryBlock(); + break; + case 'WhileStatement': + case 'DoWhileStatement': + case 'ForStatement': + case 'ForInStatement': + case 'ForOfStatement': + state.popLoopContext(); + break; + case 'AssignmentPattern': + state.popForkContext(); + break; + case 'LabeledStatement': + if (!breakableTypePattern.test(node.body.type)) { + state.popBreakContext(); + } + break; + } + + // Emits onCodePathSegmentStart events if updated. + if (!dontForward) { + forwardCurrentToHead(analyzer, node); + } + } + + /** + * Updates the code path to finalize the current code path. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ + function postprocess(analyzer, node) { + /** + * Ends the code path for the current node. + * @returns {void} + */ + function endCodePath() { + let codePath = analyzer.codePath; + + // Mark the current path as the final node. + CodePath.getState(codePath).makeFinal(); + + // Emits onCodePathSegmentEnd event of the current segments. + leaveFromCurrentSegment(analyzer, node); + + // Emits onCodePathEnd event of this code path. + analyzer.emitter.emit('onCodePathEnd', codePath, node); + codePath = analyzer.codePath = analyzer.codePath.upper; + } + switch (node.type) { + case 'Program': + case 'FunctionDeclaration': + case 'ComponentDeclaration': + case 'HookDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + case 'StaticBlock': + { + endCodePath(); + break; + } + + // The `arguments.length >= 1` case is in `preprocess` function. + case 'CallExpression': + if (node.optional === true && node.arguments.length === 0) { + CodePath.getState(analyzer.codePath).makeOptionalRight(); + } + break; + } + + /* + * Special case: The right side of class field initializer is considered + * to be its own function, so we need to end a code path in this + * case. + * + * We need to check after the other checks in order to close the + * code paths in the correct order for code like this: + * + * + * class Foo { + * a = () => {} + * } + * + * In this case, The ArrowFunctionExpression code path is closed first + * and then we need to close the code path for the PropertyDefinition + * value. + */ + if (isPropertyDefinitionValue(node)) { + endCodePath(); + } + } + + //------------------------------------------------------------------------------ + // Public Interface + //------------------------------------------------------------------------------ + + /** + * The class to analyze code paths. + * This class implements the EventGenerator interface. + */ + class CodePathAnalyzer { + /** + * @param {EventGenerator} eventGenerator An event generator to wrap. + */ + constructor(emitters) { + this.emitter = { + emit(event) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + emitters[event]?.(...args); + } + }; + this.codePath = null; + this.idGenerator = new IdGenerator('s'); + this.currentNode = null; + this.onLooped = this.onLooped.bind(this); + } + + /** + * Does the process to enter a given AST node. + * This updates state of analysis and calls `enterNode` of the wrapped. + * @param {ASTNode} node A node which is entering. + * @returns {void} + */ + enterNode(node) { + this.currentNode = node; + + // Updates the code path due to node's position in its parent node. + if (node.parent) { + preprocess(this, node); + } + + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ + processCodePathToEnter(this, node); + this.currentNode = null; + } + + /** + * Does the process to leave a given AST node. + * This updates state of analysis and calls `leaveNode` of the wrapped. + * @param {ASTNode} node A node which is leaving. + * @returns {void} + */ + leaveNode(node) { + this.currentNode = node; + + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ + processCodePathToExit(this, node); + + // Emits the last onCodePathStart/onCodePathSegmentStart events. + postprocess(this, node); + this.currentNode = null; + } + + /** + * This is called on a code path looped. + * Then this raises a looped event. + * @param {CodePathSegment} fromSegment A segment of prev. + * @param {CodePathSegment} toSegment A segment of next. + * @returns {void} + */ + onLooped(fromSegment, toSegment) { + if (fromSegment.reachable && toSegment.reachable) { + this.emitter.emit('onCodePathSegmentLoop', fromSegment, toSegment, this.currentNode); + } + } + } + codePathAnalyzer = CodePathAnalyzer; + return codePathAnalyzer; +} + +var codePathAnalyzerExports = requireCodePathAnalyzer(); +var CodePathAnalyzer = /*@__PURE__*/getDefaultExportFromCjs(codePathAnalyzerExports); + +function isHookName(s) { + return s === 'use' || /^use[A-Z0-9]/.test(s); +} +function isHook(node) { + if (node.type === 'Identifier') { + return isHookName(node.name); + } + else if (node.type === 'MemberExpression' && + !node.computed && + isHook(node.property)) { + const obj = node.object; + const isPascalCaseNameSpace = /^[A-Z].*/; + return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name); + } + else { + return false; + } +} +function isComponentName(node) { + return node.type === 'Identifier' && /^[A-Z]/.test(node.name); +} +function isReactFunction(node, functionName) { + return (('name' in node && node.name === functionName) || + (node.type === 'MemberExpression' && + 'name' in node.object && + node.object.name === 'React' && + 'name' in node.property && + node.property.name === functionName)); +} +function isForwardRefCallback(node) { + return !!(node.parent && + 'callee' in node.parent && + node.parent.callee && + isReactFunction(node.parent.callee, 'forwardRef')); +} +function isMemoCallback(node) { + return !!(node.parent && + 'callee' in node.parent && + node.parent.callee && + isReactFunction(node.parent.callee, 'memo')); +} +function isInsideComponentOrHook(node) { + while (node) { + const functionName = getFunctionName(node); + if (functionName) { + if (isComponentName(functionName) || isHook(functionName)) { + return true; + } + } + if (isForwardRefCallback(node) || isMemoCallback(node)) { + return true; + } + node = node.parent; + } + return false; +} +function isInsideDoWhileLoop(node) { + while (node) { + if (node.type === 'DoWhileStatement') { + return true; + } + node = node.parent; + } + return false; +} +function isInsideTryCatch(node) { + while (node) { + if (node.type === 'TryStatement' || node.type === 'CatchClause') { + return true; + } + node = node.parent; + } + return false; +} +function getNodeWithoutReactNamespace(node) { + if (node.type === 'MemberExpression' && + node.object.type === 'Identifier' && + node.object.name === 'React' && + node.property.type === 'Identifier' && + !node.computed) { + return node.property; + } + return node; +} +function isEffectIdentifier(node, additionalHooks) { + const isBuiltInEffect = node.type === 'Identifier' && + (node.name === 'useEffect' || + node.name === 'useLayoutEffect' || + node.name === 'useInsertionEffect'); + if (isBuiltInEffect) { + return true; + } + if (additionalHooks && node.type === 'Identifier') { + return additionalHooks.test(node.name); + } + return false; +} +function isUseEffectEventIdentifier(node) { + return node.type === 'Identifier' && node.name === 'useEffectEvent'; +} +function useEffectEventError(fn, called) { + if (fn === null) { + return (`React Hook "useEffectEvent" can only be called at the top level of your component.` + + ` It cannot be passed down.`); + } + return (`\`${fn}\` is a function created with React Hook "useEffectEvent", and can only be called from ` + + 'Effects and Effect Events in the same component.' + + (called ? '' : ' It cannot be assigned to a variable or passed down.')); +} +function isUseIdentifier(node) { + return isReactFunction(node, 'use'); +} +const rule = { + meta: { + type: 'problem', + docs: { + description: 'enforces the Rules of Hooks', + recommended: true, + url: 'https://react.dev/reference/rules/rules-of-hooks', + }, + schema: [ + { + type: 'object', + additionalProperties: false, + properties: { + additionalHooks: { + type: 'string', + }, + }, + }, + ], + }, + create(context) { + const settings = context.settings || {}; + const additionalEffectHooks = getAdditionalEffectHooksFromSettings(settings); + let lastEffect = null; + const codePathReactHooksMapStack = []; + const codePathSegmentStack = []; + const useEffectEventFunctions = new WeakSet(); + function recordAllUseEffectEventFunctions(scope) { + for (const reference of scope.references) { + const parent = reference.identifier.parent; + if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'VariableDeclarator' && + parent.init && + parent.init.type === 'CallExpression' && + parent.init.callee && + isUseEffectEventIdentifier(parent.init.callee)) { + if (reference.resolved === null) { + throw new Error('Unexpected null reference.resolved'); + } + for (const ref of reference.resolved.references) { + if (ref !== reference) { + useEffectEventFunctions.add(ref.identifier); + } + } + } + } + } + const getSourceCode = typeof context.getSourceCode === 'function' + ? () => { + return context.getSourceCode(); + } + : () => { + return context.sourceCode; + }; + const getScope = typeof context.getScope === 'function' + ? () => { + return context.getScope(); + } + : (node) => { + return getSourceCode().getScope(node); + }; + function hasFlowSuppression(node, suppression) { + const sourceCode = getSourceCode(); + const comments = sourceCode.getAllComments(); + const flowSuppressionRegex = new RegExp('\\$FlowFixMe\\[' + suppression + '\\]'); + return comments.some(commentNode => flowSuppressionRegex.test(commentNode.value) && + commentNode.loc != null && + node.loc != null && + commentNode.loc.end.line === node.loc.start.line - 1); + } + const analyzer = new CodePathAnalyzer({ + onCodePathSegmentStart: (segment) => codePathSegmentStack.push(segment), + onCodePathSegmentEnd: () => codePathSegmentStack.pop(), + onCodePathStart: () => codePathReactHooksMapStack.push(new Map()), + onCodePathEnd(codePath, codePathNode) { + const reactHooksMap = codePathReactHooksMapStack.pop(); + if ((reactHooksMap === null || reactHooksMap === void 0 ? void 0 : reactHooksMap.size) === 0) { + return; + } + else if (typeof reactHooksMap === 'undefined') { + throw new Error('Unexpected undefined reactHooksMap'); + } + const cyclic = new Set(); + function countPathsFromStart(segment, pathHistory) { + const { cache } = countPathsFromStart; + let paths = cache.get(segment.id); + const pathList = new Set(pathHistory); + if (pathList.has(segment.id)) { + const pathArray = [...pathList]; + const cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1); + for (const cyclicSegment of cyclicSegments) { + cyclic.add(cyclicSegment); + } + return BigInt('0'); + } + pathList.add(segment.id); + if (paths !== undefined) { + return paths; + } + if (codePath.thrownSegments.includes(segment)) { + paths = BigInt('0'); + } + else if (segment.prevSegments.length === 0) { + paths = BigInt('1'); + } + else { + paths = BigInt('0'); + for (const prevSegment of segment.prevSegments) { + paths += countPathsFromStart(prevSegment, pathList); + } + } + if (segment.reachable && paths === BigInt('0')) { + cache.delete(segment.id); + } + else { + cache.set(segment.id, paths); + } + return paths; + } + function countPathsToEnd(segment, pathHistory) { + const { cache } = countPathsToEnd; + let paths = cache.get(segment.id); + const pathList = new Set(pathHistory); + if (pathList.has(segment.id)) { + const pathArray = Array.from(pathList); + const cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1); + for (const cyclicSegment of cyclicSegments) { + cyclic.add(cyclicSegment); + } + return BigInt('0'); + } + pathList.add(segment.id); + if (paths !== undefined) { + return paths; + } + if (codePath.thrownSegments.includes(segment)) { + paths = BigInt('0'); + } + else if (segment.nextSegments.length === 0) { + paths = BigInt('1'); + } + else { + paths = BigInt('0'); + for (const nextSegment of segment.nextSegments) { + paths += countPathsToEnd(nextSegment, pathList); + } + } + cache.set(segment.id, paths); + return paths; + } + function shortestPathLengthToStart(segment) { + const { cache } = shortestPathLengthToStart; + let length = cache.get(segment.id); + if (length === null) { + return Infinity; + } + if (length !== undefined) { + return length; + } + cache.set(segment.id, null); + if (segment.prevSegments.length === 0) { + length = 1; + } + else { + length = Infinity; + for (const prevSegment of segment.prevSegments) { + const prevLength = shortestPathLengthToStart(prevSegment); + if (prevLength < length) { + length = prevLength; + } + } + length += 1; + } + cache.set(segment.id, length); + return length; + } + countPathsFromStart.cache = new Map(); + countPathsToEnd.cache = new Map(); + shortestPathLengthToStart.cache = new Map(); + const allPathsFromStartToEnd = countPathsToEnd(codePath.initialSegment); + const codePathFunctionName = getFunctionName(codePathNode); + const isSomewhereInsideComponentOrHook = isInsideComponentOrHook(codePathNode); + const isDirectlyInsideComponentOrHook = codePathFunctionName + ? isComponentName(codePathFunctionName) || + isHook(codePathFunctionName) + : isForwardRefCallback(codePathNode) || isMemoCallback(codePathNode); + let shortestFinalPathLength = Infinity; + for (const finalSegment of codePath.finalSegments) { + if (!finalSegment.reachable) { + continue; + } + const length = shortestPathLengthToStart(finalSegment); + if (length < shortestFinalPathLength) { + shortestFinalPathLength = length; + } + } + for (const [segment, reactHooks] of reactHooksMap) { + if (!segment.reachable) { + continue; + } + const possiblyHasEarlyReturn = segment.nextSegments.length === 0 + ? shortestFinalPathLength <= shortestPathLengthToStart(segment) + : shortestFinalPathLength < shortestPathLengthToStart(segment); + const pathsFromStartToEnd = countPathsFromStart(segment) * countPathsToEnd(segment); + const cycled = cyclic.has(segment.id); + for (const hook of reactHooks) { + if (hasFlowSuppression(hook, 'react-rule-hook')) { + continue; + } + if (isUseIdentifier(hook) && isInsideTryCatch(hook)) { + context.report({ + node: hook, + message: `React Hook "${getSourceCode().getText(hook)}" cannot be called in a try/catch block.`, + }); + } + if ((cycled || isInsideDoWhileLoop(hook)) && + !isUseIdentifier(hook)) { + context.report({ + node: hook, + message: `React Hook "${getSourceCode().getText(hook)}" may be executed ` + + 'more than once. Possibly because it is called in a loop. ' + + 'React Hooks must be called in the exact same order in ' + + 'every component render.', + }); + } + if (isDirectlyInsideComponentOrHook) { + const isAsyncFunction = codePathNode.async; + if (isAsyncFunction) { + context.report({ + node: hook, + message: `React Hook "${getSourceCode().getText(hook)}" cannot be ` + + 'called in an async function.', + }); + } + if (!cycled && + pathsFromStartToEnd !== allPathsFromStartToEnd && + !isUseIdentifier(hook) && + !isInsideDoWhileLoop(hook)) { + const message = `React Hook "${getSourceCode().getText(hook)}" is called ` + + 'conditionally. React Hooks must be called in the exact ' + + 'same order in every component render.' + + (possiblyHasEarlyReturn + ? ' Did you accidentally call a React Hook after an' + + ' early return?' + : ''); + context.report({ node: hook, message }); + } + } + else if (codePathNode.parent != null && + (codePathNode.parent.type === 'MethodDefinition' || + codePathNode.parent.type === 'ClassProperty' || + codePathNode.parent.type === 'PropertyDefinition') && + codePathNode.parent.value === codePathNode) { + const message = `React Hook "${getSourceCode().getText(hook)}" cannot be called ` + + 'in a class component. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message }); + } + else if (codePathFunctionName) { + const message = `React Hook "${getSourceCode().getText(hook)}" is called in ` + + `function "${getSourceCode().getText(codePathFunctionName)}" ` + + 'that is neither a React function component nor a custom ' + + 'React Hook function.' + + ' React component names must start with an uppercase letter.' + + ' React Hook names must start with the word "use".'; + context.report({ node: hook, message }); + } + else if (codePathNode.type === 'Program') { + const message = `React Hook "${getSourceCode().getText(hook)}" cannot be called ` + + 'at the top level. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message }); + } + else { + if (isSomewhereInsideComponentOrHook && !isUseIdentifier(hook)) { + const message = `React Hook "${getSourceCode().getText(hook)}" cannot be called ` + + 'inside a callback. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message }); + } + } + } + } + }, + }); + return { + '*'(node) { + analyzer.enterNode(node); + }, + '*:exit'(node) { + analyzer.leaveNode(node); + }, + CallExpression(node) { + var _a, _b; + if (isHook(node.callee)) { + const reactHooksMap = last(codePathReactHooksMapStack); + const codePathSegment = last(codePathSegmentStack); + let reactHooks = reactHooksMap.get(codePathSegment); + if (!reactHooks) { + reactHooks = []; + reactHooksMap.set(codePathSegment, reactHooks); + } + reactHooks.push(node.callee); + } + const nodeWithoutNamespace = getNodeWithoutReactNamespace(node.callee); + if ((isEffectIdentifier(nodeWithoutNamespace, additionalEffectHooks) || + isUseEffectEventIdentifier(nodeWithoutNamespace)) && + node.arguments.length > 0) { + lastEffect = node; + } + if (isUseEffectEventIdentifier(nodeWithoutNamespace) && + ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.type) !== 'VariableDeclarator' && + ((_b = node.parent) === null || _b === void 0 ? void 0 : _b.type) !== 'ExpressionStatement') { + const message = useEffectEventError(null, false); + context.report({ + node, + message, + }); + } + }, + Identifier(node) { + if (lastEffect == null && useEffectEventFunctions.has(node)) { + const message = useEffectEventError(getSourceCode().getText(node), node.parent.type === 'CallExpression'); + context.report({ + node, + message, + }); + } + }, + 'CallExpression:exit'(node) { + if (node === lastEffect) { + lastEffect = null; + } + }, + FunctionDeclaration(node) { + if (isInsideComponentOrHook(node)) { + recordAllUseEffectEventFunctions(getScope(node)); + } + }, + ArrowFunctionExpression(node) { + if (isInsideComponentOrHook(node)) { + recordAllUseEffectEventFunctions(getScope(node)); + } + }, + ComponentDeclaration(node) { + recordAllUseEffectEventFunctions(getScope(node)); + }, + HookDeclaration(node) { + recordAllUseEffectEventFunctions(getScope(node)); + }, + }; + }, +}; +function getFunctionName(node) { + var _a, _b, _c, _d; + if (node.type === 'ComponentDeclaration' || + node.type === 'HookDeclaration' || + node.type === 'FunctionDeclaration' || + (node.type === 'FunctionExpression' && node.id)) { + return node.id; + } + else if (node.type === 'FunctionExpression' || + node.type === 'ArrowFunctionExpression') { + if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.type) === 'VariableDeclarator' && + node.parent.init === node) { + return node.parent.id; + } + else if (((_b = node.parent) === null || _b === void 0 ? void 0 : _b.type) === 'AssignmentExpression' && + node.parent.right === node && + node.parent.operator === '=') { + return node.parent.left; + } + else if (((_c = node.parent) === null || _c === void 0 ? void 0 : _c.type) === 'Property' && + node.parent.value === node && + !node.parent.computed) { + return node.parent.key; + } + else if (((_d = node.parent) === null || _d === void 0 ? void 0 : _d.type) === 'AssignmentPattern' && + node.parent.right === node && + !node.parent.computed) { + return node.parent.left; + } + else { + return undefined; + } + } + else { + return undefined; + } +} +function last(array) { + return array[array.length - 1]; +} + +function makeDeprecatedRule(version) { + return { + meta: { + type: 'suggestion', + docs: { + description: `Deprecated: this rule has been removed in ${version}.`, + }, + schema: [], + deprecated: true, + }, + create() { + return {}; + }, + }; +} +const rules = Object.assign(Object.assign({ 'exhaustive-deps': rule$1, 'rules-of-hooks': rule }, Object.fromEntries(Object.entries(allRules).map(([name, config]) => [name, config.rule]))), { 'component-hook-factories': makeDeprecatedRule('7.1.0') }); +const basicRuleConfigs = { + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'warn', +}; +const recommendedCompilerRuleConfigs = Object.fromEntries(Object.entries(recommendedRules).map(([name, ruleConfig]) => { + return [ + `react-hooks/${name}`, + mapErrorSeverityToESlint(ruleConfig.severity), + ]; +})); +const recommendedLatestCompilerRuleConfigs = Object.fromEntries(Object.entries(recommendedLatestRules).map(([name, ruleConfig]) => { + return [ + `react-hooks/${name}`, + mapErrorSeverityToESlint(ruleConfig.severity), + ]; +})); +const recommendedRuleConfigs = Object.assign(Object.assign({}, basicRuleConfigs), recommendedCompilerRuleConfigs); +const recommendedLatestRuleConfigs = Object.assign(Object.assign({}, basicRuleConfigs), recommendedLatestCompilerRuleConfigs); +const plugins = ['react-hooks']; +const configs = { + recommended: { + plugins, + rules: recommendedRuleConfigs, + }, + 'recommended-latest': { + plugins, + rules: recommendedLatestRuleConfigs, + }, + flat: {}, +}; +const plugin = { + meta: { + name: 'eslint-plugin-react-hooks', + version: '7.0.0', + }, + rules, + configs, +}; +Object.assign(configs.flat, { + 'recommended-latest': { + plugins: { 'react-hooks': plugin }, + rules: configs['recommended-latest'].rules, + }, + recommended: { + plugins: { 'react-hooks': plugin }, + rules: configs.recommended.rules, + }, +}); + +module.exports = plugin; diff --git a/node_modules/eslint-plugin-react-hooks/index.d.ts b/node_modules/eslint-plugin-react-hooks/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7516dc1e846e2ccae8aed7b711c41447c0ede0c7 --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/index.d.ts @@ -0,0 +1,10 @@ +/** + * 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 reactHooks from './cjs/eslint-plugin-react-hooks'; + +export = reactHooks; diff --git a/node_modules/eslint-plugin-react-hooks/index.js b/node_modules/eslint-plugin-react-hooks/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3e8352af1e64371ece0ec2bdacfe11347fa602af --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/index.js @@ -0,0 +1,26 @@ +/** + * 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. + */ + +'use strict'; + +// TODO: this doesn't make sense for an ESLint rule. +// We need to fix our build process to not create bundles for "raw" packages like this. +if (process.env.NODE_ENV === 'production') { + module.exports = require('./cjs/eslint-plugin-react-hooks.production.js'); +} else { + module.exports = require('./cjs/eslint-plugin-react-hooks.development.js'); +} + +// Hint to Node’s cjs-module-lexer to make named imports work +// https://github.com/facebook/react/issues/34801#issuecomment-3433478810 +// eslint-disable-next-line ft-flow/no-unused-expressions +0 && + (module.exports = { + meta: true, + rules: true, + configs: true, + }); diff --git a/node_modules/eslint-plugin-react-hooks/package.json b/node_modules/eslint-plugin-react-hooks/package.json new file mode 100644 index 0000000000000000000000000000000000000000..701ddcfa60bd07a9dda54188c4dc733efa71b0fe --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/package.json @@ -0,0 +1,68 @@ +{ + "name": "eslint-plugin-react-hooks", + "description": "ESLint rules for React Hooks", + "version": "7.1.1", + "repository": { + "type": "git", + "url": "https://github.com/facebook/react.git", + "directory": "packages/eslint-plugin-react-hooks" + }, + "files": [ + "LICENSE", + "README.md", + "cjs", + "index.js", + "index.d.ts" + ], + "keywords": [ + "eslint", + "eslint-plugin", + "eslintplugin", + "react" + ], + "scripts": { + "build:compiler": "cd ../../compiler && yarn workspace babel-plugin-react-compiler build", + "test": "yarn build:compiler && jest", + "typecheck": "tsc --noEmit" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/facebook/react/issues" + }, + "main": "./index.js", + "types": "./index.d.ts", + "engines": { + "node": ">=18" + }, + "homepage": "https://react.dev/", + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0" + }, + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "devDependencies": { + "@babel/eslint-parser": "^7.11.4", + "@babel/preset-typescript": "^7.26.0", + "@babel/types": "^7.19.0", + "@tsconfig/strictest": "^2.0.5", + "@types/eslint": "^9.6.1", + "@types/estree": "^1.0.6", + "@types/estree-jsx": "^1.0.5", + "@types/node": "^20.2.5", + "@typescript-eslint/parser-v2": "npm:@typescript-eslint/parser@^2.26.0", + "@typescript-eslint/parser-v3": "npm:@typescript-eslint/parser@^3.10.0", + "@typescript-eslint/parser-v4": "npm:@typescript-eslint/parser@^4.1.0", + "@typescript-eslint/parser-v5": "npm:@typescript-eslint/parser@^5.62.0", + "babel-eslint": "^10.0.3", + "eslint-v7": "npm:eslint@^7.7.0", + "eslint-v8": "npm:eslint@^8.57.1", + "eslint-v9": "npm:eslint@^9.0.0", + "jest": "^29.5.0", + "typescript": "^5.4.3" + } +} diff --git a/node_modules/eslint-plugin-react-refresh/LICENSE b/node_modules/eslint-plugin-react-refresh/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..75488f19b510f43dcd7674c2c23d59f13a3a417c --- /dev/null +++ b/node_modules/eslint-plugin-react-refresh/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Arnaud Barré (https://github.com/ArnaudBarre) + +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. diff --git a/node_modules/eslint-plugin-react-refresh/README.md b/node_modules/eslint-plugin-react-refresh/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5f04163c805a03c56a5772d807973dd310f81451 --- /dev/null +++ b/node_modules/eslint-plugin-react-refresh/README.md @@ -0,0 +1,222 @@ +# eslint-plugin-react-refresh [![npm](https://img.shields.io/npm/v/eslint-plugin-react-refresh)](https://www.npmjs.com/package/eslint-plugin-react-refresh) + +Validate that your components can safely be updated with Fast Refresh. + +## Explainer + +"Fast Refresh", also known as "hot reloading", is a feature in many modern bundlers. +If you update some React component(s) on disk, then the bundler will know to update only the impacted parts of your page -- without a full page reload. + +`eslint-plugin-react-refresh` enforces that your components are structured in a way that integrations such as [react-refresh](https://www.npmjs.com/package/react-refresh) expect. + +### Limitations + +⚠️ To avoid false positives, by default this plugin is only applied on `tsx` & `jsx` files. See [Options](#options) to run on JS files. ⚠️ + +The plugin relies on naming conventions (i.e. use PascalCase for components, camelCase for util functions). This is why there are some limitations: + +- `export *` are not supported and will be reported as an error +- Anonymous function are not supported (i.e `export default function() {}`) +- Class components are not supported +- All-uppercase function export is considered an error when not using direct named export (ex `const CMS = () => <>; export { CMS }`) + +## Installation + +```sh +npm i -D eslint-plugin-react-refresh +``` + +## Usage + +This plugin provides a single rule, `react-refresh/only-export-components`. There are multiple ways to enable it. + +### Recommended config + +```js +import { defineConfig } from "eslint/config"; +import { reactRefresh } from "eslint-plugin-react-refresh"; + +export default defineConfig( + /* Main config */ + reactRefresh.configs.recommended(), +); +``` + +### Vite config + +This enables the `allowConstantExport` option which is supported by Vite React plugins. + +```js +import { defineConfig } from "eslint/config"; +import { reactRefresh } from "eslint-plugin-react-refresh"; + +export default defineConfig( + /* Main config */ + reactRefresh.configs.vite(), +); +``` + +### Next config + +This allows exports like `fetchCache` and `revalidate` which are used in Page or Layout components and don't trigger a full page reload. + +```js +import { defineConfig } from "eslint/config"; +import { reactRefresh } from "eslint-plugin-react-refresh"; + +export default defineConfig( + /* Main config */ + reactRefresh.configs.next(), +); +``` + +### Without config + +```js +import { defineConfig } from "eslint/config"; +import { reactRefresh } from "eslint-plugin-react-refresh"; + +export default defineConfig({ + // in main config for TSX/JSX source files + plugins: { + "react-refresh": reactRefresh.plugin, + }, + rules: { + "react-refresh/only-export-components": "error", + }, +}); +``` + +## Examples + +These examples are from enabling `react-refresh/only-exports-components`. + +### Fail + +```jsx +export const foo = () => {}; +export const Bar = () => <>; +``` + +```jsx +export default function () {} +export default compose()(MainComponent) +``` + +```jsx +export * from "./foo"; +``` + +```jsx +const Tab = () => {}; +export const tabs = [, ]; +``` + +```jsx +const App = () => {}; +createRoot(document.getElementById("root")).render(); +``` + +### Pass + +```jsx +export default function Foo() { + return <>; +} +``` + +```jsx +const foo = () => {}; +export const Bar = () => <>; +``` + +```jsx +import { App } from "./App"; +createRoot(document.getElementById("root")).render(); +``` + +## Options + +These options are all present on `react-refresh/only-exports-components`. + +```ts +interface Options { + extraHOCs?: string[]; + allowExportNames?: string[]; + allowConstantExport?: boolean; + checkJS?: boolean; +} + +const defaultOptions: Options = { + extraHOCs: [], + allowExportNames: [], + allowConstantExport: false, + checkJS: false, +}; +``` + +### extraHOCs (v0.5.0) + +If you're exporting components wrapped in non built-in React HOC (memo, forwardRef, lazy), you can use this option to avoid false positives. + +```json +{ + "react-refresh/only-export-components": [ + "error", + { "extraHOCs": ["observer", "withAuth"] } + ] +} +``` + +### allowExportNames (v0.4.4) + +> Default: `[]` + +If you use a framework that handles HMR of some specific exports, you can use this option to avoid warning for them. + +Example for [Remix](https://remix.run/docs/en/main/discussion/hot-module-replacement#supported-exports): + +```json +{ + "react-refresh/only-export-components": [ + "error", + { "allowExportNames": ["meta", "links", "headers", "loader", "action"] } + ] +} +``` + +### allowConstantExport (v0.4.0) + +> Default: `false` (`true` in `vite` config) + +Don't warn when a constant (string, number, boolean, templateLiteral) is exported aside one or more components. + +This should be enabled if the fast refresh implementation correctly handles this case (HMR when the constant doesn't change, propagate update to importers when the constant changes.). Vite supports it, PR welcome if you notice other integrations works well. + +```json +{ + "react-refresh/only-export-components": [ + "error", + { "allowConstantExport": true } + ] +} +``` + +Enabling this option allows code such as the following: + +```jsx +export const CONSTANT = 3; +export const Foo = () => <>; +``` + +### checkJS (v0.3.3) + +> Default: `false` + +If you're using JSX inside `.js` files (which I don't recommend because it forces you to configure every tool you use to switch the parser), you can still use the plugin by enabling this option. To reduce the number of false positive, only files importing `react` are checked. + +```json +{ + "react-refresh/only-export-components": ["error", { "checkJS": true }] +} +``` diff --git a/node_modules/eslint-plugin-react-refresh/index.d.ts b/node_modules/eslint-plugin-react-refresh/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..db1edf165cb96d788523b3c858562ad171ca61d1 --- /dev/null +++ b/node_modules/eslint-plugin-react-refresh/index.d.ts @@ -0,0 +1,40 @@ +type Rules = { "only-export-components": any }; + +export type OnlyExportComponentsOptions = { + extraHOCs?: string[]; + allowExportNames?: string[]; + allowConstantExport?: boolean; + checkJS?: boolean; +}; + +type Config = { + name: string; + plugins: { "react-refresh": { rules: Rules } }; + rules: Rules; +}; +type ConfigFn = (options?: OnlyExportComponentsOptions) => { + name: string; + plugins: { "react-refresh": { rules: Rules } }; + rules: Rules; +}; + +export const reactRefresh: { + plugin: { + rules: Rules; + }; + configs: { + recommended: ConfigFn; + vite: ConfigFn; + next: ConfigFn; + }; +}; + +declare const _default: { + rules: Rules; + configs: { + recommended: Config; + vite: Config; + next: Config; + }; +}; +export default _default; diff --git a/node_modules/eslint-plugin-react-refresh/index.js b/node_modules/eslint-plugin-react-refresh/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b9a831ee74f1112dee678202c63be81341c45478 --- /dev/null +++ b/node_modules/eslint-plugin-react-refresh/index.js @@ -0,0 +1,344 @@ +// src/only-export-components.ts +var reactComponentNameRE = /^[A-Z][a-zA-Z0-9_]*$/u; +var onlyExportComponents = { + meta: { + messages: { + exportAll: "This rule can't verify that `export *` only exports components.", + namedExport: "Fast refresh only works when a file only exports components. Use a new file to share constants or functions between components.", + anonymousExport: "Fast refresh can't handle anonymous components. Add a name to your export.", + localComponents: "Fast refresh only works when a file only exports components. Move your component(s) to a separate file. If all exports are HOCs, add them to the `extraHOCs` option.", + noExport: "Fast refresh only works when a file has exports. Move your component(s) to a separate file.", + reactContext: "Fast refresh only works when a file only exports components. Move your React context(s) to a separate file." + }, + type: "problem", + schema: [ + { + type: "object", + properties: { + extraHOCs: { type: "array", items: { type: "string" } }, + allowExportNames: { type: "array", items: { type: "string" } }, + allowConstantExport: { type: "boolean" }, + checkJS: { type: "boolean" } + }, + additionalProperties: false + } + ] + }, + defaultOptions: [], + create: (context) => { + const { + extraHOCs = [], + allowExportNames, + allowConstantExport = false, + checkJS = false + } = context.options[0] ?? {}; + const filename = context.filename; + if (filename.includes(".test.") || filename.includes(".spec.") || filename.includes(".cy.") || filename.includes(".stories.")) { + return {}; + } + const shouldScan = filename.endsWith(".jsx") || filename.endsWith(".tsx") || checkJS && filename.endsWith(".js"); + if (!shouldScan) return {}; + const allowExportNamesSet = allowExportNames ? new Set(allowExportNames) : void 0; + const validHOCs = ["memo", "forwardRef", "lazy", ...extraHOCs]; + const getHocName = (node) => { + const callee = node.type === "CallExpression" ? node.callee : node.tag; + if (callee.type === "CallExpression") { + return getHocName(callee); + } + if (callee.type === "MemberExpression") { + if (callee.property.type === "Identifier" && validHOCs.includes(callee.property.name)) { + return callee.property.name; + } + if (callee.object.type === "Identifier" && validHOCs.includes(callee.object.name)) { + return callee.object.name; + } + if (callee.object.type === "CallExpression") { + return getHocName(callee.object); + } + } + if (callee.type === "Identifier") { + return callee.name; + } + return void 0; + }; + const isCallExpressionReactComponent = (node) => { + const hocName = getHocName(node); + if (!hocName || !validHOCs.includes(hocName)) return false; + const validateArgument = hocName === "memo" || hocName === "forwardRef"; + if (!validateArgument) return true; + if (node.arguments.length === 0) return false; + const arg = skipTSWrapper(node.arguments[0]); + switch (arg.type) { + case "Identifier": + return reactComponentNameRE.test(arg.name); + case "FunctionExpression": + case "ArrowFunctionExpression": + if (!arg.id) return "needName"; + return reactComponentNameRE.test(arg.id.name); + case "CallExpression": + return isCallExpressionReactComponent(arg); + default: + return false; + } + }; + const isExpressionReactComponent = (expressionParam) => { + const exp = skipTSWrapper(expressionParam); + if (exp.type === "Identifier") { + return reactComponentNameRE.test(exp.name); + } + if (exp.type === "ArrowFunctionExpression" || exp.type === "FunctionExpression") { + if (exp.params.length > 2) return false; + if (!exp.id?.name) return "needName"; + return reactComponentNameRE.test(exp.id.name); + } + if (exp.type === "ConditionalExpression") { + const consequent = isExpressionReactComponent(exp.consequent); + const alternate = isExpressionReactComponent(exp.alternate); + if (consequent === false || alternate === false) return false; + if (consequent === "needName" || alternate === "needName") { + return "needName"; + } + return true; + } + if (exp.type === "CallExpression") { + return isCallExpressionReactComponent(exp); + } + if (exp.type === "TaggedTemplateExpression") { + const hocName = getHocName(exp); + if (!hocName || !validHOCs.includes(hocName)) return false; + return "needName"; + } + return false; + }; + return { + Program(program) { + let hasExports = false; + let hasReactExport = false; + let reactIsInScope = false; + const localComponents = []; + const nonComponentExports = []; + const reactContextExports = []; + const handleExportIdentifier = (identifierNode, initParam) => { + if (identifierNode.type !== "Identifier") { + nonComponentExports.push(identifierNode); + return; + } + if (allowExportNamesSet?.has(identifierNode.name)) return; + if (!initParam) { + if (reactComponentNameRE.test(identifierNode.name)) { + hasReactExport = true; + } else { + nonComponentExports.push(identifierNode); + } + return; + } + const init = skipTSWrapper(initParam); + if (allowConstantExport && constantExportExpressions.has(init.type)) { + return; + } + if (init.type === "CallExpression" && (init.callee.type === "Identifier" && init.callee.name === "createContext" || init.callee.type === "MemberExpression" && init.callee.property.type === "Identifier" && init.callee.property.name === "createContext")) { + reactContextExports.push(identifierNode); + return; + } + const isReactComponent = reactComponentNameRE.test(identifierNode.name) && isExpressionReactComponent(init); + if (isReactComponent === false) { + nonComponentExports.push(identifierNode); + } else { + hasReactExport = true; + } + }; + const handleExportDeclaration = (node) => { + if (node.type === "VariableDeclaration") { + for (const variable of node.declarations) { + if (variable.init === null) { + nonComponentExports.push(variable.id); + continue; + } + handleExportIdentifier(variable.id, variable.init); + } + } else if (node.type === "FunctionDeclaration") { + if (node.id === null) { + context.report({ messageId: "anonymousExport", node }); + } else { + handleExportIdentifier(node.id); + } + } else if (node.type === "ClassDeclaration") { + if (node.id === null) { + context.report({ messageId: "anonymousExport", node }); + } else if (reactComponentNameRE.test(node.id.name) && node.superClass !== null && node.body.body.some( + (item) => item.type === "MethodDefinition" && item.key.type === "Identifier" && item.key.name === "render" + )) { + hasReactExport = true; + } else { + nonComponentExports.push(node.id); + } + } else if (node.type === "CallExpression") { + const result = isCallExpressionReactComponent(node); + if (result === false) { + nonComponentExports.push(node); + } else if (result === "needName") { + context.report({ messageId: "anonymousExport", node }); + } else { + hasReactExport = true; + } + } else { + nonComponentExports.push(node); + } + }; + for (const node of program.body) { + if (node.type === "ExportAllDeclaration") { + if (node.exportKind === "type") continue; + hasExports = true; + context.report({ messageId: "exportAll", node }); + } else if (node.type === "ExportDefaultDeclaration") { + hasExports = true; + const declaration = skipTSWrapper(node.declaration); + if (declaration.type === "VariableDeclaration" || declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration" || declaration.type === "CallExpression") { + handleExportDeclaration(declaration); + } + if (declaration.type === "Identifier") { + handleExportIdentifier(declaration); + } + if (declaration.type === "ArrowFunctionExpression") { + context.report({ messageId: "anonymousExport", node }); + } + } else if (node.type === "ExportNamedDeclaration") { + if (node.exportKind === "type") continue; + const declaration = node.declaration ? skipTSWrapper(node.declaration) : null; + if (declaration?.type === "TSDeclareFunction") continue; + hasExports = true; + if (declaration) handleExportDeclaration(declaration); + for (const specifier of node.specifiers) { + if (specifier.local.type === "Identifier") { + const scope = context.sourceCode.getScope(node); + const localName = specifier.local.name; + const def = scope.variables.find((v) => v.name === localName)?.defs[0]; + if (def?.type === "ClassName") { + handleExportDeclaration(def.node); + continue; + } + } + handleExportIdentifier( + specifier.exported.type === "Identifier" && specifier.exported.name === "default" ? specifier.local : specifier.exported + ); + } + } else if (node.type === "VariableDeclaration") { + for (const variable of node.declarations) { + if (variable.id.type === "Identifier" && reactComponentNameRE.test(variable.id.name) && variable.init !== null && isExpressionReactComponent(variable.init) !== false) { + localComponents.push(variable.id); + } + } + } else if (node.type === "FunctionDeclaration") { + if (reactComponentNameRE.test(node.id.name)) { + localComponents.push(node.id); + } + } else if (node.type === "ImportDeclaration" && node.source.value === "react") { + reactIsInScope = true; + } + } + if (checkJS && !reactIsInScope) return; + if (hasExports) { + if (hasReactExport) { + for (const node of nonComponentExports) { + context.report({ messageId: "namedExport", node }); + } + for (const node of reactContextExports) { + context.report({ messageId: "reactContext", node }); + } + } else if (localComponents.length) { + for (const node of localComponents) { + context.report({ messageId: "localComponents", node }); + } + } + } else if (localComponents.length) { + for (const node of localComponents) { + context.report({ messageId: "noExport", node }); + } + } + } + }; + } +}; +var skipTSWrapper = (node) => { + if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion" || node.type === "TSInstantiationExpression") { + return node.expression; + } + return node; +}; +var constantExportExpressions = /* @__PURE__ */ new Set([ + "Literal", + // 1, "foo" + "UnaryExpression", + // -1 + "TemplateLiteral", + // `Some ${template}` + "BinaryExpression" + // 24 * 60 +]); + +// src/index.ts +var rules = { + "only-export-components": onlyExportComponents +}; +var plugin = { rules }; +var buildConfig = ({ + name, + baseOptions +}) => (options) => ({ + name: `react-refresh/${name}`, + plugins: { "react-refresh": plugin }, + rules: { + "react-refresh/only-export-components": [ + "error", + { ...baseOptions, ...options } + ] + } +}); +var configs = { + recommended: buildConfig({ name: "recommended", baseOptions: {} }), + vite: buildConfig({ + name: "vite", + baseOptions: { allowConstantExport: true } + }), + next: buildConfig({ + name: "next", + baseOptions: { + allowExportNames: [ + // https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config + "experimental_ppr", + "dynamic", + "dynamicParams", + "revalidate", + "fetchCache", + "runtime", + "preferredRegion", + "maxDuration", + // https://nextjs.org/docs/app/api-reference/functions/generate-metadata + "metadata", + "generateMetadata", + // https://nextjs.org/docs/app/api-reference/functions/generate-viewport + "viewport", + "generateViewport", + // https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata + "generateImageMetadata", + // https://nextjs.org/docs/app/api-reference/functions/generate-sitemaps + "generateSitemaps", + // https://nextjs.org/docs/app/api-reference/functions/generate-static-params + "generateStaticParams" + ] + } + }) +}; +var reactRefresh = { plugin, configs }; +var index_default = { + rules, + configs: { + recommended: configs.recommended(), + vite: configs.vite(), + next: configs.next() + } +}; +export { + index_default as default, + reactRefresh +}; diff --git a/node_modules/eslint-plugin-react-refresh/package.json b/node_modules/eslint-plugin-react-refresh/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f8d7b3bb70593562f16c9e27d90a818ebb0f777b --- /dev/null +++ b/node_modules/eslint-plugin-react-refresh/package.json @@ -0,0 +1,25 @@ +{ + "name": "eslint-plugin-react-refresh", + "description": "Validate that your components can safely be updated with Fast Refresh", + "version": "0.5.3", + "type": "module", + "author": "Arnaud Barré (https://github.com/ArnaudBarre)", + "license": "MIT", + "repository": "github:ArnaudBarre/eslint-plugin-react-refresh", + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./index.js" + } + }, + "keywords": [ + "eslint", + "eslint-plugin", + "react", + "react-refresh", + "fast refresh" + ], + "peerDependencies": { + "eslint": "^9 || ^10" + } +} \ No newline at end of file diff --git a/node_modules/eslint-scope/LICENSE b/node_modules/eslint-scope/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d36a526f7ed5d10c43c68f34622efba7e62fc8a7 --- /dev/null +++ b/node_modules/eslint-scope/LICENSE @@ -0,0 +1,22 @@ +Copyright JS Foundation and other contributors, https://js.foundation +Copyright (C) 2012-2013 Yusuke Suzuki (twitter: @Constellation) and other contributors. + +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. + +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 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. diff --git a/node_modules/eslint-scope/README.md b/node_modules/eslint-scope/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7d595e488f5fb3cf9f505ba51fec422d579b1a1c --- /dev/null +++ b/node_modules/eslint-scope/README.md @@ -0,0 +1,207 @@ +[![npm version](https://img.shields.io/npm/v/eslint-scope.svg)](https://www.npmjs.com/package/eslint-scope) +[![Downloads](https://img.shields.io/npm/dm/eslint-scope.svg)](https://www.npmjs.com/package/eslint-scope) +[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions) + +# ESLint Scope + +ESLint Scope is the [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) scope analyzer used in ESLint. It is a fork of [escope](http://github.com/estools/escope). + +## Install + +``` +npm i eslint-scope --save +``` + +## 📖 Usage + +To use in an ESM file: + +```js +import * as eslintScope from "eslint-scope"; +``` + +To use in a CommonJS file: + +```js +const eslintScope = require("eslint-scope"); +``` + +In order to analyze scope, you'll need to have an [ESTree](https://github.com/estree/estree) compliant AST structure to run it on. The primary method is `eslintScope.analyze()`, which takes two arguments: + +1. `ast` - the ESTree-compliant AST structure to analyze. +2. `options` (optional) - Options to adjust how the scope is analyzed, including: + +- `ignoreEval` (default: `false`) - Set to `true` to ignore all `eval()` calls (which would normally create scopes). +- `nodejsScope` (default: `false`) - Set to `true` to create a top-level function scope needed for CommonJS evaluation. +- `impliedStrict` (default: `false`) - Set to `true` to evaluate the code in strict mode even outside of modules and without `"use strict"`. +- `ecmaVersion` (default: `5`) - The version of ECMAScript to use to evaluate the code. +- `sourceType` (default: `"script"`) - The type of JavaScript file to evaluate. Change to `"module"` for ECMAScript module code. +- `childVisitorKeys` (default: `null`) - An object with visitor key information (like [`eslint-visitor-keys`](https://github.com/eslint/js/tree/main/packages/eslint-visitor-keys)). Without this, `eslint-scope` finds child nodes to visit algorithmically. Providing this option is a performance enhancement. +- `fallback` (default: `"iteration"`) - The strategy to use when `childVisitorKeys` is not specified. May be a function. +- `optimistic` (default: `false`) - Set to `true` to enable optimistic scope analysis. +- `jsx` (default: `false`) - Enables the tracking of JSX components as variable references. + +Example: + +```js +import * as eslintScope from "eslint-scope"; +import * as espree from "espree"; +import estraverse from "estraverse"; + +const options = { + ecmaVersion: 2022, + sourceType: "module", +}; + +const ast = espree.parse(code, { range: true, ...options }); +const scopeManager = eslintScope.analyze(ast, options); + +const currentScope = scopeManager.acquire(ast); // global scope + +estraverse.traverse(ast, { + enter(node, parent) { + // do stuff + + if (/Function/.test(node.type)) { + currentScope = scopeManager.acquire(node); // get current function scope + } + }, + leave(node, parent) { + if (/Function/.test(node.type)) { + currentScope = currentScope.upper; // set to parent scope + } + + // do stuff + }, +}); +``` + +## API + +The following section describes the API for this package. You can also read [the docs](https://eslint.org/docs/latest/extend/scope-manager-interface). + +### ScopeManager + +The `ScopeManager` class is at the core of eslint-scope and is returned when you call `eslintScope.analyze()`. It manages all scopes in a given AST. + +#### Properties + +- `scopes` - An array of all scopes. +- `globalScope` - Reference to the global scope. + +#### Methods + +- **`addGlobals(names)`** + Adds variables to the global scope and resolves references to them. + - `names` - An array of strings, the names of variables to add to the global scope. + - Returns: `undefined`. + +- **`acquire(node, inner)`** + Acquires the appropriate scope for a given node. + - `node` - The AST node to acquire the scope from. + - `inner` - Optional boolean. When `true`, returns the innermost scope, otherwise returns the outermost scope. Default is `false`. + - Returns: The acquired scope or `null` if no scope is found. + +- **`acquireAll(node)` (Deprecated)** + Acquires all scopes for a given node. + - `node` - The AST node to acquire scopes from. + - Returns: An array of scopes or `undefined` if none are found. + +- **`release(node, inner)`** + Returns the upper scope for a given node. + - `node` - The AST node to release. + - `inner` - Optional boolean. When `true`, returns the innermost upper scope, otherwise returns the outermost upper scope. Default is `false`. + - Returns: The upper scope or `null` if no upper scope exists. + +- **`getDeclaredVariables(node)`** + Get variables that are declared by the node. + - `node` - The AST node to get declarations from. + - Returns: An array of variable objects declared by the node. If the node doesn't declare any variables, it returns an empty array. + +- **`isGlobalReturn()`** + Determines if the global return statement should be allowed. + - Returns: `true` if the global return is enabled. + +- **`isModule()` (Deprecated)** + Checks if the code should be handled as an ECMAScript module. + - Returns: `true` if the sourceType is "module". + +- **`isImpliedStrict()` (Deprecated)** + Checks if implied strict mode is enabled. + - Returns: `true` if implied strict mode is enabled. + +- **`isStrictModeSupported()` (Deprecated)** + Checks if strict mode is supported based on ECMAScript version. + - Returns: `true` if the ECMAScript version supports strict mode. + +### Scope Objects + +Scopes returned by the ScopeManager methods have the following properties: + +- `type` - The type of scope (e.g., `"function"`, `"block"`, `"global"`). +- `isStrict` - `true` if this scope is in strict mode. +- `variables` - Array of variables declared in this scope. +- `set` - A Map of variable names to Variable objects for variables declared in this scope. +- `references` - Array of references in this scope. +- `through` - Array of references in this scope and its child scopes that aren't resolved in this scope or its child scopes. +- `functionExpressionScope` - `true` if this is a `"function-expression-name"` scope. +- `variableScope` - Reference to the closest variable scope. +- `upper` - Reference to the parent scope. +- `childScopes` - Array of child scopes. +- `block` - The AST node that created this scope. + +### GlobalScope + +The `GlobalScope` class is a specialized scope representing the global execution context. It extends the base `Scope` class with additional functionality for handling implicitly defined global variables. + +#### Properties + +- **`implicit`** - Tracks implicitly defined global variables (those used without declaration). + - `set` - A Map of variable names to Variable objects for implicitly defined globals. + - `variables` - Array of implicit global Variable objects. + - `left` - Array of References that need to be linked to the variable they refer to. + +### Variable Objects + +Each variable object has the following properties: + +- `name` - The variable name. +- `identifiers` - Array of identifier nodes declaring this variable. +- `references` - Array of references to this variable. +- `defs` - Array of definition objects for this variable. +- `scope` - The scope object where this variable is defined. + +## Contributing + +Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/js/issues). + +## Security Policy + +We work hard to ensure that ESLint Scope is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). + +## Build Commands + +- `npm test` - run all linting and tests +- `npm run lint` - run all linting + +## License + +ESLint Scope is licensed under a permissive BSD 2-clause license. + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Platinum Sponsors

+

Automattic

Gold Sponsors

+

Qlty Software

Silver Sponsors

+

Vite Liftoff StackBlitz

Bronze Sponsors

+

Cybozu SAP CrawlJobs Depot N-iX Ltd Icons8 Discord GitBook HeroCoders TestMu AI Open Source Office (Formerly LambdaTest)

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/eslint-scope/lib/assert.js b/node_modules/eslint-scope/lib/assert.js new file mode 100644 index 0000000000000000000000000000000000000000..da36b6a9f1f34cbc9378dcff00024f67f5fe873d --- /dev/null +++ b/node_modules/eslint-scope/lib/assert.js @@ -0,0 +1,17 @@ +/** + * @fileoverview Assertion utilities. + * @author Nicholas C. Zakas + */ + +/** + * Throws an error if the given condition is not truthy. + * @param {boolean} condition The condition to check. + * @param {string} message The message to include with the error. + * @returns {void} + * @throws {Error} When the condition is not truthy. + */ +export function assert(condition, message = "Assertion failed.") { + if (!condition) { + throw new Error(message); + } +} diff --git a/node_modules/eslint-scope/lib/definition.js b/node_modules/eslint-scope/lib/definition.js new file mode 100644 index 0000000000000000000000000000000000000000..1fc9af789f2004dde61b4c794f20a9bfd9e66485 --- /dev/null +++ b/node_modules/eslint-scope/lib/definition.js @@ -0,0 +1,85 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +import Variable from "./variable.js"; + +/** @import * as types from "eslint-scope" */ + +// Cannot implement `types.Definition` directly because it contains a union. +/** + * @constructor Definition + * @implements {Omit} + */ +class Definition { + constructor(type, name, node, parent, index, kind) { + /** + * @member {string} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). + */ + this.type = type; + + /** + * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence. + */ + this.name = name; + + /** + * @member {espree.Node} Definition#node - the enclosing node of the identifier. + */ + this.node = node; + + /** + * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier. + */ + this.parent = parent; + + /** + * @member {number?} Definition#index - the index in the declaration statement. + */ + this.index = index; + + /** + * @member {string?} Definition#kind - the kind of the declaration statement. + */ + this.kind = kind; + } +} + +/** + * @constructor ParameterDefinition + */ +class ParameterDefinition extends Definition { + constructor(name, node, index, rest) { + super(Variable.Parameter, name, node, null, index, null); + + /** + * Whether the parameter definition is a part of a rest parameter. + * @member {boolean} ParameterDefinition#rest + */ + this.rest = rest; + } +} + +export { ParameterDefinition, Definition }; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/index.d.cts b/node_modules/eslint-scope/lib/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..a989b840de84a494bcc8c6727569170874190966 --- /dev/null +++ b/node_modules/eslint-scope/lib/index.d.cts @@ -0,0 +1,1152 @@ +/** + * @fileoverview This file contains the types for ESLint Scope. + * It was initially extracted from the DefinitelyTyped repository. + */ + +/* + * MIT License + * Copyright (c) Microsoft Corporation. + * + * 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 + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import type { Visitor, VisitorOptions } from "esrecurse"; +import type * as ESTree from "estree"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +interface JSXIdentifier extends ESTree.BaseNode { + type: "JSXIdentifier"; + name: string; +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * Options for scope analysis. + */ +export interface AnalyzeOptions { + /** + * Whether to ignore `eval()` calls, which normally create scopes. + * @default false + */ + ignoreEval?: boolean; + + /** + * Whether to create a top-level function scope for CommonJS evaluation. + * @default false + */ + nodejsScope?: boolean; + + /** + * Whether to evaluate code in strict mode even outside modules or without `"use strict"`. + * @default false + */ + impliedStrict?: boolean; + + /** + * The ECMAScript version to use for evaluation (e.g., `5`, `2015`, `2022`). + * @default 5 + */ + ecmaVersion?: number; + + /** + * The type of JavaScript file to evaluate. + * @default "script" + */ + sourceType?: "script" | "module" | "commonjs"; + + /** + * Visitor key information for performance enhancement. + * @default null + */ + childVisitorKeys?: { + readonly [type: string]: ReadonlyArray; + } | null; + + /** + * Strategy to use when `childVisitorKeys` is not specified. + * @default "iteration" + */ + fallback?: "iteration" | ((node: ESTree.Node) => string[]); + + /** + * Whether to enable optimistic scope analysis. + * @default false + */ + optimistic?: boolean; + + /** + * Enables the tracking of JSX components as variable references. + * @default false + */ + jsx?: boolean; +} + +/** + * Callback function for pattern visitors. + */ +export type PatternVisitorCallback = ( + pattern: ESTree.Identifier, + misc: { + topLevel: boolean; + rest: boolean; + assignments: ESTree.AssignmentPattern[]; + }, +) => void; + +/** + * Manages the scope hierarchy of an AST. + */ +export class ScopeManager { + /** + * Creates a new `ScopeManager` instance. + * @param options Options for scope analysis. + */ + constructor(options: AnalyzeOptions); + + /** + * The global scope, initially set to `null`. + */ + globalScope: GlobalScope | null; + + /** + * All scopes in the analyzed program. + */ + scopes: Scope[]; + + /** + * Adds variables to the global scope and resolves references to them. + * @param names An array of strings, the names of variables to add to the global scope. + * @returns void + */ + addGlobals(names: ReadonlyArray): void; + + /** + * Acquires the scope for a given node. + * @param node The AST node to get the scope for. + * @param inner Whether to get the innermost scope. (default: `false`) + * @returns The scope or null if not found. + */ + acquire(node: ESTree.Node, inner?: boolean): Scope | null; + + /** + * acquire all scopes from node. + * @param node node for the acquired scope. + * @returns Scope array + * @deprecated + */ + acquireAll(node: ESTree.Node): Scope[] | null; + + /** + * Releases a scope, moving to its parent. + * @param node The AST node to release the scope for. + * @param inner Whether to release the innermost scope. (default: `false`) + * @returns The parent scope or null if not found. + */ + release(node: ESTree.Node, inner?: boolean): Scope | null; + + /** + * Gets all scopes for a given node, including parents. + * @param node The AST node to get scopes for. + * @param inner Whether to start from the innermost scope. + * @returns Array of scopes or empty array if none found. + */ + getDeclaredVariables(node: ESTree.Node): Variable[]; + + /** + * Determines if the global return statement should be allowed. + * @returns `true` if the global return is enabled. + */ + isGlobalReturn(): boolean; + + /** @deprecated */ + isModule(): boolean; + + /** @deprecated */ + isImpliedStrict(): boolean; + + /** @deprecated */ + isStrictModeSupported(): boolean; + + /** @deprecated */ + attach(): void; + + /** @deprecated */ + detach(): void; +} + +/** + * Base export class for all scopes. + */ +export class Scope< + TVariable extends Variable = Variable, + TReference extends Reference = Reference, +> { + /** + * Creates a new `Scope` instance. + * @param scopeManager The scope manager this scope belongs to. + * @param type The type of the scope. + * @param upperScope The parent scope, or null for the global scope. + * @param block The AST node that created this scope. + * @param isMethodDefinition Whether this scope is for a method definition. + */ + constructor( + scopeManager: ScopeManager, + type: typeof this.type, + upperScope: Scope | null, + block: ESTree.Node, + isMethodDefinition: boolean, + ); + + /** + * The type of the scope (e.g., 'global', 'function'). + */ + type: + | "block" + | "catch" + | "class" + | "class-field-initializer" + | "class-static-block" + | "for" + | "function" + | "function-expression-name" + | "global" + | "module" + | "switch" + | "with"; + + /** + * Whether the scope is in strict mode. + */ + isStrict: boolean; + + /** + * The parent scope, or null for the global scope. + */ + upper: Scope | null; + + /** + * The scope where variables are declared (same as this for most scopes). + */ + variableScope: Scope; + + /** + * Variables defined in this scope. + */ + variables: TVariable[]; + + /** + * References to variables in this scope. + */ + references: TReference[]; + + /** + * Child scopes. + */ + childScopes: Scope[]; + + /** + * The AST node that created this scope. + */ + block: ESTree.Node; + + /** + * Whether this is a function expression scope. + */ + functionExpressionScope: boolean; + + /** + * Map of variable names to variables. + */ + set: Map; + + /** + * The tainted variables of this scope. + * @deprecated + */ + taints: Map; + + /** + * References that pass through this scope to outer scopes. + */ + through: TReference[]; + + /** + * Dynamic flag for certain scope types. + * @deprecated + */ + dynamic: boolean; + + /** + * Direct call to eval() flag. + * @deprecated + */ + directCallToEvalScope: boolean; + + /** + * This scope flag. + * @deprecated + */ + thisFound: boolean; + + /** + * Resolves a reference in this scope. + * @param ident An AST node to get their reference object. + * @deprecated + */ + resolve(ident: ESTree.Identifier): TReference | null; + + /** + * Whether the reference is static. + * @deprecated + */ + isStatic(): boolean; + + /** + * Returns whether this scope has materialized arguments. + * @deprecated + */ + isArgumentsMaterialized(): boolean; + + /** + * Returns whether this scope has materialized `this` reference. + * @deprecated + */ + isThisMaterialized(): boolean; + + /** @deprecated */ + isUsedName(name: string): boolean; +} + +/** + * Global scope. + */ +export class GlobalScope extends Scope { + /** + * Creates a new GlobalScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param block The AST node that created this scope. + */ + constructor(scopeManager: ScopeManager, block: ESTree.Node); + + type: "global"; + + functionExpressionScope: false; + + isArgumentsMaterialized(): true; + + isThisMaterialized(): true; + + /** + * Implicit references (e.g., 'arguments' in functions). + */ + implicit: { + left: Reference[]; + set: Map; + variables: Variable[]; + }; +} + +/** + * Module scope. + */ +export class ModuleScope extends Scope { + /** + * Creates a new ModuleScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param upperScope The parent scope. + * @param block The AST node that created this scope. + */ + constructor( + scopeManager: ScopeManager, + upperScope: Scope, + block: ESTree.Node, + ); + + type: "module"; + + functionExpressionScope: false; + + isArgumentsMaterialized(): true; + + isThisMaterialized(): true; +} + +/** + * Function expression name scope. + */ +export class FunctionExpressionNameScope extends Scope { + /** + * Creates a new FunctionExpressionNameScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param upperScope The parent scope. + * @param block The AST node that created this scope. + */ + constructor( + scopeManager: ScopeManager, + upperScope: Scope, + block: ESTree.Node, + ); + + type: "function-expression-name"; + + functionExpressionScope: true; + + isArgumentsMaterialized(): true; + + isThisMaterialized(): true; +} + +/** + * Catch scope. + */ +export class CatchScope extends Scope { + /** + * Creates a new CatchScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param upperScope The parent scope. + * @param block The AST node that created this scope. + */ + constructor( + scopeManager: ScopeManager, + upperScope: Scope, + block: ESTree.Node, + ); + + type: "catch"; + + functionExpressionScope: false; + + isArgumentsMaterialized(): true; + + isThisMaterialized(): true; +} + +/** + * With scope. + */ +export class WithScope extends Scope { + /** + * Creates a new WithScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param upperScope The parent scope. + * @param block The AST node that created this scope. + */ + constructor( + scopeManager: ScopeManager, + upperScope: Scope, + block: ESTree.Node, + ); + + type: "with"; + + functionExpressionScope: false; + + isArgumentsMaterialized(): true; + + isThisMaterialized(): true; +} + +/** + * Block scope. + */ +export class BlockScope extends Scope { + /** + * Creates a new BlockScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param upperScope The parent scope. + * @param block The AST node that created this scope. + */ + constructor( + scopeManager: ScopeManager, + upperScope: Scope, + block: ESTree.Node, + ); + + type: "block"; + + functionExpressionScope: false; + + isArgumentsMaterialized(): true; + + isThisMaterialized(): true; +} + +/** + * Switch scope. + */ +export class SwitchScope extends Scope { + /** + * Creates a new SwitchScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param upperScope The parent scope. + * @param block The AST node that created this scope. + */ + constructor( + scopeManager: ScopeManager, + upperScope: Scope, + block: ESTree.Node, + ); + + type: "switch"; + + functionExpressionScope: false; + + isArgumentsMaterialized(): true; + + isThisMaterialized(): true; +} + +/** + * Function scope. + */ +export class FunctionScope extends Scope { + /** + * Creates a new FunctionScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param upperScope The parent scope. + * @param block The AST node that created this scope. + * @param isMethodDefinition Whether this scope is for a method definition. + */ + constructor( + scopeManager: ScopeManager, + upperScope: Scope, + block: ESTree.Node, + isMethodDefinition: boolean, + ); + + type: "function"; + + functionExpressionScope: false; +} + +/** + * Scope of for, for-in, and for-of statements. + */ +export class ForScope extends Scope { + /** + * Creates a new ForScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param upperScope The parent scope. + * @param block The AST node that created this scope. + */ + constructor( + scopeManager: ScopeManager, + upperScope: Scope, + block: ESTree.Node, + ); + + type: "for"; + + functionExpressionScope: false; + + isArgumentsMaterialized(): true; + + isThisMaterialized(): true; +} + +/** + * Class scope. + */ +export class ClassScope extends Scope { + /** + * Creates a new ClassScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param upperScope The parent scope. + * @param block The AST node that created this scope. + */ + constructor( + scopeManager: ScopeManager, + upperScope: Scope, + block: ESTree.Node, + ); + + type: "class"; + + functionExpressionScope: false; + + isArgumentsMaterialized(): true; + + isThisMaterialized(): true; +} + +/** + * Class field initializer scope. + */ +export class ClassFieldInitializerScope extends Scope { + /** + * Creates a new ClassFieldInitializerScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param upperScope The parent scope. + * @param block The AST node that created this scope. + */ + constructor( + scopeManager: ScopeManager, + upperScope: Scope, + block: ESTree.Node, + ); + + type: "class-field-initializer"; + + functionExpressionScope: false; + + isArgumentsMaterialized(): true; + + isThisMaterialized(): true; +} + +/** + * Class static block scope. + */ +export class ClassStaticBlockScope extends Scope { + /** + * Creates a new ClassStaticBlockScope instance. + * @param scopeManager The scope manager this scope belongs to. + * @param upperScope The parent scope. + * @param block The AST node that created this scope. + */ + constructor( + scopeManager: ScopeManager, + upperScope: Scope, + block: ESTree.Node, + ); + + type: "class-static-block"; + + functionExpressionScope: false; + + isArgumentsMaterialized(): true; + + isThisMaterialized(): true; +} + +/** + * Represents a variable in a scope. + */ +export class Variable { + static readonly CatchClause: "CatchClause"; + static readonly Parameter: "Parameter"; + static readonly FunctionName: "FunctionName"; + static readonly ClassName: "ClassName"; + static readonly Variable: "Variable"; + static readonly ImportBinding: "ImportBinding"; + static readonly ImplicitGlobalVariable: "ImplicitGlobalVariable"; + + /** + * Creates a new Variable instance. + * @param name The name of the variable. + * @param scope The scope where the variable is defined. + */ + constructor(name: string, scope: Scope); + + /** + * The name of the variable. + */ + name: string; + + /** + * The scope where the variable is defined. + */ + scope: Scope; + + /** + * Identifiers that declare this variable. + */ + identifiers: ESTree.Identifier[]; + + /** + * References to this variable. + */ + references: TReference[]; + + /** + * Definitions of this variable. + */ + defs: Definition[]; + + /** + * Whether the variable is tainted (e.g., potentially modified externally). + * @deprecated + */ + tainted: boolean; + + /** + * Stack flag for certain variable types. + * @deprecated + */ + stack: boolean; +} + +/** + * Represents a reference to a variable. + */ +export class Reference { + static readonly READ: 1; + static readonly WRITE: 2; + static readonly RW: 3; + + /** + * Creates a new Reference instance. + * @param ident The identifier node of the reference. + * @param scope The scope where the reference occurs. + * @param flag The reference flag (read, write, or read-write). + * @param writeExpr The expression being written, if applicable. + * @param maybeImplicitGlobal Information about a possible global variable, if applicable. + * @param partial Whether this is a partial reference. + * @param init Whether this is an initialization reference. + */ + constructor( + ident: ESTree.Identifier | JSXIdentifier, + scope: Scope, + flag: number, + writeExpr: ESTree.Expression | null, + maybeImplicitGlobal: { + pattern: ESTree.Pattern; + node: ESTree.Node; + } | null, + partial: boolean, + init: boolean, + ); + + /** + * The identifier node of the reference. + */ + identifier: ESTree.Identifier | JSXIdentifier; + + /** + * The variable being referenced, or null if unresolved. + */ + resolved: Variable | null; + + /** + * Whether the reference is static. + * @deprecated + */ + isStatic(): boolean; + + /** + * Whether this is a write operation. + */ + isWrite(): boolean; + + /** + * Whether this is a read operation. + */ + isRead(): boolean; + + /** + * The scope where the reference occurs. + */ + from: Scope; + + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @deprecated + */ + tainted: boolean; + + /** + * The expression being written, if applicable. + */ + writeExpr?: ESTree.Expression | null; + + /** + * Whether this is a partial reference. + * @deprecated + */ + partial?: boolean; + + /** + * Whether this is an initialization reference. + */ + init?: boolean; + + /** + * Whether this reference is only read. + * @returns True if the reference is read-only. + */ + isReadOnly(): boolean; + + /** + * Whether this reference is only written. + * @returns True if the reference is write-only. + */ + isWriteOnly(): boolean; + + /** + * Whether this reference is read-write. + * @returns True if the reference is read-write. + */ + isReadWrite(): boolean; + + /** @deprecated */ + flag: number; +} + +/** + * Represents a variable definition. + */ +export const Definition: { + /** + * Creates a new Definition instance. + * @param type The type of definition (e.g., 'Variable', 'Parameter'). + * @param name The identifier node of the definition. + * @param node The AST node where the definition occurs. + * @param parent The parent node, if applicable. + * @param index The index of the definition in a pattern, if applicable. + * @param kind The kind of variable (e.g., 'var', 'let', 'const'), if applicable. + */ + new ( + type: Definition["type"], + name: ESTree.Identifier, + node: Definition["node"], + parent: Definition["parent"], + index: number | null, + kind: string | null, + ): Definition; +}; + +export type Definition = ( + | { type: "CatchClause"; node: ESTree.CatchClause; parent: null } + | { + type: "ClassName"; + node: ESTree.ClassDeclaration | ESTree.ClassExpression; + parent: null; + } + | { + type: "FunctionName"; + node: ESTree.FunctionDeclaration | ESTree.FunctionExpression; + parent: null; + } + | { + type: "ImplicitGlobalVariable"; + node: + | ESTree.AssignmentExpression + | ESTree.ForInStatement + | ESTree.ForOfStatement; + parent: null; + } + | { + type: "ImportBinding"; + node: + | ESTree.ImportSpecifier + | ESTree.ImportDefaultSpecifier + | ESTree.ImportNamespaceSpecifier; + parent: ESTree.ImportDeclaration; + } + | { + type: "Parameter"; + node: + | ESTree.FunctionDeclaration + | ESTree.FunctionExpression + | ESTree.ArrowFunctionExpression; + parent: null; + } + | { + type: "Variable"; + node: ESTree.VariableDeclarator; + parent: ESTree.VariableDeclaration; + } +) & { + /** + * The identifier node of the definition. + */ + name: ESTree.Identifier; + + /** + * The index of the definition in a pattern, if applicable. + * @deprecated + */ + index: number | null; + + /** + * The kind of variable (e.g., 'var', 'let', 'const'), if applicable. + * @deprecated + */ + kind: string | null; +}; + +/** + * Visitor for destructuring patterns. + */ +export class PatternVisitor extends Visitor { + static isPattern( + node: ESTree.Node, + ): node is + | ESTree.Identifier + | ESTree.ObjectPattern + | ESTree.ArrayPattern + | ESTree.SpreadElement + | ESTree.RestElement + | ESTree.AssignmentPattern; + + constructor( + options: VisitorOptions | null | undefined, + rootPattern: ESTree.Pattern, + callback: PatternVisitorCallback, + ); + + rootPattern: ESTree.Pattern; + + callback: PatternVisitorCallback; + + assignments: Array; + + rightHandNodes: ESTree.Node[]; + + restElements: ESTree.RestElement[]; + + Identifier(pattern: ESTree.Identifier): void; + + Property(pattern: ESTree.Property): void; + + ArrayPattern(pattern: ESTree.ArrayPattern): void; + + AssignmentPattern(pattern: ESTree.AssignmentPattern): void; + + RestElement(pattern: ESTree.RestElement): void; + + MemberExpression(pattern: ESTree.MemberExpression): void; + + SpreadElement(pattern: ESTree.SpreadElement): void; + + ArrayExpression(pattern: ESTree.ArrayExpression): void; + + AssignmentExpression(pattern: ESTree.AssignmentExpression): void; + + CallExpression(pattern: ESTree.CallExpression): void; +} + +/** + * Visitor class for traversing AST nodes and creating variable references and bindings. + */ +export class Referencer extends Visitor { + /** + * Creates a new Referencer instance. + * @param options Options for scope analysis. + * @param scopeManager The scope manager to use. + */ + constructor( + options: VisitorOptions | null | undefined, + scopeManager: ScopeManager, + ); + + /** + * Options for scope analysis. + */ + options: VisitorOptions | null | undefined; + + /** + * The scope manager being used. + */ + scopeManager: ScopeManager; + + /** + * The parent node. + */ + parent: ESTree.Node | null; + + /** + * Whether currently inside a method definition. + */ + isInnerMethodDefinition: boolean; + + /** + * Gets the current scope. + * @returns The current scope. + */ + currentScope(): Scope; + + /** + * Closes scopes up to the given node. + * @param node The AST node. + */ + close(node: ESTree.Node): void; + + /** + * Pushes a new inner method definition state. + * @param isInnerMethodDefinition Whether inside a method definition. + * @returns The previous state. + */ + pushInnerMethodDefinition(isInnerMethodDefinition: boolean): boolean; + + /** + * Pops the inner method definition state. + * @param isInnerMethodDefinition The state to restore. + */ + popInnerMethodDefinition(isInnerMethodDefinition: boolean): void; + + /** + * References default values in patterns. + * @param pattern The pattern. + * @param assignments The assignments. + * @param maybeImplicitGlobal Information about a possible implicit global. + * @param init Whether this is an initialization. + */ + referencingDefaultValue( + pattern: ESTree.Pattern, + assignments: Array< + ESTree.AssignmentExpression | ESTree.AssignmentPattern + >, + maybeImplicitGlobal: { + pattern: ESTree.Pattern; + node: ESTree.Node; + } | null, + init: boolean, + ): void; + + /** + * Visits a pattern node. + * @param node The pattern node. + * @param options Options or callback. + * @param callback The callback function. + */ + visitPattern( + node: ESTree.Pattern, + options: { processRightHandNodes: boolean } | PatternVisitorCallback, + callback?: PatternVisitorCallback, + ): void; + + /** + * Visits a function node. + * @param node The function node. + */ + visitFunction( + node: + | ESTree.FunctionDeclaration + | ESTree.FunctionExpression + | ESTree.ArrowFunctionExpression, + ): void; + + /** + * Visits a class node. + * @param node The class node. + */ + visitClass(node: ESTree.ClassDeclaration | ESTree.ClassExpression): void; + + /** + * Visits a property node. + * @param node The property node. + */ + visitProperty(node: ESTree.Property | ESTree.MethodDefinition): void; + + /** + * Visits a for-in or for-of statement. + * @param node The for-in or for-of node. + */ + visitForIn(node: ESTree.ForInStatement | ESTree.ForOfStatement): void; + + /** + * Visits a variable declaration. + * @param variableTargetScope The scope where the variable should be defined. + * @param type The variable type. + * @param node The variable declaration node. + * @param index The index of the declarator. + */ + visitVariableDeclaration( + variableTargetScope: Scope, + type: typeof Variable.Variable, + node: ESTree.VariableDeclaration, + index: number, + ): void; + + /** + * Visits an export declaration. + * @param node The export declaration node. + */ + visitExportDeclaration( + node: + | ESTree.ExportAllDeclaration + | ESTree.ExportDefaultDeclaration + | ESTree.ExportNamedDeclaration, + ): void; + + AssignmentExpression(node: ESTree.AssignmentExpression): void; + CatchClause(node: ESTree.CatchClause): void; + Program(node: ESTree.Program): void; + Identifier(node: ESTree.Identifier): void; + PrivateIdentifier(): void; + UpdateExpression(node: ESTree.UpdateExpression): void; + MemberExpression(node: ESTree.MemberExpression): void; + Property(node: ESTree.Property): void; + PropertyDefinition(node: ESTree.PropertyDefinition): void; + StaticBlock(node: ESTree.StaticBlock): void; + MethodDefinition(node: ESTree.MethodDefinition): void; + BreakStatement(): void; + ContinueStatement(): void; + LabeledStatement(node: ESTree.LabeledStatement): void; + ForStatement(node: ESTree.ForStatement): void; + ClassExpression(node: ESTree.ClassExpression): void; + ClassDeclaration(node: ESTree.ClassDeclaration): void; + CallExpression(node: ESTree.CallExpression): void; + BlockStatement(node: ESTree.BlockStatement): void; + ThisExpression(): void; + WithStatement(node: ESTree.WithStatement): void; + VariableDeclaration(node: ESTree.VariableDeclaration): void; + SwitchStatement(node: ESTree.SwitchStatement): void; + FunctionDeclaration(node: ESTree.FunctionDeclaration): void; + FunctionExpression(node: ESTree.FunctionExpression): void; + ForOfStatement(node: ESTree.ForOfStatement): void; + ForInStatement(node: ESTree.ForInStatement): void; + ArrowFunctionExpression(node: ESTree.ArrowFunctionExpression): void; + ImportDeclaration(node: ESTree.ImportDeclaration): void; + ExportDeclaration( + node: + | ESTree.ExportAllDeclaration + | ESTree.ExportDefaultDeclaration + | ESTree.ExportNamedDeclaration, + ): void; + ExportAllDeclaration(node: ESTree.ExportAllDeclaration): void; + ExportDefaultDeclaration(node: ESTree.ExportDefaultDeclaration): void; + ExportNamedDeclaration(node: ESTree.ExportNamedDeclaration): void; + ExportSpecifier(node: ESTree.ExportSpecifier): void; + MetaProperty(): void; + JSXIdentifier(node: JSXIdentifier): void; + JSXMemberExpression(node: any): void; + JSXElement(node: any): void; + JSXOpeningElement(node: any): void; + JSXAttribute(node: any): void; + JSXExpressionContainer(node: any): void; + JSXNamespacedName(node: any): void; +} + +/** + * Analyzes the scope of an AST. + * @param ast The ESTree-compliant AST to analyze. + * @param options Options for scope analysis. + * @returns The scope manager for the analyzed AST. + */ +export function analyze( + ast: ESTree.Program, + options?: AnalyzeOptions, +): ScopeManager; + +/** + * The version of ESLint Scope. + */ +export const version: string; diff --git a/node_modules/eslint-scope/lib/index.d.ts b/node_modules/eslint-scope/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..def35507d3a55d274f6314d584f60c08f06e6a9b --- /dev/null +++ b/node_modules/eslint-scope/lib/index.d.ts @@ -0,0 +1,6 @@ +/** + * @fileoverview ESLint Scope types in ESM format. + * @author Francesco Trotta + */ + +export * from "./index.cjs"; diff --git a/node_modules/eslint-scope/lib/index.js b/node_modules/eslint-scope/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..43827c9d0c053de224c801a79c19dca4df1c83a7 --- /dev/null +++ b/node_modules/eslint-scope/lib/index.js @@ -0,0 +1,175 @@ +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + Copyright (C) 2014 Thiago de Arruda + + 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. + + 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 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. +*/ + +/** + * Escope (escope) is an ECMAScript + * scope analyzer extracted from the esmangle project. + *

+ * escope finds lexical scopes in a source program, i.e. areas of that + * program where different occurrences of the same identifier refer to the same + * variable. With each scope the contained variables are collected, and each + * identifier reference in code is linked to its corresponding variable (if + * possible). + *

+ * escope works on a syntax tree of the parsed source code which has + * to adhere to the + * Mozilla Parser API. E.g. espree is a parser + * that produces such syntax trees. + *

+ * The main interface is the {@link analyze} function. + * @module escope + */ + +import { assert } from "./assert.js"; + +import ScopeManager from "./scope-manager.js"; +import Referencer from "./referencer.js"; +import Reference from "./reference.js"; +import Variable from "./variable.js"; + +/** @import ESTree from "estree" */ + +/** + * Set the default options + * @returns {Object} options + */ +function defaultOptions() { + return { + optimistic: false, + nodejsScope: false, + impliedStrict: false, + sourceType: "script", // one of ['script', 'module', 'commonjs'] + ecmaVersion: 5, + childVisitorKeys: null, + fallback: "iteration", + }; +} + +/** + * Preform deep update on option object + * @param {Record} target Options + * @param {Record} override Updates + * @returns {Record} Updated options + */ +function updateDeeply(target, override) { + /** + * Is hash object + * @param {Object} value Test value + * @returns {value is Record} Result + */ + function isHashObject(value) { + return ( + typeof value === "object" && + value instanceof Object && + !(value instanceof Array) && + !(value instanceof RegExp) + ); + } + + for (const key in override) { + if (Object.hasOwn(override, key)) { + const val = override[key]; + + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; +} + +/** + * Main interface function. Takes an Espree syntax tree and returns the + * analyzed scopes. + * @function analyze + * @param {ESTree.Program} tree Abstract Syntax Tree + * @param {Object} providedOptions Options that tailor the scope analysis + * @param {boolean} [providedOptions.optimistic=false] the optimistic flag + * @param {boolean} [providedOptions.ignoreEval=false] whether to check 'eval()' calls + * @param {boolean} [providedOptions.nodejsScope=false] whether the whole + * script is executed under node.js environment. When enabled, escope adds + * a function scope immediately following the global scope. + * @param {boolean} [providedOptions.impliedStrict=false] implied strict mode + * (if ecmaVersion >= 5). + * @param {string} [providedOptions.sourceType='script'] the source type of the script. one of 'script', 'module', and 'commonjs' + * @param {number} [providedOptions.ecmaVersion=5] which ECMAScript version is considered + * @param {boolean} [providedOptions.jsx=false] support JSX references + * @param {Object} [providedOptions.childVisitorKeys=null] Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option. + * @param {string} [providedOptions.fallback='iteration'] A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option. + * @returns {ScopeManager} ScopeManager + */ +function analyze(tree, providedOptions) { + const options = updateDeeply(defaultOptions(), providedOptions); + const scopeManager = new ScopeManager(options); + const referencer = new Referencer(options, scopeManager); + + referencer.visit(tree); + + assert( + scopeManager.__currentScope === null, + "currentScope should be null.", + ); + + return scopeManager; +} + +/** @name module:escope.version */ +export const version = "9.1.2"; // x-release-please-version + +export { + /** @name module:escope.Reference */ + Reference, + + /** @name module:escope.Variable */ + Variable, + + /** @name module:escope.ScopeManager */ + ScopeManager, + + /** @name module:escope.Referencer */ + Referencer, + analyze, +}; + +/** @name module:escope.Definition */ +export { Definition } from "./definition.js"; + +/** @name module:escope.PatternVisitor */ +export { default as PatternVisitor } from "./pattern-visitor.js"; + +/** @name module:escope.Scope */ +export { Scope } from "./scope.js"; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/pattern-visitor.js b/node_modules/eslint-scope/lib/pattern-visitor.js new file mode 100644 index 0000000000000000000000000000000000000000..87bad2c6cbd7a96d8a2612e952a7b3c1c7b108f7 --- /dev/null +++ b/node_modules/eslint-scope/lib/pattern-visitor.js @@ -0,0 +1,157 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +import estraverse from "estraverse"; +import esrecurse from "esrecurse"; + +/** @import * as types from "eslint-scope" */ + +const { Syntax } = estraverse; + +/** + * Get last array element + * @param {Array} xs array + * @returns {any} Last elment + */ +function getLast(xs) { + return xs.at(-1) || null; +} + +/** + * Visitor for destructuring patterns. + * @implements {types.PatternVisitor} + */ +class PatternVisitor extends esrecurse.Visitor { + static isPattern(node) { + const nodeType = node.type; + + return ( + nodeType === Syntax.Identifier || + nodeType === Syntax.ObjectPattern || + nodeType === Syntax.ArrayPattern || + nodeType === Syntax.SpreadElement || + nodeType === Syntax.RestElement || + nodeType === Syntax.AssignmentPattern + ); + } + + constructor(options, rootPattern, callback) { + super(null, options); + this.rootPattern = rootPattern; + this.callback = callback; + this.assignments = []; + this.rightHandNodes = []; + this.restElements = []; + } + + Identifier(pattern) { + const lastRestElement = getLast(this.restElements); + + this.callback(pattern, { + topLevel: pattern === this.rootPattern, + rest: + lastRestElement !== null && + lastRestElement !== void 0 && + lastRestElement.argument === pattern, + assignments: this.assignments, + }); + } + + Property(property) { + // Computed property's key is a right hand node. + if (property.computed) { + this.rightHandNodes.push(property.key); + } + + // If it's shorthand, its key is same as its value. + // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). + // If it's not shorthand, the name of new variable is its value's. + this.visit(property.value); + } + + ArrayPattern(pattern) { + for (let i = 0, iz = pattern.elements.length; i < iz; ++i) { + const element = pattern.elements[i]; + + this.visit(element); + } + } + + AssignmentPattern(pattern) { + this.assignments.push(pattern); + this.visit(pattern.left); + this.rightHandNodes.push(pattern.right); + this.assignments.pop(); + } + + RestElement(pattern) { + this.restElements.push(pattern); + this.visit(pattern.argument); + this.restElements.pop(); + } + + MemberExpression(node) { + // Computed property's key is a right hand node. + if (node.computed) { + this.rightHandNodes.push(node.property); + } + + // the object is only read, write to its property. + this.rightHandNodes.push(node.object); + } + + // + // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. + // By spec, LeftHandSideExpression is Pattern or MemberExpression. + // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) + // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc... + // + + SpreadElement(node) { + this.visit(node.argument); + } + + ArrayExpression(node) { + node.elements.forEach(this.visit, this); + } + + AssignmentExpression(node) { + this.assignments.push(node); + this.visit(node.left); + this.rightHandNodes.push(node.right); + this.assignments.pop(); + } + + CallExpression(node) { + // arguments are right hand nodes. + node.arguments.forEach(a => { + this.rightHandNodes.push(a); + }); + this.visit(node.callee); + } +} + +export default PatternVisitor; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/reference.js b/node_modules/eslint-scope/lib/reference.js new file mode 100644 index 0000000000000000000000000000000000000000..223ed242f5ec460d7acca1ae649061f51f9eb340 --- /dev/null +++ b/node_modules/eslint-scope/lib/reference.js @@ -0,0 +1,173 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +/** @import * as types from "eslint-scope" */ + +const READ = 0x1; +const WRITE = 0x2; +const RW = READ | WRITE; + +/** + * A Reference represents a single occurrence of an identifier in code. + * @constructor Reference + * @implements {types.Reference} + */ +class Reference { + constructor( + ident, + scope, + flag, + writeExpr, + maybeImplicitGlobal, + partial, + init, + ) { + /** + * Identifier syntax node. + * @member {espreeIdentifier} Reference#identifier + */ + this.identifier = ident; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; + + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; + + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; + + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + */ + this.flag = flag; + if (this.isWrite()) { + /** + * If reference is writeable, this is the tree being written to it. + * @member {espreeNode} Reference#writeExpr + */ + this.writeExpr = writeExpr; + + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; + + /** + * Whether the Reference is to write of initialization. + * @member {boolean} Reference#init + */ + this.init = init; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } + + /** + * Whether the reference is static. + * @function Reference#isStatic + * @returns {boolean} static + */ + isStatic() { + return ( + !this.tainted && !!this.resolved && this.resolved.scope.isStatic() + ); + } + + /** + * Whether the reference is writeable. + * @function Reference#isWrite + * @returns {boolean} write + */ + isWrite() { + return !!(this.flag & Reference.WRITE); + } + + /** + * Whether the reference is readable. + * @function Reference#isRead + * @returns {boolean} read + */ + isRead() { + return !!(this.flag & Reference.READ); + } + + /** + * Whether the reference is read-only. + * @function Reference#isReadOnly + * @returns {boolean} read only + */ + isReadOnly() { + return this.flag === Reference.READ; + } + + /** + * Whether the reference is write-only. + * @function Reference#isWriteOnly + * @returns {boolean} write only + */ + isWriteOnly() { + return this.flag === Reference.WRITE; + } + + /** + * Whether the reference is read-write. + * @function Reference#isReadWrite + * @returns {boolean} read write + */ + isReadWrite() { + return this.flag === Reference.RW; + } +} + +/** + * @constant Reference.READ + */ +Reference.READ = READ; + +/** + * @constant Reference.WRITE + */ +Reference.WRITE = WRITE; + +/** + * @constant Reference.RW + */ +Reference.RW = RW; + +export default Reference; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/referencer.js b/node_modules/eslint-scope/lib/referencer.js new file mode 100644 index 0000000000000000000000000000000000000000..79d116327fede92885c0068be8a3212f585a83bd --- /dev/null +++ b/node_modules/eslint-scope/lib/referencer.js @@ -0,0 +1,817 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +import estraverse from "estraverse"; +import esrecurse from "esrecurse"; +import Reference from "./reference.js"; +import Variable from "./variable.js"; +import PatternVisitor from "./pattern-visitor.js"; +import { Definition, ParameterDefinition } from "./definition.js"; +import { assert } from "./assert.js"; + +/** @import * as types from "eslint-scope" */ +/** @import ESTree from "estree" */ + +const { Syntax } = estraverse; + +/** + * Traverse identifier in pattern + * @param {Object} options options + * @param {ESTree.Pattern} rootPattern root pattern + * @param {?Referencer} referencer referencer + * @param {types.PatternVisitorCallback} callback callback + * @returns {void} + */ +function traverseIdentifierInPattern( + options, + rootPattern, + referencer, + callback, +) { + // Call the callback at left hand identifier nodes, and Collect right hand nodes. + const visitor = new PatternVisitor(options, rootPattern, callback); + + visitor.visit(rootPattern); + + // Process the right hand nodes recursively. + if (referencer !== null && referencer !== void 0) { + visitor.rightHandNodes.forEach(referencer.visit, referencer); + } +} + +// Importing ImportDeclaration. +// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation +// https://github.com/estree/estree/blob/master/es6.md#importdeclaration +// FIXME: Now, we don't create module environment, because the context is +// implementation dependent. + +/** + * Visitor for import specifiers. + */ +class Importer extends esrecurse.Visitor { + constructor(declaration, referencer) { + super(null, referencer.options); + this.declaration = declaration; + this.referencer = referencer; + } + + visitImport(id, specifier) { + this.referencer.visitPattern(id, pattern => { + this.referencer + .currentScope() + .__define( + pattern, + new Definition( + Variable.ImportBinding, + pattern, + specifier, + this.declaration, + null, + null, + ), + ); + }); + } + + ImportNamespaceSpecifier(node) { + const local = node.local || node.id; + + if (local) { + this.visitImport(local, node); + } + } + + ImportDefaultSpecifier(node) { + const local = node.local || node.id; + + this.visitImport(local, node); + } + + ImportSpecifier(node) { + const local = node.local || node.id; + + if (node.name) { + this.visitImport(node.name, node); + } else { + this.visitImport(local, node); + } + } +} + +/** + * Referencing variables and creating bindings. + * @implements {types.Referencer} + */ +class Referencer extends esrecurse.Visitor { + constructor(options, scopeManager) { + super(null, options); + this.options = options; + this.scopeManager = scopeManager; + this.parent = null; + this.isInnerMethodDefinition = false; + } + + currentScope() { + return this.scopeManager.__currentScope; + } + + close(node) { + while (this.currentScope() && node === this.currentScope().block) { + this.scopeManager.__currentScope = this.currentScope().__close( + this.scopeManager, + ); + } + } + + pushInnerMethodDefinition(isInnerMethodDefinition) { + const previous = this.isInnerMethodDefinition; + + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; + } + + popInnerMethodDefinition(isInnerMethodDefinition) { + this.isInnerMethodDefinition = isInnerMethodDefinition; + } + + referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { + const scope = this.currentScope(); + + assignments.forEach(assignment => { + scope.__referencing( + pattern, + Reference.WRITE, + assignment.right, + maybeImplicitGlobal, + pattern !== assignment.left, + init, + ); + }); + } + + visitPattern(node, options, callback) { + let visitPatternOptions = options; + let visitPatternCallback = callback; + + if (typeof options === "function") { + visitPatternCallback = options; + visitPatternOptions = { processRightHandNodes: false }; + } + + traverseIdentifierInPattern( + this.options, + node, + visitPatternOptions.processRightHandNodes ? this : null, + visitPatternCallback, + ); + } + + visitFunction(node) { + let i, iz; + + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. + + if (node.type === Syntax.FunctionDeclaration) { + // id is defined in upper scope + this.currentScope().__define( + node.id, + new Definition( + Variable.FunctionName, + node.id, + node, + null, + null, + null, + ), + ); + } + + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + if (node.type === Syntax.FunctionExpression && node.id) { + this.scopeManager.__nestFunctionExpressionNameScope(node); + } + + // Consider this function is in the MethodDefinition. + this.scopeManager.__nestFunctionScope( + node, + this.isInnerMethodDefinition, + ); + + const that = this; + + /** + * Visit pattern callback + * @param {ESTree.Pattern} pattern pattern + * @param {Object} info info + * @returns {void} + */ + function visitPatternCallback(pattern, info) { + that.currentScope().__define( + pattern, + new ParameterDefinition(pattern, node, i, info.rest), + ); + + that.referencingDefaultValue(pattern, info.assignments, null, true); + } + + // Process parameter declarations. + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern( + node.params[i], + { processRightHandNodes: true }, + visitPatternCallback, + ); + } + + // if there's a rest argument, add that + if (node.rest) { + this.visitPattern( + { + type: "RestElement", + argument: node.rest, + }, + pattern => { + this.currentScope().__define( + pattern, + new ParameterDefinition( + pattern, + node, + node.params.length, + true, + ), + ); + }, + ); + } + + // In TypeScript there are a number of function-like constructs which have no body, + // so check it exists before traversing + if (node.body) { + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); + } + } + + this.close(node); + } + + visitClass(node) { + if (node.type === Syntax.ClassDeclaration) { + this.currentScope().__define( + node.id, + new Definition( + Variable.ClassName, + node.id, + node, + null, + null, + null, + ), + ); + } + + this.scopeManager.__nestClassScope(node); + + if (node.id) { + this.currentScope().__define( + node.id, + new Definition(Variable.ClassName, node.id, node), + ); + } + + this.visit(node.superClass); + this.visit(node.body); + + this.close(node); + } + + visitProperty(node) { + let previous; + + if (node.computed) { + this.visit(node.key); + } + + const isMethodDefinition = node.type === Syntax.MethodDefinition; + + if (isMethodDefinition) { + previous = this.pushInnerMethodDefinition(true); + } + this.visit(node.value); + if (isMethodDefinition) { + this.popInnerMethodDefinition(previous); + } + } + + visitForIn(node) { + if ( + node.left.type === Syntax.VariableDeclaration && + node.left.kind !== "var" + ) { + this.scopeManager.__nestForScope(node); + } + + if (node.left.type === Syntax.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, pattern => { + this.currentScope().__referencing( + pattern, + Reference.WRITE, + node.right, + null, + true, + true, + ); + }); + } else { + this.visitPattern( + node.left, + { processRightHandNodes: true }, + (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node, + }; + } + this.referencingDefaultValue( + pattern, + info.assignments, + maybeImplicitGlobal, + false, + ); + this.currentScope().__referencing( + pattern, + Reference.WRITE, + node.right, + maybeImplicitGlobal, + true, + false, + ); + }, + ); + } + this.visit(node.right); + this.visit(node.body); + + this.close(node); + } + + visitVariableDeclaration(variableTargetScope, type, node, index) { + const decl = node.declarations[index]; + const init = decl.init; + + this.visitPattern( + decl.id, + { processRightHandNodes: true }, + (pattern, info) => { + variableTargetScope.__define( + pattern, + new Definition(type, pattern, decl, node, index, node.kind), + ); + + this.referencingDefaultValue( + pattern, + info.assignments, + null, + true, + ); + if (init) { + this.currentScope().__referencing( + pattern, + Reference.WRITE, + init, + null, + !info.topLevel, + true, + ); + } + }, + ); + } + + AssignmentExpression(node) { + if (PatternVisitor.isPattern(node.left)) { + if (node.operator === "=") { + this.visitPattern( + node.left, + { processRightHandNodes: true }, + (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node, + }; + } + this.referencingDefaultValue( + pattern, + info.assignments, + maybeImplicitGlobal, + false, + ); + this.currentScope().__referencing( + pattern, + Reference.WRITE, + node.right, + maybeImplicitGlobal, + !info.topLevel, + false, + ); + }, + ); + } else { + this.currentScope().__referencing( + node.left, + Reference.RW, + node.right, + ); + } + } else { + this.visit(node.left); + } + this.visit(node.right); + } + + CatchClause(node) { + this.scopeManager.__nestCatchScope(node); + + this.visitPattern( + node.param, + { processRightHandNodes: true }, + (pattern, info) => { + this.currentScope().__define( + pattern, + new Definition( + Variable.CatchClause, + pattern, + node, + null, + null, + null, + ), + ); + this.referencingDefaultValue( + pattern, + info.assignments, + null, + true, + ); + }, + ); + this.visit(node.body); + + this.close(node); + } + + Program(node) { + this.scopeManager.__nestGlobalScope(node); + + if (this.scopeManager.isGlobalReturn()) { + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.__nestFunctionScope(node, false); + } + + if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { + this.scopeManager.__nestModuleScope(node); + } + + if ( + this.scopeManager.isStrictModeSupported() && + this.scopeManager.isImpliedStrict() + ) { + this.currentScope().isStrict = true; + } + + this.visitChildren(node); + this.close(node); + } + + Identifier(node) { + this.currentScope().__referencing(node); + } + + // eslint-disable-next-line class-methods-use-this -- Desired as instance method + PrivateIdentifier() { + // Do nothing. + } + + UpdateExpression(node) { + if (PatternVisitor.isPattern(node.argument)) { + this.currentScope().__referencing( + node.argument, + Reference.RW, + null, + ); + } else { + this.visitChildren(node); + } + } + + MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } + + Property(node) { + this.visitProperty(node); + } + + PropertyDefinition(node) { + const { computed, key, value } = node; + + if (computed) { + this.visit(key); + } + if (value) { + this.scopeManager.__nestClassFieldInitializerScope(value); + this.visit(value); + this.close(value); + } + } + + StaticBlock(node) { + this.scopeManager.__nestClassStaticBlockScope(node); + + this.visitChildren(node); + + this.close(node); + } + + MethodDefinition(node) { + this.visitProperty(node); + } + + BreakStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + ContinueStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + LabeledStatement(node) { + this.visit(node.body); + } + + ForStatement(node) { + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates + // per iteration environment. However, escope is + // a static analyzer, we only generate one scope for ForStatement. + if ( + node.init && + node.init.type === Syntax.VariableDeclaration && + node.init.kind !== "var" + ) { + this.scopeManager.__nestForScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ClassExpression(node) { + this.visitClass(node); + } + + ClassDeclaration(node) { + this.visitClass(node); + } + + CallExpression(node) { + // Check this is direct call to eval + if ( + !this.scopeManager.__ignoreEval() && + node.callee.type === Syntax.Identifier && + node.callee.name === "eval" + ) { + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); + } + + BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } + + WithStatement(node) { + this.visit(node.object); + + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); + + this.visit(node.body); + + this.close(node); + } + + VariableDeclaration(node) { + const variableTargetScope = + node.kind === "var" + ? this.currentScope().variableScope + : this.currentScope(); + + for (let i = 0, iz = node.declarations.length; i < iz; ++i) { + const decl = node.declarations[i]; + + this.visitVariableDeclaration( + variableTargetScope, + Variable.Variable, + node, + i, + ); + if (decl.init) { + this.visit(decl.init); + } + } + } + + // sec 13.11.8 + SwitchStatement(node) { + this.visit(node.discriminant); + + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } + + for (let i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } + + this.close(node); + } + + FunctionDeclaration(node) { + this.visitFunction(node); + } + + FunctionExpression(node) { + this.visitFunction(node); + } + + ForOfStatement(node) { + this.visitForIn(node); + } + + ForInStatement(node) { + this.visitForIn(node); + } + + ArrowFunctionExpression(node) { + this.visitFunction(node); + } + + ImportDeclaration(node) { + assert( + this.scopeManager.__isES6() && this.scopeManager.isModule(), + "ImportDeclaration should appear when the mode is ES6 and in the module context.", + ); + + const importer = new Importer(node, this); + + importer.visit(node); + } + + visitExportDeclaration(node) { + if (node.source) { + return; + } + if (node.declaration) { + this.visit(node.declaration); + return; + } + + this.visitChildren(node); + } + + // TODO: ExportDeclaration doesn't exist. for bc? + ExportDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportAllDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportDefaultDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportSpecifier(node) { + // TODO: `node.id` doesn't exist. for bc? + const local = node.id || node.local; + + this.visit(local); + } + + // eslint-disable-next-line class-methods-use-this -- Desired as instance method + MetaProperty() { + // do nothing. + } + + JSXIdentifier(node) { + // Special case: "this" should not count as a reference + if (this.scopeManager.__isJSXEnabled() && node.name !== "this") { + this.currentScope().__referencing(node); + } + } + + JSXMemberExpression(node) { + this.visit(node.object); + } + + JSXElement(node) { + if (this.scopeManager.__isJSXEnabled()) { + this.visit(node.openingElement); + node.children.forEach(this.visit, this); + } else { + this.visitChildren(node); + } + } + + JSXOpeningElement(node) { + if (this.scopeManager.__isJSXEnabled()) { + const nameNode = node.name; + const isComponentName = + nameNode.type === "JSXIdentifier" && + nameNode.name[0].toUpperCase() === nameNode.name[0]; + const isComponent = + isComponentName || nameNode.type === "JSXMemberExpression"; + + // we only want to visit JSXIdentifier nodes if they are capitalized + if (isComponent) { + this.visit(nameNode); + } + } + + node.attributes.forEach(this.visit, this); + } + + JSXAttribute(node) { + if (node.value) { + this.visit(node.value); + } + } + + JSXExpressionContainer(node) { + this.visit(node.expression); + } + + JSXNamespacedName(node) { + this.visit(node.namespace); + this.visit(node.name); + } +} + +export default Referencer; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/scope-manager.js b/node_modules/eslint-scope/lib/scope-manager.js new file mode 100644 index 0000000000000000000000000000000000000000..98c623868c7da059a748ea6c2a4c624a4f0860fe --- /dev/null +++ b/node_modules/eslint-scope/lib/scope-manager.js @@ -0,0 +1,298 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +import { + BlockScope, + CatchScope, + ClassFieldInitializerScope, + ClassStaticBlockScope, + ClassScope, + ForScope, + FunctionExpressionNameScope, + FunctionScope, + GlobalScope, + ModuleScope, + SwitchScope, + WithScope, +} from "./scope.js"; +import { assert } from "./assert.js"; + +/** @import * as types from "eslint-scope" */ +/** @import ESTree from "estree" */ +/** @import { Scope } from "./scope.js" */ +/** @import Variable from "./variable.js" */ + +/** + * @constructor ScopeManager + * @implements {types.ScopeManager} + */ +class ScopeManager { + constructor(options) { + this.scopes = []; + this.globalScope = null; + this.__nodeToScope = new WeakMap(); + this.__currentScope = null; + this.__options = options; + this.__declaredVariables = new WeakMap(); + } + + __isOptimistic() { + return this.__options.optimistic; + } + + __ignoreEval() { + return this.__options.ignoreEval; + } + + __isJSXEnabled() { + return this.__options.jsx === true; + } + + isGlobalReturn() { + return ( + this.__options.nodejsScope || + this.__options.sourceType === "commonjs" + ); + } + + isModule() { + return this.__options.sourceType === "module"; + } + + isImpliedStrict() { + return !!this.__options.impliedStrict; + } + + isStrictModeSupported() { + return this.__options.ecmaVersion >= 5; + } + + // Returns appropriate scope for this node. + __get(node) { + return this.__nodeToScope.get(node); + } + + /** + * Get variables that are declared by the node. + * + * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. + * If the node declares nothing, this method returns an empty array. + * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. + * @param {ESTree.Node} node a node to get. + * @returns {Variable[]} variables that declared by the node. + */ + getDeclaredVariables(node) { + return this.__declaredVariables.get(node) || []; + } + + /** + * acquire scope from node. + * @function ScopeManager#acquire + * @param {ESTree.Node} node node for the acquired scope. + * @param {?boolean} [inner=false] look up the most inner scope, default value is false. + * @returns {Scope?} Scope from node + */ + acquire(node, inner) { + /** + * predicate + * @param {Scope} testScope scope to test + * @returns {boolean} predicate + */ + function predicate(testScope) { + if ( + testScope.type === "function" && + testScope.functionExpressionScope + ) { + return false; + } + return true; + } + + const scopes = this.__get(node); + + if (!scopes || scopes.length === 0) { + return null; + } + + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; + } + + if (inner) { + for (let i = scopes.length - 1; i >= 0; --i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } else { + for (let i = 0, iz = scopes.length; i < iz; ++i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } + + return null; + } + + /** + * acquire all scopes from node. + * @function ScopeManager#acquireAll + * @param {ESTree.Node} node node for the acquired scope. + * @returns {Scope[]?} Scope array + */ + acquireAll(node) { + return this.__get(node); + } + + /** + * release the node. + * @function ScopeManager#release + * @param {ESTree.Node} node releasing node. + * @param {?boolean} [inner=false] look up the most inner scope, default value is false. + * @returns {Scope?} upper scope for the node. + */ + release(node, inner) { + const scopes = this.__get(node); + + if (scopes && scopes.length) { + const scope = scopes[0].upper; + + if (!scope) { + return null; + } + return this.acquire(scope.block, inner); + } + return null; + } + + /** + * Add global variables and resolve their references. + * @function ScopeManager#addGlobals + * @param {string[]} names Names of global variables to add. + * @returns {void} + */ + addGlobals(names) { + // @ts-ignore -- globalScope must be set before this method is called. + this.globalScope.__addVariables(names); + } + + attach() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + detach() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; + } + this.__currentScope = scope; + return scope; + } + + __nestGlobalScope(node) { + return this.__nestScope(new GlobalScope(this, node)); + } + + __nestBlockScope(node) { + return this.__nestScope( + new BlockScope(this, this.__currentScope, node), + ); + } + + __nestFunctionScope(node, isMethodDefinition) { + return this.__nestScope( + new FunctionScope( + this, + this.__currentScope, + node, + isMethodDefinition, + ), + ); + } + + __nestForScope(node) { + return this.__nestScope(new ForScope(this, this.__currentScope, node)); + } + + __nestCatchScope(node) { + return this.__nestScope( + new CatchScope(this, this.__currentScope, node), + ); + } + + __nestWithScope(node) { + return this.__nestScope(new WithScope(this, this.__currentScope, node)); + } + + __nestClassScope(node) { + return this.__nestScope( + new ClassScope(this, this.__currentScope, node), + ); + } + + __nestClassFieldInitializerScope(node) { + return this.__nestScope( + new ClassFieldInitializerScope(this, this.__currentScope, node), + ); + } + + __nestClassStaticBlockScope(node) { + return this.__nestScope( + new ClassStaticBlockScope(this, this.__currentScope, node), + ); + } + + __nestSwitchScope(node) { + return this.__nestScope( + new SwitchScope(this, this.__currentScope, node), + ); + } + + __nestModuleScope(node) { + return this.__nestScope( + new ModuleScope(this, this.__currentScope, node), + ); + } + + __nestFunctionExpressionNameScope(node) { + return this.__nestScope( + new FunctionExpressionNameScope(this, this.__currentScope, node), + ); + } + + __isES6() { + return this.__options.ecmaVersion >= 6; + } +} + +export default ScopeManager; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/scope.js b/node_modules/eslint-scope/lib/scope.js new file mode 100644 index 0000000000000000000000000000000000000000..ea7f116d9cb3fdfd3d1c3ad2ce05b8af4601fd56 --- /dev/null +++ b/node_modules/eslint-scope/lib/scope.js @@ -0,0 +1,852 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +import estraverse from "estraverse"; + +import Reference from "./reference.js"; +import Variable from "./variable.js"; +import { Definition } from "./definition.js"; +import { assert } from "./assert.js"; + +/** @import * as types from "eslint-scope" */ +/** @import ESTree from "estree" */ +/** @import ScopeManager from "./scope-manager.js" */ +/** @typedef {ESTree.Function | ESTree.Program | ESTree.StaticBlock} Block */ +/** @typedef {{pattern: unknown, node: unknown}} MaybeImplicitGlobal */ + +const { Syntax } = estraverse; + +/** + * Test if scope is struct + * @param {Scope} scope scope + * @param {Block} block block + * @param {boolean} isMethodDefinition is method definition + * @returns {boolean} is strict scope + */ +function isStrictScope(scope, block, isMethodDefinition) { + let body; + + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + if (isMethodDefinition) { + return true; + } + + if (scope.type === "class" || scope.type === "module") { + return true; + } + + if (scope.type === "block" || scope.type === "switch") { + return false; + } + + if (scope.type === "function") { + if ( + block.type === Syntax.ArrowFunctionExpression && + // @ts-ignore -- when block is ArrowFunctionExpression + block.body.type !== Syntax.BlockStatement + ) { + return false; + } + + if (block.type === Syntax.Program) { + body = block; + } else { + body = block.body; + } + + if (!body) { + return false; + } + } else if (scope.type === "global") { + body = block; + } else { + return false; + } + + // Search for a 'use strict' directive. + // @ts-ignore -- body is a function body + for (let i = 0, iz = body.body.length; i < iz; ++i) { + // @ts-ignore -- body is a function body + const stmt = body.body[i]; + + /* + * Check if the current statement is a directive. + * If it isn't, then we're past the directive prologue + * so stop the search because directives cannot + * appear after this point. + * + * Some parsers set `directive:null` on non-directive + * statements, so the `typeof` check is safer than + * checking for property existence. + */ + if (typeof stmt.directive !== "string") { + break; + } + + if (stmt.directive === "use strict") { + return true; + } + } + + return false; +} + +/** + * Register scope + * @param {ScopeManager} scopeManager scope manager + * @param {Scope} scope scope + * @returns {void} + */ +function registerScope(scopeManager, scope) { + scopeManager.scopes.push(scope); + + const scopes = scopeManager.__nodeToScope.get(scope.block); + + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [scope]); + } +} + +/** + * @constructor Scope + * @implements {types.Scope} + */ +class Scope { + constructor(scopeManager, type, upperScope, block, isMethodDefinition) { + /** + * One of "global", "module", "function", "function-expression-name", "block", "switch", "catch", "with", "for", + * "class", "class-field-initializer", "class-static-block". + * @member {string} Scope#type + */ + this.type = type; + + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); + + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints + */ + this.taints = new Map(); + + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its parent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === "global" || this.type === "with"; + + /** + * A reference to the scope-defining syntax node. + * @member {espree.Node} Scope#block + */ + this.block = block; + + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; + + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; + + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; + + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = + this.type === "global" || + this.type === "module" || + this.type === "function" || + this.type === "class-field-initializer" || + this.type === "class-static-block" + ? this + : upperScope.variableScope; + + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = /** @type {any} */ (false); + + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; + + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; + + /** @type {?Reference[]} */ + this.__left = []; + + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = upperScope; + + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = scopeManager.isStrictModeSupported() + ? isStrictScope(this, block, isMethodDefinition) + : false; + + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (this.upper) { + this.upper.childScopes.push(this); + } + + this.__declaredVariables = scopeManager.__declaredVariables; + + registerScope(scopeManager, this); + } + + __shouldStaticallyClose(scopeManager) { + return ( + !this.dynamic || + scopeManager.__isOptimistic() || + this.type === "global" + ); + } + + __staticCloseRef(ref) { + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } + + __dynamicCloseRef(ref) { + // notify all names are through to global + let current = this; + + do { + current.through.push(ref); + current = current.upper; + } while (current); + } + + __close(scopeManager) { + let closeRef; + + if (this.__shouldStaticallyClose(scopeManager)) { + closeRef = this.__staticCloseRef; + } else { + closeRef = this.__dynamicCloseRef; + } + + // Try Resolving all references in this scope. + // @ts-ignore -- __left should be an array here + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + // @ts-ignore -- __left should be an array here + const ref = this.__left[i]; + + closeRef.call(this, ref); + } + this.__left = null; + + return this.upper; + } + + // To override by function scopes. + // References in default parameters isn't resolved to variables which are in their function body. + // eslint-disable-next-line class-methods-use-this, no-unused-vars -- Desired as instance method with signature + __isValidResolution(ref, variable) { + return true; + } + + __resolve(ref) { + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + const variable = this.set.get(name); + + if (!this.__isValidResolution(ref, variable)) { + return false; + } + variable.references.push(ref); + variable.stack = + variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; + + return true; + } + + __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.__left.push(ref); + } + this.through.push(ref); + } + + __addDeclaredVariablesOfNode(variable, node) { + if (node === null || node === void 0) { + return; + } + + let variables = this.__declaredVariables.get(node); + + if (variables === null || variables === void 0) { + variables = []; + this.__declaredVariables.set(node, variables); + } + if (!variables.includes(variable)) { + variables.push(variable); + } + } + + __defineGeneric(name, set, variables, node, def) { + let variable; + + variable = set.get(name); + if (!variable) { + variable = new Variable(name, this); + set.set(name, variable); + variables.push(variable); + } + + if (def) { + variable.defs.push(def); + this.__addDeclaredVariablesOfNode(variable, def.node); + this.__addDeclaredVariablesOfNode(variable, def.parent); + } + if (node) { + variable.identifiers.push(node); + } + } + + __define(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.set, + this.variables, + node, + def, + ); + } + } + + __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { + // because Array element may be null + if ( + !node || + (node.type !== Syntax.Identifier && node.type !== "JSXIdentifier") + ) { + return; + } + + // Specially handle like `this`. + if (node.name === "super") { + return; + } + + const ref = new Reference( + node, + this, + assign || Reference.READ, + writeExpr, + maybeImplicitGlobal, + !!partial, + !!init, + ); + + this.references.push(ref); + + // @ts-ignore -- __left should be an array here + this.__left.push(ref); + } + + __detectEval() { + let current = this; + + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + } + + __detectThis() { + this.thisFound = true; + } + + __isClosed() { + return this.__left === null; + } + + /** + * returns resolved {Reference} + * @function Scope#resolve + * @param {ESTree.Identifier} ident identifier to be resolved. + * @returns {?Reference} reference + */ + resolve(ident) { + let ref, i, iz; + + assert(this.__isClosed(), "Scope should be closed."); + assert( + ident.type === Syntax.Identifier, + "Target should be identifier.", + ); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + } + + /** + * returns this scope is static + * @function Scope#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.dynamic; + } + + /** + * returns this scope has materialized arguments + * @function Scope#isArgumentsMaterialized + * @returns {any} arguments materialized + */ // eslint-disable-next-line class-methods-use-this -- Desired as instance method + isArgumentsMaterialized() { + return true; + } + + /** + * returns this scope has materialized `this` reference + * @function Scope#isThisMaterialized + * @returns {any} this materialized + */ // eslint-disable-next-line class-methods-use-this -- Desired as instance method + isThisMaterialized() { + return true; + } + + isUsedName(name) { + if (this.set.has(name)) { + return true; + } + for (let i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + } +} + +/** + * Global scope. + * @implements {types.GlobalScope} + */ +class GlobalScope extends Scope { + constructor(scopeManager, block) { + super(scopeManager, "global", null, block, false); + this.implicit = { + set: new Map(), + + /** @type {Variable[]} */ + variables: [], + + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + * @member {Reference[]} Scope#implicit#left + * @type {Reference[]} + */ + left: [], + }; + } + + __close(scopeManager) { + const implicit = []; + + // @ts-ignore -- __left should be an array here + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + // @ts-ignore -- __left should be an array here + const ref = this.__left[i]; + + if ( + ref.__maybeImplicitGlobal && + !this.set.has(ref.identifier.name) + ) { + implicit.push(ref.__maybeImplicitGlobal); + } + } + + // create an implicit global variable from assignment expression + for (let i = 0, iz = implicit.length; i < iz; ++i) { + const info = implicit[i]; + + this.__defineImplicit( + info.pattern, + new Definition( + Variable.ImplicitGlobalVariable, + info.pattern, + info.node, + null, + null, + null, + ), + ); + } + + super.__close(scopeManager); + + this.implicit.left = [...this.through]; + + return null; + } + + __defineImplicit(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.implicit.set, + this.implicit.variables, + node, + def, + ); + } + } + + __addVariables(names) { + for (const name of names) { + this.__defineGeneric(name, this.set, this.variables, null, null); + } + + const namesSet = new Set(names); + + this.through = this.through.filter(reference => { + const name = reference.identifier.name; + + if (namesSet.has(name)) { + const variable = this.set.get(name); + + reference.resolved = variable; + variable.references.push(reference); + + return false; + } + + return true; + }); + + this.implicit.variables = this.implicit.variables.filter(variable => { + const name = variable.name; + + if (namesSet.has(name)) { + this.implicit.set.delete(name); + + return false; + } + + return true; + }); + + this.implicit.left = this.implicit.left.filter( + reference => !namesSet.has(reference.identifier.name), + ); + } +} + +/** + * Module scope. + * @implements {types.ModuleScope} + */ +class ModuleScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "module", upperScope, block, false); + } +} + +/** + * Function expression name scope. + * @implements {types.FunctionExpressionNameScope} + */ +class FunctionExpressionNameScope extends Scope { + constructor(scopeManager, upperScope, block) { + super( + scopeManager, + "function-expression-name", + upperScope, + block, + false, + ); + this.__define( + block.id, + new Definition( + Variable.FunctionName, + block.id, + block, + null, + null, + null, + ), + ); + this.functionExpressionScope = /** @type {const} */ (true); + } +} + +/** + * Catch scope. + * @implements {types.CatchScope} + */ +class CatchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "catch", upperScope, block, false); + } +} + +/** + * With statement scope. + * @implements {types.WithScope} + */ +class WithScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "with", upperScope, block, false); + } + + __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return super.__close(scopeManager); + } + + // @ts-ignore -- __left should be an array here + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + // @ts-ignore -- __left should be an array here + const ref = this.__left[i]; + + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + this.__left = null; + + return this.upper; + } +} + +/** + * Block scope. + * @implements {types.BlockScope} + */ +class BlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "block", upperScope, block, false); + } +} + +/** + * Switch scope. + * @implements {types.SwitchScope} + */ +class SwitchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "switch", upperScope, block, false); + } +} + +/** + * Function scope. + * @implements {types.FunctionScope} + */ +class FunctionScope extends Scope { + constructor(scopeManager, upperScope, block, isMethodDefinition) { + super(scopeManager, "function", upperScope, block, isMethodDefinition); + + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== Syntax.ArrowFunctionExpression) { + this.__defineArguments(); + } + } + + isArgumentsMaterialized() { + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + if (this.block.type === Syntax.ArrowFunctionExpression) { + return false; + } + + if (!this.isStatic()) { + return true; + } + + const variable = this.set.get("arguments"); + + assert(variable, "Always have arguments variable."); + return variable.tainted || variable.references.length !== 0; + } + + isThisMaterialized() { + if (!this.isStatic()) { + return true; + } + return this.thisFound; + } + + __defineArguments() { + this.__defineGeneric("arguments", this.set, this.variables, null, null); + this.taints.set("arguments", true); + } + + // References in default parameters isn't resolved to variables which are in their function body. + // const x = 1 + // function f(a = x) { // This `x` is resolved to the `x` in the outer scope. + // const x = 2 + // console.log(a) + // } + __isValidResolution(ref, variable) { + // If `options.nodejsScope` is true, `this.block` becomes a Program node. + if (this.block.type === "Program") { + return true; + } + + const bodyStart = this.block.body.range[0]; + + // It's invalid resolution in the following case: + return !( + variable.scope === this && + ref.identifier.range[0] < bodyStart && // the reference is in the parameter part. + variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body. + ); + } +} + +/** + * Scope of for, for-in, and for-of statements. + * @implements {types.ForScope} + */ +class ForScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "for", upperScope, block, false); + } +} + +/** + * Class scope. + * @implements {types.ClassScope} + */ +class ClassScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class", upperScope, block, false); + } +} + +/** + * Class field initializer scope. + * @implements {types.ClassFieldInitializerScope} + */ +class ClassFieldInitializerScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class-field-initializer", upperScope, block, true); + } +} + +/** + * Class static block scope. + * @implements {types.ClassStaticBlockScope} + */ +class ClassStaticBlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class-static-block", upperScope, block, true); + } +} + +export { + Scope, + GlobalScope, + ModuleScope, + FunctionExpressionNameScope, + CatchScope, + WithScope, + BlockScope, + SwitchScope, + FunctionScope, + ForScope, + ClassScope, + ClassFieldInitializerScope, + ClassStaticBlockScope, +}; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/variable.js b/node_modules/eslint-scope/lib/variable.js new file mode 100644 index 0000000000000000000000000000000000000000..78d953957ae863bc5f7367e6ea0c2940a4880715 --- /dev/null +++ b/node_modules/eslint-scope/lib/variable.js @@ -0,0 +1,90 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +/** @import * as types from "eslint-scope" */ +/** @import Reference from "./reference.js" */ + +/** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @constructor Variable + * @implements {types.Variable} + */ +class Variable { + constructor(name, scope) { + /** + * The variable name, as given in the source code. + * @member {string} Variable#name + */ + this.name = name; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {espree.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } +} + +Variable.CatchClause = "CatchClause"; +Variable.Parameter = "Parameter"; +Variable.FunctionName = "FunctionName"; +Variable.ClassName = "ClassName"; +Variable.Variable = "Variable"; +Variable.ImportBinding = "ImportBinding"; +Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; + +export default Variable; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/package.json b/node_modules/eslint-scope/package.json new file mode 100644 index 0000000000000000000000000000000000000000..909db5250eac8b0d9f781387297a09a282f8ddaf --- /dev/null +++ b/node_modules/eslint-scope/package.json @@ -0,0 +1,66 @@ +{ + "name": "eslint-scope", + "description": "ECMAScript scope analyzer for ESLint", + "homepage": "https://github.com/eslint/js/blob/main/packages/eslint-scope/README.md", + "main": "./dist/eslint-scope.cjs", + "types": "./lib/index.d.cts", + "type": "module", + "exports": { + ".": { + "import": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "require": { + "types": "./lib/index.d.cts", + "default": "./dist/eslint-scope.cjs" + } + }, + "./package.json": "./package.json" + }, + "version": "9.1.2", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/js.git", + "directory": "packages/eslint-scope" + }, + "funding": "https://opencollective.com/eslint", + "keywords": [ + "eslint" + ], + "bugs": { + "url": "https://github.com/eslint/js/issues" + }, + "license": "BSD-2-Clause", + "scripts": { + "build": "rollup -c", + "lint:types": "attw --pack", + "pretest": "npm run build", + "test": "node Makefile.js test && npm run test:types", + "test:types": "tsc -p tsconfig.json && tsc -p tests/types/tsconfig.json" + }, + "files": [ + "LICENSE", + "README.md", + "lib", + "dist/eslint-scope.cjs" + ], + "dependencies": { + "@types/esrecurse": "^4.3.1", + "@types/estree": "^1.0.8", + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "devDependencies": { + "@typescript-eslint/parser": "^8.7.0", + "chai": "^6.0.0", + "eslint": ">=10.0.0-rc.0 <10.0.0 || ^10.0.0", + "eslint-visitor-keys": "^5.0.1", + "espree": "^11.2.0", + "npm-license": "^0.3.3", + "shelljs": "^0.8.5" + } +} diff --git a/node_modules/eslint-visitor-keys/LICENSE b/node_modules/eslint-visitor-keys/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..17a25538d9bd634bc079642d35d7a6422a0d850d --- /dev/null +++ b/node_modules/eslint-visitor-keys/LICENSE @@ -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 contributors + + 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. diff --git a/node_modules/eslint-visitor-keys/README.md b/node_modules/eslint-visitor-keys/README.md new file mode 100644 index 0000000000000000000000000000000000000000..94894e2e10dce80ee1eb53459b297b449e4b2ea0 --- /dev/null +++ b/node_modules/eslint-visitor-keys/README.md @@ -0,0 +1,123 @@ +# eslint-visitor-keys + +[![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) +[![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) +[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions) + +Constants and utilities about visitor keys to traverse AST. + +## 💿 Installation + +Use [npm] to install. + +```bash +$ npm install eslint-visitor-keys +``` + +### Requirements + +- [Node.js] `^20.19.0`, `^22.13.0`, or `>=24` + +## 📖 Usage + +To use in an ESM file: + +```js +import * as evk from "eslint-visitor-keys"; +``` + +To use in a CommonJS file: + +```js +const evk = require("eslint-visitor-keys"); +``` + +### evk.KEYS + +> type: `{ [type: string]: string[] | undefined }` + +Visitor keys. This keys are frozen. + +This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. + +For example: + +``` +console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] +``` + +### evk.getKeys(node) + +> type: `(node: object) => string[]` + +Get the visitor keys of a given AST node. + +This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. + +This will be used to traverse unknown nodes. + +For example: + +```js +const node = { + type: "AssignmentExpression", + left: { type: "Identifier", name: "foo" }, + right: { type: "Literal", value: 0 }, +}; +console.log(evk.getKeys(node)); // → ["type", "left", "right"] +``` + +### evk.unionWith(additionalKeys) + +> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` + +Make the union set with `evk.KEYS` and the given keys. + +- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. +- It removes duplicated keys as keeping the first one. + +For example: + +```js +console.log( + evk.unionWith({ + MethodDefinition: ["decorators"], + }), +); // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } +``` + +## 📰 Change log + +See [GitHub releases](https://github.com/eslint/js/releases). + +## 🍻 Contributing + +Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). + +### Development commands + +- `npm test` runs tests and measures code coverage. +- `npm run lint` checks source codes with ESLint. +- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser. + +[npm]: https://www.npmjs.com/ +[Node.js]: https://nodejs.org/ +[ESTree]: https://github.com/estree/estree + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Platinum Sponsors

+

Automattic

Gold Sponsors

+

Qlty Software Shopify

Silver Sponsors

+

Vite Liftoff StackBlitz

Bronze Sponsors

+

Cybozu SAP CrawlJobs Depot N-iX Ltd Icons8 Discord GitBook HeroCoders TestMu AI Open Source Office (Formerly LambdaTest)

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/eslint-visitor-keys/lib/index.js b/node_modules/eslint-visitor-keys/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6e5269cf634aee25664de5b5559b723e27472675 --- /dev/null +++ b/node_modules/eslint-visitor-keys/lib/index.js @@ -0,0 +1,67 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ +import KEYS from "./visitor-keys.js"; + +/** + * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys + */ + +// List to ignore keys. +const KEY_BLACKLIST = new Set([ + "parent", + "leadingComments", + "trailingComments", +]); + +/** + * Check whether a given key should be used or not. + * @param {string} key The key to check. + * @returns {boolean} `true` if the key should be used. + */ +function filterKey(key) { + return !KEY_BLACKLIST.has(key) && key[0] !== "_"; +} + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +export function getKeys(node) { + return Object.keys(node).filter(filterKey); +} +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */ + +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +export function unionWith(additionalKeys) { + const retv = + /** @type {{ [type: string]: ReadonlyArray }} */ + (Object.assign({}, KEYS)); + + for (const type of Object.keys(additionalKeys)) { + if (Object.hasOwn(retv, type)) { + const keys = new Set(additionalKeys[type]); + + for (const key of retv[type]) { + keys.add(key); + } + + retv[type] = Object.freeze(Array.from(keys)); + } else { + retv[type] = Object.freeze(Array.from(additionalKeys[type])); + } + } + + return Object.freeze(retv); +} + +export { KEYS }; diff --git a/node_modules/eslint-visitor-keys/lib/visitor-keys.js b/node_modules/eslint-visitor-keys/lib/visitor-keys.js new file mode 100644 index 0000000000000000000000000000000000000000..cddbcd9c0d94262b31e80b1c8c5d2967c12f522a --- /dev/null +++ b/node_modules/eslint-visitor-keys/lib/visitor-keys.js @@ -0,0 +1,118 @@ +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */ + +/** + * @type {VisitorKeys} + */ +const KEYS = { + ArrayExpression: ["elements"], + ArrayPattern: ["elements"], + ArrowFunctionExpression: ["params", "body"], + AssignmentExpression: ["left", "right"], + AssignmentPattern: ["left", "right"], + AwaitExpression: ["argument"], + BinaryExpression: ["left", "right"], + BlockStatement: ["body"], + BreakStatement: ["label"], + CallExpression: ["callee", "arguments"], + CatchClause: ["param", "body"], + ChainExpression: ["expression"], + ClassBody: ["body"], + ClassDeclaration: ["id", "superClass", "body"], + ClassExpression: ["id", "superClass", "body"], + ConditionalExpression: ["test", "consequent", "alternate"], + ContinueStatement: ["label"], + DebuggerStatement: [], + DoWhileStatement: ["body", "test"], + EmptyStatement: [], + ExperimentalRestProperty: ["argument"], + ExperimentalSpreadProperty: ["argument"], + ExportAllDeclaration: ["exported", "source", "attributes"], + ExportDefaultDeclaration: ["declaration"], + ExportNamedDeclaration: [ + "declaration", + "specifiers", + "source", + "attributes", + ], + ExportSpecifier: ["local", "exported"], + ExpressionStatement: ["expression"], + ForInStatement: ["left", "right", "body"], + ForOfStatement: ["left", "right", "body"], + ForStatement: ["init", "test", "update", "body"], + FunctionDeclaration: ["id", "params", "body"], + FunctionExpression: ["id", "params", "body"], + Identifier: [], + IfStatement: ["test", "consequent", "alternate"], + ImportAttribute: ["key", "value"], + ImportDeclaration: ["specifiers", "source", "attributes"], + ImportDefaultSpecifier: ["local"], + ImportExpression: ["source", "options"], + ImportNamespaceSpecifier: ["local"], + ImportSpecifier: ["imported", "local"], + JSXAttribute: ["name", "value"], + JSXClosingElement: ["name"], + JSXClosingFragment: [], + JSXElement: ["openingElement", "children", "closingElement"], + JSXEmptyExpression: [], + JSXExpressionContainer: ["expression"], + JSXFragment: ["openingFragment", "children", "closingFragment"], + JSXIdentifier: [], + JSXMemberExpression: ["object", "property"], + JSXNamespacedName: ["namespace", "name"], + JSXOpeningElement: ["name", "attributes"], + JSXOpeningFragment: [], + JSXSpreadAttribute: ["argument"], + JSXSpreadChild: ["expression"], + JSXText: [], + LabeledStatement: ["label", "body"], + Literal: [], + LogicalExpression: ["left", "right"], + MemberExpression: ["object", "property"], + MetaProperty: ["meta", "property"], + MethodDefinition: ["key", "value"], + NewExpression: ["callee", "arguments"], + ObjectExpression: ["properties"], + ObjectPattern: ["properties"], + PrivateIdentifier: [], + Program: ["body"], + Property: ["key", "value"], + PropertyDefinition: ["key", "value"], + RestElement: ["argument"], + ReturnStatement: ["argument"], + SequenceExpression: ["expressions"], + SpreadElement: ["argument"], + StaticBlock: ["body"], + Super: [], + SwitchCase: ["test", "consequent"], + SwitchStatement: ["discriminant", "cases"], + TaggedTemplateExpression: ["tag", "quasi"], + TemplateElement: [], + TemplateLiteral: ["quasis", "expressions"], + ThisExpression: [], + ThrowStatement: ["argument"], + TryStatement: ["block", "handler", "finalizer"], + UnaryExpression: ["argument"], + UpdateExpression: ["argument"], + VariableDeclaration: ["declarations"], + VariableDeclarator: ["id", "init"], + WhileStatement: ["test", "body"], + WithStatement: ["object", "body"], + YieldExpression: ["argument"], +}; + +// Types. +const NODE_TYPES = Object.keys(KEYS); + +// Freeze the keys. +for (const type of NODE_TYPES) { + Object.freeze(KEYS[type]); +} +Object.freeze(KEYS); + +export default KEYS; diff --git a/node_modules/eslint-visitor-keys/package.json b/node_modules/eslint-visitor-keys/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d61f90619c2d85199adcafbc2f4d293fe6142384 --- /dev/null +++ b/node_modules/eslint-visitor-keys/package.json @@ -0,0 +1,57 @@ +{ + "name": "eslint-visitor-keys", + "version": "5.0.1", + "description": "Constants and utilities about visitor keys to traverse AST.", + "type": "module", + "main": "dist/eslint-visitor-keys.cjs", + "types": "./dist/index.d.ts", + "exports": { + ".": [ + { + "import": "./lib/index.js", + "require": "./dist/eslint-visitor-keys.cjs" + }, + "./dist/eslint-visitor-keys.cjs" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist/index.d.ts", + "dist/visitor-keys.d.ts", + "dist/eslint-visitor-keys.cjs", + "dist/eslint-visitor-keys.d.cts", + "lib" + ], + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "devDependencies": { + "rollup-plugin-dts": "^6.2.3", + "tsd": "^0.33.0" + }, + "scripts": { + "build": "npm run build:cjs && npm run build:types", + "build:cjs": "rollup -c", + "build:debug": "npm run build:cjs -- -m && npm run build:types", + "build:types": "tsc -v && tsc", + "test": "mocha \"tests/**/*.test.cjs\" && mocha \"tests/**/*.test.js\" && npm run test:types", + "test:coverage": "c8 npm test", + "test:types": "tsd" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/js.git", + "directory": "packages/eslint-visitor-keys" + }, + "funding": "https://opencollective.com/eslint", + "keywords": [ + "eslint" + ], + "author": "Toru Nagashima (https://github.com/mysticatea)", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/eslint/js/issues" + }, + "homepage": "https://github.com/eslint/js/blob/main/packages/eslint-visitor-keys/README.md", + "sideEffects": false +} diff --git a/node_modules/eslint/lib/rules/newline-before-return.js b/node_modules/eslint/lib/rules/newline-before-return.js new file mode 100644 index 0000000000000000000000000000000000000000..d9ebc9c18007a04c31d448e19a1774b5c7a98ab1 --- /dev/null +++ b/node_modules/eslint/lib/rules/newline-before-return.js @@ -0,0 +1,242 @@ +/** + * @fileoverview Rule to require newlines before `return` statement + * @author Kai Cataldo + * @deprecated in ESLint v4.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require an empty line before `return` statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/newline-before-return", + }, + + fixable: "whitespace", + schema: [], + messages: { + expected: "Expected newline before return statement.", + }, + + deprecated: { + message: "The rule was replaced with a more general rule.", + url: "https://eslint.org/blog/2017/06/eslint-v4.0.0-released/", + deprecatedSince: "4.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: "The new rule moved to a plugin.", + url: "https://eslint.org/docs/latest/rules/padding-line-between-statements#examples", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "padding-line-between-statements", + url: "https://eslint.style/rules/padding-line-between-statements", + }, + }, + ], + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tests whether node is preceded by supplied tokens + * @param {ASTNode} node node to check + * @param {Array} testTokens array of tokens to test against + * @returns {boolean} Whether or not the node is preceded by one of the supplied tokens + * @private + */ + function isPrecededByTokens(node, testTokens) { + const tokenBefore = sourceCode.getTokenBefore(node); + + return testTokens.includes(tokenBefore.value); + } + + /** + * Checks whether node is the first node after statement or in block + * @param {ASTNode} node node to check + * @returns {boolean} Whether or not the node is the first node after statement or in block + * @private + */ + function isFirstNode(node) { + const parentType = node.parent.type; + + if (node.parent.body) { + return Array.isArray(node.parent.body) + ? node.parent.body[0] === node + : node.parent.body === node; + } + + if (parentType === "IfStatement") { + return isPrecededByTokens(node, ["else", ")"]); + } + if (parentType === "DoWhileStatement") { + return isPrecededByTokens(node, ["do"]); + } + if (parentType === "SwitchCase") { + return isPrecededByTokens(node, [":"]); + } + return isPrecededByTokens(node, [")"]); + } + + /** + * Returns the number of lines of comments that precede the node + * @param {ASTNode} node node to check for overlapping comments + * @param {number} lineNumTokenBefore line number of previous token, to check for overlapping comments + * @returns {number} Number of lines of comments that precede the node + * @private + */ + function calcCommentLines(node, lineNumTokenBefore) { + const comments = sourceCode.getCommentsBefore(node); + let numLinesComments = 0; + + if (!comments.length) { + return numLinesComments; + } + + comments.forEach(comment => { + numLinesComments++; + + if (comment.type === "Block") { + numLinesComments += + comment.loc.end.line - comment.loc.start.line; + } + + // avoid counting lines with inline comments twice + if (comment.loc.start.line === lineNumTokenBefore) { + numLinesComments--; + } + + if (comment.loc.end.line === node.loc.start.line) { + numLinesComments--; + } + }); + + return numLinesComments; + } + + /** + * Returns the line number of the token before the node that is passed in as an argument + * @param {ASTNode} node The node to use as the start of the calculation + * @returns {number} Line number of the token before `node` + * @private + */ + function getLineNumberOfTokenBefore(node) { + const tokenBefore = sourceCode.getTokenBefore(node); + let lineNumTokenBefore; + + /** + * Global return (at the beginning of a script) is a special case. + * If there is no token before `return`, then we expect no line + * break before the return. Comments are allowed to occupy lines + * before the global return, just no blank lines. + * Setting lineNumTokenBefore to zero in that case results in the + * desired behavior. + */ + if (tokenBefore) { + lineNumTokenBefore = tokenBefore.loc.end.line; + } else { + lineNumTokenBefore = 0; // global return at beginning of script + } + + return lineNumTokenBefore; + } + + /** + * Checks whether node is preceded by a newline + * @param {ASTNode} node node to check + * @returns {boolean} Whether or not the node is preceded by a newline + * @private + */ + function hasNewlineBefore(node) { + const lineNumNode = node.loc.start.line; + const lineNumTokenBefore = getLineNumberOfTokenBefore(node); + const commentLines = calcCommentLines(node, lineNumTokenBefore); + + return lineNumNode - lineNumTokenBefore - commentLines > 1; + } + + /** + * Checks whether it is safe to apply a fix to a given return statement. + * + * The fix is not considered safe if the given return statement has leading comments, + * as we cannot safely determine if the newline should be added before or after the comments. + * For more information, see: https://github.com/eslint/eslint/issues/5958#issuecomment-222767211 + * @param {ASTNode} node The return statement node to check. + * @returns {boolean} `true` if it can fix the node. + * @private + */ + function canFix(node) { + const leadingComments = sourceCode.getCommentsBefore(node); + const lastLeadingComment = leadingComments.at(-1); + const tokenBefore = sourceCode.getTokenBefore(node); + + if (leadingComments.length === 0) { + return true; + } + + /* + * if the last leading comment ends in the same line as the previous token and + * does not share a line with the `return` node, we can consider it safe to fix. + * Example: + * function a() { + * var b; //comment + * return; + * } + */ + if ( + lastLeadingComment.loc.end.line === tokenBefore.loc.end.line && + lastLeadingComment.loc.end.line !== node.loc.start.line + ) { + return true; + } + + return false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ReturnStatement(node) { + if (!isFirstNode(node) && !hasNewlineBefore(node)) { + context.report({ + node, + messageId: "expected", + fix(fixer) { + if (canFix(node)) { + const tokenBefore = + sourceCode.getTokenBefore(node); + const newlines = + node.loc.start.line === + tokenBefore.loc.end.line + ? "\n\n" + : "\n"; + + return fixer.insertTextBefore(node, newlines); + } + return null; + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/newline-per-chained-call.js b/node_modules/eslint/lib/rules/newline-per-chained-call.js new file mode 100644 index 0000000000000000000000000000000000000000..c56e946606ac0b7b71a0b4f67c808ab9a2a9c130 --- /dev/null +++ b/node_modules/eslint/lib/rules/newline-per-chained-call.js @@ -0,0 +1,159 @@ +/** + * @fileoverview Rule to ensure newline per method call when chaining calls + * @author Rajendra Patil + * @author Burak Yigit Kaya + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "newline-per-chained-call", + url: "https://eslint.style/rules/newline-per-chained-call", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require a newline after each call in a method chain", + recommended: false, + url: "https://eslint.org/docs/latest/rules/newline-per-chained-call", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + ignoreChainWithDepth: { + type: "integer", + minimum: 1, + maximum: 10, + default: 2, + }, + }, + additionalProperties: false, + }, + ], + messages: { + expected: "Expected line break before `{{callee}}`.", + }, + }, + + create(context) { + const options = context.options[0] || {}, + ignoreChainWithDepth = options.ignoreChainWithDepth || 2; + + const sourceCode = context.sourceCode; + + /** + * Get the prefix of a given MemberExpression node. + * If the MemberExpression node is a computed value it returns a + * left bracket. If not it returns a period. + * @param {ASTNode} node A MemberExpression node to get + * @returns {string} The prefix of the node. + */ + function getPrefix(node) { + if (node.computed) { + if (node.optional) { + return "?.["; + } + return "["; + } + if (node.optional) { + return "?."; + } + return "."; + } + + /** + * Gets the property text of a given MemberExpression node. + * If the text is multiline, this returns only the first line. + * @param {ASTNode} node A MemberExpression node to get. + * @returns {string} The property text of the node. + */ + function getPropertyText(node) { + const prefix = getPrefix(node); + const lines = sourceCode + .getText(node.property) + .split(astUtils.LINEBREAK_MATCHER); + const suffix = node.computed && lines.length === 1 ? "]" : ""; + + return prefix + lines[0] + suffix; + } + + return { + "CallExpression:exit"(node) { + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type !== "MemberExpression") { + return; + } + + let parent = astUtils.skipChainExpression(callee.object); + let depth = 1; + + while (parent && parent.callee) { + depth += 1; + parent = astUtils.skipChainExpression( + astUtils.skipChainExpression(parent.callee).object, + ); + } + + if ( + depth > ignoreChainWithDepth && + astUtils.isTokenOnSameLine(callee.object, callee.property) + ) { + const firstTokenAfterObject = sourceCode.getTokenAfter( + callee.object, + astUtils.isNotClosingParenToken, + ); + + context.report({ + node: callee.property, + loc: { + start: firstTokenAfterObject.loc.start, + end: callee.loc.end, + }, + messageId: "expected", + data: { + callee: getPropertyText(callee), + }, + fix(fixer) { + return fixer.insertTextBefore( + firstTokenAfterObject, + "\n", + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-alert.js b/node_modules/eslint/lib/rules/no-alert.js new file mode 100644 index 0000000000000000000000000000000000000000..d1a3c5baadf5167882e2d864d76375e35d4f91cd --- /dev/null +++ b/node_modules/eslint/lib/rules/no-alert.js @@ -0,0 +1,149 @@ +/** + * @fileoverview Rule to flag use of alert, confirm, prompt + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + getStaticPropertyName: getPropertyName, + getVariableByName, + skipChainExpression, +} = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks if the given name is a prohibited identifier. + * @param {string} name The name to check + * @returns {boolean} Whether or not the name is prohibited. + */ +function isProhibitedIdentifier(name) { + return /^(?:alert|confirm|prompt)$/u.test(name); +} + +/** + * Finds the eslint-scope reference in the given scope. + * @param {Object} scope The scope to search. + * @param {ASTNode} node The identifier node. + * @returns {Reference|null} Returns the found reference or null if none were found. + */ +function findReference(scope, node) { + const references = scope.references.filter( + reference => + reference.identifier.range[0] === node.range[0] && + reference.identifier.range[1] === node.range[1], + ); + + if (references.length === 1) { + return references[0]; + } + return null; +} + +/** + * Checks if the given identifier node is shadowed in the given scope. + * @param {Object} scope The current scope. + * @param {string} node The identifier node to check + * @returns {boolean} Whether or not the name is shadowed. + */ +function isShadowed(scope, node) { + const reference = findReference(scope, node); + + return ( + reference && reference.resolved && reference.resolved.defs.length > 0 + ); +} + +/** + * Checks if the given identifier node is a ThisExpression in the global scope or the global window property. + * @param {Object} scope The current scope. + * @param {string} node The identifier node to check + * @returns {boolean} Whether or not the node is a reference to the global object. + */ +function isGlobalThisReferenceOrGlobalWindow(scope, node) { + if (scope.type === "global" && node.type === "ThisExpression") { + return true; + } + if ( + node.type === "Identifier" && + (node.name === "window" || + (node.name === "globalThis" && + getVariableByName(scope, "globalThis"))) + ) { + return !isShadowed(scope, node); + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `alert`, `confirm`, and `prompt`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-alert", + }, + + schema: [], + + messages: { + unexpected: "Unexpected {{name}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + const callee = skipChainExpression(node.callee), + currentScope = sourceCode.getScope(node); + + // without window. + if (callee.type === "Identifier") { + const name = callee.name; + + if ( + !isShadowed(currentScope, callee) && + isProhibitedIdentifier(callee.name) + ) { + context.report({ + node, + messageId: "unexpected", + data: { name }, + }); + } + } else if ( + callee.type === "MemberExpression" && + isGlobalThisReferenceOrGlobalWindow( + currentScope, + callee.object, + ) + ) { + const name = getPropertyName(callee); + + if (isProhibitedIdentifier(name)) { + context.report({ + node, + messageId: "unexpected", + data: { name }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-array-constructor.js b/node_modules/eslint/lib/rules/no-array-constructor.js new file mode 100644 index 0000000000000000000000000000000000000000..298f845f0e8c1dad0e054bedc24e25b450e3dd01 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-array-constructor.js @@ -0,0 +1,194 @@ +/** + * @fileoverview Disallow construction of dense arrays using the Array constructor + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + getVariableByName, + isClosingParenToken, + isOpeningParenToken, + isStartOfExpressionStatement, + needsPrecedingSemicolon, +} = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `Array` constructors", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-array-constructor", + }, + + fixable: "code", + + hasSuggestions: true, + + schema: [], + + messages: { + preferLiteral: "The array literal notation [] is preferable.", + useLiteral: "Replace with an array literal.", + useLiteralAfterSemicolon: + "Replace with an array literal, add preceding semicolon.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Checks if there are comments in Array constructor expressions. + * @param {ASTNode} node A CallExpression or NewExpression node. + * @returns {boolean} True if there are comments, false otherwise. + */ + function hasCommentsInArrayConstructor(node) { + const firstToken = sourceCode.getFirstToken(node); + const lastToken = sourceCode.getLastToken(node); + + let lastRelevantToken = sourceCode.getLastToken(node.callee); + + while ( + lastRelevantToken !== lastToken && + !isOpeningParenToken(lastRelevantToken) + ) { + lastRelevantToken = sourceCode.getTokenAfter(lastRelevantToken); + } + + return sourceCode.commentsExistBetween( + firstToken, + lastRelevantToken, + ); + } + + /** + * Gets the text between the calling parentheses of a CallExpression or NewExpression. + * @param {ASTNode} node A CallExpression or NewExpression node. + * @returns {string} The text between the calling parentheses, or an empty string if there are none. + */ + function getArgumentsText(node) { + const lastToken = sourceCode.getLastToken(node); + + if (!isClosingParenToken(lastToken)) { + return ""; + } + + let firstToken = node.callee; + + do { + firstToken = sourceCode.getTokenAfter(firstToken); + if (!firstToken || firstToken === lastToken) { + return ""; + } + } while (!isOpeningParenToken(firstToken)); + + return sourceCode.text.slice( + firstToken.range[1], + lastToken.range[0], + ); + } + + /** + * Disallow construction of dense arrays using the Array constructor + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function check(node) { + if ( + node.callee.type !== "Identifier" || + node.callee.name !== "Array" || + node.typeArguments || + (node.arguments.length === 1 && + node.arguments[0].type !== "SpreadElement") + ) { + return; + } + + const variable = getVariableByName( + sourceCode.getScope(node), + "Array", + ); + + /* + * Check if `Array` is a predefined global variable: predefined globals have no declarations, + * meaning that the `identifiers` list of the variable object is empty. + */ + if (variable && variable.identifiers.length === 0) { + const argsText = getArgumentsText(node); + let fixText; + let messageId; + + const nonSpreadCount = node.arguments.reduce( + (count, arg) => + arg.type !== "SpreadElement" ? count + 1 : count, + 0, + ); + + const shouldSuggest = + node.optional || + (node.arguments.length > 0 && nonSpreadCount < 2) || + hasCommentsInArrayConstructor(node); + + /* + * Check if the suggested change should include a preceding semicolon or not. + * Due to JavaScript's ASI rules, a missing semicolon may be inserted automatically + * before an expression like `Array()` or `new Array()`, but not when the expression + * is changed into an array literal like `[]`. + */ + if ( + isStartOfExpressionStatement(node) && + needsPrecedingSemicolon(sourceCode, node) + ) { + fixText = `;[${argsText}]`; + messageId = "useLiteralAfterSemicolon"; + } else { + fixText = `[${argsText}]`; + messageId = "useLiteral"; + } + + context.report({ + node, + messageId: "preferLiteral", + fix(fixer) { + if (shouldSuggest) { + return null; + } + + return fixer.replaceText(node, fixText); + }, + suggest: [ + { + messageId, + fix(fixer) { + if (shouldSuggest) { + return fixer.replaceText(node, fixText); + } + + return null; + }, + }, + ], + }); + } + } + + return { + CallExpression: check, + NewExpression: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-async-promise-executor.js b/node_modules/eslint/lib/rules/no-async-promise-executor.js new file mode 100644 index 0000000000000000000000000000000000000000..34906f4e4d9944babc416521371645a3ca7367ef --- /dev/null +++ b/node_modules/eslint/lib/rules/no-async-promise-executor.js @@ -0,0 +1,51 @@ +/** + * @fileoverview disallow using an async function as a Promise executor + * @author Teddy Katz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow using an async function as a Promise executor", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-async-promise-executor", + }, + + fixable: null, + schema: [], + messages: { + async: "Promise executor functions should not be async.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + "NewExpression[callee.name='Promise'][arguments.0.async=true]"( + node, + ) { + if (!sourceCode.isGlobalReference(node.callee)) { + return; + } + + context.report({ + node: sourceCode.getFirstToken( + node.arguments[0], + token => token.value === "async", + ), + messageId: "async", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-await-in-loop.js b/node_modules/eslint/lib/rules/no-await-in-loop.js new file mode 100644 index 0000000000000000000000000000000000000000..2945257d11047d6bb396b2b1e2b2ae04ab5843ad --- /dev/null +++ b/node_modules/eslint/lib/rules/no-await-in-loop.js @@ -0,0 +1,115 @@ +/** + * @fileoverview Rule to disallow uses of await inside of loops. + * @author Nat Mote (nmote) + */ +"use strict"; + +/** + * Check whether it should stop traversing ancestors at the given node. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if it should stop traversing. + */ +function isBoundary(node) { + const t = node.type; + + return ( + t === "FunctionDeclaration" || + t === "FunctionExpression" || + t === "ArrowFunctionExpression" || + /* + * Don't report the await expressions on for-await-of loop since it's + * asynchronous iteration intentionally. + */ + (t === "ForOfStatement" && node.await === true) + ); +} + +/** + * Check whether the given node is in loop. + * @param {ASTNode} node A node to check. + * @param {ASTNode} parent A parent node to check. + * @returns {boolean} `true` if the node is in loop. + */ +function isLooped(node, parent) { + switch (parent.type) { + case "ForStatement": + return ( + node === parent.test || + node === parent.update || + node === parent.body + ); + + case "ForOfStatement": + case "ForInStatement": + return ( + node === parent.body || + (node === parent.left && node.kind === "await using") + ); + + case "WhileStatement": + case "DoWhileStatement": + return node === parent.test || node === parent.body; + + default: + return false; + } +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow `await` inside of loops", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-await-in-loop", + }, + + schema: [], + + messages: { + unexpectedAwait: "Unexpected `await` inside a loop.", + }, + }, + create(context) { + /** + * Validate an await expression. + * @param {ASTNode} awaitNode An AwaitExpression or ForOfStatement node to validate. + * @returns {void} + */ + function validate(awaitNode) { + if ( + awaitNode.type === "VariableDeclaration" && + awaitNode.kind !== "await using" + ) { + return; + } + + if (awaitNode.type === "ForOfStatement" && !awaitNode.await) { + return; + } + + let node = awaitNode; + let parent = node.parent; + + while (parent && !isBoundary(parent)) { + if (isLooped(node, parent)) { + context.report({ + node: awaitNode, + messageId: "unexpectedAwait", + }); + return; + } + node = parent; + parent = parent.parent; + } + } + + return { + AwaitExpression: validate, + ForOfStatement: validate, + VariableDeclaration: validate, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-bitwise.js b/node_modules/eslint/lib/rules/no-bitwise.js new file mode 100644 index 0000000000000000000000000000000000000000..10149ed618e99618776150b2c2daff859028e6f8 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-bitwise.js @@ -0,0 +1,145 @@ +/** + * @fileoverview Rule to flag bitwise identifiers + * @author Nicholas C. Zakas + */ + +"use strict"; + +/* + * + * Set of bitwise operators. + * + */ +const BITWISE_OPERATORS = [ + "^", + "|", + "&", + "<<", + ">>", + ">>>", + "^=", + "|=", + "&=", + "<<=", + ">>=", + ">>>=", + "~", +]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allow: [], + int32Hint: false, + }, + ], + + docs: { + description: "Disallow bitwise operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-bitwise", + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { + enum: BITWISE_OPERATORS, + }, + uniqueItems: true, + }, + int32Hint: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "Unexpected use of '{{operator}}'.", + }, + }, + + create(context) { + const [{ allow: allowed, int32Hint }] = context.options; + + /** + * Reports an unexpected use of a bitwise operator. + * @param {ASTNode} node Node which contains the bitwise operator. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "unexpected", + data: { operator: node.operator }, + }); + } + + /** + * Checks if the given node has a bitwise operator. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node has a bitwise operator. + */ + function hasBitwiseOperator(node) { + return BITWISE_OPERATORS.includes(node.operator); + } + + /** + * Checks if exceptions were provided, e.g. `{ allow: ['~', '|'] }`. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node has a bitwise operator. + */ + function allowedOperator(node) { + return allowed.includes(node.operator); + } + + /** + * Checks if the given bitwise operator is used for integer typecasting, i.e. "|0" + * @param {ASTNode} node The node to check. + * @returns {boolean} whether the node is used in integer typecasting. + */ + function isInt32Hint(node) { + return ( + int32Hint && + node.operator === "|" && + node.right && + node.right.type === "Literal" && + node.right.value === 0 + ); + } + + /** + * Report if the given node contains a bitwise operator. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNodeForBitwiseOperator(node) { + if ( + hasBitwiseOperator(node) && + !allowedOperator(node) && + !isInt32Hint(node) + ) { + report(node); + } + } + + return { + AssignmentExpression: checkNodeForBitwiseOperator, + BinaryExpression: checkNodeForBitwiseOperator, + UnaryExpression: checkNodeForBitwiseOperator, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-buffer-constructor.js b/node_modules/eslint/lib/rules/no-buffer-constructor.js new file mode 100644 index 0000000000000000000000000000000000000000..6a48b55737b1e3bbbc91a54a17a2b2b4d455d955 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-buffer-constructor.js @@ -0,0 +1,74 @@ +/** + * @fileoverview disallow use of the Buffer() constructor + * @author Teddy Katz + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-deprecated-api", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-deprecated-api.md", + }, + }, + ], + }, + + type: "problem", + + docs: { + description: "Disallow use of the `Buffer()` constructor", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-buffer-constructor", + }, + + schema: [], + + messages: { + deprecated: + "{{expr}} is deprecated. Use Buffer.from(), Buffer.alloc(), or Buffer.allocUnsafe() instead.", + }, + }, + + create(context) { + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + "CallExpression[callee.name='Buffer'], NewExpression[callee.name='Buffer']"( + node, + ) { + context.report({ + node, + messageId: "deprecated", + data: { + expr: + node.type === "CallExpression" + ? "Buffer()" + : "new Buffer()", + }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-caller.js b/node_modules/eslint/lib/rules/no-caller.js new file mode 100644 index 0000000000000000000000000000000000000000..50790ff0e179a1a865136fdbe0cd4f3466740e22 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-caller.js @@ -0,0 +1,52 @@ +/** + * @fileoverview Rule to flag use of arguments.callee and arguments.caller. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow the use of `arguments.caller` or `arguments.callee`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-caller", + }, + + schema: [], + + messages: { + unexpected: "Avoid arguments.{{prop}}.", + }, + }, + + create(context) { + return { + MemberExpression(node) { + const objectName = node.object.name, + propertyName = node.property.name; + + if ( + objectName === "arguments" && + !node.computed && + propertyName && + propertyName.match(/^calle[er]$/u) + ) { + context.report({ + node, + messageId: "unexpected", + data: { prop: propertyName }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-case-declarations.js b/node_modules/eslint/lib/rules/no-case-declarations.js new file mode 100644 index 0000000000000000000000000000000000000000..168594aad9dce8c26c7265e24dc217ac1ca10bcd --- /dev/null +++ b/node_modules/eslint/lib/rules/no-case-declarations.js @@ -0,0 +1,80 @@ +/** + * @fileoverview Rule to flag use of an lexical declarations inside a case clause + * @author Erik Arvidsson + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow lexical declarations in case clauses", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-case-declarations", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + addBrackets: "Add {} brackets around the case block.", + unexpected: "Unexpected lexical declaration in case block.", + }, + }, + + create(context) { + /** + * Checks whether or not a node is a lexical declaration. + * @param {ASTNode} node A direct child statement of a switch case. + * @returns {boolean} Whether or not the node is a lexical declaration. + */ + function isLexicalDeclaration(node) { + switch (node.type) { + case "FunctionDeclaration": + case "ClassDeclaration": + return true; + case "VariableDeclaration": + return node.kind !== "var"; + default: + return false; + } + } + + return { + SwitchCase(node) { + for (let i = 0; i < node.consequent.length; i++) { + const statement = node.consequent[i]; + + if (isLexicalDeclaration(statement)) { + context.report({ + node: statement, + messageId: "unexpected", + suggest: [ + { + messageId: "addBrackets", + fix: fixer => [ + fixer.insertTextBefore( + node.consequent[0], + "{ ", + ), + fixer.insertTextAfter( + node.consequent.at(-1), + " }", + ), + ], + }, + ], + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-catch-shadow.js b/node_modules/eslint/lib/rules/no-catch-shadow.js new file mode 100644 index 0000000000000000000000000000000000000000..b47ac324830551cae063e97e89fdfa4f385baac4 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-catch-shadow.js @@ -0,0 +1,96 @@ +/** + * @fileoverview Rule to flag variable leak in CatchClauses in IE 8 and earlier + * @author Ian Christian Myers + * @deprecated in ESLint v5.1.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `catch` clause parameters from shadowing variables in the outer scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-catch-shadow", + }, + + deprecated: { + message: "This rule was renamed.", + url: "https://eslint.org/blog/2018/07/eslint-v5.1.0-released/", + deprecatedSince: "5.1.0", + availableUntil: "11.0.0", + replacedBy: [ + { + rule: { + name: "no-shadow", + url: "https://eslint.org/docs/rules/no-shadow", + }, + }, + ], + }, + schema: [], + + messages: { + mutable: + "Value of '{{name}}' may be overwritten in IE 8 and earlier.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if the parameters are been shadowed + * @param {Object} scope current scope + * @param {string} name parameter name + * @returns {boolean} True is its been shadowed + */ + function paramIsShadowing(scope, name) { + return astUtils.getVariableByName(scope, name) !== null; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "CatchClause[param!=null]"(node) { + let scope = sourceCode.getScope(node); + + /* + * When ecmaVersion >= 6, CatchClause creates its own scope + * so start from one upper scope to exclude the current node + */ + if (scope.block === node) { + scope = scope.upper; + } + + if (paramIsShadowing(scope, node.param.name)) { + context.report({ + node, + messageId: "mutable", + data: { name: node.param.name }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-class-assign.js b/node_modules/eslint/lib/rules/no-class-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..649769598d3dd32f205d3c6fc2063e4e6ee7195b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-class-assign.js @@ -0,0 +1,66 @@ +/** + * @fileoverview A rule to disallow modifying variables of class declarations + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow reassigning class members", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-class-assign", + }, + + schema: [], + + messages: { + class: "'{{name}}' is a class.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + astUtils + .getModifyingReferences(variable.references) + .forEach(reference => { + context.report({ + node: reference.identifier, + messageId: "class", + data: { name: reference.identifier.name }, + }); + }); + } + + /** + * Finds and reports references that are non initializer and writable. + * @param {ASTNode} node A ClassDeclaration/ClassExpression node to check. + * @returns {void} + */ + function checkForClass(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + } + + return { + ClassDeclaration: checkForClass, + ClassExpression: checkForClass, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-compare-neg-zero.js b/node_modules/eslint/lib/rules/no-compare-neg-zero.js new file mode 100644 index 0000000000000000000000000000000000000000..a5683164f81ea076c2ec89af3ec2deb064c07236 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-compare-neg-zero.js @@ -0,0 +1,74 @@ +/** + * @fileoverview The rule should warn against code that tries to compare against -0. + * @author Aladdin-ADD + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow comparing against `-0`", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-compare-neg-zero", + }, + + fixable: null, + schema: [], + + messages: { + unexpected: + "Do not use the '{{operator}}' operator to compare against -0.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks a given node is -0 + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is -0. + */ + function isNegZero(node) { + return ( + node.type === "UnaryExpression" && + node.operator === "-" && + node.argument.type === "Literal" && + node.argument.value === 0 + ); + } + const OPERATORS_TO_CHECK = new Set([ + ">", + ">=", + "<", + "<=", + "==", + "===", + "!=", + "!==", + ]); + + return { + BinaryExpression(node) { + if (OPERATORS_TO_CHECK.has(node.operator)) { + if (isNegZero(node.left) || isNegZero(node.right)) { + context.report({ + node, + messageId: "unexpected", + data: { operator: node.operator }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-cond-assign.js b/node_modules/eslint/lib/rules/no-cond-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..a686e690a6712431a51b48c30e6077271a3e2791 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-cond-assign.js @@ -0,0 +1,175 @@ +/** + * @fileoverview Rule to flag assignment in a conditional statement's test expression + * @author Stephen Murray + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TEST_CONDITION_PARENT_TYPES = new Set([ + "IfStatement", + "WhileStatement", + "DoWhileStatement", + "ForStatement", + "ConditionalExpression", +]); + +const NODE_DESCRIPTIONS = { + DoWhileStatement: "a 'do...while' statement", + ForStatement: "a 'for' statement", + IfStatement: "an 'if' statement", + WhileStatement: "a 'while' statement", +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: ["except-parens"], + + docs: { + description: + "Disallow assignment operators in conditional expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-cond-assign", + }, + + schema: [ + { + enum: ["except-parens", "always"], + }, + ], + + messages: { + unexpected: "Unexpected assignment within {{type}}.", + + // must match JSHint's error message + missing: + "Expected a conditional expression and instead saw an assignment.", + }, + }, + + create(context) { + const [prohibitAssign] = context.options; + const sourceCode = context.sourceCode; + + /** + * Check whether an AST node is the test expression for a conditional statement. + * @param {!Object} node The node to test. + * @returns {boolean} `true` if the node is the text expression for a conditional statement; otherwise, `false`. + */ + function isConditionalTestExpression(node) { + return ( + node.parent && + TEST_CONDITION_PARENT_TYPES.has(node.parent.type) && + node === node.parent.test + ); + } + + /** + * Given an AST node, perform a bottom-up search for the first ancestor that represents a conditional statement. + * @param {!Object} node The node to use at the start of the search. + * @returns {?Object} The closest ancestor node that represents a conditional statement. + */ + function findConditionalAncestor(node) { + let currentAncestor = node; + + do { + if (isConditionalTestExpression(currentAncestor)) { + return currentAncestor.parent; + } + } while ( + (currentAncestor = currentAncestor.parent) && + !astUtils.isFunction(currentAncestor) + ); + + return null; + } + + /** + * Check whether the code represented by an AST node is enclosed in two sets of parentheses. + * @param {!Object} node The node to test. + * @returns {boolean} `true` if the code is enclosed in two sets of parentheses; otherwise, `false`. + */ + function isParenthesisedTwice(node) { + const previousToken = sourceCode.getTokenBefore(node, 1), + nextToken = sourceCode.getTokenAfter(node, 1); + + return ( + astUtils.isParenthesised(sourceCode, node) && + previousToken && + astUtils.isOpeningParenToken(previousToken) && + previousToken.range[1] <= node.range[0] && + astUtils.isClosingParenToken(nextToken) && + nextToken.range[0] >= node.range[1] + ); + } + + /** + * Check a conditional statement's test expression for top-level assignments that are not enclosed in parentheses. + * @param {!Object} node The node for the conditional statement. + * @returns {void} + */ + function testForAssign(node) { + if ( + node.test && + node.test.type === "AssignmentExpression" && + (node.type === "ForStatement" + ? !astUtils.isParenthesised(sourceCode, node.test) + : !isParenthesisedTwice(node.test)) + ) { + context.report({ + node: node.test, + messageId: "missing", + }); + } + } + + /** + * Check whether an assignment expression is descended from a conditional statement's test expression. + * @param {!Object} node The node for the assignment expression. + * @returns {void} + */ + function testForConditionalAncestor(node) { + const ancestor = findConditionalAncestor(node); + + if (ancestor) { + context.report({ + node, + messageId: "unexpected", + data: { + type: NODE_DESCRIPTIONS[ancestor.type] || ancestor.type, + }, + }); + } + } + + if (prohibitAssign === "always") { + return { + AssignmentExpression: testForConditionalAncestor, + }; + } + + return { + DoWhileStatement: testForAssign, + ForStatement: testForAssign, + IfStatement: testForAssign, + WhileStatement: testForAssign, + ConditionalExpression: testForAssign, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-confusing-arrow.js b/node_modules/eslint/lib/rules/no-confusing-arrow.js new file mode 100644 index 0000000000000000000000000000000000000000..1b3e7982888ce256bb06aea9d071e964d40cb34e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-confusing-arrow.js @@ -0,0 +1,127 @@ +/** + * @fileoverview A rule to warn against using arrow functions when they could be + * confused with comparisons + * @author Jxck + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils.js"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a node is a conditional expression. + * @param {ASTNode} node node to test + * @returns {boolean} `true` if the node is a conditional expression. + */ +function isConditional(node) { + return node && node.type === "ConditionalExpression"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "no-confusing-arrow", + url: "https://eslint.style/rules/no-confusing-arrow", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: + "Disallow arrow functions where they could be confused with comparisons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-confusing-arrow", + }, + + fixable: "code", + + schema: [ + { + type: "object", + properties: { + allowParens: { type: "boolean", default: true }, + onlyOneSimpleParam: { type: "boolean", default: false }, + }, + additionalProperties: false, + }, + ], + + messages: { + confusing: + "Arrow function used ambiguously with a conditional expression.", + }, + }, + + create(context) { + const config = context.options[0] || {}; + const allowParens = config.allowParens || config.allowParens === void 0; + const onlyOneSimpleParam = config.onlyOneSimpleParam; + const sourceCode = context.sourceCode; + + /** + * Reports if an arrow function contains an ambiguous conditional. + * @param {ASTNode} node A node to check and report. + * @returns {void} + */ + function checkArrowFunc(node) { + const body = node.body; + + if ( + isConditional(body) && + !(allowParens && astUtils.isParenthesised(sourceCode, body)) && + !( + onlyOneSimpleParam && + !( + node.params.length === 1 && + node.params[0].type === "Identifier" + ) + ) + ) { + context.report({ + node, + messageId: "confusing", + fix(fixer) { + // if `allowParens` is not set to true don't bother wrapping in parens + return ( + allowParens && + fixer.replaceText( + node.body, + `(${sourceCode.getText(node.body)})`, + ) + ); + }, + }); + } + } + + return { + ArrowFunctionExpression: checkArrowFunc, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-console.js b/node_modules/eslint/lib/rules/no-console.js new file mode 100644 index 0000000000000000000000000000000000000000..b7eacd98bde8d358171b481b08c8bd1edf189c34 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-console.js @@ -0,0 +1,227 @@ +/** + * @fileoverview Rule to flag use of console object + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Reference} Reference */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{}], + + docs: { + description: "Disallow the use of `console`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-console", + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { + type: "string", + }, + minItems: 1, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + hasSuggestions: true, + + messages: { + unexpected: "Unexpected console statement.", + limited: + "Unexpected console statement. Only these console methods are allowed: {{ allowed }}.", + removeConsole: "Remove the console.{{ propertyName }}().", + removeMethodCall: "Remove the console method call.", + }, + }, + + create(context) { + const [{ allow: allowed = [] }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Checks whether the given reference is 'console' or not. + * @param {Reference} reference The reference to check. + * @returns {boolean} `true` if the reference is 'console'. + */ + function isConsole(reference) { + const id = reference.identifier; + + return id && id.name === "console"; + } + + /** + * Checks whether the property name of the given MemberExpression node + * is allowed by options or not. + * @param {ASTNode} node The MemberExpression node to check. + * @returns {boolean} `true` if the property name of the node is allowed. + */ + function isAllowed(node) { + const propertyName = astUtils.getStaticPropertyName(node); + + return propertyName && allowed.includes(propertyName); + } + + /** + * Checks whether the given reference is a member access which is not + * allowed by options or not. + * @param {Reference} reference The reference to check. + * @returns {boolean} `true` if the reference is a member access which + * is not allowed by options. + */ + function isMemberAccessExceptAllowed(reference) { + const node = reference.identifier; + const parent = node.parent; + + return ( + parent.type === "MemberExpression" && + parent.object === node && + !isAllowed(parent) + ); + } + + /** + * Checks if removing the ExpressionStatement node will cause ASI to + * break. + * eg. + * foo() + * console.log(); + * [1, 2, 3].forEach(a => doSomething(a)) + * + * Removing the console.log(); statement should leave two statements, but + * here the two statements will become one because [ causes continuation after + * foo(). + * @param {ASTNode} node The ExpressionStatement node to check. + * @returns {boolean} `true` if ASI will break after removing the ExpressionStatement + * node. + */ + function maybeAsiHazard(node) { + const SAFE_TOKENS_BEFORE = /^[:;{]$/u; // One of :;{ + const UNSAFE_CHARS_AFTER = /^[-[(/+`]/u; // One of [(/+-` + + const tokenBefore = sourceCode.getTokenBefore(node); + const tokenAfter = sourceCode.getTokenAfter(node); + + return ( + Boolean(tokenAfter) && + UNSAFE_CHARS_AFTER.test(tokenAfter.value) && + tokenAfter.value !== "++" && + tokenAfter.value !== "--" && + Boolean(tokenBefore) && + !SAFE_TOKENS_BEFORE.test(tokenBefore.value) + ); + } + + /** + * Checks if the MemberExpression node's parent.parent.parent is a + * Program, BlockStatement, StaticBlock, or SwitchCase node. This check + * is necessary to avoid providing a suggestion that might cause a syntax error. + * + * eg. if (a) console.log(b), removing console.log() here will lead to a + * syntax error. + * if (a) { console.log(b) }, removing console.log() here is acceptable. + * + * Additionally, it checks if the callee of the CallExpression node is + * the node itself. + * + * eg. foo(console.log), cannot provide a suggestion here. + * @param {ASTNode} node The MemberExpression node to check. + * @returns {boolean} `true` if a suggestion can be provided for a node. + */ + function canProvideSuggestions(node) { + return ( + node.parent.type === "CallExpression" && + node.parent.callee === node && + node.parent.parent.type === "ExpressionStatement" && + astUtils.STATEMENT_LIST_PARENTS.has( + node.parent.parent.parent.type, + ) && + !maybeAsiHazard(node.parent.parent) + ); + } + + /** + * Reports the given reference as a violation. + * @param {Reference} reference The reference to report. + * @returns {void} + */ + function report(reference) { + const node = reference.identifier.parent; + + const suggest = []; + + if (canProvideSuggestions(node)) { + const suggestion = { + fix(fixer) { + return fixer.remove(node.parent.parent); + }, + }; + + if (node.computed) { + suggestion.messageId = "removeMethodCall"; + } else { + suggestion.messageId = "removeConsole"; + suggestion.data = { propertyName: node.property.name }; + } + suggest.push(suggestion); + } + context.report({ + node, + loc: node.loc, + messageId: allowed.length ? "limited" : "unexpected", + data: { allowed: allowed.join(", ") }, + suggest, + }); + } + + return { + "Program:exit"(node) { + const scope = sourceCode.getScope(node); + const consoleVar = astUtils.getVariableByName(scope, "console"); + const shadowed = consoleVar && consoleVar.defs.length > 0; + + /* + * 'scope.through' includes all references to undefined + * variables. If the variable 'console' is not defined, it uses + * 'scope.through'. + */ + const references = consoleVar + ? consoleVar.references + : scope.through.filter(isConsole); + + if (!shadowed) { + references + .filter(isMemberAccessExceptAllowed) + .forEach(report); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-const-assign.js b/node_modules/eslint/lib/rules/no-const-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..5e126c80e327e13011db54655e58061da19834d2 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-const-assign.js @@ -0,0 +1,73 @@ +/** + * @fileoverview A rule to disallow modifying variables that are declared using `const` + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const CONSTANT_BINDINGS = new Set(["const", "using", "await using"]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow reassigning `const`, `using`, and `await using` variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-const-assign", + }, + + schema: [], + + messages: { + const: "'{{name}}' is constant.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + astUtils + .getModifyingReferences(variable.references) + .forEach(reference => { + context.report({ + node: reference.identifier, + messageId: "const", + data: { name: reference.identifier.name }, + }); + }); + } + + return { + VariableDeclaration(node) { + if (CONSTANT_BINDINGS.has(node.kind)) { + sourceCode + .getDeclaredVariables(node) + .forEach(checkVariable); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-constant-binary-expression.js b/node_modules/eslint/lib/rules/no-constant-binary-expression.js new file mode 100644 index 0000000000000000000000000000000000000000..e360631147e2fff316646ef6dbdd2512f3de5945 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-constant-binary-expression.js @@ -0,0 +1,603 @@ +/** + * @fileoverview Rule to flag constant comparisons and logical expressions that always/never short circuit + * @author Jordan Eldredge + */ + +"use strict"; + +const { + isNullLiteral, + isConstant, + isReferenceToGlobalVariable, + isLogicalAssignmentOperator, + ECMASCRIPT_GLOBALS, +} = require("./utils/ast-utils"); + +const NUMERIC_OR_STRING_BINARY_OPERATORS = new Set([ + "+", + "-", + "*", + "/", + "%", + "|", + "^", + "&", + "**", + "<<", + ">>", + ">>>", +]); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a node is `null` or `undefined`. Similar to the one + * found in ast-utils.js, but this one correctly handles the edge case that + * `undefined` has been redefined. + * @param {Scope} scope Scope in which the expression was found. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `null` or `undefined`. + * @public + */ +function isNullOrUndefined(scope, node) { + return ( + isNullLiteral(node) || + (node.type === "Identifier" && + node.name === "undefined" && + isReferenceToGlobalVariable(scope, node)) || + (node.type === "UnaryExpression" && node.operator === "void") + ); +} + +/** + * Test if an AST node has a statically knowable constant nullishness. Meaning, + * it will always resolve to a constant value of either: `null`, `undefined` + * or not `null` _or_ `undefined`. An expression that can vary between those + * three states at runtime would return `false`. + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The AST node being tested. + * @param {boolean} nonNullish if `true` then nullish values are not considered constant. + * @returns {boolean} Does `node` have constant nullishness? + */ +function hasConstantNullishness(scope, node, nonNullish) { + if (nonNullish && isNullOrUndefined(scope, node)) { + return false; + } + + switch (node.type) { + case "ObjectExpression": // Objects are never nullish + case "ArrayExpression": // Arrays are never nullish + case "ArrowFunctionExpression": // Functions never nullish + case "FunctionExpression": // Functions are never nullish + case "ClassExpression": // Classes are never nullish + case "NewExpression": // Objects are never nullish + case "Literal": // Nullish, or non-nullish, literals never change + case "TemplateLiteral": // A string is never nullish + case "UpdateExpression": // Numbers are never nullish + case "BinaryExpression": // Numbers, strings, or booleans are never nullish + return true; + case "CallExpression": { + if (node.callee.type !== "Identifier") { + return false; + } + const functionName = node.callee.name; + + return ( + (functionName === "Boolean" || + functionName === "String" || + functionName === "Number") && + isReferenceToGlobalVariable(scope, node.callee) + ); + } + case "LogicalExpression": { + return ( + node.operator === "??" && + hasConstantNullishness(scope, node.right, true) + ); + } + case "AssignmentExpression": + if (node.operator === "=") { + return hasConstantNullishness(scope, node.right, nonNullish); + } + + /* + * Handling short-circuiting assignment operators would require + * walking the scope. We won't attempt that (for now...) / + */ + if (isLogicalAssignmentOperator(node.operator)) { + return false; + } + + /* + * The remaining assignment expressions all result in a numeric or + * string (non-nullish) value: + * "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&=" + */ + + return true; + case "UnaryExpression": + /* + * "void" Always returns `undefined` + * "typeof" All types are strings, and thus non-nullish + * "!" Boolean is never nullish + * "delete" Returns a boolean, which is never nullish + * Math operators always return numbers or strings, neither of which + * are non-nullish "+", "-", "~" + */ + + return true; + case "SequenceExpression": { + const last = node.expressions.at(-1); + + return hasConstantNullishness(scope, last, nonNullish); + } + case "Identifier": + return ( + node.name === "undefined" && + isReferenceToGlobalVariable(scope, node) + ); + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + +/** + * Test if an AST node is a boolean value that never changes. Specifically we + * test for: + * 1. Literal booleans (`true` or `false`) + * 2. Unary `!` expressions with a constant value + * 3. Constant booleans created via the `Boolean` global function + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The node to test + * @returns {boolean} Is `node` guaranteed to be a boolean? + */ +function isStaticBoolean(scope, node) { + switch (node.type) { + case "Literal": + return typeof node.value === "boolean"; + case "CallExpression": + return ( + node.callee.type === "Identifier" && + node.callee.name === "Boolean" && + isReferenceToGlobalVariable(scope, node.callee) && + (node.arguments.length === 0 || + isConstant(scope, node.arguments[0], true)) + ); + case "UnaryExpression": + return ( + node.operator === "!" && isConstant(scope, node.argument, true) + ); + default: + return false; + } +} + +/** + * Test if an AST node will always give the same result when compared to a + * boolean value. Note that comparison to boolean values is different than + * truthiness. + * https://262.ecma-international.org/5.1/#sec-11.9.3 + * + * JavaScript `==` operator works by converting the boolean to `1` (true) or + * `+0` (false) and then checks the values `==` equality to that number. + * @param {Scope} scope The scope in which node was found. + * @param {ASTNode} node The node to test. + * @returns {boolean} Will `node` always coerce to the same boolean value? + */ +function hasConstantLooseBooleanComparison(scope, node) { + switch (node.type) { + case "ObjectExpression": + case "ClassExpression": + /** + * In theory objects like: + * + * `{toString: () => a}` + * `{valueOf: () => a}` + * + * Or a classes like: + * + * `class { static toString() { return a } }` + * `class { static valueOf() { return a } }` + * + * Are not constant verifiably when `inBooleanPosition` is + * false, but it's an edge case we've opted not to handle. + */ + return true; + case "ArrayExpression": { + const nonSpreadElements = node.elements.filter( + e => + // Elements can be `null` in sparse arrays: `[,,]`; + e !== null && e.type !== "SpreadElement", + ); + + /* + * Possible future direction if needed: We could check if the + * single value would result in variable boolean comparison. + * For now we will err on the side of caution since `[x]` could + * evaluate to `[0]` or `[1]`. + */ + return node.elements.length === 0 || nonSpreadElements.length > 1; + } + case "ArrowFunctionExpression": + case "FunctionExpression": + return true; + case "UnaryExpression": + if ( + node.operator === "void" || // Always returns `undefined` + node.operator === "typeof" // All `typeof` strings, when coerced to number, are not 0 or 1. + ) { + return true; + } + if (node.operator === "!") { + return isConstant(scope, node.argument, true); + } + + /* + * We won't try to reason about +, -, ~, or delete + * In theory, for the mathematical operators, we could look at the + * argument and try to determine if it coerces to a constant numeric + * value. + */ + return false; + case "NewExpression": // Objects might have custom `.valueOf` or `.toString`. + return false; + case "CallExpression": { + if ( + node.callee.type === "Identifier" && + node.callee.name === "Boolean" && + isReferenceToGlobalVariable(scope, node.callee) + ) { + return ( + node.arguments.length === 0 || + isConstant(scope, node.arguments[0], true) + ); + } + return false; + } + case "Literal": // True or false, literals never change + return true; + case "Identifier": + return ( + node.name === "undefined" && + isReferenceToGlobalVariable(scope, node) + ); + case "TemplateLiteral": + /* + * In theory we could try to check if the quasi are sufficient to + * prove that the expression will always be true, but it would be + * tricky to get right. For example: `000.${foo}000` + */ + return node.expressions.length === 0; + case "AssignmentExpression": + if (node.operator === "=") { + return hasConstantLooseBooleanComparison(scope, node.right); + } + + /* + * Handling short-circuiting assignment operators would require + * walking the scope. We won't attempt that (for now...) + * + * The remaining assignment expressions all result in a numeric or + * string (non-nullish) values which could be truthy or falsy: + * "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&=" + */ + return false; + case "SequenceExpression": { + const last = node.expressions.at(-1); + + return hasConstantLooseBooleanComparison(scope, last); + } + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + +/** + * Test if an AST node will always give the same result when _strictly_ compared + * to a boolean value. This can happen if the expression can never be boolean, or + * if it is always the same boolean value. + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The node to test + * @returns {boolean} Will `node` always give the same result when compared to a + * static boolean value? + */ +function hasConstantStrictBooleanComparison(scope, node) { + switch (node.type) { + case "ObjectExpression": // Objects are not booleans + case "ArrayExpression": // Arrays are not booleans + case "ArrowFunctionExpression": // Functions are not booleans + case "FunctionExpression": + case "ClassExpression": // Classes are not booleans + case "NewExpression": // Objects are not booleans + case "TemplateLiteral": // Strings are not booleans + case "Literal": // True, false, or not boolean, literals never change. + case "UpdateExpression": // Numbers are not booleans + return true; + case "BinaryExpression": + return NUMERIC_OR_STRING_BINARY_OPERATORS.has(node.operator); + case "UnaryExpression": { + if (node.operator === "delete") { + return false; + } + if (node.operator === "!") { + return isConstant(scope, node.argument, true); + } + + /* + * The remaining operators return either strings or numbers, neither + * of which are boolean. + */ + return true; + } + case "SequenceExpression": { + const last = node.expressions.at(-1); + + return hasConstantStrictBooleanComparison(scope, last); + } + case "Identifier": + return ( + node.name === "undefined" && + isReferenceToGlobalVariable(scope, node) + ); + case "AssignmentExpression": + if (node.operator === "=") { + return hasConstantStrictBooleanComparison(scope, node.right); + } + + /* + * Handling short-circuiting assignment operators would require + * walking the scope. We won't attempt that (for now...) + */ + if (isLogicalAssignmentOperator(node.operator)) { + return false; + } + + /* + * The remaining assignment expressions all result in either a number + * or a string, neither of which can ever be boolean. + */ + return true; + case "CallExpression": { + if (node.callee.type !== "Identifier") { + return false; + } + const functionName = node.callee.name; + + if ( + (functionName === "String" || functionName === "Number") && + isReferenceToGlobalVariable(scope, node.callee) + ) { + return true; + } + if ( + functionName === "Boolean" && + isReferenceToGlobalVariable(scope, node.callee) + ) { + return ( + node.arguments.length === 0 || + isConstant(scope, node.arguments[0], true) + ); + } + return false; + } + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + +/** + * Test if an AST node will always result in a newly constructed object + * @param {Scope} scope The scope in which the node was found. + * @param {ASTNode} node The node to test + * @returns {boolean} Will `node` always be new? + */ +function isAlwaysNew(scope, node) { + switch (node.type) { + case "ObjectExpression": + case "ArrayExpression": + case "ArrowFunctionExpression": + case "FunctionExpression": + case "ClassExpression": + return true; + case "NewExpression": { + if (node.callee.type !== "Identifier") { + return false; + } + + /* + * All the built-in constructors are always new, but + * user-defined constructors could return a sentinel + * object. + * + * Catching these is especially useful for primitive constructors + * which return boxed values, a surprising gotcha' in JavaScript. + */ + return ( + Object.hasOwn(ECMASCRIPT_GLOBALS, node.callee.name) && + isReferenceToGlobalVariable(scope, node.callee) + ); + } + case "Literal": + // Regular expressions are objects, and thus always new + return typeof node.regex === "object"; + case "SequenceExpression": { + const last = node.expressions.at(-1); + + return isAlwaysNew(scope, last); + } + case "AssignmentExpression": + if (node.operator === "=") { + return isAlwaysNew(scope, node.right); + } + return false; + case "ConditionalExpression": + return ( + isAlwaysNew(scope, node.consequent) && + isAlwaysNew(scope, node.alternate) + ); + case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior. + case "JSXFragment": + return false; + default: + return false; + } +} + +/** + * Checks if one operand will cause the result to be constant. + * @param {Scope} scope Scope in which the expression was found. + * @param {ASTNode} a One side of the expression + * @param {ASTNode} b The other side of the expression + * @param {string} operator The binary expression operator + * @returns {ASTNode | null} The node which will cause the expression to have a constant result. + */ +function findBinaryExpressionConstantOperand(scope, a, b, operator) { + if (operator === "==" || operator === "!=") { + if ( + (isNullOrUndefined(scope, a) && + hasConstantNullishness(scope, b, false)) || + (isStaticBoolean(scope, a) && + hasConstantLooseBooleanComparison(scope, b)) + ) { + return b; + } + } else if (operator === "===" || operator === "!==") { + if ( + (isNullOrUndefined(scope, a) && + hasConstantNullishness(scope, b, false)) || + (isStaticBoolean(scope, a) && + hasConstantStrictBooleanComparison(scope, b)) + ) { + return b; + } + } + return null; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + docs: { + description: + "Disallow expressions where the operation doesn't affect the value", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-constant-binary-expression", + }, + schema: [], + messages: { + constantBinaryOperand: + "Unexpected constant binary expression. Compares constantly with the {{otherSide}}-hand side of the `{{operator}}`.", + constantShortCircuit: + "Unexpected constant {{property}} on the left-hand side of a `{{operator}}` expression.", + alwaysNew: + "Unexpected comparison to newly constructed object. These two values can never be equal.", + bothAlwaysNew: + "Unexpected comparison of two newly constructed objects. These two values can never be equal.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + LogicalExpression(node) { + const { operator, left } = node; + const scope = sourceCode.getScope(node); + + if ( + (operator === "&&" || operator === "||") && + isConstant(scope, left, true) + ) { + context.report({ + node: left, + messageId: "constantShortCircuit", + data: { property: "truthiness", operator }, + }); + } else if ( + operator === "??" && + hasConstantNullishness(scope, left, false) + ) { + context.report({ + node: left, + messageId: "constantShortCircuit", + data: { property: "nullishness", operator }, + }); + } + }, + BinaryExpression(node) { + const scope = sourceCode.getScope(node); + const { right, left, operator } = node; + const rightConstantOperand = + findBinaryExpressionConstantOperand( + scope, + left, + right, + operator, + ); + const leftConstantOperand = findBinaryExpressionConstantOperand( + scope, + right, + left, + operator, + ); + + if (rightConstantOperand) { + context.report({ + node: rightConstantOperand, + messageId: "constantBinaryOperand", + data: { operator, otherSide: "left" }, + }); + } else if (leftConstantOperand) { + context.report({ + node: leftConstantOperand, + messageId: "constantBinaryOperand", + data: { operator, otherSide: "right" }, + }); + } else if (operator === "===" || operator === "!==") { + if (isAlwaysNew(scope, left)) { + context.report({ node: left, messageId: "alwaysNew" }); + } else if (isAlwaysNew(scope, right)) { + context.report({ node: right, messageId: "alwaysNew" }); + } + } else if (operator === "==" || operator === "!=") { + /* + * If both sides are "new", then both sides are objects and + * therefore they will be compared by reference even with `==` + * equality. + */ + if (isAlwaysNew(scope, left) && isAlwaysNew(scope, right)) { + context.report({ + node: left, + messageId: "bothAlwaysNew", + }); + } + } + }, + + /* + * In theory we could handle short-circuiting assignment operators, + * for some constant values, but that would require walking the + * scope to find the value of the variable being assigned. This is + * dependent on https://github.com/eslint/eslint/issues/13776 + * + * AssignmentExpression() {}, + */ + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-constant-condition.js b/node_modules/eslint/lib/rules/no-constant-condition.js new file mode 100644 index 0000000000000000000000000000000000000000..4ecd5a3d2e74fd70234dd9e20d4163d93246d7e2 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-constant-condition.js @@ -0,0 +1,177 @@ +/** + * @fileoverview Rule to flag use constant conditions + * @author Christian Schulz + */ + +"use strict"; + +const { isConstant } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [{ checkLoops: "allExceptWhileTrue" }], + + docs: { + description: "Disallow constant expressions in conditions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-constant-condition", + }, + + schema: [ + { + type: "object", + properties: { + checkLoops: { + enum: [ + "all", + "allExceptWhileTrue", + "none", + true, + false, + ], + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "Unexpected constant condition.", + }, + }, + + create(context) { + const loopSetStack = []; + const sourceCode = context.sourceCode; + let [{ checkLoops }] = context.options; + + if (checkLoops === true) { + checkLoops = "all"; + } else if (checkLoops === false) { + checkLoops = "none"; + } + + let loopsInCurrentScope = new Set(); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Tracks when the given node contains a constant condition. + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function trackConstantConditionLoop(node) { + if ( + node.test && + isConstant(sourceCode.getScope(node), node.test, true) + ) { + loopsInCurrentScope.add(node); + } + } + + /** + * Reports when the set contains the given constant condition node + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function checkConstantConditionLoopInSet(node) { + if (loopsInCurrentScope.has(node)) { + loopsInCurrentScope.delete(node); + context.report({ node: node.test, messageId: "unexpected" }); + } + } + + /** + * Reports when the given node contains a constant condition. + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function reportIfConstant(node) { + if ( + node.test && + isConstant(sourceCode.getScope(node), node.test, true) + ) { + context.report({ node: node.test, messageId: "unexpected" }); + } + } + + /** + * Stores current set of constant loops in loopSetStack temporarily + * and uses a new set to track constant loops + * @returns {void} + * @private + */ + function enterFunction() { + loopSetStack.push(loopsInCurrentScope); + loopsInCurrentScope = new Set(); + } + + /** + * Reports when the set still contains stored constant conditions + * @returns {void} + * @private + */ + function exitFunction() { + loopsInCurrentScope = loopSetStack.pop(); + } + + /** + * Checks node when checkLoops option is enabled + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function checkLoop(node) { + if (checkLoops === "all" || checkLoops === "allExceptWhileTrue") { + trackConstantConditionLoop(node); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ConditionalExpression: reportIfConstant, + IfStatement: reportIfConstant, + WhileStatement(node) { + if ( + node.test.type === "Literal" && + node.test.value === true && + checkLoops === "allExceptWhileTrue" + ) { + return; + } + + checkLoop(node); + }, + "WhileStatement:exit": checkConstantConditionLoopInSet, + DoWhileStatement: checkLoop, + "DoWhileStatement:exit": checkConstantConditionLoopInSet, + ForStatement: checkLoop, + "ForStatement > .test": node => checkLoop(node.parent), + "ForStatement:exit": checkConstantConditionLoopInSet, + FunctionDeclaration: enterFunction, + "FunctionDeclaration:exit": exitFunction, + FunctionExpression: enterFunction, + "FunctionExpression:exit": exitFunction, + YieldExpression: () => loopsInCurrentScope.clear(), + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-constructor-return.js b/node_modules/eslint/lib/rules/no-constructor-return.js new file mode 100644 index 0000000000000000000000000000000000000000..ed9e03db4348c9283d8d6fbe48f3e70d77131187 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-constructor-return.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Rule to disallow returning value from constructor. + * @author Pig Fang + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow returning value from constructor", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-constructor-return", + }, + + schema: [], + + fixable: null, + + messages: { + unexpected: "Unexpected return statement in constructor.", + }, + }, + + create(context) { + const stack = []; + + return { + onCodePathStart(_, node) { + stack.push(node); + }, + onCodePathEnd() { + stack.pop(); + }, + ReturnStatement(node) { + const last = stack.at(-1); + + if (!last.parent) { + return; + } + + if ( + last.parent.type === "MethodDefinition" && + last.parent.kind === "constructor" && + node.argument + ) { + context.report({ + node, + messageId: "unexpected", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-continue.js b/node_modules/eslint/lib/rules/no-continue.js new file mode 100644 index 0000000000000000000000000000000000000000..6671c619b9d5cf295558b0ce5ded7657d590a81f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-continue.js @@ -0,0 +1,38 @@ +/** + * @fileoverview Rule to flag use of continue statement + * @author Borislav Zhivkov + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `continue` statements", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-continue", + }, + + schema: [], + + messages: { + unexpected: "Unexpected use of continue statement.", + }, + }, + + create(context) { + return { + ContinueStatement(node) { + context.report({ node, messageId: "unexpected" }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-control-regex.js b/node_modules/eslint/lib/rules/no-control-regex.js new file mode 100644 index 0000000000000000000000000000000000000000..a0221b4b4308fd60d1d7e8d38903497b46511035 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-control-regex.js @@ -0,0 +1,142 @@ +/** + * @fileoverview Rule to forbid control characters from regular expressions. + * @author Nicholas C. Zakas + */ + +"use strict"; + +const RegExpValidator = require("@eslint-community/regexpp").RegExpValidator; +const collector = new (class { + constructor() { + this._source = ""; + this._controlChars = []; + this._validator = new RegExpValidator(this); + } + + onPatternEnter() { + /* + * `RegExpValidator` may parse the pattern twice in one `validatePattern`. + * So `this._controlChars` should be cleared here as well. + * + * For example, the `/(?\x1f)/` regex will parse the pattern twice. + * This is based on the content described in Annex B. + * If the regex contains a `GroupName` and the `u` flag is not used, `ParseText` will be called twice. + * See https://tc39.es/ecma262/2023/multipage/additional-ecmascript-features-for-web-browsers.html#sec-parsepattern-annexb + */ + this._controlChars = []; + } + + onCharacter(start, end, cp) { + if ( + cp >= 0x00 && + cp <= 0x1f && + (this._source.codePointAt(start) === cp || + this._source.slice(start, end).startsWith("\\x") || + this._source.slice(start, end).startsWith("\\u")) + ) { + this._controlChars.push(`\\x${`0${cp.toString(16)}`.slice(-2)}`); + } + } + + collectControlChars(regexpStr, flags) { + const uFlag = typeof flags === "string" && flags.includes("u"); + const vFlag = typeof flags === "string" && flags.includes("v"); + + this._controlChars = []; + this._source = regexpStr; + + try { + this._validator.validatePattern(regexpStr, void 0, void 0, { + unicode: uFlag, + unicodeSets: vFlag, + }); // Call onCharacter hook + } catch { + // Ignore syntax errors in RegExp. + } + return this._controlChars; + } +})(); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow control characters in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-control-regex", + }, + + schema: [], + + messages: { + unexpected: + "Unexpected control character(s) in regular expression: {{controlChars}}.", + }, + }, + + create(context) { + /** + * Get the regex expression + * @param {ASTNode} node `Literal` node to evaluate + * @returns {{ pattern: string, flags: string | null } | null} Regex if found (the given node is either a regex literal + * or a string literal that is the pattern argument of a RegExp constructor call). Otherwise `null`. If flags cannot be determined, + * the `flags` property will be `null`. + * @private + */ + function getRegExp(node) { + if (node.regex) { + return node.regex; + } + if ( + typeof node.value === "string" && + (node.parent.type === "NewExpression" || + node.parent.type === "CallExpression") && + node.parent.callee.type === "Identifier" && + node.parent.callee.name === "RegExp" && + node.parent.arguments[0] === node + ) { + const pattern = node.value; + const flags = + node.parent.arguments.length > 1 && + node.parent.arguments[1].type === "Literal" && + typeof node.parent.arguments[1].value === "string" + ? node.parent.arguments[1].value + : null; + + return { pattern, flags }; + } + + return null; + } + + return { + Literal(node) { + const regExp = getRegExp(node); + + if (regExp) { + const { pattern, flags } = regExp; + const controlCharacters = collector.collectControlChars( + pattern, + flags, + ); + + if (controlCharacters.length > 0) { + context.report({ + node, + messageId: "unexpected", + data: { + controlChars: controlCharacters.join(", "), + }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-debugger.js b/node_modules/eslint/lib/rules/no-debugger.js new file mode 100644 index 0000000000000000000000000000000000000000..66bc1be1e620dff02e548ae8f0f58a20cfee0db9 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-debugger.js @@ -0,0 +1,41 @@ +/** + * @fileoverview Rule to flag use of a debugger statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow the use of `debugger`", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-debugger", + }, + + fixable: null, + schema: [], + + messages: { + unexpected: "Unexpected 'debugger' statement.", + }, + }, + + create(context) { + return { + DebuggerStatement(node) { + context.report({ + node, + messageId: "unexpected", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-delete-var.js b/node_modules/eslint/lib/rules/no-delete-var.js new file mode 100644 index 0000000000000000000000000000000000000000..7dfe002af4cc161c9a431fe706b5d3aff094e1f1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-delete-var.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Rule to flag when deleting variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow deleting variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-delete-var", + }, + + schema: [], + + messages: { + unexpected: "Variables should not be deleted.", + }, + }, + + create(context) { + return { + UnaryExpression(node) { + if ( + node.operator === "delete" && + node.argument.type === "Identifier" + ) { + context.report({ node, messageId: "unexpected" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-div-regex.js b/node_modules/eslint/lib/rules/no-div-regex.js new file mode 100644 index 0000000000000000000000000000000000000000..69845bbda93ef1ea00325dadec38abd8be2e1d39 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-div-regex.js @@ -0,0 +1,60 @@ +/** + * @fileoverview Rule to check for ambiguous div operator in regexes + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow equal signs explicitly at the beginning of regular expressions", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-div-regex", + }, + + fixable: "code", + + schema: [], + + messages: { + unexpected: + "A regular expression literal can be confused with '/='.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Literal(node) { + const token = sourceCode.getFirstToken(node); + + if ( + token.type === "RegularExpression" && + token.value[1] === "=" + ) { + context.report({ + node, + messageId: "unexpected", + fix(fixer) { + return fixer.replaceTextRange( + [token.range[0] + 1, token.range[0] + 2], + "[=]", + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-args.js b/node_modules/eslint/lib/rules/no-dupe-args.js new file mode 100644 index 0000000000000000000000000000000000000000..45629efa959860f491c36a5262bb730d6a376c59 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-args.js @@ -0,0 +1,98 @@ +/** + * @fileoverview Rule to flag duplicate arguments + * @author Jamund Ferguson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Definition} Definition */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow duplicate arguments in `function` definitions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-args", + }, + + schema: [], + + messages: { + unexpected: "Duplicate param '{{name}}'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks whether or not a given definition is a parameter's. + * @param {Definition} def A definition to check. + * @returns {boolean} `true` if the definition is a parameter's. + */ + function isParameter(def) { + return def.type === "Parameter"; + } + + /** + * Determines if a given node has duplicate parameters. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkParams(node) { + const variables = sourceCode.getDeclaredVariables(node); + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + + // Checks and reports duplications. + const defs = variable.defs.filter(isParameter); + const loc = { + start: astUtils.getOpeningParenOfParams(node, sourceCode) + .loc.start, + end: sourceCode.getTokenBefore(node.body).loc.end, + }; + + if (defs.length >= 2) { + context.report({ + loc, + messageId: "unexpected", + data: { name: variable.name }, + }); + } + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: checkParams, + FunctionExpression: checkParams, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-class-members.js b/node_modules/eslint/lib/rules/no-dupe-class-members.js new file mode 100644 index 0000000000000000000000000000000000000000..2d38d6e66605339383301ff359b1da5d78372e1d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-class-members.js @@ -0,0 +1,116 @@ +/** + * @fileoverview A rule to disallow duplicate name in class members. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate class members", + dialects: ["JavaScript", "TypeScript"], + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-class-members", + }, + + schema: [], + + messages: { + unexpected: "Duplicate name '{{name}}'.", + }, + }, + + create(context) { + let stack = []; + + /** + * Gets state of a given member name. + * @param {string} name A name of a member. + * @param {boolean} isStatic A flag which specifies that is a static member. + * @returns {Object} A state of a given member name. + * - retv.init {boolean} A flag which shows the name is declared as normal member. + * - retv.get {boolean} A flag which shows the name is declared as getter. + * - retv.set {boolean} A flag which shows the name is declared as setter. + */ + function getState(name, isStatic) { + const stateMap = stack.at(-1); + const key = `$${name}`; // to avoid "__proto__". + + if (!stateMap[key]) { + stateMap[key] = { + nonStatic: { init: false, get: false, set: false }, + static: { init: false, get: false, set: false }, + }; + } + + return stateMap[key][isStatic ? "static" : "nonStatic"]; + } + + return { + // Initializes the stack of state of member declarations. + Program() { + stack = []; + }, + + // Initializes state of member declarations for the class. + ClassBody() { + stack.push(Object.create(null)); + }, + + // Disposes the state for the class. + "ClassBody:exit"() { + stack.pop(); + }, + + // Reports the node if its name has been declared already. + "MethodDefinition, PropertyDefinition"(node) { + if ( + node.value && + node.value.type === "TSEmptyBodyFunctionExpression" + ) { + return; + } + + const name = astUtils.getStaticPropertyName(node); + const kind = + node.type === "MethodDefinition" ? node.kind : "field"; + + if (name === null || kind === "constructor") { + return; + } + + const state = getState(name, node.static); + let isDuplicate; + + if (kind === "get") { + isDuplicate = state.init || state.get; + state.get = true; + } else if (kind === "set") { + isDuplicate = state.init || state.set; + state.set = true; + } else { + isDuplicate = state.init || state.get || state.set; + state.init = true; + } + + if (isDuplicate) { + context.report({ + loc: node.key.loc, + messageId: "unexpected", + data: { name }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-else-if.js b/node_modules/eslint/lib/rules/no-dupe-else-if.js new file mode 100644 index 0000000000000000000000000000000000000000..7c4195819a1bda9250b33e1a03f39ccb3aaf78a7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-else-if.js @@ -0,0 +1,145 @@ +/** + * @fileoverview Rule to disallow duplicate conditions in if-else-if chains + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the first given array is a subset of the second given array. + * @param {Function} comparator A function to compare two elements, should return `true` if they are equal. + * @param {Array} arrA The array to compare from. + * @param {Array} arrB The array to compare against. + * @returns {boolean} `true` if the array `arrA` is a subset of the array `arrB`. + */ +function isSubsetByComparator(comparator, arrA, arrB) { + return arrA.every(a => arrB.some(b => comparator(a, b))); +} + +/** + * Splits the given node by the given logical operator. + * @param {string} operator Logical operator `||` or `&&`. + * @param {ASTNode} node The node to split. + * @returns {ASTNode[]} Array of conditions that makes the node when joined by the operator. + */ +function splitByLogicalOperator(operator, node) { + if (node.type === "LogicalExpression" && node.operator === operator) { + return [ + ...splitByLogicalOperator(operator, node.left), + ...splitByLogicalOperator(operator, node.right), + ]; + } + return [node]; +} + +const splitByOr = splitByLogicalOperator.bind(null, "||"); +const splitByAnd = splitByLogicalOperator.bind(null, "&&"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate conditions in if-else-if chains", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-else-if", + }, + + schema: [], + + messages: { + unexpected: + "This branch can never execute. Its condition is a duplicate or covered by previous conditions in the if-else-if chain.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Determines whether the two given nodes are considered to be equal. In particular, given that the nodes + * represent expressions in a boolean context, `||` and `&&` can be considered as commutative operators. + * @param {ASTNode} a First node. + * @param {ASTNode} b Second node. + * @returns {boolean} `true` if the nodes are considered to be equal. + */ + function equal(a, b) { + if (a.type !== b.type) { + return false; + } + + if ( + a.type === "LogicalExpression" && + (a.operator === "||" || a.operator === "&&") && + a.operator === b.operator + ) { + return ( + (equal(a.left, b.left) && equal(a.right, b.right)) || + (equal(a.left, b.right) && equal(a.right, b.left)) + ); + } + + return astUtils.equalTokens(a, b, sourceCode); + } + + const isSubset = isSubsetByComparator.bind(null, equal); + + return { + IfStatement(node) { + const test = node.test, + conditionsToCheck = + test.type === "LogicalExpression" && + test.operator === "&&" + ? [test, ...splitByAnd(test)] + : [test]; + let current = node, + listToCheck = conditionsToCheck.map(c => + splitByOr(c).map(splitByAnd), + ); + + while ( + current.parent && + current.parent.type === "IfStatement" && + current.parent.alternate === current + ) { + current = current.parent; + + const currentOrOperands = splitByOr(current.test).map( + splitByAnd, + ); + + listToCheck = listToCheck.map(orOperands => + orOperands.filter( + orOperand => + !currentOrOperands.some(currentOrOperand => + isSubset(currentOrOperand, orOperand), + ), + ), + ); + + if ( + listToCheck.some(orOperands => orOperands.length === 0) + ) { + context.report({ node: test, messageId: "unexpected" }); + break; + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-dupe-keys.js b/node_modules/eslint/lib/rules/no-dupe-keys.js new file mode 100644 index 0000000000000000000000000000000000000000..a17cb343ddd466b02a02f90eb672083c28133ea4 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-dupe-keys.js @@ -0,0 +1,165 @@ +/** + * @fileoverview Rule to flag use of duplicate keys in an object. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const GET_KIND = /^(?:init|get)$/u; +const SET_KIND = /^(?:init|set)$/u; + +/** + * The class which stores properties' information of an object. + */ +class ObjectInfo { + /** + * @param {ObjectInfo|null} upper The information of the outer object. + * @param {ASTNode} node The ObjectExpression node of this information. + */ + constructor(upper, node) { + this.upper = upper; + this.node = node; + this.properties = new Map(); + } + + /** + * Gets the information of the given Property node. + * @param {ASTNode} node The Property node to get. + * @returns {{get: boolean, set: boolean}} The information of the property. + */ + getPropertyInfo(node) { + const name = astUtils.getStaticPropertyName(node); + + if (!this.properties.has(name)) { + this.properties.set(name, { get: false, set: false }); + } + return this.properties.get(name); + } + + /** + * Checks whether the given property has been defined already or not. + * @param {ASTNode} node The Property node to check. + * @returns {boolean} `true` if the property has been defined. + */ + isPropertyDefined(node) { + const entry = this.getPropertyInfo(node); + + return ( + (GET_KIND.test(node.kind) && entry.get) || + (SET_KIND.test(node.kind) && entry.set) + ); + } + + /** + * Defines the given property. + * @param {ASTNode} node The Property node to define. + * @returns {void} + */ + defineProperty(node) { + const entry = this.getPropertyInfo(node); + + if (GET_KIND.test(node.kind)) { + entry.get = true; + } + if (SET_KIND.test(node.kind)) { + entry.set = true; + } + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate keys in object literals", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-dupe-keys", + }, + + schema: [], + + messages: { + unexpected: "Duplicate key '{{name}}'.", + }, + }, + + create(context) { + let info = null; + + return { + ObjectExpression(node) { + info = new ObjectInfo(info, node); + }, + "ObjectExpression:exit"() { + info = info.upper; + }, + + Property(node) { + const name = astUtils.getStaticPropertyName(node); + + // Skip destructuring. + if (node.parent.type !== "ObjectExpression") { + return; + } + + // Skip if the name is not static. + if (name === null) { + return; + } + + /* + * Skip if the property node is a proto setter. + * Proto setter is a special syntax that sets + * object's prototype instead of creating a property. + * It can be in one of the following forms: + * + * __proto__: + * '__proto__': + * "__proto__": + * + * Duplicate proto setters produce parsing errors, + * so we can just skip them to not interfere with + * regular properties named "__proto__". + */ + if ( + name === "__proto__" && + node.kind === "init" && + !node.computed && + !node.shorthand && + !node.method + ) { + return; + } + + // Reports if the name is defined already. + if (info.isPropertyDefined(node)) { + context.report({ + node: info.node, + loc: node.key.loc, + messageId: "unexpected", + data: { name }, + }); + } + + // Update info. + info.defineProperty(node); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-duplicate-case.js b/node_modules/eslint/lib/rules/no-duplicate-case.js new file mode 100644 index 0000000000000000000000000000000000000000..161b1a0bdb7973a1ee1bbd27da2631421f28bedc --- /dev/null +++ b/node_modules/eslint/lib/rules/no-duplicate-case.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Rule to disallow a duplicate case label. + * @author Dieter Oberkofler + * @author Burak Yigit Kaya + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow duplicate case labels", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-duplicate-case", + }, + + schema: [], + + messages: { + unexpected: "Duplicate case label.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Determines whether the two given nodes are considered to be equal. + * @param {ASTNode} a First node. + * @param {ASTNode} b Second node. + * @returns {boolean} `true` if the nodes are considered to be equal. + */ + function equal(a, b) { + if (a.type !== b.type) { + return false; + } + + return astUtils.equalTokens(a, b, sourceCode); + } + return { + SwitchStatement(node) { + const previousTests = []; + + for (const switchCase of node.cases) { + if (switchCase.test) { + const test = switchCase.test; + + if ( + previousTests.some(previousTest => + equal(previousTest, test), + ) + ) { + context.report({ + node: switchCase, + messageId: "unexpected", + }); + } else { + previousTests.push(test); + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-duplicate-imports.js b/node_modules/eslint/lib/rules/no-duplicate-imports.js new file mode 100644 index 0000000000000000000000000000000000000000..0a4fa4a5287ff1e647231482b199cab5109e3583 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-duplicate-imports.js @@ -0,0 +1,367 @@ +/** + * @fileoverview Restrict usage of duplicate imports. + * @author Simen Bekkhus + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const NAMED_TYPES = ["ImportSpecifier", "ExportSpecifier"]; +const NAMESPACE_TYPES = [ + "ImportNamespaceSpecifier", + "ExportNamespaceSpecifier", +]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Check if an import/export type belongs to (ImportSpecifier|ExportSpecifier) or (ImportNamespaceSpecifier|ExportNamespaceSpecifier). + * @param {string} importExportType An import/export type to check. + * @param {string} type Can be "named" or "namespace" + * @returns {boolean} True if import/export type belongs to (ImportSpecifier|ExportSpecifier) or (ImportNamespaceSpecifier|ExportNamespaceSpecifier) and false if it doesn't. + */ +function isImportExportSpecifier(importExportType, type) { + const arrayToCheck = type === "named" ? NAMED_TYPES : NAMESPACE_TYPES; + + return arrayToCheck.includes(importExportType); +} + +/** + * Return the type of (import|export). + * @param {ASTNode} node A node to get. + * @returns {string} The type of the (import|export). + */ +function getImportExportType(node) { + if (node.specifiers && node.specifiers.length > 0) { + const nodeSpecifiers = node.specifiers; + const index = nodeSpecifiers.findIndex( + ({ type }) => + isImportExportSpecifier(type, "named") || + isImportExportSpecifier(type, "namespace"), + ); + const i = index > -1 ? index : 0; + + return nodeSpecifiers[i].type; + } + if (node.type === "ExportAllDeclaration") { + if (node.exported) { + return "ExportNamespaceSpecifier"; + } + return "ExportAll"; + } + return "SideEffectImport"; +} + +/** + * Returns a boolean indicates if two (import|export) can be merged + * @param {ASTNode} node1 A node to check. + * @param {ASTNode} node2 A node to check. + * @returns {boolean} True if two (import|export) can be merged, false if they can't. + */ +function isImportExportCanBeMerged(node1, node2) { + const importExportType1 = getImportExportType(node1); + const importExportType2 = getImportExportType(node2); + + if ( + (node1.importKind === "type" || node1.exportKind === "type") && + (node2.importKind === "type" || node2.exportKind === "type") + ) { + const isDefault1 = importExportType1 === "ImportDefaultSpecifier"; + const isDefault2 = importExportType2 === "ImportDefaultSpecifier"; + const isNamed1 = isImportExportSpecifier(importExportType1, "named"); + const isNamed2 = isImportExportSpecifier(importExportType2, "named"); + + if ((isDefault1 && isNamed2) || (isDefault2 && isNamed1)) { + return false; + } + } + + if ( + (importExportType1 === "ExportAll" && + importExportType2 !== "ExportAll" && + importExportType2 !== "SideEffectImport") || + (importExportType1 !== "ExportAll" && + importExportType1 !== "SideEffectImport" && + importExportType2 === "ExportAll") + ) { + return false; + } + if ( + (isImportExportSpecifier(importExportType1, "namespace") && + isImportExportSpecifier(importExportType2, "named")) || + (isImportExportSpecifier(importExportType2, "namespace") && + isImportExportSpecifier(importExportType1, "named")) + ) { + return false; + } + return true; +} + +/** + * Returns a boolean if we should report (import|export). + * @param {ASTNode} node A node to be reported or not. + * @param {[ASTNode]} previousNodes An array contains previous nodes of the module imported or exported. + * @param {boolean} allowSeparateTypeImports Whether to allow separate type and value imports. + * @returns {boolean} True if the (import|export) should be reported. + */ +function shouldReportImportExport( + node, + previousNodes, + allowSeparateTypeImports, +) { + let i = 0; + + while (i < previousNodes.length) { + const previousNode = previousNodes[i]; + + if (allowSeparateTypeImports) { + const isTypeNode = + node.importKind === "type" || node.exportKind === "type"; + const isTypePrevious = + previousNode.importKind === "type" || + previousNode.exportKind === "type"; + + if (isTypeNode !== isTypePrevious) { + i++; + continue; + } + } + + if (isImportExportCanBeMerged(node, previousNode)) { + return true; + } + i++; + } + return false; +} + +/** + * Returns array contains only nodes with declarations types equal to type. + * @param {[{node: ASTNode, declarationType: string}]} nodes An array contains objects, each object contains a node and a declaration type. + * @param {string} type Declaration type. + * @returns {[ASTNode]} An array contains only nodes with declarations types equal to type. + */ +function getNodesByDeclarationType(nodes, type) { + return nodes + .filter(({ declarationType }) => declarationType === type) + .map(({ node }) => node); +} + +/** + * Returns the name of the module imported or re-exported. + * @param {ASTNode} node A node to get. + * @returns {string} The name of the module, or empty string if no name. + */ +function getModule(node) { + if (node && node.source && node.source.value) { + return node.source.value.trim(); + } + return ""; +} + +/** + * Checks if the (import|export) can be merged with at least one import or one export, and reports if so. + * @param {RuleContext} context The ESLint rule context object. + * @param {ASTNode} node A node to get. + * @param {Map} modules A Map object contains as a key a module name and as value an array contains objects, each object contains a node and a declaration type. + * @param {string} declarationType A declaration type can be an import or export. + * @param {boolean} includeExports Whether or not to check for exports in addition to imports. + * @param {boolean} allowSeparateTypeImports Whether to allow separate type and value imports. + * @returns {void} No return value. + */ +function checkAndReport( + context, + node, + modules, + declarationType, + includeExports, + allowSeparateTypeImports, +) { + const module = getModule(node); + + if (modules.has(module)) { + const previousNodes = modules.get(module); + const messagesIds = []; + const importNodes = getNodesByDeclarationType(previousNodes, "import"); + let exportNodes; + + if (includeExports) { + exportNodes = getNodesByDeclarationType(previousNodes, "export"); + } + if (declarationType === "import") { + if ( + shouldReportImportExport( + node, + importNodes, + allowSeparateTypeImports, + ) + ) { + messagesIds.push("import"); + } + if (includeExports) { + if ( + shouldReportImportExport( + node, + exportNodes, + allowSeparateTypeImports, + ) + ) { + messagesIds.push("importAs"); + } + } + } else if (declarationType === "export") { + if ( + shouldReportImportExport( + node, + exportNodes, + allowSeparateTypeImports, + ) + ) { + messagesIds.push("export"); + } + if ( + shouldReportImportExport( + node, + importNodes, + allowSeparateTypeImports, + ) + ) { + messagesIds.push("exportAs"); + } + } + messagesIds.forEach(messageId => + context.report({ + node, + messageId, + data: { + module, + }, + }), + ); + } +} + +/** + * @callback nodeCallback + * @param {ASTNode} node A node to handle. + */ + +/** + * Returns a function handling the (imports|exports) of a given file + * @param {RuleContext} context The ESLint rule context object. + * @param {Map} modules A Map object contains as a key a module name and as value an array contains objects, each object contains a node and a declaration type. + * @param {string} declarationType A declaration type can be an import or export. + * @param {boolean} includeExports Whether or not to check for exports in addition to imports. + * @param {boolean} allowSeparateTypeImports Whether to allow separate type and value imports. + * @returns {nodeCallback} A function passed to ESLint to handle the statement. + */ +function handleImportsExports( + context, + modules, + declarationType, + includeExports, + allowSeparateTypeImports, +) { + return function (node) { + const module = getModule(node); + + if (module) { + checkAndReport( + context, + node, + modules, + declarationType, + includeExports, + allowSeparateTypeImports, + ); + const currentNode = { node, declarationType }; + let nodes = [currentNode]; + + if (modules.has(module)) { + const previousNodes = modules.get(module); + + nodes = [...previousNodes, currentNode]; + } + modules.set(module, nodes); + } + }; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + includeExports: false, + allowSeparateTypeImports: false, + }, + ], + + docs: { + description: "Disallow duplicate module imports", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-duplicate-imports", + }, + + schema: [ + { + type: "object", + properties: { + includeExports: { + type: "boolean", + }, + allowSeparateTypeImports: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + import: "'{{module}}' import is duplicated.", + importAs: "'{{module}}' import is duplicated as export.", + export: "'{{module}}' export is duplicated.", + exportAs: "'{{module}}' export is duplicated as import.", + }, + }, + + create(context) { + const [{ includeExports, allowSeparateTypeImports }] = context.options; + const modules = new Map(); + const handlers = { + ImportDeclaration: handleImportsExports( + context, + modules, + "import", + includeExports, + allowSeparateTypeImports, + ), + }; + + if (includeExports) { + handlers.ExportNamedDeclaration = handleImportsExports( + context, + modules, + "export", + includeExports, + allowSeparateTypeImports, + ); + handlers.ExportAllDeclaration = handleImportsExports( + context, + modules, + "export", + includeExports, + allowSeparateTypeImports, + ); + } + return handlers; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-else-return.js b/node_modules/eslint/lib/rules/no-else-return.js new file mode 100644 index 0000000000000000000000000000000000000000..54c1be8271b98d3b6098683322ccbeba7c1e245c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-else-return.js @@ -0,0 +1,456 @@ +/** + * @fileoverview Rule to flag `else` after a `return` in `if` + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const FixTracker = require("./utils/fix-tracker"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Scope} Scope */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{ allowElseIf: true }], + + docs: { + description: + "Disallow `else` blocks after `return` statements in `if` statements", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-else-return", + }, + + schema: [ + { + type: "object", + properties: { + allowElseIf: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + unexpected: "Unnecessary 'else' after 'return'.", + }, + }, + + create(context) { + const [{ allowElseIf }] = context.options; + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks whether the given names can be safely used to declare block-scoped variables + * in the given scope. Name collisions can produce redeclaration syntax errors, + * or silently change references and modify behavior of the original code. + * + * This is not a generic function. In particular, it is assumed that the scope is a function scope or + * a function's inner scope, and that the names can be valid identifiers in the given scope. + * @param {string[]} names Array of variable names. + * @param {Scope} scope Function scope or a function's inner scope. + * @returns {boolean} True if all names can be safely declared, false otherwise. + */ + function isSafeToDeclare(names, scope) { + if (names.length === 0) { + return true; + } + + const functionScope = scope.variableScope; + + /* + * If this is a function scope, scope.variables will contain parameters, implicit variables such as "arguments", + * all function-scoped variables ('var'), and block-scoped variables defined in the scope. + * If this is an inner scope, scope.variables will contain block-scoped variables defined in the scope. + * + * Redeclaring any of these would cause a syntax error, except for the implicit variables. + */ + const declaredVariables = scope.variables.filter( + ({ defs }) => defs.length > 0, + ); + + if (declaredVariables.some(({ name }) => names.includes(name))) { + return false; + } + + // Redeclaring a catch variable would also cause a syntax error. + if (scope !== functionScope && scope.upper.type === "catch") { + if ( + scope.upper.variables.some(({ name }) => + names.includes(name), + ) + ) { + return false; + } + } + + /* + * Redeclaring an implicit variable, such as "arguments", would not cause a syntax error. + * However, if the variable was used, declaring a new one with the same name would change references + * and modify behavior. + */ + const usedImplicitVariables = scope.variables.filter( + ({ defs, references }) => + defs.length === 0 && references.length > 0, + ); + + if ( + usedImplicitVariables.some(({ name }) => names.includes(name)) + ) { + return false; + } + + /* + * Declaring a variable with a name that was already used to reference a variable from an upper scope + * would change references and modify behavior. + */ + if (scope.through.some(t => names.includes(t.identifier.name))) { + return false; + } + + /* + * If the scope is an inner scope (not the function scope), an uninitialized `var` variable declared inside + * the scope node (directly or in one of its descendants) is neither declared nor 'through' in the scope. + * + * For example, this would be a syntax error "Identifier 'a' has already been declared": + * function foo() { if (bar) { let a; if (baz) { var a; } } } + */ + if (scope !== functionScope) { + const scopeNodeRange = scope.block.range; + const variablesToCheck = functionScope.variables.filter( + ({ name }) => names.includes(name), + ); + + if ( + variablesToCheck.some(v => + v.defs.some( + ({ node: { range } }) => + scopeNodeRange[0] <= range[0] && + range[1] <= scopeNodeRange[1], + ), + ) + ) { + return false; + } + } + + return true; + } + + /** + * Checks whether the removal of `else` and its braces is safe from variable name collisions. + * @param {Node} node The 'else' node. + * @param {Scope} scope The scope in which the node and the whole 'if' statement is. + * @returns {boolean} True if it is safe, false otherwise. + */ + function isSafeFromNameCollisions(node, scope) { + if (node.type === "FunctionDeclaration") { + // Conditional function declaration. Scope and hoisting are unpredictable, different engines work differently. + return false; + } + + if (node.type !== "BlockStatement") { + return true; + } + + const elseBlockScope = scope.childScopes.find( + ({ block }) => block === node, + ); + + if (!elseBlockScope) { + // ecmaVersion < 6, `else` block statement cannot have its own scope, no possible collisions. + return true; + } + + /* + * elseBlockScope is supposed to merge into its upper scope. elseBlockScope.variables array contains + * only block-scoped variables (such as let and const variables or class and function declarations) + * defined directly in the elseBlockScope. These are exactly the only names that could cause collisions. + */ + const namesToCheck = elseBlockScope.variables.map( + ({ name }) => name, + ); + + return isSafeToDeclare(namesToCheck, scope); + } + + /** + * Display the context report if rule is violated + * @param {Node} elseNode The 'else' node + * @returns {void} + */ + function displayReport(elseNode) { + const currentScope = sourceCode.getScope(elseNode.parent); + + context.report({ + node: elseNode, + messageId: "unexpected", + fix(fixer) { + if (!isSafeFromNameCollisions(elseNode, currentScope)) { + return null; + } + + const startToken = sourceCode.getFirstToken(elseNode); + const elseToken = sourceCode.getTokenBefore(startToken); + const source = sourceCode.getText(elseNode); + const lastIfToken = sourceCode.getTokenBefore(elseToken); + let fixedSource, firstTokenOfElseBlock; + + if ( + startToken.type === "Punctuator" && + startToken.value === "{" + ) { + firstTokenOfElseBlock = + sourceCode.getTokenAfter(startToken); + } else { + firstTokenOfElseBlock = startToken; + } + + /* + * If the if block does not have curly braces and does not end in a semicolon + * and the else block starts with (, [, /, +, ` or -, then it is not + * safe to remove the else keyword, because ASI will not add a semicolon + * after the if block + */ + const ifBlockMaybeUnsafe = + elseNode.parent.consequent.type !== "BlockStatement" && + lastIfToken.value !== ";"; + const elseBlockUnsafe = /^[([/+`-]/u.test( + firstTokenOfElseBlock.value, + ); + + if (ifBlockMaybeUnsafe && elseBlockUnsafe) { + return null; + } + + const endToken = sourceCode.getLastToken(elseNode); + const lastTokenOfElseBlock = + sourceCode.getTokenBefore(endToken); + + if (lastTokenOfElseBlock.value !== ";") { + const nextToken = sourceCode.getTokenAfter(endToken); + + const nextTokenUnsafe = + nextToken && /^[([/+`-]/u.test(nextToken.value); + const nextTokenOnSameLine = + nextToken && + nextToken.loc.start.line === + lastTokenOfElseBlock.loc.start.line; + + /* + * If the else block contents does not end in a semicolon, + * and the else block starts with (, [, /, +, ` or -, then it is not + * safe to remove the else block, because ASI will not add a semicolon + * after the remaining else block contents + */ + if ( + nextTokenUnsafe || + (nextTokenOnSameLine && nextToken.value !== "}") + ) { + return null; + } + } + + if ( + startToken.type === "Punctuator" && + startToken.value === "{" + ) { + fixedSource = source.slice(1, -1); + } else { + fixedSource = source; + } + + /* + * Extend the replacement range to include the entire + * function to avoid conflicting with no-useless-return. + * https://github.com/eslint/eslint/issues/8026 + * + * Also, to avoid name collisions between two else blocks. + */ + return new FixTracker(fixer, sourceCode) + .retainEnclosingFunction(elseNode) + .replaceTextRange( + [elseToken.range[0], elseNode.range[1]], + fixedSource, + ); + }, + }); + } + + /** + * Check to see if the node is a ReturnStatement + * @param {Node} node The node being evaluated + * @returns {boolean} True if node is a return + */ + function checkForReturn(node) { + return node.type === "ReturnStatement"; + } + + /** + * Naive return checking, does not iterate through the whole + * BlockStatement because we make the assumption that the ReturnStatement + * will be the last node in the body of the BlockStatement. + * @param {Node} node The consequent/alternate node + * @returns {boolean} True if it has a return + */ + function naiveHasReturn(node) { + if (node.type === "BlockStatement") { + const body = node.body, + lastChildNode = body.at(-1); + + return lastChildNode && checkForReturn(lastChildNode); + } + return checkForReturn(node); + } + + /** + * Check to see if the node is valid for evaluation, + * meaning it has an else. + * @param {Node} node The node being evaluated + * @returns {boolean} True if the node is valid + */ + function hasElse(node) { + return node.alternate && node.consequent; + } + + /** + * If the consequent is an IfStatement, check to see if it has an else + * and both its consequent and alternate path return, meaning this is + * a nested case of rule violation. If-Else not considered currently. + * @param {Node} node The consequent node + * @returns {boolean} True if this is a nested rule violation + */ + function checkForIf(node) { + return ( + node.type === "IfStatement" && + hasElse(node) && + naiveHasReturn(node.alternate) && + naiveHasReturn(node.consequent) + ); + } + + /** + * Check the consequent/body node to make sure it is not + * a ReturnStatement or an IfStatement that returns on both + * code paths. + * @param {Node} node The consequent or body node + * @returns {boolean} `true` if it is a Return/If node that always returns. + */ + function checkForReturnOrIf(node) { + return checkForReturn(node) || checkForIf(node); + } + + /** + * Check whether a node returns in every codepath. + * @param {Node} node The node to be checked + * @returns {boolean} `true` if it returns on every codepath. + */ + function alwaysReturns(node) { + if (node.type === "BlockStatement") { + // If we have a BlockStatement, check each consequent body node. + return node.body.some(checkForReturnOrIf); + } + + /* + * If not a block statement, make sure the consequent isn't a + * ReturnStatement or an IfStatement with returns on both paths. + */ + return checkForReturnOrIf(node); + } + + /** + * Check the if statement, but don't catch else-if blocks. + * @returns {void} + * @param {Node} node The node for the if statement to check + * @private + */ + function checkIfWithoutElse(node) { + const parent = node.parent; + + /* + * Fixing this would require splitting one statement into two, so no error should + * be reported if this node is in a position where only one statement is allowed. + */ + if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { + return; + } + + const consequents = []; + let alternate; + + for ( + let currentNode = node; + currentNode.type === "IfStatement"; + currentNode = currentNode.alternate + ) { + if (!currentNode.alternate) { + return; + } + consequents.push(currentNode.consequent); + alternate = currentNode.alternate; + } + + if (consequents.every(alwaysReturns)) { + displayReport(alternate); + } + } + + /** + * Check the if statement + * @returns {void} + * @param {Node} node The node for the if statement to check + * @private + */ + function checkIfWithElse(node) { + const parent = node.parent; + + /* + * Fixing this would require splitting one statement into two, so no error should + * be reported if this node is in a position where only one statement is allowed. + */ + if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { + return; + } + + const alternate = node.alternate; + + if (alternate && alwaysReturns(node.consequent)) { + displayReport(alternate); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "IfStatement:exit": allowElseIf + ? checkIfWithoutElse + : checkIfWithElse, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-empty-character-class.js b/node_modules/eslint/lib/rules/no-empty-character-class.js new file mode 100644 index 0000000000000000000000000000000000000000..eccee1d1a8cba7bd3003ce76214891d528da91d2 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-character-class.js @@ -0,0 +1,83 @@ +/** + * @fileoverview Rule to flag the use of empty character classes in regular expressions + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const parser = new RegExpParser(); +const QUICK_TEST_REGEX = /\[\]/u; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow empty character classes in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-empty-character-class", + }, + + schema: [], + + messages: { + unexpected: "Empty class.", + }, + }, + + create(context) { + return { + "Literal[regex]"(node) { + const { pattern, flags } = node.regex; + + if (!QUICK_TEST_REGEX.test(pattern)) { + return; + } + + let regExpAST; + + try { + regExpAST = parser.parsePattern( + pattern, + 0, + pattern.length, + { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v"), + }, + ); + } catch { + // Ignore regular expressions that regexpp cannot parse + return; + } + + visitRegExpAST(regExpAST, { + onCharacterClassEnter(characterClass) { + if ( + !characterClass.negate && + characterClass.elements.length === 0 + ) { + context.report({ node, messageId: "unexpected" }); + } + }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-empty-function.js b/node_modules/eslint/lib/rules/no-empty-function.js new file mode 100644 index 0000000000000000000000000000000000000000..208ab4267894b9ce9f97b9eae6245f121c0b96c8 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-function.js @@ -0,0 +1,235 @@ +/** + * @fileoverview Rule to disallow empty functions. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const ALLOW_OPTIONS = Object.freeze([ + "functions", + "arrowFunctions", + "generatorFunctions", + "methods", + "generatorMethods", + "getters", + "setters", + "constructors", + "asyncFunctions", + "asyncMethods", + "privateConstructors", + "protectedConstructors", + "decoratedFunctions", + "overrideMethods", +]); + +/** + * Gets the kind of a given function node. + * @param {ASTNode} node A function node to get. This is one of + * an ArrowFunctionExpression, a FunctionDeclaration, or a + * FunctionExpression. + * @returns {string} The kind of the function. This is one of "functions", + * "arrowFunctions", "generatorFunctions", "asyncFunctions", "methods", + * "generatorMethods", "asyncMethods", "getters", "setters", and + * "constructors". + */ +function getKind(node) { + const parent = node.parent; + let kind; + + if (node.type === "ArrowFunctionExpression") { + return "arrowFunctions"; + } + + // Detects main kind. + if (parent.type === "Property") { + if (parent.kind === "get") { + return "getters"; + } + if (parent.kind === "set") { + return "setters"; + } + kind = parent.method ? "methods" : "functions"; + } else if (parent.type === "MethodDefinition") { + if (parent.kind === "get") { + return "getters"; + } + if (parent.kind === "set") { + return "setters"; + } + if (parent.kind === "constructor") { + return "constructors"; + } + kind = "methods"; + } else { + kind = "functions"; + } + + // Detects prefix. + let prefix; + + if (node.generator) { + prefix = "generator"; + } else if (node.async) { + prefix = "async"; + } else { + return kind; + } + return prefix + kind[0].toUpperCase() + kind.slice(1); +} + +/** + * Checks if a constructor function has parameter properties. + * @param {ASTNode} node The function node to examine. + * @returns {boolean} True if the constructor has parameter properties, false otherwise. + */ +function isParameterPropertiesConstructor(node) { + return node.params.some(param => param.type === "TSParameterProperty"); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "suggestion", + + defaultOptions: [{ allow: [] }], + + docs: { + description: "Disallow empty functions", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-empty-function", + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { enum: ALLOW_OPTIONS }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "Unexpected empty {{name}}.", + suggestComment: "Add comment inside empty {{name}}.", + }, + }, + + create(context) { + const [{ allow }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Checks if the given function node is allowed to be empty. + * @param {ASTNode} node The function node to check. + * @returns {boolean} True if the function is allowed to be empty, false otherwise. + */ + function isAllowedEmptyFunction(node) { + const kind = getKind(node); + + if (allow.includes(kind)) { + return true; + } + + if (kind === "constructors") { + if ( + (node.parent.accessibility === "private" && + allow.includes("privateConstructors")) || + (node.parent.accessibility === "protected" && + allow.includes("protectedConstructors")) || + isParameterPropertiesConstructor(node) + ) { + return true; + } + } + + if (/(?:g|s)etters|methods$/iu.test(kind)) { + if ( + (node.parent.decorators?.length && + allow.includes("decoratedFunctions")) || + (node.parent.override && allow.includes("overrideMethods")) + ) { + return true; + } + } + + return false; + } + + /** + * Reports a given function node if the node matches the following patterns. + * + * - Not allowed by options. + * - The body is empty. + * - The body doesn't have any comments. + * @param {ASTNode} node A function node to report. This is one of + * an ArrowFunctionExpression, a FunctionDeclaration, or a + * FunctionExpression. + * @returns {void} + */ + function reportIfEmpty(node) { + const name = astUtils.getFunctionNameWithKind(node); + const innerComments = sourceCode.getTokens(node.body, { + includeComments: true, + filter: astUtils.isCommentToken, + }); + + if ( + !isAllowedEmptyFunction(node) && + node.body.type === "BlockStatement" && + node.body.body.length === 0 && + innerComments.length === 0 + ) { + context.report({ + node, + loc: node.body.loc, + messageId: "unexpected", + data: { name }, + suggest: [ + { + messageId: "suggestComment", + data: { name }, + fix(fixer) { + const range = [ + node.body.range[0] + 1, + node.body.range[1] - 1, + ]; + + return fixer.replaceTextRange( + range, + " /* empty */ ", + ); + }, + }, + ], + }); + } + } + + return { + ArrowFunctionExpression: reportIfEmpty, + FunctionDeclaration: reportIfEmpty, + FunctionExpression: reportIfEmpty, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-empty-pattern.js b/node_modules/eslint/lib/rules/no-empty-pattern.js new file mode 100644 index 0000000000000000000000000000000000000000..da75ad954cd96a333aae07fd98022f8297104722 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-pattern.js @@ -0,0 +1,85 @@ +/** + * @fileoverview Rule to disallow an empty pattern + * @author Alberto Rodríguez + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowObjectPatternsAsParameters: false, + }, + ], + + docs: { + description: "Disallow empty destructuring patterns", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-empty-pattern", + }, + + schema: [ + { + type: "object", + properties: { + allowObjectPatternsAsParameters: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "Unexpected empty {{type}} pattern.", + }, + }, + + create(context) { + const [{ allowObjectPatternsAsParameters }] = context.options; + + return { + ObjectPattern(node) { + if (node.properties.length > 0) { + return; + } + + // Allow {} and {} = {} empty object patterns as parameters when allowObjectPatternsAsParameters is true + if ( + allowObjectPatternsAsParameters && + (astUtils.isFunction(node.parent) || + (node.parent.type === "AssignmentPattern" && + astUtils.isFunction(node.parent.parent) && + node.parent.right.type === "ObjectExpression" && + node.parent.right.properties.length === 0)) + ) { + return; + } + + context.report({ + node, + messageId: "unexpected", + data: { type: "object" }, + }); + }, + ArrayPattern(node) { + if (node.elements.length === 0) { + context.report({ + node, + messageId: "unexpected", + data: { type: "array" }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-empty-static-block.js b/node_modules/eslint/lib/rules/no-empty-static-block.js new file mode 100644 index 0000000000000000000000000000000000000000..488b5ed726565903addfaa651403d273dc9f26c7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty-static-block.js @@ -0,0 +1,73 @@ +/** + * @fileoverview Rule to disallow empty static blocks. + * @author Sosuke Suzuki + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "suggestion", + + docs: { + description: "Disallow empty static blocks", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-empty-static-block", + }, + + schema: [], + + messages: { + unexpected: "Unexpected empty static block.", + suggestComment: "Add comment inside empty static block.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + StaticBlock(node) { + if (node.body.length === 0) { + const openingBrace = sourceCode.getFirstToken(node, { + skip: 1, + }); + const closingBrace = sourceCode.getLastToken(node); + + if ( + sourceCode.getCommentsBefore(closingBrace).length === 0 + ) { + context.report({ + loc: { + start: openingBrace.loc.start, + end: closingBrace.loc.end, + }, + messageId: "unexpected", + suggest: [ + { + messageId: "suggestComment", + fix(fixer) { + const range = [ + openingBrace.range[1], + closingBrace.range[0], + ]; + + return fixer.replaceTextRange( + range, + " /* empty */ ", + ); + }, + }, + ], + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-empty.js b/node_modules/eslint/lib/rules/no-empty.js new file mode 100644 index 0000000000000000000000000000000000000000..dd30e4197a836a7a5eeaae283b35fcbd11829ed6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-empty.js @@ -0,0 +1,153 @@ +/** + * @fileoverview Rule to flag use of an empty block statement + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "suggestion", + + defaultOptions: [ + { + allowEmptyCatch: false, + }, + ], + + docs: { + description: "Disallow empty block statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-empty", + }, + + schema: [ + { + type: "object", + properties: { + allowEmptyCatch: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "Empty {{type}} statement.", + suggestComment: "Add comment inside empty {{type}} statement.", + }, + }, + + create(context) { + const [{ allowEmptyCatch }] = context.options; + const sourceCode = context.sourceCode; + + return { + BlockStatement(node) { + // if the body is not empty, we can just return immediately + if (node.body.length !== 0) { + return; + } + + // a function is generally allowed to be empty + if (astUtils.isFunction(node.parent)) { + return; + } + + if (allowEmptyCatch && node.parent.type === "CatchClause") { + return; + } + + // any other block is only allowed to be empty, if it contains a comment + if (sourceCode.getCommentsInside(node).length > 0) { + return; + } + + context.report({ + node, + messageId: "unexpected", + data: { type: "block" }, + suggest: [ + { + messageId: "suggestComment", + data: { type: "block" }, + fix(fixer) { + const range = [ + node.range[0] + 1, + node.range[1] - 1, + ]; + + return fixer.replaceTextRange( + range, + " /* empty */ ", + ); + }, + }, + ], + }); + }, + + SwitchStatement(node) { + if ( + typeof node.cases === "undefined" || + node.cases.length === 0 + ) { + const openingBrace = sourceCode.getTokenAfter( + node.discriminant, + astUtils.isOpeningBraceToken, + ); + + const closingBrace = sourceCode.getLastToken(node); + + if ( + sourceCode.commentsExistBetween( + openingBrace, + closingBrace, + ) + ) { + return; + } + + context.report({ + node, + loc: { + start: openingBrace.loc.start, + end: closingBrace.loc.end, + }, + messageId: "unexpected", + data: { type: "switch" }, + suggest: [ + { + messageId: "suggestComment", + data: { type: "switch" }, + fix(fixer) { + const range = [ + openingBrace.range[1], + closingBrace.range[0], + ]; + + return fixer.replaceTextRange( + range, + " /* empty */ ", + ); + }, + }, + ], + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-eq-null.js b/node_modules/eslint/lib/rules/no-eq-null.js new file mode 100644 index 0000000000000000000000000000000000000000..edda5e6c9d66ab25acd29efe9513d9c652f24d2e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-eq-null.js @@ -0,0 +1,51 @@ +/** + * @fileoverview Rule to flag comparisons to null without a type-checking + * operator. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `null` comparisons without type-checking operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-eq-null", + }, + + schema: [], + + messages: { + unexpected: "Use '===' to compare with null.", + }, + }, + + create(context) { + return { + BinaryExpression(node) { + const badOperator = + node.operator === "==" || node.operator === "!="; + + if ( + (node.right.type === "Literal" && + node.right.raw === "null" && + badOperator) || + (node.left.type === "Literal" && + node.left.raw === "null" && + badOperator) + ) { + context.report({ node, messageId: "unexpected" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-eval.js b/node_modules/eslint/lib/rules/no-eval.js new file mode 100644 index 0000000000000000000000000000000000000000..ff3a9830fd775066e3986a2553a7a14f3199bc0b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-eval.js @@ -0,0 +1,301 @@ +/** + * @fileoverview Rule to flag use of eval() statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Scope} Scope */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const candidatesOfGlobalObject = Object.freeze([ + "global", + "window", + "globalThis", +]); + +/** + * Checks a given node is a MemberExpression node which has the specified name's + * property. + * @param {ASTNode} node A node to check. + * @param {string} name A name to check. + * @returns {boolean} `true` if the node is a MemberExpression node which has + * the specified name's property + */ +function isMember(node, name) { + return astUtils.isSpecificMemberAccess(node, null, name); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowIndirect: false, + }, + ], + + docs: { + description: "Disallow the use of `eval()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-eval", + }, + + schema: [ + { + type: "object", + properties: { + allowIndirect: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: "`eval` can be harmful.", + }, + }, + + create(context) { + const [{ allowIndirect }] = context.options; + const sourceCode = context.sourceCode; + let funcInfo = null; + + /** + * Pushes a `this` scope (non-arrow function, class static block, or class field initializer) information to the stack. + * Top-level scopes are handled separately. + * + * This is used in order to check whether or not `this` binding is a + * reference to the global object. + * @param {ASTNode} node A node of the scope. + * For functions, this is one of FunctionDeclaration, FunctionExpression. + * For class static blocks, this is StaticBlock. + * For class field initializers, this can be any node that is PropertyDefinition#value. + * @returns {void} + */ + function enterThisScope(node) { + const strict = sourceCode.getScope(node).isStrict; + + funcInfo = { + upper: funcInfo, + node, + strict, + isTopLevelOfScript: false, + defaultThis: false, + initialized: strict, + }; + } + + /** + * Pops a variable scope from the stack. + * @returns {void} + */ + function exitThisScope() { + funcInfo = funcInfo.upper; + } + + /** + * Reports a given node. + * + * `node` is `Identifier` or `MemberExpression`. + * The parent of `node` might be `CallExpression`. + * + * The location of the report is always `eval` `Identifier` (or possibly + * `Literal`). The type of the report is `CallExpression` if the parent is + * `CallExpression`. Otherwise, it's the given node type. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function report(node) { + const parent = node.parent; + const locationNode = + node.type === "MemberExpression" ? node.property : node; + + const reportNode = + parent.type === "CallExpression" && parent.callee === node + ? parent + : node; + + context.report({ + node: reportNode, + loc: locationNode.loc, + messageId: "unexpected", + }); + } + + /** + * Reports accesses of `eval` via the global object. + * @param {Scope} globalScope The global scope. + * @returns {void} + */ + function reportAccessingEvalViaGlobalObject(globalScope) { + for (let i = 0; i < candidatesOfGlobalObject.length; ++i) { + const name = candidatesOfGlobalObject[i]; + const variable = astUtils.getVariableByName(globalScope, name); + + if (!variable) { + continue; + } + + const references = variable.references; + + for (let j = 0; j < references.length; ++j) { + const identifier = references[j].identifier; + let node = identifier.parent; + + // To detect code like `window.window.eval`. + while (isMember(node, name)) { + node = node.parent; + } + + // Reports. + if (isMember(node, "eval")) { + report(node); + } + } + } + } + + /** + * Reports all accesses of `eval` (excludes direct calls to eval). + * @param {Scope} globalScope The global scope. + * @returns {void} + */ + function reportAccessingEval(globalScope) { + const variable = astUtils.getVariableByName(globalScope, "eval"); + + if (!variable) { + return; + } + + const references = variable.references; + + for (let i = 0; i < references.length; ++i) { + const reference = references[i]; + const id = reference.identifier; + + if (id.name === "eval" && !astUtils.isCallee(id)) { + // Is accessing to eval (excludes direct calls to eval) + report(id); + } + } + } + + if (allowIndirect) { + // Checks only direct calls to eval. It's simple! + return { + "CallExpression:exit"(node) { + const callee = node.callee; + + /* + * Optional call (`eval?.("code")`) is not direct eval. + * The direct eval is only step 6.a.vi of https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation + * But the optional call is https://tc39.es/ecma262/#sec-optional-chaining-chain-evaluation + */ + if ( + !node.optional && + astUtils.isSpecificId(callee, "eval") + ) { + report(callee); + } + }, + }; + } + + return { + "CallExpression:exit"(node) { + const callee = node.callee; + + if (astUtils.isSpecificId(callee, "eval")) { + report(callee); + } + }, + + Program(node) { + const scope = sourceCode.getScope(node), + features = + context.languageOptions.parserOptions.ecmaFeatures || + {}, + strict = + scope.isStrict || + node.sourceType === "module" || + (features.globalReturn && + scope.childScopes[0].isStrict), + isTopLevelOfScript = + node.sourceType !== "module" && !features.globalReturn; + + funcInfo = { + upper: null, + node, + strict, + isTopLevelOfScript, + defaultThis: true, + initialized: true, + }; + }, + + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + exitThisScope(); + reportAccessingEval(globalScope); + reportAccessingEvalViaGlobalObject(globalScope); + }, + + FunctionDeclaration: enterThisScope, + "FunctionDeclaration:exit": exitThisScope, + FunctionExpression: enterThisScope, + "FunctionExpression:exit": exitThisScope, + "PropertyDefinition > *.value": enterThisScope, + "PropertyDefinition > *.value:exit": exitThisScope, + StaticBlock: enterThisScope, + "StaticBlock:exit": exitThisScope, + + ThisExpression(node) { + if (!isMember(node.parent, "eval")) { + return; + } + + /* + * `this.eval` is found. + * Checks whether or not the value of `this` is the global object. + */ + if (!funcInfo.initialized) { + funcInfo.initialized = true; + funcInfo.defaultThis = astUtils.isDefaultThisBinding( + funcInfo.node, + sourceCode, + ); + } + + // `this` at the top level of scripts always refers to the global object + if ( + funcInfo.isTopLevelOfScript || + (!funcInfo.strict && funcInfo.defaultThis) + ) { + // `this.eval` is possible built-in `eval`. + report(node.parent); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-ex-assign.js b/node_modules/eslint/lib/rules/no-ex-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..6215a5e05aad5bd328f296fa4416277376bd65f3 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-ex-assign.js @@ -0,0 +1,57 @@ +/** + * @fileoverview Rule to flag assignment of the exception parameter + * @author Stephen Murray + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow reassigning exceptions in `catch` clauses", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-ex-assign", + }, + + schema: [], + + messages: { + unexpected: "Do not assign to the exception parameter.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + astUtils + .getModifyingReferences(variable.references) + .forEach(reference => { + context.report({ + node: reference.identifier, + messageId: "unexpected", + }); + }); + } + + return { + CatchClause(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extend-native.js b/node_modules/eslint/lib/rules/no-extend-native.js new file mode 100644 index 0000000000000000000000000000000000000000..d1a6d12dbb122cd89c2032f80b559df3193292ea --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extend-native.js @@ -0,0 +1,180 @@ +/** + * @fileoverview Rule to flag adding properties to native object's prototypes. + * @author David Nelson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{ exceptions: [] }], + + docs: { + description: "Disallow extending native types", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extend-native", + }, + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpected: + "{{builtin}} prototype is read only, properties should not be added.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const exceptions = new Set(context.options[0].exceptions); + const modifiedBuiltins = new Set( + Object.keys(astUtils.ECMASCRIPT_GLOBALS) + .filter(builtin => builtin[0].toUpperCase() === builtin[0]) + .filter(builtin => !exceptions.has(builtin)), + ); + + /** + * Reports a lint error for the given node. + * @param {ASTNode} node The node to report. + * @param {string} builtin The name of the native builtin being extended. + * @returns {void} + */ + function reportNode(node, builtin) { + context.report({ + node, + messageId: "unexpected", + data: { + builtin, + }, + }); + } + + /** + * Check to see if the `prototype` property of the given object + * identifier node is being accessed. + * @param {ASTNode} identifierNode The Identifier representing the object + * to check. + * @returns {boolean} True if the identifier is the object of a + * MemberExpression and its `prototype` property is being accessed, + * false otherwise. + */ + function isPrototypePropertyAccessed(identifierNode) { + return Boolean( + identifierNode && + identifierNode.parent && + identifierNode.parent.type === "MemberExpression" && + identifierNode.parent.object === identifierNode && + astUtils.getStaticPropertyName(identifierNode.parent) === + "prototype", + ); + } + + /** + * Check if it's an assignment to the property of the given node. + * Example: `*.prop = 0` // the `*` is the given node. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if an assignment to the property of the node. + */ + function isAssigningToPropertyOf(node) { + return ( + node.parent.type === "MemberExpression" && + node.parent.object === node && + node.parent.parent.type === "AssignmentExpression" && + node.parent.parent.left === node.parent + ); + } + + /** + * Checks if the given node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`. + */ + function isInDefinePropertyCall(node) { + return ( + node.parent.type === "CallExpression" && + node.parent.arguments[0] === node && + astUtils.isSpecificMemberAccess( + node.parent.callee, + "Object", + /^definePropert(?:y|ies)$/u, + ) + ); + } + + /** + * Check to see if object prototype access is part of a prototype + * extension. There are three ways a prototype can be extended: + * 1. Assignment to prototype property (Object.prototype.foo = 1) + * 2. Object.defineProperty()/Object.defineProperties() on a prototype + * If prototype extension is detected, report the AssignmentExpression + * or CallExpression node. + * @param {ASTNode} identifierNode The Identifier representing the object + * which prototype is being accessed and possibly extended. + * @returns {void} + */ + function checkAndReportPrototypeExtension(identifierNode) { + if (!isPrototypePropertyAccessed(identifierNode)) { + return; // This is not `*.prototype` access. + } + + /* + * `identifierNode.parent` is a MemberExpression `*.prototype`. + * If it's an optional member access, it may be wrapped by a `ChainExpression` node. + */ + const prototypeNode = + identifierNode.parent.parent.type === "ChainExpression" + ? identifierNode.parent.parent + : identifierNode.parent; + + if (isAssigningToPropertyOf(prototypeNode)) { + // `*.prototype` -> MemberExpression -> AssignmentExpression + reportNode(prototypeNode.parent.parent, identifierNode.name); + } else if (isInDefinePropertyCall(prototypeNode)) { + // `*.prototype` -> CallExpression + reportNode(prototypeNode.parent, identifierNode.name); + } + } + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + modifiedBuiltins.forEach(builtin => { + const builtinVar = globalScope.set.get(builtin); + + if (builtinVar && builtinVar.references) { + builtinVar.references + .map(ref => ref.identifier) + .forEach(checkAndReportPrototypeExtension); + } + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extra-bind.js b/node_modules/eslint/lib/rules/no-extra-bind.js new file mode 100644 index 0000000000000000000000000000000000000000..73164f8d40946275a0f504b0a9347c5bc9a9f332 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-bind.js @@ -0,0 +1,224 @@ +/** + * @fileoverview Rule to flag unnecessary bind calls + * @author Bence Dányi + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SIDE_EFFECT_FREE_NODE_TYPES = new Set([ + "Literal", + "Identifier", + "ThisExpression", + "FunctionExpression", +]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary calls to `.bind()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extra-bind", + }, + + schema: [], + fixable: "code", + + messages: { + unexpected: "The function binding is unnecessary.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Checks if a node is free of side effects. + * + * This check is stricter than it needs to be, in order to keep the implementation simple. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is known to be side-effect free, false otherwise. + */ + function isSideEffectFree(node) { + return SIDE_EFFECT_FREE_NODE_TYPES.has(node.type); + } + + /** + * Reports a given function node. + * @param {ASTNode} node A node to report. This is a FunctionExpression or + * an ArrowFunctionExpression. + * @returns {void} + */ + function report(node) { + const memberNode = node.parent; + const callNode = + memberNode.parent.type === "ChainExpression" + ? memberNode.parent.parent + : memberNode.parent; + + context.report({ + node: callNode, + messageId: "unexpected", + loc: memberNode.property.loc, + + fix(fixer) { + if (!isSideEffectFree(callNode.arguments[0])) { + return null; + } + + /* + * The list of the first/last token pair of a removal range. + * This is two parts because closing parentheses may exist between the method name and arguments. + * E.g. `(function(){}.bind ) (obj)` + * ^^^^^ ^^^^^ < removal ranges + * E.g. `(function(){}?.['bind'] ) ?.(obj)` + * ^^^^^^^^^^ ^^^^^^^ < removal ranges + */ + const tokenPairs = [ + [ + // `.`, `?.`, or `[` token. + sourceCode.getTokenAfter( + memberNode.object, + astUtils.isNotClosingParenToken, + ), + + // property name or `]` token. + sourceCode.getLastToken(memberNode), + ], + [ + // `?.` or `(` token of arguments. + sourceCode.getTokenAfter( + memberNode, + astUtils.isNotClosingParenToken, + ), + + // `)` token of arguments. + sourceCode.getLastToken(callNode), + ], + ]; + const firstTokenToRemove = tokenPairs[0][0]; + const lastTokenToRemove = tokenPairs[1][1]; + + if ( + sourceCode.commentsExistBetween( + firstTokenToRemove, + lastTokenToRemove, + ) + ) { + return null; + } + + return tokenPairs.map(([start, end]) => + fixer.removeRange([start.range[0], end.range[1]]), + ); + }, + }); + } + + /** + * Checks whether or not a given function node is the callee of `.bind()` + * method. + * + * e.g. `(function() {}.bind(foo))` + * @param {ASTNode} node A node to report. This is a FunctionExpression or + * an ArrowFunctionExpression. + * @returns {boolean} `true` if the node is the callee of `.bind()` method. + */ + function isCalleeOfBindMethod(node) { + if (!astUtils.isSpecificMemberAccess(node.parent, null, "bind")) { + return false; + } + + // The node of `*.bind` member access. + const bindNode = + node.parent.parent.type === "ChainExpression" + ? node.parent.parent + : node.parent; + + return ( + bindNode.parent.type === "CallExpression" && + bindNode.parent.callee === bindNode && + bindNode.parent.arguments.length === 1 && + bindNode.parent.arguments[0].type !== "SpreadElement" + ); + } + + /** + * Adds a scope information object to the stack. + * @param {ASTNode} node A node to add. This node is a FunctionExpression + * or a FunctionDeclaration node. + * @returns {void} + */ + function enterFunction(node) { + scopeInfo = { + isBound: isCalleeOfBindMethod(node), + thisFound: false, + upper: scopeInfo, + }; + } + + /** + * Removes the scope information object from the top of the stack. + * At the same time, this reports the function node if the function has + * `.bind()` and the `this` keywords found. + * @param {ASTNode} node A node to remove. This node is a + * FunctionExpression or a FunctionDeclaration node. + * @returns {void} + */ + function exitFunction(node) { + if (scopeInfo.isBound && !scopeInfo.thisFound) { + report(node); + } + + scopeInfo = scopeInfo.upper; + } + + /** + * Reports a given arrow function if the function is callee of `.bind()` + * method. + * @param {ASTNode} node A node to report. This node is an + * ArrowFunctionExpression. + * @returns {void} + */ + function exitArrowFunction(node) { + if (isCalleeOfBindMethod(node)) { + report(node); + } + } + + /** + * Set the mark as the `this` keyword was found in this scope. + * @returns {void} + */ + function markAsThisFound() { + if (scopeInfo) { + scopeInfo.thisFound = true; + } + } + + return { + "ArrowFunctionExpression:exit": exitArrowFunction, + FunctionDeclaration: enterFunction, + "FunctionDeclaration:exit": exitFunction, + FunctionExpression: enterFunction, + "FunctionExpression:exit": exitFunction, + ThisExpression: markAsThisFound, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extra-boolean-cast.js b/node_modules/eslint/lib/rules/no-extra-boolean-cast.js new file mode 100644 index 0000000000000000000000000000000000000000..18019a8cd1cec3ed8294f8f4d49a31688c9852ef --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-boolean-cast.js @@ -0,0 +1,420 @@ +/** + * @fileoverview Rule to flag unnecessary double negation in Boolean contexts + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const eslintUtils = require("@eslint-community/eslint-utils"); + +const precedence = astUtils.getPrecedence; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{}], + + docs: { + description: "Disallow unnecessary boolean casts", + recommended: true, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-extra-boolean-cast", + }, + + schema: [ + { + anyOf: [ + { + type: "object", + properties: { + enforceForInnerExpressions: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + + // deprecated + { + type: "object", + properties: { + enforceForLogicalOperands: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + fixable: "code", + + messages: { + unexpectedCall: "Redundant Boolean call.", + unexpectedNegation: "Redundant double negation.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ enforceForLogicalOperands, enforceForInnerExpressions }] = + context.options; + + // Node types which have a test which will coerce values to booleans. + const BOOLEAN_NODE_TYPES = new Set([ + "IfStatement", + "DoWhileStatement", + "WhileStatement", + "ConditionalExpression", + "ForStatement", + ]); + + /** + * Check if a node is a Boolean function or constructor. + * @param {ASTNode} node the node + * @returns {boolean} If the node is Boolean function or constructor + */ + function isBooleanFunctionOrConstructorCall(node) { + // Boolean() and new Boolean() + return ( + (node.type === "CallExpression" || + node.type === "NewExpression") && + node.callee.type === "Identifier" && + node.callee.name === "Boolean" + ); + } + + /** + * Check if a node is in a context where its value would be coerced to a boolean at runtime. + * @param {ASTNode} node The node + * @returns {boolean} If it is in a boolean context + */ + function isInBooleanContext(node) { + return ( + (isBooleanFunctionOrConstructorCall(node.parent) && + node === node.parent.arguments[0]) || + (BOOLEAN_NODE_TYPES.has(node.parent.type) && + node === node.parent.test) || + // ! + (node.parent.type === "UnaryExpression" && + node.parent.operator === "!") + ); + } + + /** + * Checks whether the node is a context that should report an error + * Acts recursively if it is in a logical context + * @param {ASTNode} node the node + * @returns {boolean} If the node is in one of the flagged contexts + */ + function isInFlaggedContext(node) { + if (node.parent.type === "ChainExpression") { + return isInFlaggedContext(node.parent); + } + + /* + * legacy behavior - enforceForLogicalOperands will only recurse on + * logical expressions, not on other contexts. + * enforceForInnerExpressions will recurse on logical expressions + * as well as the other recursive syntaxes. + */ + + if (enforceForLogicalOperands || enforceForInnerExpressions) { + if (node.parent.type === "LogicalExpression") { + if ( + node.parent.operator === "||" || + node.parent.operator === "&&" + ) { + return isInFlaggedContext(node.parent); + } + + // Check the right hand side of a `??` operator. + if ( + enforceForInnerExpressions && + node.parent.operator === "??" && + node.parent.right === node + ) { + return isInFlaggedContext(node.parent); + } + } + } + + if (enforceForInnerExpressions) { + if ( + node.parent.type === "ConditionalExpression" && + (node.parent.consequent === node || + node.parent.alternate === node) + ) { + return isInFlaggedContext(node.parent); + } + + /* + * Check last expression only in a sequence, i.e. if ((1, 2, Boolean(3))) {}, since + * the others don't affect the result of the expression. + */ + if ( + node.parent.type === "SequenceExpression" && + node.parent.expressions.at(-1) === node + ) { + return isInFlaggedContext(node.parent); + } + } + + return isInBooleanContext(node); + } + + /** + * Check if a node has comments inside. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if it has comments inside. + */ + function hasCommentsInside(node) { + return Boolean(sourceCode.getCommentsInside(node).length); + } + + /** + * Checks if the given node is wrapped in grouping parentheses. Parentheses for constructs such as if() don't count. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is parenthesized. + * @private + */ + function isParenthesized(node) { + return eslintUtils.isParenthesized(1, node, sourceCode); + } + + /** + * Determines whether the given node needs to be parenthesized when replacing the previous node. + * It assumes that `previousNode` is the node to be reported by this rule, so it has a limited list + * of possible parent node types. By the same assumption, the node's role in a particular parent is already known. + * @param {ASTNode} previousNode Previous node. + * @param {ASTNode} node The node to check. + * @throws {Error} (Unreachable.) + * @returns {boolean} `true` if the node needs to be parenthesized. + */ + function needsParens(previousNode, node) { + if (previousNode.parent.type === "ChainExpression") { + return needsParens(previousNode.parent, node); + } + + if (isParenthesized(previousNode)) { + // parentheses around the previous node will stay, so there is no need for an additional pair + return false; + } + + // parent of the previous node will become parent of the replacement node + const parent = previousNode.parent; + + switch (parent.type) { + case "CallExpression": + case "NewExpression": + return node.type === "SequenceExpression"; + case "IfStatement": + case "DoWhileStatement": + case "WhileStatement": + case "ForStatement": + case "SequenceExpression": + return false; + case "ConditionalExpression": + if (previousNode === parent.test) { + return precedence(node) <= precedence(parent); + } + if ( + previousNode === parent.consequent || + previousNode === parent.alternate + ) { + return ( + precedence(node) < + precedence({ type: "AssignmentExpression" }) + ); + } + + /* c8 ignore next */ + throw new Error( + "Ternary child must be test, consequent, or alternate.", + ); + case "UnaryExpression": + return precedence(node) < precedence(parent); + case "LogicalExpression": + if ( + astUtils.isMixedLogicalAndCoalesceExpressions( + node, + parent, + ) + ) { + return true; + } + if (previousNode === parent.left) { + return precedence(node) < precedence(parent); + } + return precedence(node) <= precedence(parent); + + /* c8 ignore next */ + default: + throw new Error(`Unexpected parent type: ${parent.type}`); + } + } + + return { + UnaryExpression(node) { + const parent = node.parent; + + // Exit early if it's guaranteed not to match + if ( + node.operator !== "!" || + parent.type !== "UnaryExpression" || + parent.operator !== "!" + ) { + return; + } + + if (isInFlaggedContext(parent)) { + context.report({ + node: parent, + messageId: "unexpectedNegation", + fix(fixer) { + if (hasCommentsInside(parent)) { + return null; + } + + if (needsParens(parent, node.argument)) { + return fixer.replaceText( + parent, + `(${sourceCode.getText(node.argument)})`, + ); + } + + let prefix = ""; + const tokenBefore = + sourceCode.getTokenBefore(parent); + const firstReplacementToken = + sourceCode.getFirstToken(node.argument); + + if ( + tokenBefore && + tokenBefore.range[1] === parent.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBefore, + firstReplacementToken, + ) + ) { + prefix = " "; + } + + return fixer.replaceText( + parent, + prefix + sourceCode.getText(node.argument), + ); + }, + }); + } + }, + + CallExpression(node) { + if ( + node.callee.type !== "Identifier" || + node.callee.name !== "Boolean" + ) { + return; + } + + if (isInFlaggedContext(node)) { + context.report({ + node, + messageId: "unexpectedCall", + fix(fixer) { + const parent = node.parent; + + if (node.arguments.length === 0) { + if ( + parent.type === "UnaryExpression" && + parent.operator === "!" + ) { + /* + * !Boolean() -> true + */ + + if (hasCommentsInside(parent)) { + return null; + } + + const replacement = "true"; + let prefix = ""; + const tokenBefore = + sourceCode.getTokenBefore(parent); + + if ( + tokenBefore && + tokenBefore.range[1] === + parent.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBefore, + replacement, + ) + ) { + prefix = " "; + } + + return fixer.replaceText( + parent, + prefix + replacement, + ); + } + + /* + * Boolean() -> false + */ + + if (hasCommentsInside(node)) { + return null; + } + + return fixer.replaceText(node, "false"); + } + + if (node.arguments.length === 1) { + const argument = node.arguments[0]; + + if ( + argument.type === "SpreadElement" || + hasCommentsInside(node) + ) { + return null; + } + + /* + * Boolean(expression) -> expression + */ + + if (needsParens(node, argument)) { + return fixer.replaceText( + node, + `(${sourceCode.getText(argument)})`, + ); + } + + return fixer.replaceText( + node, + sourceCode.getText(argument), + ); + } + + // two or more arguments + return null; + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extra-label.js b/node_modules/eslint/lib/rules/no-extra-label.js new file mode 100644 index 0000000000000000000000000000000000000000..c191eee7ffd93808bfa30b3ad06d486ab7acbe78 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-label.js @@ -0,0 +1,169 @@ +/** + * @fileoverview Rule to disallow unnecessary labels + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary labels", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-extra-label", + }, + + schema: [], + fixable: "code", + + messages: { + unexpected: "This label '{{name}}' is unnecessary.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Creates a new scope with a breakable statement. + * @param {ASTNode} node A node to create. This is a BreakableStatement. + * @returns {void} + */ + function enterBreakableStatement(node) { + scopeInfo = { + label: + node.parent.type === "LabeledStatement" + ? node.parent.label + : null, + breakable: true, + upper: scopeInfo, + }; + } + + /** + * Removes the top scope of the stack. + * @returns {void} + */ + function exitBreakableStatement() { + scopeInfo = scopeInfo.upper; + } + + /** + * Creates a new scope with a labeled statement. + * + * This ignores it if the body is a breakable statement. + * In this case it's handled in the `enterBreakableStatement` function. + * @param {ASTNode} node A node to create. This is a LabeledStatement. + * @returns {void} + */ + function enterLabeledStatement(node) { + if (!astUtils.isBreakableStatement(node.body)) { + scopeInfo = { + label: node.label, + breakable: false, + upper: scopeInfo, + }; + } + } + + /** + * Removes the top scope of the stack. + * + * This ignores it if the body is a breakable statement. + * In this case it's handled in the `exitBreakableStatement` function. + * @param {ASTNode} node A node. This is a LabeledStatement. + * @returns {void} + */ + function exitLabeledStatement(node) { + if (!astUtils.isBreakableStatement(node.body)) { + scopeInfo = scopeInfo.upper; + } + } + + /** + * Reports a given control node if it's unnecessary. + * @param {ASTNode} node A node. This is a BreakStatement or a + * ContinueStatement. + * @returns {void} + */ + function reportIfUnnecessary(node) { + if (!node.label) { + return; + } + + const labelNode = node.label; + + for (let info = scopeInfo; info !== null; info = info.upper) { + if ( + info.breakable || + (info.label && info.label.name === labelNode.name) + ) { + if ( + info.breakable && + info.label && + info.label.name === labelNode.name + ) { + context.report({ + node: labelNode, + messageId: "unexpected", + data: labelNode, + fix(fixer) { + const breakOrContinueToken = + sourceCode.getFirstToken(node); + + if ( + sourceCode.commentsExistBetween( + breakOrContinueToken, + labelNode, + ) + ) { + return null; + } + + return fixer.removeRange([ + breakOrContinueToken.range[1], + labelNode.range[1], + ]); + }, + }); + } + return; + } + } + } + + return { + WhileStatement: enterBreakableStatement, + "WhileStatement:exit": exitBreakableStatement, + DoWhileStatement: enterBreakableStatement, + "DoWhileStatement:exit": exitBreakableStatement, + ForStatement: enterBreakableStatement, + "ForStatement:exit": exitBreakableStatement, + ForInStatement: enterBreakableStatement, + "ForInStatement:exit": exitBreakableStatement, + ForOfStatement: enterBreakableStatement, + "ForOfStatement:exit": exitBreakableStatement, + SwitchStatement: enterBreakableStatement, + "SwitchStatement:exit": exitBreakableStatement, + LabeledStatement: enterLabeledStatement, + "LabeledStatement:exit": exitLabeledStatement, + BreakStatement: reportIfUnnecessary, + ContinueStatement: reportIfUnnecessary, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extra-parens.js b/node_modules/eslint/lib/rules/no-extra-parens.js new file mode 100644 index 0000000000000000000000000000000000000000..133ad0b3eaed5d3cb032d313946308b93303236b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-parens.js @@ -0,0 +1,1669 @@ +/** + * @fileoverview Disallow parenthesising higher precedence subexpressions. + * @author Michael Ficarra + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const { + isParenthesized: isParenthesizedRaw, +} = require("@eslint-community/eslint-utils"); +const astUtils = require("./utils/ast-utils.js"); + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "no-extra-parens", + url: "https://eslint.style/rules/no-extra-parens", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow unnecessary parentheses", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extra-parens", + }, + + fixable: "code", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["functions"], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["all"], + }, + { + type: "object", + properties: { + conditionalAssign: { type: "boolean" }, + ternaryOperandBinaryExpressions: { + type: "boolean", + }, + nestedBinaryExpressions: { type: "boolean" }, + returnAssign: { type: "boolean" }, + ignoreJSX: { + enum: [ + "none", + "all", + "single-line", + "multi-line", + ], + }, + enforceForArrowConditionals: { + type: "boolean", + }, + enforceForSequenceExpressions: { + type: "boolean", + }, + enforceForNewInMemberExpressions: { + type: "boolean", + }, + enforceForFunctionPrototypeMethods: { + type: "boolean", + }, + allowParensAfterCommentPattern: { + type: "string", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + messages: { + unexpected: "Unnecessary parentheses around expression.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const tokensToIgnore = new WeakSet(); + const precedence = astUtils.getPrecedence; + const ALL_NODES = context.options[0] !== "functions"; + const EXCEPT_COND_ASSIGN = + ALL_NODES && + context.options[1] && + context.options[1].conditionalAssign === false; + const EXCEPT_COND_TERNARY = + ALL_NODES && + context.options[1] && + context.options[1].ternaryOperandBinaryExpressions === false; + const NESTED_BINARY = + ALL_NODES && + context.options[1] && + context.options[1].nestedBinaryExpressions === false; + const EXCEPT_RETURN_ASSIGN = + ALL_NODES && + context.options[1] && + context.options[1].returnAssign === false; + const IGNORE_JSX = + ALL_NODES && context.options[1] && context.options[1].ignoreJSX; + const IGNORE_ARROW_CONDITIONALS = + ALL_NODES && + context.options[1] && + context.options[1].enforceForArrowConditionals === false; + const IGNORE_SEQUENCE_EXPRESSIONS = + ALL_NODES && + context.options[1] && + context.options[1].enforceForSequenceExpressions === false; + const IGNORE_NEW_IN_MEMBER_EXPR = + ALL_NODES && + context.options[1] && + context.options[1].enforceForNewInMemberExpressions === false; + const IGNORE_FUNCTION_PROTOTYPE_METHODS = + ALL_NODES && + context.options[1] && + context.options[1].enforceForFunctionPrototypeMethods === false; + const ALLOW_PARENS_AFTER_COMMENT_PATTERN = + ALL_NODES && + context.options[1] && + context.options[1].allowParensAfterCommentPattern; + + const PRECEDENCE_OF_ASSIGNMENT_EXPR = precedence({ + type: "AssignmentExpression", + }); + const PRECEDENCE_OF_UPDATE_EXPR = precedence({ + type: "UpdateExpression", + }); + + let reportsBuffer; + + /** + * Determines whether the given node is a `call` or `apply` method call, invoked directly on a `FunctionExpression` node. + * Example: function(){}.call() + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is an immediate `call` or `apply` method call. + * @private + */ + function isImmediateFunctionPrototypeMethodCall(node) { + const callNode = astUtils.skipChainExpression(node); + + if (callNode.type !== "CallExpression") { + return false; + } + const callee = astUtils.skipChainExpression(callNode.callee); + + return ( + callee.type === "MemberExpression" && + callee.object.type === "FunctionExpression" && + ["call", "apply"].includes( + astUtils.getStaticPropertyName(callee), + ) + ); + } + + /** + * Determines if this rule should be enforced for a node given the current configuration. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the rule should be enforced for this node. + * @private + */ + function ruleApplies(node) { + if (node.type === "JSXElement" || node.type === "JSXFragment") { + const isSingleLine = node.loc.start.line === node.loc.end.line; + + switch (IGNORE_JSX) { + // Exclude this JSX element from linting + case "all": + return false; + + // Exclude this JSX element if it is multi-line element + case "multi-line": + return isSingleLine; + + // Exclude this JSX element if it is single-line element + case "single-line": + return !isSingleLine; + + // Nothing special to be done for JSX elements + case "none": + break; + + // no default + } + } + + if ( + node.type === "SequenceExpression" && + IGNORE_SEQUENCE_EXPRESSIONS + ) { + return false; + } + + if ( + isImmediateFunctionPrototypeMethodCall(node) && + IGNORE_FUNCTION_PROTOTYPE_METHODS + ) { + return false; + } + + return ( + ALL_NODES || + node.type === "FunctionExpression" || + node.type === "ArrowFunctionExpression" + ); + } + + /** + * Determines if a node is surrounded by parentheses. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is parenthesised. + * @private + */ + function isParenthesised(node) { + return isParenthesizedRaw(1, node, sourceCode); + } + + /** + * Determines if a node is surrounded by parentheses twice. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is doubly parenthesised. + * @private + */ + function isParenthesisedTwice(node) { + return isParenthesizedRaw(2, node, sourceCode); + } + + /** + * Determines if a node is surrounded by (potentially) invalid parentheses. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is incorrectly parenthesised. + * @private + */ + function hasExcessParens(node) { + return ruleApplies(node) && isParenthesised(node); + } + + /** + * Determines if a node that is expected to be parenthesised is surrounded by + * (potentially) invalid extra parentheses. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is has an unexpected extra pair of parentheses. + * @private + */ + function hasDoubleExcessParens(node) { + return ruleApplies(node) && isParenthesisedTwice(node); + } + + /** + * Determines if a node that is expected to be parenthesised is surrounded by + * (potentially) invalid extra parentheses with considering precedence level of the node. + * If the preference level of the node is not higher or equal to precedence lower limit, it also checks + * whether the node is surrounded by parentheses twice or not. + * @param {ASTNode} node The node to be checked. + * @param {number} precedenceLowerLimit The lower limit of precedence. + * @returns {boolean} True if the node is has an unexpected extra pair of parentheses. + * @private + */ + function hasExcessParensWithPrecedence(node, precedenceLowerLimit) { + if (ruleApplies(node) && isParenthesised(node)) { + if ( + precedence(node) >= precedenceLowerLimit || + isParenthesisedTwice(node) + ) { + return true; + } + } + return false; + } + + /** + * Determines if a node test expression is allowed to have a parenthesised assignment + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the assignment can be parenthesised. + * @private + */ + function isCondAssignException(node) { + return ( + EXCEPT_COND_ASSIGN && node.test.type === "AssignmentExpression" + ); + } + + /** + * Determines if a node is in a return statement + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is in a return statement. + * @private + */ + function isInReturnStatement(node) { + for ( + let currentNode = node; + currentNode; + currentNode = currentNode.parent + ) { + if ( + currentNode.type === "ReturnStatement" || + (currentNode.type === "ArrowFunctionExpression" && + currentNode.body.type !== "BlockStatement") + ) { + return true; + } + } + + return false; + } + + /** + * Determines if a constructor function is newed-up with parens + * @param {ASTNode} newExpression The NewExpression node to be checked. + * @returns {boolean} True if the constructor is called with parens. + * @private + */ + function isNewExpressionWithParens(newExpression) { + const lastToken = sourceCode.getLastToken(newExpression); + const penultimateToken = sourceCode.getTokenBefore(lastToken); + + return ( + newExpression.arguments.length > 0 || + // The expression should end with its own parens, e.g., new new foo() is not a new expression with parens + (astUtils.isOpeningParenToken(penultimateToken) && + astUtils.isClosingParenToken(lastToken) && + newExpression.callee.range[1] < newExpression.range[1]) + ); + } + + /** + * Determines if a node is or contains an assignment expression + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is or contains an assignment expression. + * @private + */ + function containsAssignment(node) { + if (node.type === "AssignmentExpression") { + return true; + } + if ( + node.type === "ConditionalExpression" && + (node.consequent.type === "AssignmentExpression" || + node.alternate.type === "AssignmentExpression") + ) { + return true; + } + if ( + (node.left && node.left.type === "AssignmentExpression") || + (node.right && node.right.type === "AssignmentExpression") + ) { + return true; + } + + return false; + } + + /** + * Determines if a node is contained by or is itself a return statement and is allowed to have a parenthesised assignment + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the assignment can be parenthesised. + * @private + */ + function isReturnAssignException(node) { + if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) { + return false; + } + + if (node.type === "ReturnStatement") { + return node.argument && containsAssignment(node.argument); + } + if ( + node.type === "ArrowFunctionExpression" && + node.body.type !== "BlockStatement" + ) { + return containsAssignment(node.body); + } + return containsAssignment(node); + } + + /** + * Determines if a node following a [no LineTerminator here] restriction is + * surrounded by (potentially) invalid extra parentheses. + * @param {Token} token The token preceding the [no LineTerminator here] restriction. + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is incorrectly parenthesised. + * @private + */ + function hasExcessParensNoLineTerminator(token, node) { + if (token.loc.end.line === node.loc.start.line) { + return hasExcessParens(node); + } + + return hasDoubleExcessParens(node); + } + + /** + * Determines whether a node should be preceded by an additional space when removing parens + * @param {ASTNode} node node to evaluate; must be surrounded by parentheses + * @returns {boolean} `true` if a space should be inserted before the node + * @private + */ + function requiresLeadingSpace(node) { + const leftParenToken = sourceCode.getTokenBefore(node); + const tokenBeforeLeftParen = sourceCode.getTokenBefore( + leftParenToken, + { includeComments: true }, + ); + const tokenAfterLeftParen = sourceCode.getTokenAfter( + leftParenToken, + { includeComments: true }, + ); + + return ( + tokenBeforeLeftParen && + tokenBeforeLeftParen.range[1] === leftParenToken.range[0] && + leftParenToken.range[1] === tokenAfterLeftParen.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBeforeLeftParen, + tokenAfterLeftParen, + ) + ); + } + + /** + * Determines whether a node should be followed by an additional space when removing parens + * @param {ASTNode} node node to evaluate; must be surrounded by parentheses + * @returns {boolean} `true` if a space should be inserted after the node + * @private + */ + function requiresTrailingSpace(node) { + const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 }); + const rightParenToken = nextTwoTokens[0]; + const tokenAfterRightParen = nextTwoTokens[1]; + const tokenBeforeRightParen = sourceCode.getLastToken(node); + + return ( + rightParenToken && + tokenAfterRightParen && + !sourceCode.isSpaceBetween( + rightParenToken, + tokenAfterRightParen, + ) && + !astUtils.canTokensBeAdjacent( + tokenBeforeRightParen, + tokenAfterRightParen, + ) + ); + } + + /** + * Determines if a given expression node is an IIFE + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if the given node is an IIFE + */ + function isIIFE(node) { + const maybeCallNode = astUtils.skipChainExpression(node); + + return ( + maybeCallNode.type === "CallExpression" && + maybeCallNode.callee.type === "FunctionExpression" + ); + } + + /** + * Determines if the given node can be the assignment target in destructuring or the LHS of an assignment. + * This is to avoid an autofix that could change behavior because parsers mistakenly allow invalid syntax, + * such as `(a = b) = c` and `[(a = b) = c] = []`. Ideally, this function shouldn't be necessary. + * @param {ASTNode} [node] The node to check + * @returns {boolean} `true` if the given node can be a valid assignment target + */ + function canBeAssignmentTarget(node) { + return ( + node && + (node.type === "Identifier" || node.type === "MemberExpression") + ); + } + + /** + * Checks if a node is fixable. + * A node is fixable if removing a single pair of surrounding parentheses does not turn it + * into a directive after fixing other nodes. + * Almost all nodes are fixable, except if all of the following conditions are met: + * The node is a string Literal + * It has a single pair of parentheses + * It is the only child of an ExpressionStatement + * @param {ASTNode} node The node to evaluate. + * @returns {boolean} Whether or not the node is fixable. + * @private + */ + function isFixable(node) { + // if it's not a string literal it can be autofixed + if (node.type !== "Literal" || typeof node.value !== "string") { + return true; + } + if (isParenthesisedTwice(node)) { + return true; + } + return !astUtils.isTopLevelExpressionStatement(node.parent); + } + + /** + * Report the node + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function report(node) { + const leftParenToken = sourceCode.getTokenBefore(node); + const rightParenToken = sourceCode.getTokenAfter(node); + + if (!isParenthesisedTwice(node)) { + if (tokensToIgnore.has(sourceCode.getFirstToken(node))) { + return; + } + + if (isIIFE(node) && !isParenthesised(node.callee)) { + return; + } + + if (ALLOW_PARENS_AFTER_COMMENT_PATTERN) { + const commentsBeforeLeftParenToken = + sourceCode.getCommentsBefore(leftParenToken); + const totalCommentsBeforeLeftParenTokenCount = + commentsBeforeLeftParenToken.length; + const ignorePattern = new RegExp( + ALLOW_PARENS_AFTER_COMMENT_PATTERN, + "u", + ); + + if ( + totalCommentsBeforeLeftParenTokenCount > 0 && + ignorePattern.test( + commentsBeforeLeftParenToken[ + totalCommentsBeforeLeftParenTokenCount - 1 + ].value, + ) + ) { + return; + } + } + } + + /** + * Finishes reporting + * @returns {void} + * @private + */ + function finishReport() { + context.report({ + node, + loc: leftParenToken.loc, + messageId: "unexpected", + fix: isFixable(node) + ? fixer => { + const parenthesizedSource = + sourceCode.text.slice( + leftParenToken.range[1], + rightParenToken.range[0], + ); + + return fixer.replaceTextRange( + [ + leftParenToken.range[0], + rightParenToken.range[1], + ], + (requiresLeadingSpace(node) ? " " : "") + + parenthesizedSource + + (requiresTrailingSpace(node) + ? " " + : ""), + ); + } + : null, + }); + } + + if (reportsBuffer) { + reportsBuffer.reports.push({ node, finishReport }); + return; + } + + finishReport(); + } + + /** + * Evaluate a argument of the node. + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkArgumentWithPrecedence(node) { + if ( + hasExcessParensWithPrecedence(node.argument, precedence(node)) + ) { + report(node.argument); + } + } + + /** + * Check if a member expression contains a call expression + * @param {ASTNode} node MemberExpression node to evaluate + * @returns {boolean} true if found, false if not + */ + function doesMemberExpressionContainCallExpression(node) { + let currentNode = node.object; + let currentNodeType = node.object.type; + + while (currentNodeType === "MemberExpression") { + currentNode = currentNode.object; + currentNodeType = currentNode.type; + } + + return currentNodeType === "CallExpression"; + } + + /** + * Evaluate a new call + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkCallNew(node) { + const callee = node.callee; + + if (hasExcessParensWithPrecedence(callee, precedence(node))) { + if ( + hasDoubleExcessParens(callee) || + !( + isIIFE(node) || + // (new A)(); new (new A)(); + (callee.type === "NewExpression" && + !isNewExpressionWithParens(callee) && + !( + node.type === "NewExpression" && + !isNewExpressionWithParens(node) + )) || + // new (a().b)(); new (a.b().c); + (node.type === "NewExpression" && + callee.type === "MemberExpression" && + doesMemberExpressionContainCallExpression( + callee, + )) || + // (a?.b)(); (a?.())(); + (!node.optional && callee.type === "ChainExpression") + ) + ) { + report(node.callee); + } + } + node.arguments + .filter(arg => + hasExcessParensWithPrecedence( + arg, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ), + ) + .forEach(report); + } + + /** + * Evaluate binary logicals + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkBinaryLogical(node) { + const prec = precedence(node); + const leftPrecedence = precedence(node.left); + const rightPrecedence = precedence(node.right); + const isExponentiation = node.operator === "**"; + const shouldSkipLeft = + NESTED_BINARY && + (node.left.type === "BinaryExpression" || + node.left.type === "LogicalExpression"); + const shouldSkipRight = + NESTED_BINARY && + (node.right.type === "BinaryExpression" || + node.right.type === "LogicalExpression"); + + if (!shouldSkipLeft && hasExcessParens(node.left)) { + if ( + (!( + ["AwaitExpression", "UnaryExpression"].includes( + node.left.type, + ) && isExponentiation + ) && + !astUtils.isMixedLogicalAndCoalesceExpressions( + node.left, + node, + ) && + (leftPrecedence > prec || + (leftPrecedence === prec && !isExponentiation))) || + isParenthesisedTwice(node.left) + ) { + report(node.left); + } + } + + if (!shouldSkipRight && hasExcessParens(node.right)) { + if ( + (!astUtils.isMixedLogicalAndCoalesceExpressions( + node.right, + node, + ) && + (rightPrecedence > prec || + (rightPrecedence === prec && isExponentiation))) || + isParenthesisedTwice(node.right) + ) { + report(node.right); + } + } + } + + /** + * Check the parentheses around the super class of the given class definition. + * @param {ASTNode} node The node of class declarations to check. + * @returns {void} + */ + function checkClass(node) { + if (!node.superClass) { + return; + } + + /* + * If `node.superClass` is a LeftHandSideExpression, parentheses are extra. + * Otherwise, parentheses are needed. + */ + const hasExtraParens = + precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR + ? hasExcessParens(node.superClass) + : hasDoubleExcessParens(node.superClass); + + if (hasExtraParens) { + report(node.superClass); + } + } + + /** + * Check the parentheses around the argument of the given spread operator. + * @param {ASTNode} node The node of spread elements/properties to check. + * @returns {void} + */ + function checkSpreadOperator(node) { + if ( + hasExcessParensWithPrecedence( + node.argument, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.argument); + } + } + + /** + * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration + * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node + * @returns {void} + */ + function checkExpressionOrExportStatement(node) { + const firstToken = isParenthesised(node) + ? sourceCode.getTokenBefore(node) + : sourceCode.getFirstToken(node); + const secondToken = sourceCode.getTokenAfter( + firstToken, + astUtils.isNotOpeningParenToken, + ); + const thirdToken = secondToken + ? sourceCode.getTokenAfter(secondToken) + : null; + const tokenAfterClosingParens = secondToken + ? sourceCode.getTokenAfter( + secondToken, + astUtils.isNotClosingParenToken, + ) + : null; + + if ( + astUtils.isOpeningParenToken(firstToken) && + (astUtils.isOpeningBraceToken(secondToken) || + (secondToken.type === "Keyword" && + (secondToken.value === "function" || + secondToken.value === "class" || + (secondToken.value === "let" && + tokenAfterClosingParens && + (astUtils.isOpeningBracketToken( + tokenAfterClosingParens, + ) || + tokenAfterClosingParens.type === + "Identifier")))) || + (secondToken && + secondToken.type === "Identifier" && + secondToken.value === "async" && + thirdToken && + thirdToken.type === "Keyword" && + thirdToken.value === "function")) + ) { + tokensToIgnore.add(secondToken); + } + + const hasExtraParens = + node.parent.type === "ExportDefaultDeclaration" + ? hasExcessParensWithPrecedence( + node, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + : hasExcessParens(node); + + if (hasExtraParens) { + report(node); + } + } + + /** + * Finds the path from the given node to the specified ancestor. + * @param {ASTNode} node First node in the path. + * @param {ASTNode} ancestor Last node in the path. + * @returns {ASTNode[]} Path, including both nodes. + * @throws {Error} If the given node does not have the specified ancestor. + */ + function pathToAncestor(node, ancestor) { + const path = [node]; + let currentNode = node; + + while (currentNode !== ancestor) { + currentNode = currentNode.parent; + + /* c8 ignore start */ + if (currentNode === null) { + throw new Error( + "Nodes are not in the ancestor-descendant relationship.", + ); + } /* c8 ignore stop */ + + path.push(currentNode); + } + + return path; + } + + /** + * Finds the path from the given node to the specified descendant. + * @param {ASTNode} node First node in the path. + * @param {ASTNode} descendant Last node in the path. + * @returns {ASTNode[]} Path, including both nodes. + * @throws {Error} If the given node does not have the specified descendant. + */ + function pathToDescendant(node, descendant) { + return pathToAncestor(descendant, node).reverse(); + } + + /** + * Checks whether the syntax of the given ancestor of an 'in' expression inside a for-loop initializer + * is preventing the 'in' keyword from being interpreted as a part of an ill-formed for-in loop. + * @param {ASTNode} node Ancestor of an 'in' expression. + * @param {ASTNode} child Child of the node, ancestor of the same 'in' expression or the 'in' expression itself. + * @returns {boolean} True if the keyword 'in' would be interpreted as the 'in' operator, without any parenthesis. + */ + function isSafelyEnclosingInExpression(node, child) { + switch (node.type) { + case "ArrayExpression": + case "ArrayPattern": + case "BlockStatement": + case "ObjectExpression": + case "ObjectPattern": + case "TemplateLiteral": + return true; + case "ArrowFunctionExpression": + case "FunctionExpression": + return node.params.includes(child); + case "CallExpression": + case "NewExpression": + return node.arguments.includes(child); + case "MemberExpression": + return node.computed && node.property === child; + case "ConditionalExpression": + return node.consequent === child; + default: + return false; + } + } + + /** + * Starts a new reports buffering. Warnings will be stored in a buffer instead of being reported immediately. + * An additional logic that requires multiple nodes (e.g. a whole subtree) may dismiss some of the stored warnings. + * @returns {void} + */ + function startNewReportsBuffering() { + reportsBuffer = { + upper: reportsBuffer, + inExpressionNodes: [], + reports: [], + }; + } + + /** + * Ends the current reports buffering. + * @returns {void} + */ + function endCurrentReportsBuffering() { + const { upper, inExpressionNodes, reports } = reportsBuffer; + + if (upper) { + upper.inExpressionNodes.push(...inExpressionNodes); + upper.reports.push(...reports); + } else { + // flush remaining reports + reports.forEach(({ finishReport }) => finishReport()); + } + + reportsBuffer = upper; + } + + /** + * Checks whether the given node is in the current reports buffer. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is in the current buffer, false otherwise. + */ + function isInCurrentReportsBuffer(node) { + return reportsBuffer.reports.some(r => r.node === node); + } + + /** + * Removes the given node from the current reports buffer. + * @param {ASTNode} node Node to remove. + * @returns {void} + */ + function removeFromCurrentReportsBuffer(node) { + reportsBuffer.reports = reportsBuffer.reports.filter( + r => r.node !== node, + ); + } + + /** + * Checks whether a node is a MemberExpression at NewExpression's callee. + * @param {ASTNode} node node to check. + * @returns {boolean} True if the node is a MemberExpression at NewExpression's callee. false otherwise. + */ + function isMemberExpInNewCallee(node) { + if (node.type === "MemberExpression") { + return node.parent.type === "NewExpression" && + node.parent.callee === node + ? true + : node.parent.object === node && + isMemberExpInNewCallee(node.parent); + } + return false; + } + + /** + * Checks if the left-hand side of an assignment is an identifier, the operator is one of + * `=`, `&&=`, `||=` or `??=` and the right-hand side is an anonymous class or function. + * + * As per https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation, an + * assignment involving one of the operators `=`, `&&=`, `||=` or `??=` where the right-hand + * side is an anonymous class or function and the left-hand side is an *unparenthesized* + * identifier has different semantics than other assignments. + * Specifically, when an expression like `foo = function () {}` is evaluated, `foo.name` + * will be set to the string "foo", i.e. the identifier name. The same thing does not happen + * when evaluating `(foo) = function () {}`. + * Since the parenthesizing of the identifier in the left-hand side is significant in this + * special case, the parentheses, if present, should not be flagged as unnecessary. + * @param {ASTNode} node an AssignmentExpression node. + * @returns {boolean} `true` if the left-hand side of the assignment is an identifier, the + * operator is one of `=`, `&&=`, `||=` or `??=` and the right-hand side is an anonymous + * class or function; otherwise, `false`. + */ + function isAnonymousFunctionAssignmentException({ + left, + operator, + right, + }) { + if ( + left.type === "Identifier" && + ["=", "&&=", "||=", "??="].includes(operator) + ) { + const rhsType = right.type; + + if (rhsType === "ArrowFunctionExpression") { + return true; + } + if ( + (rhsType === "FunctionExpression" || + rhsType === "ClassExpression") && + !right.id + ) { + return true; + } + } + return false; + } + + return { + ArrayExpression(node) { + node.elements + .filter( + e => + e && + hasExcessParensWithPrecedence( + e, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ), + ) + .forEach(report); + }, + + ArrayPattern(node) { + node.elements + .filter(e => canBeAssignmentTarget(e) && hasExcessParens(e)) + .forEach(report); + }, + + ArrowFunctionExpression(node) { + if (isReturnAssignException(node)) { + return; + } + + if ( + node.body.type === "ConditionalExpression" && + IGNORE_ARROW_CONDITIONALS + ) { + return; + } + + if (node.body.type !== "BlockStatement") { + const firstBodyToken = sourceCode.getFirstToken( + node.body, + astUtils.isNotOpeningParenToken, + ); + const tokenBeforeFirst = + sourceCode.getTokenBefore(firstBodyToken); + + if ( + astUtils.isOpeningParenToken(tokenBeforeFirst) && + astUtils.isOpeningBraceToken(firstBodyToken) + ) { + tokensToIgnore.add(firstBodyToken); + } + if ( + hasExcessParensWithPrecedence( + node.body, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.body); + } + } + }, + + AssignmentExpression(node) { + if ( + canBeAssignmentTarget(node.left) && + hasExcessParens(node.left) && + (!isAnonymousFunctionAssignmentException(node) || + isParenthesisedTwice(node.left)) + ) { + report(node.left); + } + + if ( + !isReturnAssignException(node) && + hasExcessParensWithPrecedence(node.right, precedence(node)) + ) { + report(node.right); + } + }, + + BinaryExpression(node) { + if (reportsBuffer && node.operator === "in") { + reportsBuffer.inExpressionNodes.push(node); + } + + checkBinaryLogical(node); + }, + + CallExpression: checkCallNew, + + ConditionalExpression(node) { + if (isReturnAssignException(node)) { + return; + } + + const availableTypes = new Set([ + "BinaryExpression", + "LogicalExpression", + ]); + + if ( + !( + EXCEPT_COND_TERNARY && + availableTypes.has(node.test.type) + ) && + !isCondAssignException(node) && + hasExcessParensWithPrecedence( + node.test, + precedence({ + type: "LogicalExpression", + operator: "||", + }), + ) + ) { + report(node.test); + } + + if ( + !( + EXCEPT_COND_TERNARY && + availableTypes.has(node.consequent.type) + ) && + hasExcessParensWithPrecedence( + node.consequent, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.consequent); + } + + if ( + !( + EXCEPT_COND_TERNARY && + availableTypes.has(node.alternate.type) + ) && + hasExcessParensWithPrecedence( + node.alternate, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.alternate); + } + }, + + DoWhileStatement(node) { + if ( + hasExcessParens(node.test) && + !isCondAssignException(node) + ) { + report(node.test); + } + }, + + ExportDefaultDeclaration: node => + checkExpressionOrExportStatement(node.declaration), + ExpressionStatement: node => + checkExpressionOrExportStatement(node.expression), + + ForInStatement(node) { + if (node.left.type !== "VariableDeclaration") { + const firstLeftToken = sourceCode.getFirstToken( + node.left, + astUtils.isNotOpeningParenToken, + ); + + if ( + firstLeftToken.value === "let" && + astUtils.isOpeningBracketToken( + sourceCode.getTokenAfter( + firstLeftToken, + astUtils.isNotClosingParenToken, + ), + ) + ) { + // ForInStatement#left expression cannot start with `let[`. + tokensToIgnore.add(firstLeftToken); + } + } + + if (hasExcessParens(node.left)) { + report(node.left); + } + + if (hasExcessParens(node.right)) { + report(node.right); + } + }, + + ForOfStatement(node) { + if (node.left.type !== "VariableDeclaration") { + const firstLeftToken = sourceCode.getFirstToken( + node.left, + astUtils.isNotOpeningParenToken, + ); + + if (firstLeftToken.value === "let") { + // ForOfStatement#left expression cannot start with `let`. + tokensToIgnore.add(firstLeftToken); + } + } + + if (hasExcessParens(node.left)) { + report(node.left); + } + + if ( + hasExcessParensWithPrecedence( + node.right, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.right); + } + }, + + ForStatement(node) { + if ( + node.test && + hasExcessParens(node.test) && + !isCondAssignException(node) + ) { + report(node.test); + } + + if (node.update && hasExcessParens(node.update)) { + report(node.update); + } + + if (node.init) { + if (node.init.type !== "VariableDeclaration") { + const firstToken = sourceCode.getFirstToken( + node.init, + astUtils.isNotOpeningParenToken, + ); + + if ( + firstToken.value === "let" && + astUtils.isOpeningBracketToken( + sourceCode.getTokenAfter( + firstToken, + astUtils.isNotClosingParenToken, + ), + ) + ) { + // ForStatement#init expression cannot start with `let[`. + tokensToIgnore.add(firstToken); + } + } + + startNewReportsBuffering(); + + if (hasExcessParens(node.init)) { + report(node.init); + } + } + }, + + "ForStatement > *.init:exit"(node) { + /* + * Removing parentheses around `in` expressions might change semantics and cause errors. + * + * For example, this valid for loop: + * for (let a = (b in c); ;); + * after removing parentheses would be treated as an invalid for-in loop: + * for (let a = b in c; ;); + */ + + if (reportsBuffer.reports.length) { + reportsBuffer.inExpressionNodes.forEach( + inExpressionNode => { + const path = pathToDescendant( + node, + inExpressionNode, + ); + let nodeToExclude; + + for (let i = 0; i < path.length; i++) { + const pathNode = path[i]; + + if (i < path.length - 1) { + const nextPathNode = path[i + 1]; + + if ( + isSafelyEnclosingInExpression( + pathNode, + nextPathNode, + ) + ) { + // The 'in' expression in safely enclosed by the syntax of its ancestor nodes (e.g. by '{}' or '[]'). + return; + } + } + + if (isParenthesised(pathNode)) { + if (isInCurrentReportsBuffer(pathNode)) { + // This node was supposed to be reported, but parentheses might be necessary. + + if (isParenthesisedTwice(pathNode)) { + /* + * This node is parenthesised twice, it certainly has at least one pair of `extra` parentheses. + * If the --fix option is on, the current fixing iteration will remove only one pair of parentheses. + * The remaining pair is safely enclosing the 'in' expression. + */ + return; + } + + // Exclude the outermost node only. + if (!nodeToExclude) { + nodeToExclude = pathNode; + } + + // Don't break the loop here, there might be some safe nodes or parentheses that will stay inside. + } else { + // This node will stay parenthesised, the 'in' expression in safely enclosed by '()'. + return; + } + } + } + + // Exclude the node from the list (i.e. treat parentheses as necessary) + removeFromCurrentReportsBuffer(nodeToExclude); + }, + ); + } + + endCurrentReportsBuffering(); + }, + + IfStatement(node) { + if ( + hasExcessParens(node.test) && + !isCondAssignException(node) + ) { + report(node.test); + } + }, + + ImportExpression(node) { + const { source } = node; + + if (source.type === "SequenceExpression") { + if (hasDoubleExcessParens(source)) { + report(source); + } + } else if (hasExcessParens(source)) { + report(source); + } + }, + + LogicalExpression: checkBinaryLogical, + + MemberExpression(node) { + const shouldAllowWrapOnce = + isMemberExpInNewCallee(node) && + doesMemberExpressionContainCallExpression(node); + const nodeObjHasExcessParens = shouldAllowWrapOnce + ? hasDoubleExcessParens(node.object) + : hasExcessParens(node.object) && + !( + isImmediateFunctionPrototypeMethodCall( + node.parent, + ) && + node.parent.callee === node && + IGNORE_FUNCTION_PROTOTYPE_METHODS + ); + + if ( + nodeObjHasExcessParens && + precedence(node.object) >= precedence(node) && + (node.computed || + !( + astUtils.isDecimalInteger(node.object) || + // RegExp literal is allowed to have parens (#1589) + (node.object.type === "Literal" && + node.object.regex) + )) + ) { + report(node.object); + } + + if ( + nodeObjHasExcessParens && + node.object.type === "CallExpression" + ) { + report(node.object); + } + + if ( + nodeObjHasExcessParens && + !IGNORE_NEW_IN_MEMBER_EXPR && + node.object.type === "NewExpression" && + isNewExpressionWithParens(node.object) + ) { + report(node.object); + } + + if ( + nodeObjHasExcessParens && + node.optional && + node.object.type === "ChainExpression" + ) { + report(node.object); + } + + if (node.computed && hasExcessParens(node.property)) { + report(node.property); + } + }, + + "MethodDefinition[computed=true]"(node) { + if ( + hasExcessParensWithPrecedence( + node.key, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.key); + } + }, + + NewExpression: checkCallNew, + + ObjectExpression(node) { + node.properties + .filter( + property => + property.value && + hasExcessParensWithPrecedence( + property.value, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ), + ) + .forEach(property => report(property.value)); + }, + + ObjectPattern(node) { + node.properties + .filter(property => { + const value = property.value; + + return ( + canBeAssignmentTarget(value) && + hasExcessParens(value) + ); + }) + .forEach(property => report(property.value)); + }, + + Property(node) { + if (node.computed) { + const { key } = node; + + if ( + key && + hasExcessParensWithPrecedence( + key, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(key); + } + } + }, + + PropertyDefinition(node) { + if ( + node.computed && + hasExcessParensWithPrecedence( + node.key, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.key); + } + + if ( + node.value && + hasExcessParensWithPrecedence( + node.value, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(node.value); + } + }, + + RestElement(node) { + const argument = node.argument; + + if ( + canBeAssignmentTarget(argument) && + hasExcessParens(argument) + ) { + report(argument); + } + }, + + ReturnStatement(node) { + const returnToken = sourceCode.getFirstToken(node); + + if (isReturnAssignException(node)) { + return; + } + + if ( + node.argument && + hasExcessParensNoLineTerminator( + returnToken, + node.argument, + ) && + // RegExp literal is allowed to have parens (#1589) + !(node.argument.type === "Literal" && node.argument.regex) + ) { + report(node.argument); + } + }, + + SequenceExpression(node) { + const precedenceOfNode = precedence(node); + + node.expressions + .filter(e => + hasExcessParensWithPrecedence(e, precedenceOfNode), + ) + .forEach(report); + }, + + SwitchCase(node) { + if (node.test && hasExcessParens(node.test)) { + report(node.test); + } + }, + + SwitchStatement(node) { + if (hasExcessParens(node.discriminant)) { + report(node.discriminant); + } + }, + + ThrowStatement(node) { + const throwToken = sourceCode.getFirstToken(node); + + if ( + hasExcessParensNoLineTerminator(throwToken, node.argument) + ) { + report(node.argument); + } + }, + + UnaryExpression: checkArgumentWithPrecedence, + UpdateExpression(node) { + if (node.prefix) { + checkArgumentWithPrecedence(node); + } else { + const { argument } = node; + const operatorToken = sourceCode.getLastToken(node); + + if ( + argument.loc.end.line === operatorToken.loc.start.line + ) { + checkArgumentWithPrecedence(node); + } else { + if (hasDoubleExcessParens(argument)) { + report(argument); + } + } + } + }, + AwaitExpression: checkArgumentWithPrecedence, + + VariableDeclarator(node) { + if ( + node.init && + hasExcessParensWithPrecedence( + node.init, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) && + // RegExp literal is allowed to have parens (#1589) + !(node.init.type === "Literal" && node.init.regex) + ) { + report(node.init); + } + }, + + WhileStatement(node) { + if ( + hasExcessParens(node.test) && + !isCondAssignException(node) + ) { + report(node.test); + } + }, + + WithStatement(node) { + if (hasExcessParens(node.object)) { + report(node.object); + } + }, + + YieldExpression(node) { + if (node.argument) { + const yieldToken = sourceCode.getFirstToken(node); + + if ( + (precedence(node.argument) >= precedence(node) && + hasExcessParensNoLineTerminator( + yieldToken, + node.argument, + )) || + hasDoubleExcessParens(node.argument) + ) { + report(node.argument); + } + } + }, + + ClassDeclaration: checkClass, + ClassExpression: checkClass, + + SpreadElement: checkSpreadOperator, + SpreadProperty: checkSpreadOperator, + ExperimentalSpreadProperty: checkSpreadOperator, + + TemplateLiteral(node) { + node.expressions + .filter(e => e && hasExcessParens(e)) + .forEach(report); + }, + + AssignmentPattern(node) { + const { left, right } = node; + + if (canBeAssignmentTarget(left) && hasExcessParens(left)) { + report(left); + } + + if ( + right && + hasExcessParensWithPrecedence( + right, + PRECEDENCE_OF_ASSIGNMENT_EXPR, + ) + ) { + report(right); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-extra-semi.js b/node_modules/eslint/lib/rules/no-extra-semi.js new file mode 100644 index 0000000000000000000000000000000000000000..a408edaf9555ef04d7a2c908c5ad328d79199c64 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-extra-semi.js @@ -0,0 +1,167 @@ +/** + * @fileoverview Rule to flag use of unnecessary semicolons + * @author Nicholas C. Zakas + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const FixTracker = require("./utils/fix-tracker"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "no-extra-semi", + url: "https://eslint.style/rules/no-extra-semi", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: "Disallow unnecessary semicolons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-extra-semi", + }, + + fixable: "code", + schema: [], + + messages: { + unexpected: "Unnecessary semicolon.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Checks if a node or token is fixable. + * A node is fixable if it can be removed without turning a subsequent statement into a directive after fixing other nodes. + * @param {Token} nodeOrToken The node or token to check. + * @returns {boolean} Whether or not the node is fixable. + */ + function isFixable(nodeOrToken) { + const nextToken = sourceCode.getTokenAfter(nodeOrToken); + + if (!nextToken || nextToken.type !== "String") { + return true; + } + const stringNode = sourceCode.getNodeByRangeIndex( + nextToken.range[0], + ); + + return !astUtils.isTopLevelExpressionStatement(stringNode.parent); + } + + /** + * Reports an unnecessary semicolon error. + * @param {Node|Token} nodeOrToken A node or a token to be reported. + * @returns {void} + */ + function report(nodeOrToken) { + context.report({ + node: nodeOrToken, + messageId: "unexpected", + fix: isFixable(nodeOrToken) + ? fixer => + /* + * Expand the replacement range to include the surrounding + * tokens to avoid conflicting with semi. + * https://github.com/eslint/eslint/issues/7928 + */ + new FixTracker(fixer, context.sourceCode) + .retainSurroundingTokens(nodeOrToken) + .remove(nodeOrToken) + : null, + }); + } + + /** + * Checks for a part of a class body. + * This checks tokens from a specified token to a next MethodDefinition or the end of class body. + * @param {Token} firstToken The first token to check. + * @returns {void} + */ + function checkForPartOfClassBody(firstToken) { + for ( + let token = firstToken; + token.type === "Punctuator" && + !astUtils.isClosingBraceToken(token); + token = sourceCode.getTokenAfter(token) + ) { + if (astUtils.isSemicolonToken(token)) { + report(token); + } + } + } + + return { + /** + * Reports this empty statement, except if the parent node is a loop. + * @param {Node} node A EmptyStatement node to be reported. + * @returns {void} + */ + EmptyStatement(node) { + const parent = node.parent, + allowedParentTypes = [ + "ForStatement", + "ForInStatement", + "ForOfStatement", + "WhileStatement", + "DoWhileStatement", + "IfStatement", + "LabeledStatement", + "WithStatement", + ]; + + if (!allowedParentTypes.includes(parent.type)) { + report(node); + } + }, + + /** + * Checks tokens from the head of this class body to the first MethodDefinition or the end of this class body. + * @param {Node} node A ClassBody node to check. + * @returns {void} + */ + ClassBody(node) { + checkForPartOfClassBody(sourceCode.getFirstToken(node, 1)); // 0 is `{`. + }, + + /** + * Checks tokens from this MethodDefinition to the next MethodDefinition or the end of this class body. + * @param {Node} node A MethodDefinition node of the start point. + * @returns {void} + */ + "MethodDefinition, PropertyDefinition, StaticBlock"(node) { + checkForPartOfClassBody(sourceCode.getTokenAfter(node)); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-fallthrough.js b/node_modules/eslint/lib/rules/no-fallthrough.js new file mode 100644 index 0000000000000000000000000000000000000000..5a2caae0e679b7b773eae5a0ddfec13226a57dcc --- /dev/null +++ b/node_modules/eslint/lib/rules/no-fallthrough.js @@ -0,0 +1,246 @@ +/** + * @fileoverview Rule to flag fall-through cases in switch statements. + * @author Matt DuVall + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { directivesPattern } = require("../shared/directives"); +const { isAnySegmentReachable } = require("./utils/code-path-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_FALLTHROUGH_COMMENT = /falls?\s?through/iu; + +/** + * Checks whether or not a given comment string is really a fallthrough comment and not an ESLint directive. + * @param {string} comment The comment string to check. + * @param {RegExp} fallthroughCommentPattern The regular expression used for checking for fallthrough comments. + * @returns {boolean} `true` if the comment string is truly a fallthrough comment. + */ +function isFallThroughComment(comment, fallthroughCommentPattern) { + return ( + fallthroughCommentPattern.test(comment) && + !directivesPattern.test(comment.trim()) + ); +} + +/** + * Checks whether or not a given case has a fallthrough comment. + * @param {ASTNode} caseWhichFallsThrough SwitchCase node which falls through. + * @param {ASTNode} subsequentCase The case after caseWhichFallsThrough. + * @param {RuleContext} context A rule context which stores comments. + * @param {RegExp} fallthroughCommentPattern A pattern to match comment to. + * @returns {null | object} the comment if the case has a valid fallthrough comment, otherwise null + */ +function getFallthroughComment( + caseWhichFallsThrough, + subsequentCase, + context, + fallthroughCommentPattern, +) { + const sourceCode = context.sourceCode; + + if ( + caseWhichFallsThrough.consequent.length === 1 && + caseWhichFallsThrough.consequent[0].type === "BlockStatement" + ) { + const trailingCloseBrace = sourceCode.getLastToken( + caseWhichFallsThrough.consequent[0], + ); + const commentInBlock = sourceCode + .getCommentsBefore(trailingCloseBrace) + .pop(); + + if ( + commentInBlock && + isFallThroughComment( + commentInBlock.value, + fallthroughCommentPattern, + ) + ) { + return commentInBlock; + } + } + + const comment = sourceCode.getCommentsBefore(subsequentCase).pop(); + + if ( + comment && + isFallThroughComment(comment.value, fallthroughCommentPattern) + ) { + return comment; + } + + return null; +} + +/** + * Checks whether a node and a token are separated by blank lines + * @param {ASTNode} node The node to check + * @param {Token} token The token to compare against + * @returns {boolean} `true` if there are blank lines between node and token + */ +function hasBlankLinesBetween(node, token) { + return token.loc.start.line > node.loc.end.line + 1; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowEmptyCase: false, + reportUnusedFallthroughComment: false, + }, + ], + + docs: { + description: "Disallow fallthrough of `case` statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-fallthrough", + }, + + schema: [ + { + type: "object", + properties: { + commentPattern: { + type: "string", + }, + allowEmptyCase: { + type: "boolean", + }, + reportUnusedFallthroughComment: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + messages: { + unusedFallthroughComment: + "Found a comment that would permit fallthrough, but case cannot fall through.", + case: "Expected a 'break' statement before 'case'.", + default: "Expected a 'break' statement before 'default'.", + }, + }, + + create(context) { + const codePathSegments = []; + let currentCodePathSegments = new Set(); + const sourceCode = context.sourceCode; + const [ + { allowEmptyCase, commentPattern, reportUnusedFallthroughComment }, + ] = context.options; + const fallthroughCommentPattern = commentPattern + ? new RegExp(commentPattern, "u") + : DEFAULT_FALLTHROUGH_COMMENT; + + /* + * We need to use leading comments of the next SwitchCase node because + * trailing comments is wrong if semicolons are omitted. + */ + let previousCase = null; + + return { + onCodePathStart() { + codePathSegments.push(currentCodePathSegments); + currentCodePathSegments = new Set(); + }, + + onCodePathEnd() { + currentCodePathSegments = codePathSegments.pop(); + }, + + onUnreachableCodePathSegmentStart(segment) { + currentCodePathSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + onCodePathSegmentStart(segment) { + currentCodePathSegments.add(segment); + }, + + onCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + SwitchCase(node) { + /* + * Checks whether or not there is a fallthrough comment. + * And reports the previous fallthrough node if that does not exist. + */ + + if (previousCase && previousCase.node.parent === node.parent) { + const previousCaseFallthroughComment = + getFallthroughComment( + previousCase.node, + node, + context, + fallthroughCommentPattern, + ); + + if ( + previousCase.isFallthrough && + !previousCaseFallthroughComment + ) { + context.report({ + messageId: node.test ? "case" : "default", + node, + }); + } else if ( + reportUnusedFallthroughComment && + !previousCase.isSwitchExitReachable && + previousCaseFallthroughComment + ) { + context.report({ + messageId: "unusedFallthroughComment", + node: previousCaseFallthroughComment, + }); + } + } + previousCase = null; + }, + + "SwitchCase:exit"(node) { + const nextToken = sourceCode.getTokenAfter(node); + + /* + * `reachable` meant fall through because statements preceded by + * `break`, `return`, or `throw` are unreachable. + * And allows empty cases and the last case. + */ + const isSwitchExitReachable = isAnySegmentReachable( + currentCodePathSegments, + ); + const isFallthrough = + isSwitchExitReachable && + (node.consequent.length > 0 || + (!allowEmptyCase && + hasBlankLinesBetween(node, nextToken))) && + node.parent.cases.at(-1) !== node; + + previousCase = { + node, + isSwitchExitReachable, + isFallthrough, + }; + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-floating-decimal.js b/node_modules/eslint/lib/rules/no-floating-decimal.js new file mode 100644 index 0000000000000000000000000000000000000000..569be727ec8736566acd007e3e0be807d5392853 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-floating-decimal.js @@ -0,0 +1,99 @@ +/** + * @fileoverview Rule to flag use of a leading/trailing decimal point in a numeric literal + * @author James Allardice + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "no-floating-decimal", + url: "https://eslint.style/rules/no-floating-decimal", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: + "Disallow leading or trailing decimal points in numeric literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-floating-decimal", + }, + + schema: [], + fixable: "code", + messages: { + leading: "A leading decimal point can be confused with a dot.", + trailing: "A trailing decimal point can be confused with a dot.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Literal(node) { + if (typeof node.value === "number") { + if (node.raw.startsWith(".")) { + context.report({ + node, + messageId: "leading", + fix(fixer) { + const tokenBefore = + sourceCode.getTokenBefore(node); + const needsSpaceBefore = + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBefore, + `0${node.raw}`, + ); + + return fixer.insertTextBefore( + node, + needsSpaceBefore ? " 0" : "0", + ); + }, + }); + } + if (node.raw.indexOf(".") === node.raw.length - 1) { + context.report({ + node, + messageId: "trailing", + fix: fixer => fixer.insertTextAfter(node, "0"), + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-func-assign.js b/node_modules/eslint/lib/rules/no-func-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..a17d4b8e6cccb213dc91f66c21365af6af1c4e6b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-func-assign.js @@ -0,0 +1,77 @@ +/** + * @fileoverview Rule to flag use of function declaration identifiers as variables. + * @author Ian Christian Myers + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow reassigning `function` declarations", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-func-assign", + }, + + schema: [], + + messages: { + isAFunction: "'{{name}}' is a function.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Reports a reference if is non initializer and writable. + * @param {References} references Collection of reference to check. + * @returns {void} + */ + function checkReference(references) { + astUtils.getModifyingReferences(references).forEach(reference => { + context.report({ + node: reference.identifier, + messageId: "isAFunction", + data: { + name: reference.identifier.name, + }, + }); + }); + } + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if (variable.defs[0].type === "FunctionName") { + checkReference(variable.references); + } + } + + /** + * Checks parameters of a given function node. + * @param {ASTNode} node A function node to check. + * @returns {void} + */ + function checkForFunction(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + } + + return { + FunctionDeclaration: checkForFunction, + FunctionExpression: checkForFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-global-assign.js b/node_modules/eslint/lib/rules/no-global-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..6f238449559214174a0064050a7e4fa0886f0124 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-global-assign.js @@ -0,0 +1,101 @@ +/** + * @fileoverview Rule to disallow assignments to native objects or read-only global variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{ exceptions: [] }], + + docs: { + description: + "Disallow assignments to native objects or read-only global variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-global-assign", + }, + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + globalShouldNotBeModified: + "Read-only global '{{name}}' should not be modified.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ exceptions }] = context.options; + + /** + * Reports write references. + * @param {Reference} reference A reference to check. + * @param {number} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {void} + */ + function checkReference(reference, index, references) { + const identifier = reference.identifier; + + if ( + reference.init === false && + reference.isWrite() && + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ + (index === 0 || references[index - 1].identifier !== identifier) + ) { + context.report({ + node: identifier, + messageId: "globalShouldNotBeModified", + data: { + name: identifier.name, + }, + }); + } + } + + /** + * Reports write references if a given variable is read-only builtin. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if ( + variable.writeable === false && + !exceptions.includes(variable.name) + ) { + variable.references.forEach(checkReference); + } + } + + return { + Program(node) { + const globalScope = sourceCode.getScope(node); + + globalScope.variables.forEach(checkVariable); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-implicit-coercion.js b/node_modules/eslint/lib/rules/no-implicit-coercion.js new file mode 100644 index 0000000000000000000000000000000000000000..fb6d6a8e95435bf22b5f46fc1bf8bbb0d3810562 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-implicit-coercion.js @@ -0,0 +1,468 @@ +/** + * @fileoverview A rule to disallow the type conversions with shorter notations. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/u; +const ALLOWABLE_OPERATORS = ["~", "!!", "+", "- -", "-", "*"]; + +/** + * Checks whether or not a node is a double logical negating. + * @param {ASTNode} node An UnaryExpression node to check. + * @returns {boolean} Whether or not the node is a double logical negating. + */ +function isDoubleLogicalNegating(node) { + return ( + node.operator === "!" && + node.argument.type === "UnaryExpression" && + node.argument.operator === "!" + ); +} + +/** + * Checks whether or not a node is a binary negating of `.indexOf()` method calling. + * @param {ASTNode} node An UnaryExpression node to check. + * @returns {boolean} Whether or not the node is a binary negating of `.indexOf()` method calling. + */ +function isBinaryNegatingOfIndexOf(node) { + if (node.operator !== "~") { + return false; + } + const callNode = astUtils.skipChainExpression(node.argument); + + return ( + callNode.type === "CallExpression" && + astUtils.isSpecificMemberAccess(callNode.callee, null, INDEX_OF_PATTERN) + ); +} + +/** + * Checks whether or not a node is a multiplying by one. + * @param {BinaryExpression} node A BinaryExpression node to check. + * @returns {boolean} Whether or not the node is a multiplying by one. + */ +function isMultiplyByOne(node) { + return ( + node.operator === "*" && + ((node.left.type === "Literal" && node.left.value === 1) || + (node.right.type === "Literal" && node.right.value === 1)) + ); +} + +/** + * Checks whether the given node logically represents multiplication by a fraction of `1`. + * For example, `a * 1` in `a * 1 / b` is technically multiplication by `1`, but the + * whole expression can be logically interpreted as `a * (1 / b)` rather than `(a * 1) / b`. + * @param {BinaryExpression} node A BinaryExpression node to check. + * @param {SourceCode} sourceCode The source code object. + * @returns {boolean} Whether or not the node is a multiplying by a fraction of `1`. + */ +function isMultiplyByFractionOfOne(node, sourceCode) { + return ( + node.type === "BinaryExpression" && + node.operator === "*" && + node.right.type === "Literal" && + node.right.value === 1 && + node.parent.type === "BinaryExpression" && + node.parent.operator === "/" && + node.parent.left === node && + !astUtils.isParenthesised(sourceCode, node) + ); +} + +/** + * Checks whether the result of a node is numeric or not + * @param {ASTNode} node The node to test + * @returns {boolean} true if the node is a number literal or a `Number()`, `parseInt` or `parseFloat` call + */ +function isNumeric(node) { + return ( + (node.type === "Literal" && typeof node.value === "number") || + (node.type === "CallExpression" && + (node.callee.name === "Number" || + node.callee.name === "parseInt" || + node.callee.name === "parseFloat")) + ); +} + +/** + * Returns the first non-numeric operand in a BinaryExpression. Designed to be + * used from bottom to up since it walks up the BinaryExpression trees using + * node.parent to find the result. + * @param {BinaryExpression} node The BinaryExpression node to be walked up on + * @returns {ASTNode|null} The first non-numeric item in the BinaryExpression tree or null + */ +function getNonNumericOperand(node) { + const left = node.left, + right = node.right; + + if (right.type !== "BinaryExpression" && !isNumeric(right)) { + return right; + } + + if (left.type !== "BinaryExpression" && !isNumeric(left)) { + return left; + } + + return null; +} + +/** + * Checks whether an expression evaluates to a string. + * @param {ASTNode} node node that represents the expression to check. + * @returns {boolean} Whether or not the expression evaluates to a string. + */ +function isStringType(node) { + return ( + astUtils.isStringLiteral(node) || + (node.type === "CallExpression" && + node.callee.type === "Identifier" && + node.callee.name === "String") + ); +} + +/** + * Checks whether a node is an empty string literal or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the passed in node is an + * empty string literal or not. + */ +function isEmptyString(node) { + return ( + astUtils.isStringLiteral(node) && + (node.value === "" || + (node.type === "TemplateLiteral" && + node.quasis.length === 1 && + node.quasis[0].value.cooked === "")) + ); +} + +/** + * Checks whether or not a node is a concatenating with an empty string. + * @param {ASTNode} node A BinaryExpression node to check. + * @returns {boolean} Whether or not the node is a concatenating with an empty string. + */ +function isConcatWithEmptyString(node) { + return ( + node.operator === "+" && + ((isEmptyString(node.left) && !isStringType(node.right)) || + (isEmptyString(node.right) && !isStringType(node.left))) + ); +} + +/** + * Checks whether or not a node is appended with an empty string. + * @param {ASTNode} node An AssignmentExpression node to check. + * @returns {boolean} Whether or not the node is appended with an empty string. + */ +function isAppendEmptyString(node) { + return node.operator === "+=" && isEmptyString(node.right); +} + +/** + * Returns the operand that is not an empty string from a flagged BinaryExpression. + * @param {ASTNode} node The flagged BinaryExpression node to check. + * @returns {ASTNode} The operand that is not an empty string from a flagged BinaryExpression. + */ +function getNonEmptyOperand(node) { + return isEmptyString(node.left) ? node.right : node.left; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "suggestion", + + docs: { + description: "Disallow shorthand type conversions", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-implicit-coercion", + }, + + fixable: "code", + + schema: [ + { + type: "object", + properties: { + boolean: { + type: "boolean", + }, + number: { + type: "boolean", + }, + string: { + type: "boolean", + }, + disallowTemplateShorthand: { + type: "boolean", + }, + allow: { + type: "array", + items: { + enum: ALLOWABLE_OPERATORS, + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [ + { + allow: [], + boolean: true, + disallowTemplateShorthand: false, + number: true, + string: true, + }, + ], + + messages: { + implicitCoercion: + "Unexpected implicit coercion encountered. Use `{{recommendation}}` instead.", + useRecommendation: "Use `{{recommendation}}` instead.", + }, + }, + + create(context) { + const [options] = context.options; + const sourceCode = context.sourceCode; + + /** + * Reports an error and autofixes the node + * @param {ASTNode} node An ast node to report the error on. + * @param {string} recommendation The recommended code for the issue + * @param {bool} shouldSuggest Whether this report should offer a suggestion + * @param {bool} shouldFix Whether this report should fix the node + * @returns {void} + */ + function report(node, recommendation, shouldSuggest, shouldFix) { + /** + * Fix function + * @param {RuleFixer} fixer The fixer to fix. + * @returns {Fix} The fix object. + */ + function fix(fixer) { + const tokenBefore = sourceCode.getTokenBefore(node); + + if ( + tokenBefore?.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent(tokenBefore, recommendation) + ) { + return fixer.replaceText(node, ` ${recommendation}`); + } + + return fixer.replaceText(node, recommendation); + } + + context.report({ + node, + messageId: "implicitCoercion", + data: { recommendation }, + fix(fixer) { + if (!shouldFix) { + return null; + } + + return fix(fixer); + }, + suggest: [ + { + messageId: "useRecommendation", + data: { recommendation }, + fix(fixer) { + if (shouldFix || !shouldSuggest) { + return null; + } + + return fix(fixer); + }, + }, + ], + }); + } + + return { + UnaryExpression(node) { + let operatorAllowed; + + // !!foo + operatorAllowed = options.allow.includes("!!"); + if ( + !operatorAllowed && + options.boolean && + isDoubleLogicalNegating(node) + ) { + const recommendation = `Boolean(${sourceCode.getText(node.argument.argument)})`; + const variable = astUtils.getVariableByName( + sourceCode.getScope(node), + "Boolean", + ); + const booleanExists = variable?.identifiers.length === 0; + + report(node, recommendation, true, booleanExists); + } + + // ~foo.indexOf(bar) + operatorAllowed = options.allow.includes("~"); + if ( + !operatorAllowed && + options.boolean && + isBinaryNegatingOfIndexOf(node) + ) { + // `foo?.indexOf(bar) !== -1` will be true (== found) if the `foo` is nullish. So use `>= 0` in that case. + const comparison = + node.argument.type === "ChainExpression" + ? ">= 0" + : "!== -1"; + const recommendation = `${sourceCode.getText(node.argument)} ${comparison}`; + + report(node, recommendation, false, false); + } + + // +foo + operatorAllowed = options.allow.includes("+"); + if ( + !operatorAllowed && + options.number && + node.operator === "+" && + !isNumeric(node.argument) + ) { + const recommendation = `Number(${sourceCode.getText(node.argument)})`; + + report(node, recommendation, true, false); + } + + // -(-foo) + operatorAllowed = options.allow.includes("- -"); + if ( + !operatorAllowed && + options.number && + node.operator === "-" && + node.argument.type === "UnaryExpression" && + node.argument.operator === "-" && + !isNumeric(node.argument.argument) + ) { + const recommendation = `Number(${sourceCode.getText(node.argument.argument)})`; + + report(node, recommendation, true, false); + } + }, + + // Use `:exit` to prevent double reporting + "BinaryExpression:exit"(node) { + let operatorAllowed; + + // 1 * foo + operatorAllowed = options.allow.includes("*"); + const nonNumericOperand = + !operatorAllowed && + options.number && + isMultiplyByOne(node) && + !isMultiplyByFractionOfOne(node, sourceCode) && + getNonNumericOperand(node); + + if (nonNumericOperand) { + const recommendation = `Number(${sourceCode.getText(nonNumericOperand)})`; + + report(node, recommendation, true, false); + } + + // foo - 0 + operatorAllowed = options.allow.includes("-"); + if ( + !operatorAllowed && + options.number && + node.operator === "-" && + node.right.type === "Literal" && + node.right.value === 0 && + !isNumeric(node.left) + ) { + const recommendation = `Number(${sourceCode.getText(node.left)})`; + + report(node, recommendation, true, false); + } + + // "" + foo + operatorAllowed = options.allow.includes("+"); + if ( + !operatorAllowed && + options.string && + isConcatWithEmptyString(node) + ) { + const recommendation = `String(${sourceCode.getText(getNonEmptyOperand(node))})`; + + report(node, recommendation, true, false); + } + }, + + AssignmentExpression(node) { + // foo += "" + const operatorAllowed = options.allow.includes("+"); + + if ( + !operatorAllowed && + options.string && + isAppendEmptyString(node) + ) { + const code = sourceCode.getText(getNonEmptyOperand(node)); + const recommendation = `${code} = String(${code})`; + + report(node, recommendation, true, false); + } + }, + + TemplateLiteral(node) { + if (!options.disallowTemplateShorthand) { + return; + } + + // tag`${foo}` + if (node.parent.type === "TaggedTemplateExpression") { + return; + } + + // `` or `${foo}${bar}` + if (node.expressions.length !== 1) { + return; + } + + // `prefix${foo}` + if (node.quasis[0].value.cooked !== "") { + return; + } + + // `${foo}postfix` + if (node.quasis[1].value.cooked !== "") { + return; + } + + // if the expression is already a string, then this isn't a coercion + if (isStringType(node.expressions[0])) { + return; + } + + const code = sourceCode.getText(node.expressions[0]); + const recommendation = `String(${code})`; + + report(node, recommendation, true, false); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-implicit-globals.js b/node_modules/eslint/lib/rules/no-implicit-globals.js new file mode 100644 index 0000000000000000000000000000000000000000..c291cd86bb6533c91689a5c20fdc97f20c6db2da --- /dev/null +++ b/node_modules/eslint/lib/rules/no-implicit-globals.js @@ -0,0 +1,187 @@ +/** + * @fileoverview Rule to check for implicit global variables, functions and classes. + * @author Joshua Peek + */ + +"use strict"; + +const ASSIGNMENT_NODES = new Set([ + "AssignmentExpression", + "ForInStatement", + "ForOfStatement", +]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + lexicalBindings: false, + }, + ], + + docs: { + description: "Disallow declarations in the global scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-implicit-globals", + }, + + schema: [ + { + type: "object", + properties: { + lexicalBindings: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + globalNonLexicalBinding: + "Unexpected {{kind}} declaration in the global scope, wrap in an IIFE for a local variable, assign as global property for a global variable.", + globalLexicalBinding: + "Unexpected {{kind}} declaration in the global scope, wrap in a block or in an IIFE.", + globalVariableLeak: + "Global variable leak, declare the variable if it is intended to be local.", + assignmentToReadonlyGlobal: + "Unexpected assignment to read-only global variable.", + redeclarationOfReadonlyGlobal: + "Unexpected redeclaration of read-only global variable.", + }, + }, + + create(context) { + const [{ lexicalBindings: checkLexicalBindings }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Reports the node. + * @param {ASTNode} node Node to report. + * @param {string} messageId Id of the message to report. + * @param {string|undefined} kind Declaration kind, can be 'var', 'const', 'let', function or class. + * @returns {void} + */ + function report(node, messageId, kind) { + context.report({ + node, + messageId, + data: { + kind, + }, + }); + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + + scope.variables.forEach(variable => { + // Only ESLint global variables have the `writable` key. + const isReadonlyEslintGlobalVariable = + variable.writeable === false; + const isWritableEslintGlobalVariable = + variable.writeable === true; + + if (isWritableEslintGlobalVariable) { + // Everything is allowed with writable ESLint global variables. + return; + } + + // Variables exported by "exported" block comments + if (variable.eslintExported) { + return; + } + + variable.defs.forEach(def => { + const defNode = def.node; + + if ( + def.type === "FunctionName" || + (def.type === "Variable" && + def.parent.kind === "var") + ) { + if (isReadonlyEslintGlobalVariable) { + report( + defNode, + "redeclarationOfReadonlyGlobal", + ); + } else { + report( + defNode, + "globalNonLexicalBinding", + def.type === "FunctionName" + ? "function" + : `'${def.parent.kind}'`, + ); + } + } + + if (checkLexicalBindings) { + if ( + def.type === "ClassName" || + (def.type === "Variable" && + (def.parent.kind === "let" || + def.parent.kind === "const")) + ) { + if (isReadonlyEslintGlobalVariable) { + report( + defNode, + "redeclarationOfReadonlyGlobal", + ); + } else { + report( + defNode, + "globalLexicalBinding", + def.type === "ClassName" + ? "class" + : `'${def.parent.kind}'`, + ); + } + } + } + }); + + if ( + isReadonlyEslintGlobalVariable && + variable.defs.length === 0 + ) { + variable.references.forEach(reference => { + if (reference.isWrite() && !reference.isRead()) { + let assignmentParent = + reference.identifier.parent; + + while ( + assignmentParent && + !ASSIGNMENT_NODES.has(assignmentParent.type) + ) { + assignmentParent = assignmentParent.parent; + } + + report( + assignmentParent ?? reference.identifier, + "assignmentToReadonlyGlobal", + ); + } + }); + } + }); + + // Undeclared assigned variables. + scope.implicit.variables.forEach(variable => { + // def.node is an AssignmentExpression, ForInStatement or ForOfStatement. + variable.defs.forEach(def => { + report(def.node, "globalVariableLeak"); + }); + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-implied-eval.js b/node_modules/eslint/lib/rules/no-implied-eval.js new file mode 100644 index 0000000000000000000000000000000000000000..b5fdac4f53eca7e48cfede1aff6992a06e4f491c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-implied-eval.js @@ -0,0 +1,171 @@ +/** + * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { getStaticValue } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `eval()`-like methods", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-implied-eval", + }, + + schema: [], + + messages: { + impliedEval: + "Implied eval. Consider passing a function instead of a string.", + execScript: "Implied eval. Do not use execScript().", + }, + }, + + create(context) { + const GLOBAL_CANDIDATES = Object.freeze([ + "global", + "window", + "globalThis", + "self", + ]); + const EVAL_LIKE_FUNC_PATTERN = + /^(?:set(?:Interval|Timeout)|execScript)$/u; + const sourceCode = context.sourceCode; + + /** + * Checks whether a node is evaluated as a string or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is evaluated as a string. + */ + function isEvaluatedString(node) { + if ( + (node.type === "Literal" && typeof node.value === "string") || + node.type === "TemplateLiteral" + ) { + return true; + } + if (node.type === "BinaryExpression" && node.operator === "+") { + return ( + isEvaluatedString(node.left) || + isEvaluatedString(node.right) + ); + } + return false; + } + + /** + * Reports if the `CallExpression` node has evaluated argument. + * @param {ASTNode} node A CallExpression to check. + * @returns {void} + */ + function reportImpliedEvalCallExpression(node) { + const [firstArgument] = node.arguments; + + if (firstArgument) { + const staticValue = getStaticValue( + firstArgument, + sourceCode.getScope(node), + ); + const isStaticString = + staticValue && typeof staticValue.value === "string"; + const isString = + isStaticString || isEvaluatedString(firstArgument); + + if (isString) { + const calleeName = + node.callee.type === "Identifier" + ? node.callee.name + : astUtils.getStaticPropertyName(node.callee); + const isExecScript = calleeName === "execScript"; + context.report({ + node, + messageId: isExecScript ? "execScript" : "impliedEval", + }); + } + } + } + + /** + * Reports calls of `implied eval` via the global references. + * @param {Variable} globalVar A global variable to check. + * @returns {void} + */ + function reportImpliedEvalViaGlobal(globalVar) { + const { references, name } = globalVar; + + references.forEach(ref => { + const identifier = ref.identifier; + let node = identifier.parent; + + while (astUtils.isSpecificMemberAccess(node, null, name)) { + node = node.parent; + } + + if ( + astUtils.isSpecificMemberAccess( + node, + null, + EVAL_LIKE_FUNC_PATTERN, + ) + ) { + const calleeNode = + node.parent.type === "ChainExpression" + ? node.parent + : node; + const parent = calleeNode.parent; + + if ( + parent.type === "CallExpression" && + parent.callee === calleeNode + ) { + reportImpliedEvalCallExpression(parent); + } + } + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + CallExpression(node) { + if ( + astUtils.isSpecificId( + node.callee, + EVAL_LIKE_FUNC_PATTERN, + ) && + sourceCode.isGlobalReference(node.callee) + ) { + reportImpliedEvalCallExpression(node); + } + }, + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + GLOBAL_CANDIDATES.map(candidate => + astUtils.getVariableByName(globalScope, candidate), + ) + .filter( + globalVar => !!globalVar && globalVar.defs.length === 0, + ) + .forEach(reportImpliedEvalViaGlobal); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-import-assign.js b/node_modules/eslint/lib/rules/no-import-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..7fe526b66fffe760a4138afa3c6415b563f4e88a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-import-assign.js @@ -0,0 +1,227 @@ +/** + * @fileoverview Rule to flag updates of imported bindings. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const { findVariable } = require("@eslint-community/eslint-utils"); +const astUtils = require("./utils/ast-utils"); + +const WellKnownMutationFunctions = { + Object: /^(?:assign|definePropert(?:y|ies)|freeze|setPrototypeOf)$/u, + Reflect: /^(?:(?:define|delete)Property|set(?:PrototypeOf)?)$/u, +}; + +/** + * Check if a given node is LHS of an assignment node. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is LHS. + */ +function isAssignmentLeft(node) { + const { parent } = node; + + return ( + (parent.type === "AssignmentExpression" && parent.left === node) || + // Destructuring assignments + parent.type === "ArrayPattern" || + (parent.type === "Property" && + parent.value === node && + parent.parent.type === "ObjectPattern") || + parent.type === "RestElement" || + (parent.type === "AssignmentPattern" && parent.left === node) + ); +} + +/** + * Check if a given node is the operand of mutation unary operator. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is the operand of mutation unary operator. + */ +function isOperandOfMutationUnaryOperator(node) { + const argumentNode = + node.parent.type === "ChainExpression" ? node.parent : node; + const { parent } = argumentNode; + + return ( + (parent.type === "UpdateExpression" && + parent.argument === argumentNode) || + (parent.type === "UnaryExpression" && + parent.operator === "delete" && + parent.argument === argumentNode) + ); +} + +/** + * Check if a given node is the iteration variable of `for-in`/`for-of` syntax. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is the iteration variable. + */ +function isIterationVariable(node) { + const { parent } = node; + + return ( + (parent.type === "ForInStatement" && parent.left === node) || + (parent.type === "ForOfStatement" && parent.left === node) + ); +} + +/** + * Check if a given node is at the first argument of a well-known mutation function. + * - `Object.assign` + * - `Object.defineProperty` + * - `Object.defineProperties` + * - `Object.freeze` + * - `Object.setPrototypeOf` + * - `Reflect.defineProperty` + * - `Reflect.deleteProperty` + * - `Reflect.set` + * - `Reflect.setPrototypeOf` + * @param {ASTNode} node The node to check. + * @param {Scope} scope A `escope.Scope` object to find variable (whichever). + * @returns {boolean} `true` if the node is at the first argument of a well-known mutation function. + */ +function isArgumentOfWellKnownMutationFunction(node, scope) { + const { parent } = node; + + if (parent.type !== "CallExpression" || parent.arguments[0] !== node) { + return false; + } + const callee = astUtils.skipChainExpression(parent.callee); + + if ( + !astUtils.isSpecificMemberAccess( + callee, + "Object", + WellKnownMutationFunctions.Object, + ) && + !astUtils.isSpecificMemberAccess( + callee, + "Reflect", + WellKnownMutationFunctions.Reflect, + ) + ) { + return false; + } + const variable = findVariable(scope, callee.object); + + return variable !== null && variable.scope.type === "global"; +} + +/** + * Check if the identifier node is placed at to update members. + * @param {ASTNode} id The Identifier node to check. + * @param {Scope} scope A `escope.Scope` object to find variable (whichever). + * @returns {boolean} `true` if the member of `id` was updated. + */ +function isMemberWrite(id, scope) { + const { parent } = id; + + return ( + (parent.type === "MemberExpression" && + parent.object === id && + (isAssignmentLeft(parent) || + isOperandOfMutationUnaryOperator(parent) || + isIterationVariable(parent))) || + isArgumentOfWellKnownMutationFunction(id, scope) + ); +} + +/** + * Get the mutation node. + * @param {ASTNode} id The Identifier node to get. + * @returns {ASTNode} The mutation node. + */ +function getWriteNode(id) { + let node = id.parent; + + while ( + node && + node.type !== "AssignmentExpression" && + node.type !== "UpdateExpression" && + node.type !== "UnaryExpression" && + node.type !== "CallExpression" && + node.type !== "ForInStatement" && + node.type !== "ForOfStatement" + ) { + node = node.parent; + } + + return node || id; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow assigning to imported bindings", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-import-assign", + }, + + schema: [], + + messages: { + readonly: "'{{name}}' is read-only.", + readonlyMember: "The members of '{{name}}' are read-only.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + ImportDeclaration(node) { + const scope = sourceCode.getScope(node); + + for (const variable of sourceCode.getDeclaredVariables(node)) { + const shouldCheckMembers = variable.defs.some( + d => d.node.type === "ImportNamespaceSpecifier", + ); + let prevIdNode = null; + + for (const reference of variable.references) { + const idNode = reference.identifier; + + /* + * AssignmentPattern (e.g. `[a = 0] = b`) makes two write + * references for the same identifier. This should skip + * the one of the two in order to prevent redundant reports. + */ + if (idNode === prevIdNode) { + continue; + } + prevIdNode = idNode; + + if (reference.isWrite()) { + context.report({ + node: getWriteNode(idNode), + messageId: "readonly", + data: { name: idNode.name }, + }); + } else if ( + shouldCheckMembers && + isMemberWrite(idNode, scope) + ) { + context.report({ + node: getWriteNode(idNode), + messageId: "readonlyMember", + data: { name: idNode.name }, + }); + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-inline-comments.js b/node_modules/eslint/lib/rules/no-inline-comments.js new file mode 100644 index 0000000000000000000000000000000000000000..dac9eec1a1ecadb630298bc54e45a9c84a8cb086 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-inline-comments.js @@ -0,0 +1,115 @@ +/** + * @fileoverview Enforces or disallows inline comments. + * @author Greg Cochard + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{}], + + docs: { + description: "Disallow inline comments after code", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-inline-comments", + }, + + schema: [ + { + type: "object", + properties: { + ignorePattern: { + type: "string", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedInlineComment: "Unexpected comment inline with code.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ ignorePattern }] = context.options; + const customIgnoreRegExp = + ignorePattern && new RegExp(ignorePattern, "u"); + + /** + * Will check that comments are not on lines starting with or ending with code + * @param {ASTNode} node The comment node to check + * @private + * @returns {void} + */ + function testCodeAroundComment(node) { + const startLine = String(sourceCode.lines[node.loc.start.line - 1]), + endLine = String(sourceCode.lines[node.loc.end.line - 1]), + preamble = startLine.slice(0, node.loc.start.column).trim(), + postamble = endLine.slice(node.loc.end.column).trim(), + isPreambleEmpty = !preamble, + isPostambleEmpty = !postamble; + + // Nothing on both sides + if (isPreambleEmpty && isPostambleEmpty) { + return; + } + + // Matches the ignore pattern + if (customIgnoreRegExp && customIgnoreRegExp.test(node.value)) { + return; + } + + // JSX Exception + if ( + (isPreambleEmpty || preamble === "{") && + (isPostambleEmpty || postamble === "}") + ) { + const enclosingNode = sourceCode.getNodeByRangeIndex( + node.range[0], + ); + + if ( + enclosingNode && + enclosingNode.type === "JSXEmptyExpression" + ) { + return; + } + } + + // Don't report ESLint directive comments + if (astUtils.isDirectiveComment(node)) { + return; + } + + context.report({ + node, + messageId: "unexpectedInlineComment", + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + sourceCode + .getAllComments() + .filter(token => token.type !== "Shebang") + .forEach(testCodeAroundComment); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-inner-declarations.js b/node_modules/eslint/lib/rules/no-inner-declarations.js new file mode 100644 index 0000000000000000000000000000000000000000..ec6c4952ad5444d29ab4407b25319cf2b27aad95 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-inner-declarations.js @@ -0,0 +1,147 @@ +/** + * @fileoverview Rule to enforce declarations in program or function body root. + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const validParent = new Set([ + "Program", + "StaticBlock", + "ExportNamedDeclaration", + "ExportDefaultDeclaration", +]); +const validBlockStatementParent = new Set([ + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", +]); + +/** + * Finds the nearest enclosing context where this rule allows declarations and returns its description. + * @param {ASTNode} node Node to search from. + * @returns {string} Description. One of "program", "function body", "class static block body". + */ +function getAllowedBodyDescription(node) { + let { parent } = node; + + while (parent) { + if (parent.type === "StaticBlock") { + return "class static block body"; + } + + if (astUtils.isFunction(parent)) { + return "function body"; + } + + ({ parent } = parent); + } + + return "program"; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: ["functions", { blockScopedFunctions: "allow" }], + + docs: { + description: + "Disallow variable or `function` declarations in nested blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-inner-declarations", + }, + + schema: [ + { + enum: ["functions", "both"], + }, + { + type: "object", + properties: { + blockScopedFunctions: { + enum: ["allow", "disallow"], + }, + }, + additionalProperties: false, + }, + ], + + messages: { + moveDeclToRoot: "Move {{type}} declaration to {{body}} root.", + }, + }, + + create(context) { + const both = context.options[0] === "both"; + const { blockScopedFunctions } = context.options[1]; + + const sourceCode = context.sourceCode; + const ecmaVersion = context.languageOptions.ecmaVersion; + + /** + * Ensure that a given node is at a program or function body's root. + * @param {ASTNode} node Declaration node to check. + * @returns {void} + */ + function check(node) { + const parent = node.parent; + + if ( + parent.type === "BlockStatement" && + validBlockStatementParent.has(parent.parent.type) + ) { + return; + } + + if (validParent.has(parent.type)) { + return; + } + + context.report({ + node, + messageId: "moveDeclToRoot", + data: { + type: + node.type === "FunctionDeclaration" + ? "function" + : "variable", + body: getAllowedBodyDescription(node), + }, + }); + } + + return { + FunctionDeclaration(node) { + const isInStrictCode = sourceCode.getScope(node).upper.isStrict; + + if ( + blockScopedFunctions === "allow" && + ecmaVersion >= 2015 && + isInStrictCode + ) { + return; + } + + check(node); + }, + VariableDeclaration(node) { + if (both && node.kind === "var") { + check(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-invalid-regexp.js b/node_modules/eslint/lib/rules/no-invalid-regexp.js new file mode 100644 index 0000000000000000000000000000000000000000..47b849e3455dfe37908fb303380b5ce677cbaa9a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-invalid-regexp.js @@ -0,0 +1,244 @@ +/** + * @fileoverview Validate strings passed to the RegExp constructor + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const RegExpValidator = require("@eslint-community/regexpp").RegExpValidator; +const validator = new RegExpValidator(); +const validFlags = "dgimsuvy"; +const undefined1 = void 0; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [{}], + + docs: { + description: + "Disallow invalid regular expression strings in `RegExp` constructors", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-invalid-regexp", + }, + + schema: [ + { + type: "object", + properties: { + allowConstructorFlags: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + regexMessage: "{{message}}.", + }, + }, + + create(context) { + const [{ allowConstructorFlags }] = context.options; + let allowedFlags = []; + + if (allowConstructorFlags) { + const temp = allowConstructorFlags + .join("") + .replace(new RegExp(`[${validFlags}]`, "gu"), ""); + + if (temp) { + allowedFlags = [...new Set(temp)]; + } + } + + /** + * Reports error with the provided message. + * @param {ASTNode} node The node holding the invalid RegExp + * @param {string} message The message to report. + * @returns {void} + */ + function report(node, message) { + context.report({ + node, + messageId: "regexMessage", + data: { message }, + }); + } + + /** + * Check if node is a string + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if its a string + * @private + */ + function isString(node) { + return ( + node && + node.type === "Literal" && + typeof node.value === "string" + ); + } + + /** + * Gets flags of a regular expression created by the given `RegExp()` or `new RegExp()` call + * Examples: + * new RegExp(".") // => "" + * new RegExp(".", "gu") // => "gu" + * new RegExp(".", flags) // => null + * @param {ASTNode} node `CallExpression` or `NewExpression` node + * @returns {string|null} flags if they can be determined, `null` otherwise + * @private + */ + function getFlags(node) { + if (node.arguments.length < 2) { + return ""; + } + + if (isString(node.arguments[1])) { + return node.arguments[1].value; + } + + return null; + } + + /** + * Check syntax error in a given pattern. + * @param {string} pattern The RegExp pattern to validate. + * @param {Object} flags The RegExp flags to validate. + * @param {boolean} [flags.unicode] The Unicode flag. + * @param {boolean} [flags.unicodeSets] The UnicodeSets flag. + * @returns {string|null} The syntax error. + */ + function validateRegExpPattern(pattern, flags) { + try { + validator.validatePattern( + pattern, + undefined1, + undefined1, + flags, + ); + return null; + } catch (err) { + return err.message; + } + } + + /** + * Check syntax error in a given flags. + * @param {string|null} flags The RegExp flags to validate. + * @param {string|null} flagsToCheck The RegExp invalid flags. + * @param {string} allFlags all valid and allowed flags. + * @returns {string|null} The syntax error. + */ + function validateRegExpFlags(flags, flagsToCheck, allFlags) { + const duplicateFlags = []; + + if (typeof flagsToCheck === "string") { + for (const flag of flagsToCheck) { + if (allFlags.includes(flag)) { + duplicateFlags.push(flag); + } + } + } + + /* + * `regexpp` checks the combination of `u` and `v` flags when parsing `Pattern` according to `ecma262`, + * but this rule may check only the flag when the pattern is unidentifiable, so check it here. + * https://tc39.es/ecma262/multipage/text-processing.html#sec-parsepattern + */ + if (flags && flags.includes("u") && flags.includes("v")) { + return "Regex 'u' and 'v' flags cannot be used together"; + } + + if (duplicateFlags.length > 0) { + return `Duplicate flags ('${duplicateFlags.join("")}') supplied to RegExp constructor`; + } + + if (!flagsToCheck) { + return null; + } + + return `Invalid flags supplied to RegExp constructor '${flagsToCheck}'`; + } + + return { + "CallExpression, NewExpression"(node) { + if ( + node.callee.type !== "Identifier" || + node.callee.name !== "RegExp" + ) { + return; + } + + const flags = getFlags(node); + let flagsToCheck = flags; + const allFlags = + allowedFlags.length > 0 + ? validFlags.split("").concat(allowedFlags) + : validFlags.split(""); + + if (flags) { + allFlags.forEach(flag => { + flagsToCheck = flagsToCheck.replace(flag, ""); + }); + } + + let message = validateRegExpFlags( + flags, + flagsToCheck, + allFlags, + ); + + if (message) { + report(node, message); + return; + } + + if (!isString(node.arguments[0])) { + return; + } + + const pattern = node.arguments[0].value; + + message = + // If flags are unknown, report the regex only if its pattern is invalid both with and without the "u" flag + flags === null + ? validateRegExpPattern(pattern, { + unicode: true, + unicodeSets: false, + }) && + validateRegExpPattern(pattern, { + unicode: false, + unicodeSets: true, + }) && + validateRegExpPattern(pattern, { + unicode: false, + unicodeSets: false, + }) + : validateRegExpPattern(pattern, { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v"), + }); + + if (message) { + report(node, message); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-invalid-this.js b/node_modules/eslint/lib/rules/no-invalid-this.js new file mode 100644 index 0000000000000000000000000000000000000000..41fa6b2880708a1f0bae6cb05de6f404728711e9 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-invalid-this.js @@ -0,0 +1,177 @@ +/** + * @fileoverview A rule to disallow `this` keywords in contexts where the value of `this` is `undefined`. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if the given code path is a code path with lexical `this` binding. + * That is, if `this` within the code path refers to `this` of surrounding code path. + * @param {CodePath} codePath Code path. + * @param {ASTNode} node Node that started the code path. + * @returns {boolean} `true` if it is a code path with lexical `this` binding. + */ +function isCodePathWithLexicalThis(codePath, node) { + return ( + codePath.origin === "function" && + node.type === "ArrowFunctionExpression" + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{ capIsConstructor: true }], + + docs: { + description: + "Disallow use of `this` in contexts where the value of `this` is `undefined`", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-invalid-this", + }, + + schema: [ + { + type: "object", + properties: { + capIsConstructor: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedThis: "Unexpected 'this'.", + }, + }, + + create(context) { + const [{ capIsConstructor }] = context.options; + const stack = [], + sourceCode = context.sourceCode; + + /** + * Gets the current checking context. + * + * The return value has a flag that whether or not `this` keyword is valid. + * The flag is initialized when got at the first time. + * @returns {{valid: boolean}} + * an object which has a flag that whether or not `this` keyword is valid. + */ + stack.getCurrent = function () { + const current = this.at(-1); + + if (!current.init) { + current.init = true; + current.valid = !astUtils.isDefaultThisBinding( + current.node, + sourceCode, + { capIsConstructor }, + ); + } + return current; + }; + + return { + onCodePathStart(codePath, node) { + if (isCodePathWithLexicalThis(codePath, node)) { + return; + } + + if (codePath.origin === "program") { + const scope = sourceCode.getScope(node); + const features = + context.languageOptions.parserOptions.ecmaFeatures || + {}; + + // `this` at the top level of scripts always refers to the global object + stack.push({ + init: true, + node, + valid: !( + node.sourceType === "module" || + (features.globalReturn && + scope.childScopes[0].isStrict) + ), + }); + + return; + } + + /* + * `init: false` means that `valid` isn't determined yet. + * Most functions don't use `this`, and the calculation for `valid` + * is relatively costly, so we'll calculate it lazily when the first + * `this` within the function is traversed. A special case are non-strict + * functions, because `this` refers to the global object and therefore is + * always valid, so we can set `init: true` right away. + */ + stack.push({ + init: !sourceCode.getScope(node).isStrict, + node, + valid: true, + }); + }, + + onCodePathEnd(codePath, node) { + if (isCodePathWithLexicalThis(codePath, node)) { + return; + } + + stack.pop(); + }, + + "AccessorProperty > *.value"(node) { + stack.push({ + init: true, + node, + valid: true, + }); + }, + + "AccessorProperty:exit"() { + stack.pop(); + }, + + // Reports if `this` of the current context is invalid. + ThisExpression(node) { + // Special case: skip `this` if it's the value of an AccessorProperty + if ( + node.parent.type === "AccessorProperty" && + node.parent.value === node + ) { + return; + } + + const current = stack.getCurrent(); + + if (current && !current.valid) { + context.report({ + node, + messageId: "unexpectedThis", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-irregular-whitespace.js b/node_modules/eslint/lib/rules/no-irregular-whitespace.js new file mode 100644 index 0000000000000000000000000000000000000000..4aaaad1d267f91b92efb43bf135fcf377c7e939d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-irregular-whitespace.js @@ -0,0 +1,292 @@ +/** + * @fileoverview Rule to disallow whitespace that is not a tab or space, whitespace inside strings and comments are allowed + * @author Jonathan Kingston + * @author Christophe Porteneuve + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const ALL_IRREGULARS = + /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000\u2028\u2029]/u; +const IRREGULAR_WHITESPACE = + /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000]+/gu; +const IRREGULAR_LINE_TERMINATORS = /[\u2028\u2029]/gu; +const LINE_BREAK = astUtils.createGlobalLinebreakMatcher(); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + skipComments: false, + skipJSXText: false, + skipRegExps: false, + skipStrings: true, + skipTemplates: false, + }, + ], + + docs: { + description: "Disallow irregular whitespace", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-irregular-whitespace", + }, + + schema: [ + { + type: "object", + properties: { + skipComments: { + type: "boolean", + }, + skipStrings: { + type: "boolean", + }, + skipTemplates: { + type: "boolean", + }, + skipRegExps: { + type: "boolean", + }, + skipJSXText: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + noIrregularWhitespace: "Irregular whitespace not allowed.", + }, + }, + + create(context) { + const [ + { + skipComments, + skipStrings, + skipRegExps, + skipTemplates, + skipJSXText, + }, + ] = context.options; + + const sourceCode = context.sourceCode; + const commentNodes = sourceCode.getAllComments(); + + // Module store of errors that we have found + let errors = []; + + /** + * Removes errors that occur inside the given node + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeWhitespaceError(node) { + const locStart = node.loc.start; + const locEnd = node.loc.end; + + errors = errors.filter( + ({ loc: { start: errorLocStart } }) => + errorLocStart.line < locStart.line || + (errorLocStart.line === locStart.line && + errorLocStart.column < locStart.column) || + (errorLocStart.line === locEnd.line && + errorLocStart.column >= locEnd.column) || + errorLocStart.line > locEnd.line, + ); + } + + /** + * Checks literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInLiteral(node) { + const shouldCheckStrings = + skipStrings && typeof node.value === "string"; + const shouldCheckRegExps = skipRegExps && Boolean(node.regex); + + if (shouldCheckStrings || shouldCheckRegExps) { + // If we have irregular characters remove them from the errors list + if (ALL_IRREGULARS.test(node.raw)) { + removeWhitespaceError(node); + } + } + } + + /** + * Checks template string literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInTemplateLiteral(node) { + if (typeof node.value.raw === "string") { + if (ALL_IRREGULARS.test(node.value.raw)) { + removeWhitespaceError(node); + } + } + } + + /** + * Checks comment nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInComment(node) { + if (ALL_IRREGULARS.test(node.value)) { + removeWhitespaceError(node); + } + } + + /** + * Checks JSX nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrorsInJSXText(node) { + if (ALL_IRREGULARS.test(node.raw)) { + removeWhitespaceError(node); + } + } + + /** + * Checks the program source for irregular whitespace + * @param {ASTNode} node The program node + * @returns {void} + * @private + */ + function checkForIrregularWhitespace(node) { + const sourceLines = sourceCode.lines; + + sourceLines.forEach((sourceLine, lineIndex) => { + const lineNumber = lineIndex + 1; + let match; + + while ( + (match = IRREGULAR_WHITESPACE.exec(sourceLine)) !== null + ) { + errors.push({ + node, + messageId: "noIrregularWhitespace", + loc: { + start: { + line: lineNumber, + column: match.index, + }, + end: { + line: lineNumber, + column: match.index + match[0].length, + }, + }, + }); + } + }); + } + + /** + * Checks the program source for irregular line terminators + * @param {ASTNode} node The program node + * @returns {void} + * @private + */ + function checkForIrregularLineTerminators(node) { + const source = sourceCode.getText(), + sourceLines = sourceCode.lines, + linebreaks = source.match(LINE_BREAK); + let lastLineIndex = -1, + match; + + while ((match = IRREGULAR_LINE_TERMINATORS.exec(source)) !== null) { + const lineIndex = + linebreaks.indexOf(match[0], lastLineIndex + 1) || 0; + + errors.push({ + node, + messageId: "noIrregularWhitespace", + loc: { + start: { + line: lineIndex + 1, + column: sourceLines[lineIndex].length, + }, + end: { + line: lineIndex + 2, + column: 0, + }, + }, + }); + + lastLineIndex = lineIndex; + } + } + + /** + * A no-op function to act as placeholder for comment accumulation when the `skipComments` option is `false`. + * @returns {void} + * @private + */ + function noop() {} + + const nodes = {}; + + if (ALL_IRREGULARS.test(sourceCode.getText())) { + nodes.Program = function (node) { + /* + * As we can easily fire warnings for all white space issues with + * all the source its simpler to fire them here. + * This means we can check all the application code without having + * to worry about issues caused in the parser tokens. + * When writing this code also evaluating per node was missing out + * connecting tokens in some cases. + * We can later filter the errors when they are found to be not an + * issue in nodes we don't care about. + */ + checkForIrregularWhitespace(node); + checkForIrregularLineTerminators(node); + }; + + nodes.Literal = removeInvalidNodeErrorsInLiteral; + nodes.TemplateElement = skipTemplates + ? removeInvalidNodeErrorsInTemplateLiteral + : noop; + nodes.JSXText = skipJSXText + ? removeInvalidNodeErrorsInJSXText + : noop; + nodes["Program:exit"] = function () { + if (skipComments) { + // First strip errors occurring in comment nodes. + commentNodes.forEach(removeInvalidNodeErrorsInComment); + } + + // If we have any errors remaining report on them + errors.forEach(error => context.report(error)); + }; + } else { + nodes.Program = noop; + } + + return nodes; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-iterator.js b/node_modules/eslint/lib/rules/no-iterator.js new file mode 100644 index 0000000000000000000000000000000000000000..6451e334d2efe664f3bcaeb56fc6317ae871bfd2 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-iterator.js @@ -0,0 +1,48 @@ +/** + * @fileoverview Rule to flag usage of __iterator__ property + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getStaticPropertyName } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of the `__iterator__` property", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-iterator", + }, + + schema: [], + + messages: { + noIterator: "Reserved name '__iterator__'.", + }, + }, + + create(context) { + return { + MemberExpression(node) { + if (getStaticPropertyName(node) === "__iterator__") { + context.report({ + node, + messageId: "noIterator", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-label-var.js b/node_modules/eslint/lib/rules/no-label-var.js new file mode 100644 index 0000000000000000000000000000000000000000..a878941307300d65678d69df30cbfdc73dd62f5e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-label-var.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Rule to flag labels that are the same as an identifier + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow labels that share a name with a variable", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-label-var", + }, + + schema: [], + + messages: { + identifierClashWithLabel: + "Found identifier with same name as label.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if the identifier is present inside current scope + * @param {Object} scope current scope + * @param {string} name To evaluate + * @returns {boolean} True if its present + * @private + */ + function findIdentifier(scope, name) { + return astUtils.getVariableByName(scope, name) !== null; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + LabeledStatement(node) { + // Fetch the innermost scope. + const scope = sourceCode.getScope(node); + + /* + * Recursively find the identifier walking up the scope, starting + * with the innermost scope. + */ + if (findIdentifier(scope, node.label.name)) { + context.report({ + node, + messageId: "identifierClashWithLabel", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-labels.js b/node_modules/eslint/lib/rules/no-labels.js new file mode 100644 index 0000000000000000000000000000000000000000..45eb8af74393712af900222a930e074474cb8b72 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-labels.js @@ -0,0 +1,156 @@ +/** + * @fileoverview Disallow Labeled Statements + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowLoop: false, + allowSwitch: false, + }, + ], + + docs: { + description: "Disallow labeled statements", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-labels", + }, + + schema: [ + { + type: "object", + properties: { + allowLoop: { + type: "boolean", + }, + allowSwitch: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedLabel: "Unexpected labeled statement.", + unexpectedLabelInBreak: "Unexpected label in break statement.", + unexpectedLabelInContinue: + "Unexpected label in continue statement.", + }, + }, + + create(context) { + const [{ allowLoop, allowSwitch }] = context.options; + let scopeInfo = null; + + /** + * Gets the kind of a given node. + * @param {ASTNode} node A node to get. + * @returns {string} The kind of the node. + */ + function getBodyKind(node) { + if (astUtils.isLoop(node)) { + return "loop"; + } + if (node.type === "SwitchStatement") { + return "switch"; + } + return "other"; + } + + /** + * Checks whether the label of a given kind is allowed or not. + * @param {string} kind A kind to check. + * @returns {boolean} `true` if the kind is allowed. + */ + function isAllowed(kind) { + switch (kind) { + case "loop": + return allowLoop; + case "switch": + return allowSwitch; + default: + return false; + } + } + + /** + * Checks whether a given name is a label of a loop or not. + * @param {string} label A name of a label to check. + * @returns {boolean} `true` if the name is a label of a loop. + */ + function getKind(label) { + let info = scopeInfo; + + while (info) { + if (info.label === label) { + return info.kind; + } + info = info.upper; + } + + /* c8 ignore next */ + return "other"; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + LabeledStatement(node) { + scopeInfo = { + label: node.label.name, + kind: getBodyKind(node.body), + upper: scopeInfo, + }; + }, + + "LabeledStatement:exit"(node) { + if (!isAllowed(scopeInfo.kind)) { + context.report({ + node, + messageId: "unexpectedLabel", + }); + } + + scopeInfo = scopeInfo.upper; + }, + + BreakStatement(node) { + if (node.label && !isAllowed(getKind(node.label.name))) { + context.report({ + node, + messageId: "unexpectedLabelInBreak", + }); + } + }, + + ContinueStatement(node) { + if (node.label && !isAllowed(getKind(node.label.name))) { + context.report({ + node, + messageId: "unexpectedLabelInContinue", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-lone-blocks.js b/node_modules/eslint/lib/rules/no-lone-blocks.js new file mode 100644 index 0000000000000000000000000000000000000000..94421b8f86ba188be7da20341af272f1f8963868 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-lone-blocks.js @@ -0,0 +1,140 @@ +/** + * @fileoverview Rule to flag blocks with no reason to exist + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary nested blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-lone-blocks", + }, + + schema: [], + + messages: { + redundantBlock: "Block is redundant.", + redundantNestedBlock: "Nested block is redundant.", + }, + }, + + create(context) { + // A stack of lone blocks to be checked for block-level bindings + const loneBlocks = []; + let ruleDef; + const sourceCode = context.sourceCode; + + /** + * Reports a node as invalid. + * @param {ASTNode} node The node to be reported. + * @returns {void} + */ + function report(node) { + const messageId = + node.parent.type === "BlockStatement" || + node.parent.type === "StaticBlock" + ? "redundantNestedBlock" + : "redundantBlock"; + + context.report({ + node, + messageId, + }); + } + + /** + * Checks for any occurrence of a BlockStatement in a place where lists of statements can appear + * @param {ASTNode} node The node to check + * @returns {boolean} True if the node is a lone block. + */ + function isLoneBlock(node) { + return ( + node.parent.type === "BlockStatement" || + node.parent.type === "StaticBlock" || + node.parent.type === "Program" || + // Don't report blocks in switch cases if the block is the only statement of the case. + (node.parent.type === "SwitchCase" && + !( + node.parent.consequent[0] === node && + node.parent.consequent.length === 1 + )) + ); + } + + /** + * Checks the enclosing block of the current node for block-level bindings, + * and "marks it" as valid if any. + * @param {ASTNode} node The current node to check. + * @returns {void} + */ + function markLoneBlock(node) { + if (loneBlocks.length === 0) { + return; + } + + const block = node.parent; + + if (loneBlocks.at(-1) === block) { + loneBlocks.pop(); + } + } + + // Default rule definition: report all lone blocks + ruleDef = { + BlockStatement(node) { + if (isLoneBlock(node)) { + report(node); + } + }, + }; + + // ES6: report blocks without block-level bindings, or that's only child of another block + if (context.languageOptions.ecmaVersion >= 2015) { + ruleDef = { + BlockStatement(node) { + if (isLoneBlock(node)) { + loneBlocks.push(node); + } + }, + "BlockStatement:exit"(node) { + if (loneBlocks.length > 0 && loneBlocks.at(-1) === node) { + loneBlocks.pop(); + report(node); + } else if ( + (node.parent.type === "BlockStatement" || + node.parent.type === "StaticBlock") && + node.parent.body.length === 1 + ) { + report(node); + } + }, + }; + + ruleDef.VariableDeclaration = function (node) { + if (node.kind !== "var") { + markLoneBlock(node); + } + }; + + ruleDef.FunctionDeclaration = function (node) { + if (sourceCode.getScope(node).isStrict) { + markLoneBlock(node); + } + }; + + ruleDef.ClassDeclaration = markLoneBlock; + } + + return ruleDef; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-lonely-if.js b/node_modules/eslint/lib/rules/no-lonely-if.js new file mode 100644 index 0000000000000000000000000000000000000000..65af96071242eb4740f14485ed8695231c500388 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-lonely-if.js @@ -0,0 +1,126 @@ +/** + * @fileoverview Rule to disallow if as the only statement in an else block + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `if` statements as the only statement in `else` blocks", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-lonely-if", + }, + + schema: [], + fixable: "code", + + messages: { + unexpectedLonelyIf: + "Unexpected if as the only statement in an else block.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + IfStatement(node) { + const parent = node.parent, + grandparent = parent.parent; + + if ( + parent && + parent.type === "BlockStatement" && + parent.body.length === 1 && + !astUtils.areBracesNecessary(parent, sourceCode) && + grandparent && + grandparent.type === "IfStatement" && + parent === grandparent.alternate + ) { + context.report({ + node, + messageId: "unexpectedLonelyIf", + fix(fixer) { + const openingElseCurly = + sourceCode.getFirstToken(parent); + const closingElseCurly = + sourceCode.getLastToken(parent); + const elseKeyword = + sourceCode.getTokenBefore(openingElseCurly); + const tokenAfterElseBlock = + sourceCode.getTokenAfter(closingElseCurly); + const lastIfToken = sourceCode.getLastToken( + node.consequent, + ); + const sourceText = sourceCode.getText(); + + if ( + sourceText + .slice( + openingElseCurly.range[1], + node.range[0], + ) + .trim() || + sourceText + .slice( + node.range[1], + closingElseCurly.range[0], + ) + .trim() + ) { + // Don't fix if there are any non-whitespace characters interfering (e.g. comments) + return null; + } + + if ( + node.consequent.type !== "BlockStatement" && + lastIfToken.value !== ";" && + tokenAfterElseBlock && + (node.consequent.loc.end.line === + tokenAfterElseBlock.loc.start.line || + /^[([/+`-]/u.test( + tokenAfterElseBlock.value, + ) || + lastIfToken.value === "++" || + lastIfToken.value === "--") + ) { + /* + * If the `if` statement has no block, and is not followed by a semicolon, make sure that fixing + * the issue would not change semantics due to ASI. If this would happen, don't do a fix. + */ + return null; + } + + return fixer.replaceTextRange( + [ + openingElseCurly.range[0], + closingElseCurly.range[1], + ], + (elseKeyword.range[1] === + openingElseCurly.range[0] + ? " " + : "") + sourceCode.getText(node), + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-loop-func.js b/node_modules/eslint/lib/rules/no-loop-func.js new file mode 100644 index 0000000000000000000000000000000000000000..a986a18eef42dbdcc6a153d2d4ecdce6c4d29be0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-loop-func.js @@ -0,0 +1,272 @@ +/** + * @fileoverview Rule to flag creation of function inside a loop + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Reference} Reference */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const CONSTANT_BINDINGS = new Set(["const", "using", "await using"]); + +/** + * Identifies is a node is a FunctionExpression which is part of an IIFE + * @param {ASTNode} node Node to test + * @returns {boolean} True if it's an IIFE + */ +function isIIFE(node) { + return ( + (node.type === "FunctionExpression" || + node.type === "ArrowFunctionExpression") && + node.parent && + node.parent.type === "CallExpression" && + node.parent.callee === node + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow function declarations that contain unsafe references inside loop statements", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-loop-func", + }, + + schema: [], + + messages: { + unsafeRefs: + "Function declared in a loop contains unsafe references to variable(s) {{ varNames }}.", + }, + }, + + create(context) { + const SKIPPED_IIFE_NODES = new Set(); + const sourceCode = context.sourceCode; + + /** + * Gets the containing loop node of a specified node. + * + * We don't need to check nested functions, so this ignores those, with the exception of IIFE. + * `Scope.through` contains references of nested functions. + * @param {ASTNode} node An AST node to get. + * @returns {ASTNode|null} The containing loop node of the specified node, or + * `null`. + */ + function getContainingLoopNode(node) { + for ( + let currentNode = node; + currentNode.parent; + currentNode = currentNode.parent + ) { + const parent = currentNode.parent; + + switch (parent.type) { + case "WhileStatement": + case "DoWhileStatement": + return parent; + + case "ForStatement": + // `init` is outside of the loop. + if (parent.init !== currentNode) { + return parent; + } + break; + + case "ForInStatement": + case "ForOfStatement": + // `right` is outside of the loop. + if (parent.right !== currentNode) { + return parent; + } + break; + + case "ArrowFunctionExpression": + case "FunctionExpression": + case "FunctionDeclaration": + // We need to check nested functions only in case of IIFE. + if (SKIPPED_IIFE_NODES.has(parent)) { + break; + } + + return null; + default: + break; + } + } + + return null; + } + + /** + * Gets the containing loop node of a given node. + * If the loop was nested, this returns the most outer loop. + * @param {ASTNode} node A node to get. This is a loop node. + * @param {ASTNode|null} excludedNode A node that the result node should not + * include. + * @returns {ASTNode} The most outer loop node. + */ + function getTopLoopNode(node, excludedNode) { + const border = excludedNode ? excludedNode.range[1] : 0; + let retv = node; + let containingLoopNode = node; + + while ( + containingLoopNode && + containingLoopNode.range[0] >= border + ) { + retv = containingLoopNode; + containingLoopNode = getContainingLoopNode(containingLoopNode); + } + + return retv; + } + + /** + * Checks whether a given reference which refers to an upper scope's variable is + * safe or not. + * @param {ASTNode} loopNode A containing loop node. + * @param {Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is safe or not. + */ + function isSafe(loopNode, reference) { + const variable = reference.resolved; + const definition = variable && variable.defs[0]; + const declaration = definition && definition.parent; + const kind = + declaration && declaration.type === "VariableDeclaration" + ? declaration.kind + : ""; + + // Constant variables are safe. + if (CONSTANT_BINDINGS.has(kind)) { + return true; + } + + /* + * Variables which are declared by `let` in the loop is safe. + * It's a different instance from the next loop step's. + */ + if ( + kind === "let" && + declaration.range[0] > loopNode.range[0] && + declaration.range[1] < loopNode.range[1] + ) { + return true; + } + + /* + * WriteReferences which exist after this border are unsafe because those + * can modify the variable. + */ + const border = getTopLoopNode( + loopNode, + kind === "let" ? declaration : null, + ).range[0]; + + /** + * Checks whether a given reference is safe or not. + * The reference is every reference of the upper scope's variable we are + * looking now. + * + * It's safe if the reference matches one of the following condition. + * - is readonly. + * - doesn't exist inside a local function and after the border. + * @param {Reference} upperRef A reference to check. + * @returns {boolean} `true` if the reference is safe. + */ + function isSafeReference(upperRef) { + const id = upperRef.identifier; + + return ( + !upperRef.isWrite() || + (variable.scope.variableScope === + upperRef.from.variableScope && + id.range[0] < border) + ); + } + + return ( + Boolean(variable) && variable.references.every(isSafeReference) + ); + } + + /** + * Reports functions which match the following condition: + * + * - has a loop node in ancestors. + * - has any references which refers to an unsafe variable. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function checkForLoops(node) { + const loopNode = getContainingLoopNode(node); + + if (!loopNode) { + return; + } + + const references = sourceCode.getScope(node).through; + + // Check if the function is not asynchronous or a generator function + if (!(node.async || node.generator)) { + if (isIIFE(node)) { + const isFunctionExpression = + node.type === "FunctionExpression"; + + // Check if the function is referenced elsewhere in the code + const isFunctionReferenced = + isFunctionExpression && node.id + ? references.some( + r => r.identifier.name === node.id.name, + ) + : false; + + if (!isFunctionReferenced) { + SKIPPED_IIFE_NODES.add(node); + return; + } + } + } + + const unsafeRefs = [ + ...new Set( + references + .filter(r => r.resolved && !isSafe(loopNode, r)) + .map(r => r.identifier.name), + ), + ]; + + if (unsafeRefs.length > 0) { + context.report({ + node, + messageId: "unsafeRefs", + data: { varNames: `'${unsafeRefs.join("', '")}'` }, + }); + } + } + + return { + ArrowFunctionExpression: checkForLoops, + FunctionExpression: checkForLoops, + FunctionDeclaration: checkForLoops, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-loss-of-precision.js b/node_modules/eslint/lib/rules/no-loss-of-precision.js new file mode 100644 index 0000000000000000000000000000000000000000..438bd146d54ecbb69f727a4b195176b60c8ee0bc --- /dev/null +++ b/node_modules/eslint/lib/rules/no-loss-of-precision.js @@ -0,0 +1,248 @@ +/** + * @fileoverview Rule to flag numbers that will lose significant figure precision at runtime + * @author Jacob Moore + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** Class representing a number in scientific notation. */ +class ScientificNotation { + /** @type {string} The digits of the coefficient. A decimal point is implied after the first digit. */ + coefficient; + + /** @type {number} The order of magnitude. */ + magnitude; + + constructor(coefficient, magnitude) { + this.coefficient = coefficient; + this.magnitude = magnitude; + } + + /* c8 ignore start -- debug only */ + toString() { + return `${this.coefficient[0]}${this.coefficient.length > 1 ? `.${this.coefficient.slice(1)}` : ""}e${this.magnitude}`; + } + /* c8 ignore stop */ +} + +/** + * Returns whether the node is number literal + * @param {Node} node the node literal being evaluated + * @returns {boolean} true if the node is a number literal + */ +function isNumber(node) { + return typeof node.value === "number"; +} + +/** + * Gets the source code of the given number literal. Removes `_` numeric separators from the result. + * @param {Node} node the number `Literal` node + * @returns {string} raw source code of the literal, without numeric separators + */ +function getRaw(node) { + return node.raw.replace(/_/gu, ""); +} + +/** + * Checks whether the number is base ten + * @param {ASTNode} node the node being evaluated + * @returns {boolean} true if the node is in base ten + */ +function isBaseTen(node) { + const prefixes = ["0x", "0X", "0b", "0B", "0o", "0O"]; + + return ( + prefixes.every(prefix => !node.raw.startsWith(prefix)) && + !/^0[0-7]+$/u.test(node.raw) + ); +} + +/** + * Checks that the user-intended non-base ten number equals the actual number after is has been converted to the Number type + * @param {Node} node the node being evaluated + * @returns {boolean} true if they do not match + */ +function notBaseTenLosesPrecision(node) { + const rawString = getRaw(node).toUpperCase(); + let base; + + if (rawString.startsWith("0B")) { + base = 2; + } else if (rawString.startsWith("0X")) { + base = 16; + } else { + base = 8; + } + + return !rawString.endsWith(node.value.toString(base).toUpperCase()); +} + +/** + * Returns the number stripped of leading zeros + * @param {string} numberAsString the string representation of the number + * @returns {string} the stripped string + */ +function removeLeadingZeros(numberAsString) { + for (let i = 0; i < numberAsString.length; i++) { + if (numberAsString[i] !== "0") { + return numberAsString.slice(i); + } + } + return numberAsString; +} + +/** + * Returns the number stripped of trailing zeros + * @param {string} numberAsString the string representation of the number + * @returns {string} the stripped string + */ +function removeTrailingZeros(numberAsString) { + for (let i = numberAsString.length - 1; i >= 0; i--) { + if (numberAsString[i] !== "0") { + return numberAsString.slice(0, i + 1); + } + } + return numberAsString; +} + +/** + * Converts an integer to an object containing the integer's coefficient and order of magnitude + * @param {string} stringInteger the string representation of the integer being converted + * @returns {ScientificNotation} the object containing the integer's coefficient and order of magnitude + */ +function normalizeInteger(stringInteger) { + const trimmedInteger = removeLeadingZeros(stringInteger); + const significantDigits = removeTrailingZeros(trimmedInteger); + + return new ScientificNotation(significantDigits, trimmedInteger.length - 1); +} + +/** + * Converts a float to an object containing the float's coefficient and order of magnitude + * @param {string} stringFloat the string representation of the float being converted + * @returns {ScientificNotation} the object containing the float's coefficient and order of magnitude + */ +function normalizeFloat(stringFloat) { + const trimmedFloat = removeLeadingZeros(stringFloat); + const indexOfDecimalPoint = trimmedFloat.indexOf("."); + + switch (indexOfDecimalPoint) { + case 0: { + const significantDigits = removeLeadingZeros(trimmedFloat.slice(1)); + + return new ScientificNotation( + significantDigits, + significantDigits.length - trimmedFloat.length, + ); + } + case -1: + return new ScientificNotation( + trimmedFloat, + trimmedFloat.length - 1, + ); + default: + return new ScientificNotation( + trimmedFloat.replace(".", ""), + indexOfDecimalPoint - 1, + ); + } +} + +/** + * Converts a base ten number to proper scientific notation + * @param {string} stringNumber the string representation of the base ten number to be converted + * @param {boolean} parseAsFloat if true, the coefficient will be always parsed as a float, regardless of whether a decimal point is present + * @returns {ScientificNotation} the object containing the number's coefficient and order of magnitude + */ +function convertNumberToScientificNotation(stringNumber, parseAsFloat) { + const splitNumber = stringNumber.split("e"); + const originalCoefficient = splitNumber[0]; + const normalizedNumber = + parseAsFloat || stringNumber.includes(".") + ? normalizeFloat(originalCoefficient) + : normalizeInteger(originalCoefficient); + if (splitNumber.length > 1) { + normalizedNumber.magnitude += parseInt(splitNumber[1], 10); + } + + return normalizedNumber; +} + +/** + * Checks that the user-intended base ten number equals the actual number after is has been converted to the Number type + * @param {Node} node the node being evaluated + * @returns {boolean} true if they do not match + */ +function baseTenLosesPrecision(node) { + const rawNumber = getRaw(node).toLowerCase(); + const normalizedRawNumber = convertNumberToScientificNotation( + rawNumber, + false, + ); + const requestedPrecision = normalizedRawNumber.coefficient.length; + + if (requestedPrecision > 100) { + return true; + } + const storedNumber = node.value.toPrecision(requestedPrecision); + const normalizedStoredNumber = convertNumberToScientificNotation( + storedNumber, + true, + ); + + return ( + normalizedRawNumber.magnitude !== normalizedStoredNumber.magnitude || + normalizedRawNumber.coefficient !== normalizedStoredNumber.coefficient + ); +} + +/** + * Checks that the user-intended number equals the actual number after is has been converted to the Number type + * @param {Node} node the node being evaluated + * @returns {boolean} true if they do not match + */ +function losesPrecision(node) { + return isBaseTen(node) + ? baseTenLosesPrecision(node) + : notBaseTenLosesPrecision(node); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow literal numbers that lose precision", + dialects: ["JavaScript", "TypeScript"], + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-loss-of-precision", + }, + schema: [], + messages: { + noLossOfPrecision: + "This number literal will lose precision at runtime.", + }, + }, + + create(context) { + return { + Literal(node) { + if (node.value && isNumber(node) && losesPrecision(node)) { + context.report({ + messageId: "noLossOfPrecision", + node, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-magic-numbers.js b/node_modules/eslint/lib/rules/no-magic-numbers.js new file mode 100644 index 0000000000000000000000000000000000000000..f5eeb5fa12b8d8cb2db14380bcc09e73feba9ffd --- /dev/null +++ b/node_modules/eslint/lib/rules/no-magic-numbers.js @@ -0,0 +1,370 @@ +/** + * @fileoverview Rule to flag statements that use magic numbers (adapted from https://github.com/danielstjules/buddy.js) + * @author Vincent Lemeunier + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +// Maximum array length by the ECMAScript Specification. +const MAX_ARRAY_LENGTH = 2 ** 32 - 1; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Convert the value to bigint if it's a string. Otherwise return the value as-is. + * @param {bigint|number|string} x The value to normalize. + * @returns {bigint|number} The normalized value. + */ +function normalizeIgnoreValue(x) { + if (typeof x === "string") { + return BigInt(x.slice(0, -1)); + } + return x; +} + +/** + * Checks if the node parent is a TypeScript enum member + * @param {ASTNode} node The node to be validated + * @returns {boolean} True if the node parent is a TypeScript enum member + */ +function isParentTSEnumDeclaration(node) { + return node.parent.type === "TSEnumMember"; +} + +/** + * Checks if the node is a valid TypeScript numeric literal type. + * @param {ASTNode} node The node to be validated + * @returns {boolean} True if the node is a TypeScript numeric literal type + */ +function isTSNumericLiteralType(node) { + let ancestor = node.parent; + + // Go up while we're part of a type union + while (ancestor.parent.type === "TSUnionType") { + ancestor = ancestor.parent; + } + + // Check if the final ancestor is in a type alias declaration + return ancestor.parent.type === "TSTypeAliasDeclaration"; +} + +/** + * Checks if the node parent is a readonly class property + * @param {ASTNode} node The node to be validated + * @returns {boolean} True if the node parent is a readonly class property + */ +function isParentTSReadonlyPropertyDefinition(node) { + if (node.parent?.type === "PropertyDefinition" && node.parent.readonly) { + return true; + } + + return false; +} + +/** + * Checks if the node is part of a type indexed access (eg. Foo[4]) + * @param {ASTNode} node The node to be validated + * @returns {boolean} True if the node is part of an indexed access + */ +function isAncestorTSIndexedAccessType(node) { + let ancestor = node.parent; + + /* + * Go up another level while we're part of a type union (eg. 1 | 2) or + * intersection (eg. 1 & 2) + */ + while ( + ancestor.parent.type === "TSUnionType" || + ancestor.parent.type === "TSIntersectionType" + ) { + ancestor = ancestor.parent; + } + + return ancestor.parent.type === "TSIndexedAccessType"; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow magic numbers", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-magic-numbers", + }, + + schema: [ + { + type: "object", + properties: { + detectObjects: { + type: "boolean", + }, + enforceConst: { + type: "boolean", + }, + ignore: { + type: "array", + items: { + anyOf: [ + { type: "number" }, + { + type: "string", + pattern: "^[+-]?(?:0|[1-9][0-9]*)n$", + }, + ], + }, + uniqueItems: true, + }, + ignoreArrayIndexes: { + type: "boolean", + }, + ignoreDefaultValues: { + type: "boolean", + }, + ignoreClassFieldInitialValues: { + type: "boolean", + }, + ignoreEnums: { + type: "boolean", + }, + ignoreNumericLiteralTypes: { + type: "boolean", + }, + ignoreReadonlyClassProperties: { + type: "boolean", + }, + ignoreTypeIndexes: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [ + { + detectObjects: false, + enforceConst: false, + ignore: [], + ignoreArrayIndexes: false, + ignoreDefaultValues: false, + ignoreClassFieldInitialValues: false, + ignoreEnums: false, + ignoreNumericLiteralTypes: false, + ignoreReadonlyClassProperties: false, + ignoreTypeIndexes: false, + }, + ], + + messages: { + useConst: "Number constants declarations must use 'const'.", + noMagic: "No magic number: {{raw}}.", + }, + }, + + create(context) { + const { + detectObjects, + enforceConst, + ignore: rawIgnore, + ignoreArrayIndexes, + ignoreDefaultValues, + ignoreClassFieldInitialValues, + ignoreEnums, + ignoreNumericLiteralTypes, + ignoreReadonlyClassProperties, + ignoreTypeIndexes, + } = context.options[0]; + const ignore = new Set(rawIgnore.map(normalizeIgnoreValue)); + + const okTypes = detectObjects + ? [] + : ["ObjectExpression", "Property", "AssignmentExpression"]; + + /** + * Returns whether the rule is configured to ignore the given value + * @param {bigint|number} value The value to check + * @returns {boolean} true if the value is ignored + */ + function isIgnoredValue(value) { + return ignore.has(value); + } + + /** + * Returns whether the number is a default value assignment. + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the number is a default value + */ + function isDefaultValue(fullNumberNode) { + const parent = fullNumberNode.parent; + + return ( + parent.type === "AssignmentPattern" && + parent.right === fullNumberNode + ); + } + + /** + * Returns whether the number is the initial value of a class field. + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the number is the initial value of a class field. + */ + function isClassFieldInitialValue(fullNumberNode) { + const parent = fullNumberNode.parent; + + return ( + parent.type === "PropertyDefinition" && + parent.value === fullNumberNode + ); + } + + /** + * Returns whether the given node is used as a radix within parseInt() or Number.parseInt() + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the node is radix + */ + function isParseIntRadix(fullNumberNode) { + const parent = fullNumberNode.parent; + + return ( + parent.type === "CallExpression" && + fullNumberNode === parent.arguments[1] && + (astUtils.isSpecificId(parent.callee, "parseInt") || + astUtils.isSpecificMemberAccess( + parent.callee, + "Number", + "parseInt", + )) + ); + } + + /** + * Returns whether the given node is a direct child of a JSX node. + * In particular, it aims to detect numbers used as prop values in JSX tags. + * Example: + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @returns {boolean} true if the node is a JSX number + */ + function isJSXNumber(fullNumberNode) { + return fullNumberNode.parent.type.indexOf("JSX") === 0; + } + + /** + * Returns whether the given node is used as an array index. + * Value must coerce to a valid array index name: "0", "1", "2" ... "4294967294". + * + * All other values, like "-1", "2.5", or "4294967295", are just "normal" object properties, + * which can be created and accessed on an array in addition to the array index properties, + * but they don't affect array's length and are not considered by methods such as .map(), .forEach() etc. + * + * The maximum array length by the specification is 2 ** 32 - 1 = 4294967295, + * thus the maximum valid index is 2 ** 32 - 2 = 4294967294. + * + * All notations are allowed, as long as the value coerces to one of "0", "1", "2" ... "4294967294". + * + * Valid examples: + * a[0], a[1], a[1.2e1], a[0xAB], a[0n], a[1n] + * a[-0] (same as a[0] because -0 coerces to "0") + * a[-0n] (-0n evaluates to 0n) + * + * Invalid examples: + * a[-1], a[-0xAB], a[-1n], a[2.5], a[1.23e1], a[12e-1] + * a[4294967295] (above the max index, it's an access to a regular property a["4294967295"]) + * a[999999999999999999999] (even if it wasn't above the max index, it would be a["1e+21"]) + * a[1e310] (same as a["Infinity"]) + * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node + * @param {bigint|number} value Value expressed by the fullNumberNode + * @returns {boolean} true if the node is a valid array index + */ + function isArrayIndex(fullNumberNode, value) { + const parent = fullNumberNode.parent; + + return ( + parent.type === "MemberExpression" && + parent.property === fullNumberNode && + (Number.isInteger(value) || typeof value === "bigint") && + value >= 0 && + value < MAX_ARRAY_LENGTH + ); + } + + return { + Literal(node) { + if (!astUtils.isNumericLiteral(node)) { + return; + } + + let fullNumberNode; + let value; + let raw; + + // Treat unary minus/plus as a part of the number + if ( + node.parent.type === "UnaryExpression" && + ["-", "+"].includes(node.parent.operator) + ) { + fullNumberNode = node.parent; + value = + node.parent.operator === "-" ? -node.value : node.value; + raw = `${node.parent.operator}${node.raw}`; + } else { + fullNumberNode = node; + value = node.value; + raw = node.raw; + } + + const parent = fullNumberNode.parent; + + // Always allow radix arguments and JSX props + if ( + isIgnoredValue(value) || + (ignoreDefaultValues && isDefaultValue(fullNumberNode)) || + (ignoreClassFieldInitialValues && + isClassFieldInitialValue(fullNumberNode)) || + (ignoreEnums && + isParentTSEnumDeclaration(fullNumberNode)) || + (ignoreNumericLiteralTypes && + isTSNumericLiteralType(fullNumberNode)) || + (ignoreTypeIndexes && + isAncestorTSIndexedAccessType(fullNumberNode)) || + (ignoreReadonlyClassProperties && + isParentTSReadonlyPropertyDefinition(fullNumberNode)) || + isParseIntRadix(fullNumberNode) || + isJSXNumber(fullNumberNode) || + (ignoreArrayIndexes && isArrayIndex(fullNumberNode, value)) + ) { + return; + } + + if (parent.type === "VariableDeclarator") { + if (enforceConst && parent.parent.kind !== "const") { + context.report({ + node: fullNumberNode, + messageId: "useConst", + }); + } + } else if ( + !okTypes.includes(parent.type) || + (parent.type === "AssignmentExpression" && + parent.left.type === "Identifier") + ) { + context.report({ + node: fullNumberNode, + messageId: "noMagic", + data: { + raw, + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-misleading-character-class.js b/node_modules/eslint/lib/rules/no-misleading-character-class.js new file mode 100644 index 0000000000000000000000000000000000000000..c7223335fc4105da2b6d539833d23825225c740b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-misleading-character-class.js @@ -0,0 +1,595 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +const { + CALL, + CONSTRUCT, + ReferenceTracker, + getStaticValue, + getStringIfConstant, +} = require("@eslint-community/eslint-utils"); +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); +const { + isCombiningCharacter, + isEmojiModifier, + isRegionalIndicatorSymbol, + isSurrogatePair, +} = require("./utils/unicode"); +const astUtils = require("./utils/ast-utils.js"); +const { isValidWithUnicodeFlag } = require("./utils/regular-expressions"); +const { + parseStringLiteral, + parseTemplateToken, +} = require("./utils/char-source"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * @typedef {import('@eslint-community/regexpp').AST.Character} Character + * @typedef {import('@eslint-community/regexpp').AST.CharacterClassElement} CharacterClassElement + */ + +/** + * Iterate character sequences of a given nodes. + * + * CharacterClassRange syntax can steal a part of character sequence, + * so this function reverts CharacterClassRange syntax and restore the sequence. + * @param {CharacterClassElement[]} nodes The node list to iterate character sequences. + * @returns {IterableIterator} The list of character sequences. + */ +function* iterateCharacterSequence(nodes) { + /** @type {Character[]} */ + let seq = []; + + for (const node of nodes) { + switch (node.type) { + case "Character": + seq.push(node); + break; + + case "CharacterClassRange": + seq.push(node.min); + yield seq; + seq = [node.max]; + break; + + case "CharacterSet": + case "CharacterClass": // [[]] nesting character class + case "ClassStringDisjunction": // \q{...} + case "ExpressionCharacterClass": // [A--B] + if (seq.length > 0) { + yield seq; + seq = []; + } + break; + + // no default + } + } + + if (seq.length > 0) { + yield seq; + } +} + +/** + * Checks whether the given character node is a Unicode code point escape or not. + * @param {Character} char the character node to check. + * @returns {boolean} `true` if the character node is a Unicode code point escape. + */ +function isUnicodeCodePointEscape(char) { + return /^\\u\{[\da-f]+\}$/iu.test(char.raw); +} + +/** + * Each function returns matched characters if it detects that kind of problem. + * @type {Record IterableIterator>} + */ +const findCharacterSequences = { + *surrogatePairWithoutUFlag(chars) { + for (const [index, char] of chars.entries()) { + const previous = chars[index - 1]; + + if ( + previous && + char && + isSurrogatePair(previous.value, char.value) && + !isUnicodeCodePointEscape(previous) && + !isUnicodeCodePointEscape(char) + ) { + yield [previous, char]; + } + } + }, + + *surrogatePair(chars) { + for (const [index, char] of chars.entries()) { + const previous = chars[index - 1]; + + if ( + previous && + char && + isSurrogatePair(previous.value, char.value) && + (isUnicodeCodePointEscape(previous) || + isUnicodeCodePointEscape(char)) + ) { + yield [previous, char]; + } + } + }, + + *combiningClass(chars, unfilteredChars) { + /* + * When `allowEscape` is `true`, a combined character should only be allowed if the combining mark appears as an escape sequence. + * This means that the base character should be considered even if it's escaped. + */ + for (const [index, char] of chars.entries()) { + const previous = unfilteredChars[index - 1]; + + if ( + previous && + char && + isCombiningCharacter(char.value) && + !isCombiningCharacter(previous.value) + ) { + yield [previous, char]; + } + } + }, + + *emojiModifier(chars) { + for (const [index, char] of chars.entries()) { + const previous = chars[index - 1]; + + if ( + previous && + char && + isEmojiModifier(char.value) && + !isEmojiModifier(previous.value) + ) { + yield [previous, char]; + } + } + }, + + *regionalIndicatorSymbol(chars) { + for (const [index, char] of chars.entries()) { + const previous = chars[index - 1]; + + if ( + previous && + char && + isRegionalIndicatorSymbol(char.value) && + isRegionalIndicatorSymbol(previous.value) + ) { + yield [previous, char]; + } + } + }, + + *zwj(chars) { + let sequence = null; + + for (const [index, char] of chars.entries()) { + const previous = chars[index - 1]; + const next = chars[index + 1]; + + if ( + previous && + char && + next && + char.value === 0x200d && + previous.value !== 0x200d && + next.value !== 0x200d + ) { + if (sequence) { + if (sequence.at(-1) === previous) { + sequence.push(char, next); // append to the sequence + } else { + yield sequence; + sequence = chars.slice(index - 1, index + 2); + } + } else { + sequence = chars.slice(index - 1, index + 2); + } + } + } + + if (sequence) { + yield sequence; + } + }, +}; + +const kinds = Object.keys(findCharacterSequences); + +/** + * Gets the value of the given node if it's a static value other than a regular expression object, + * or the node's `regex` property. + * The purpose of this method is to provide a replacement for `getStaticValue` in environments where certain regular expressions cannot be evaluated. + * A known example is Node.js 18 which does not support the `v` flag. + * Calling `getStaticValue` on a regular expression node with the `v` flag on Node.js 18 always returns `null`. + * A limitation of this method is that it can only detect a regular expression if the specified node is itself a regular expression literal node. + * @param {ASTNode | undefined} node The node to be inspected. + * @param {Scope} initialScope Scope to start finding variables. This function tries to resolve identifier references which are in the given scope. + * @returns {{ value: any } | { regex: { pattern: string, flags: string } } | null} The static value of the node, or `null`. + */ +function getStaticValueOrRegex(node, initialScope) { + if (!node) { + return null; + } + if (node.type === "Literal" && node.regex) { + return { regex: node.regex }; + } + + const staticValue = getStaticValue(node, initialScope); + + if (staticValue?.value instanceof RegExp) { + return null; + } + return staticValue; +} + +/** + * Checks whether a specified regexpp character is represented as an acceptable escape sequence. + * This function requires the source text of the character to be known. + * @param {Character} char Character to check. + * @param {string} charSource Source text of the character to check. + * @returns {boolean} Whether the specified regexpp character is represented as an acceptable escape sequence. + */ +function checkForAcceptableEscape(char, charSource) { + if (!charSource.startsWith("\\")) { + return false; + } + const match = /(?<=^\\+).$/su.exec(charSource); + + return match?.[0] !== String.fromCodePoint(char.value); +} + +/** + * Checks whether a specified regexpp character is represented as an acceptable escape sequence. + * This function works with characters that are produced by a string or template literal. + * It requires the source text and the CodeUnit list of the literal to be known. + * @param {Character} char Character to check. + * @param {string} nodeSource Source text of the string or template literal that produces the character. + * @param {CodeUnit[]} codeUnits List of CodeUnit objects of the literal that produces the character. + * @returns {boolean} Whether the specified regexpp character is represented as an acceptable escape sequence. + */ +function checkForAcceptableEscapeInString(char, nodeSource, codeUnits) { + const firstIndex = char.start; + const lastIndex = char.end - 1; + const start = codeUnits[firstIndex].start; + const end = codeUnits[lastIndex].end; + const charSource = nodeSource.slice(start, end); + + return checkForAcceptableEscape(char, charSource); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowEscape: false, + }, + ], + + docs: { + description: + "Disallow characters which are made with multiple code points in character class syntax", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-misleading-character-class", + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + allowEscape: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + surrogatePairWithoutUFlag: + "Unexpected surrogate pair in character class. Use 'u' flag.", + surrogatePair: "Unexpected surrogate pair in character class.", + combiningClass: "Unexpected combined character in character class.", + emojiModifier: "Unexpected modified Emoji in character class.", + regionalIndicatorSymbol: + "Unexpected national flag in character class.", + zwj: "Unexpected joined character sequence in character class.", + suggestUnicodeFlag: "Add unicode 'u' flag to regex.", + }, + }, + create(context) { + const [{ allowEscape }] = context.options; + const sourceCode = context.sourceCode; + const parser = new RegExpParser(); + const checkedPatternNodes = new Set(); + + /** + * Verify a given regular expression. + * @param {Node} node The node to report. + * @param {string} pattern The regular expression pattern to verify. + * @param {string} flags The flags of the regular expression. + * @param {Function} unicodeFixer Fixer for missing "u" flag. + * @returns {void} + */ + function verify(node, pattern, flags, unicodeFixer) { + let patternNode; + + try { + patternNode = parser.parsePattern(pattern, 0, pattern.length, { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v"), + }); + } catch { + // Ignore regular expressions with syntax errors + return; + } + + let codeUnits = null; + + /** + * Checks whether a specified regexpp character is represented as an acceptable escape sequence. + * For the purposes of this rule, an escape sequence is considered acceptable if it consists of one or more backslashes followed by the character being escaped. + * @param {Character} char Character to check. + * @returns {boolean} Whether the specified regexpp character is represented as an acceptable escape sequence. + */ + function isAcceptableEscapeSequence(char) { + if (node.type === "Literal" && node.regex) { + return checkForAcceptableEscape(char, char.raw); + } + if (node.type === "Literal" && typeof node.value === "string") { + const nodeSource = node.raw; + + codeUnits ??= parseStringLiteral(nodeSource); + + return checkForAcceptableEscapeInString( + char, + nodeSource, + codeUnits, + ); + } + if (astUtils.isStaticTemplateLiteral(node)) { + const nodeSource = sourceCode.getText(node); + + codeUnits ??= parseTemplateToken(nodeSource); + + return checkForAcceptableEscapeInString( + char, + nodeSource, + codeUnits, + ); + } + return false; + } + + const foundKindMatches = new Map(); + + visitRegExpAST(patternNode, { + onCharacterClassEnter(ccNode) { + for (const unfilteredChars of iterateCharacterSequence( + ccNode.elements, + )) { + let chars; + + if (allowEscape) { + // Replace escape sequences with null to avoid having them flagged. + chars = unfilteredChars.map(char => + isAcceptableEscapeSequence(char) ? null : char, + ); + } else { + chars = unfilteredChars; + } + for (const kind of kinds) { + const matches = findCharacterSequences[kind]( + chars, + unfilteredChars, + ); + + if (foundKindMatches.has(kind)) { + foundKindMatches.get(kind).push(...matches); + } else { + foundKindMatches.set(kind, [...matches]); + } + } + } + }, + }); + + /** + * Finds the report loc(s) for a range of matches. + * Only literals and expression-less templates generate granular errors. + * @param {Character[][]} matches Lists of individual characters being reported on. + * @returns {Location[]} locs for context.report. + * @see https://github.com/eslint/eslint/pull/17515 + */ + function getNodeReportLocations(matches) { + if ( + !astUtils.isStaticTemplateLiteral(node) && + node.type !== "Literal" + ) { + return matches.length ? [node.loc] : []; + } + return matches.map(chars => { + const firstIndex = chars[0].start; + const lastIndex = chars.at(-1).end - 1; + let start; + let end; + + if (node.type === "TemplateLiteral") { + const source = sourceCode.getText(node); + const offset = node.range[0]; + + codeUnits ??= parseTemplateToken(source); + start = offset + codeUnits[firstIndex].start; + end = offset + codeUnits[lastIndex].end; + } else if (typeof node.value === "string") { + // String Literal + const source = node.raw; + const offset = node.range[0]; + + codeUnits ??= parseStringLiteral(source); + start = offset + codeUnits[firstIndex].start; + end = offset + codeUnits[lastIndex].end; + } else { + // RegExp Literal + const offset = node.range[0] + 1; // Add 1 to skip the leading slash. + + start = offset + firstIndex; + end = offset + lastIndex + 1; + } + + return { + start: sourceCode.getLocFromIndex(start), + end: sourceCode.getLocFromIndex(end), + }; + }); + } + + for (const [kind, matches] of foundKindMatches) { + let suggest; + + if (kind === "surrogatePairWithoutUFlag") { + suggest = [ + { + messageId: "suggestUnicodeFlag", + fix: unicodeFixer, + }, + ]; + } + + const locs = getNodeReportLocations(matches); + + for (const loc of locs) { + context.report({ + node, + loc, + messageId: kind, + suggest, + }); + } + } + } + + return { + "Literal[regex]"(node) { + if (checkedPatternNodes.has(node)) { + return; + } + verify(node, node.regex.pattern, node.regex.flags, fixer => { + if ( + !isValidWithUnicodeFlag( + context.languageOptions.ecmaVersion, + node.regex.pattern, + ) + ) { + return null; + } + + return fixer.insertTextAfter(node, "u"); + }); + }, + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + + /* + * Iterate calls of RegExp. + * E.g., `new RegExp()`, `RegExp()`, `new window.RegExp()`, + * `const {RegExp: a} = window; new a()`, etc... + */ + for (const { node: refNode } of tracker.iterateGlobalReferences( + { + RegExp: { [CALL]: true, [CONSTRUCT]: true }, + }, + )) { + let pattern, flags; + const [patternNode, flagsNode] = refNode.arguments; + const evaluatedPattern = getStaticValueOrRegex( + patternNode, + scope, + ); + + if (!evaluatedPattern) { + continue; + } + if (flagsNode) { + if (evaluatedPattern.regex) { + pattern = evaluatedPattern.regex.pattern; + checkedPatternNodes.add(patternNode); + } else { + pattern = String(evaluatedPattern.value); + } + flags = getStringIfConstant(flagsNode, scope); + } else { + if (evaluatedPattern.regex) { + continue; + } + pattern = String(evaluatedPattern.value); + flags = ""; + } + + if (typeof flags === "string") { + verify(patternNode, pattern, flags, fixer => { + if ( + !isValidWithUnicodeFlag( + context.languageOptions.ecmaVersion, + pattern, + ) + ) { + return null; + } + + if (refNode.arguments.length === 1) { + const penultimateToken = + sourceCode.getLastToken(refNode, { + skip: 1, + }); // skip closing parenthesis + + return fixer.insertTextAfter( + penultimateToken, + astUtils.isCommaToken(penultimateToken) + ? ' "u",' + : ', "u"', + ); + } + + if ( + (flagsNode.type === "Literal" && + typeof flagsNode.value === "string") || + flagsNode.type === "TemplateLiteral" + ) { + const range = [ + flagsNode.range[0], + flagsNode.range[1] - 1, + ]; + + return fixer.insertTextAfterRange(range, "u"); + } + + return null; + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-mixed-operators.js b/node_modules/eslint/lib/rules/no-mixed-operators.js new file mode 100644 index 0000000000000000000000000000000000000000..73dc127a4aa5ff1fec9cfb176e856276e70d1cce --- /dev/null +++ b/node_modules/eslint/lib/rules/no-mixed-operators.js @@ -0,0 +1,253 @@ +/** + * @fileoverview Rule to disallow mixed binary operators. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils.js"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const ARITHMETIC_OPERATORS = ["+", "-", "*", "/", "%", "**"]; +const BITWISE_OPERATORS = ["&", "|", "^", "~", "<<", ">>", ">>>"]; +const COMPARISON_OPERATORS = ["==", "!=", "===", "!==", ">", ">=", "<", "<="]; +const LOGICAL_OPERATORS = ["&&", "||"]; +const RELATIONAL_OPERATORS = ["in", "instanceof"]; +const TERNARY_OPERATOR = ["?:"]; +const COALESCE_OPERATOR = ["??"]; +const ALL_OPERATORS = [].concat( + ARITHMETIC_OPERATORS, + BITWISE_OPERATORS, + COMPARISON_OPERATORS, + LOGICAL_OPERATORS, + RELATIONAL_OPERATORS, + TERNARY_OPERATOR, + COALESCE_OPERATOR, +); +const DEFAULT_GROUPS = [ + ARITHMETIC_OPERATORS, + BITWISE_OPERATORS, + COMPARISON_OPERATORS, + LOGICAL_OPERATORS, + RELATIONAL_OPERATORS, +]; +const TARGET_NODE_TYPE = /^(?:Binary|Logical|Conditional)Expression$/u; + +/** + * Normalizes options. + * @param {Object|undefined} options A options object to normalize. + * @returns {Object} Normalized option object. + */ +function normalizeOptions(options = {}) { + const hasGroups = options.groups && options.groups.length > 0; + const groups = hasGroups ? options.groups : DEFAULT_GROUPS; + const allowSamePrecedence = options.allowSamePrecedence !== false; + + return { + groups, + allowSamePrecedence, + }; +} + +/** + * Checks whether any group which includes both given operator exists or not. + * @param {Array} groups A list of groups to check. + * @param {string} left An operator. + * @param {string} right Another operator. + * @returns {boolean} `true` if such group existed. + */ +function includesBothInAGroup(groups, left, right) { + return groups.some(group => group.includes(left) && group.includes(right)); +} + +/** + * Checks whether the given node is a conditional expression and returns the test node else the left node. + * @param {ASTNode} node A node which can be a BinaryExpression or a LogicalExpression node. + * This parent node can be BinaryExpression, LogicalExpression + * , or a ConditionalExpression node + * @returns {ASTNode} node the appropriate node(left or test). + */ +function getChildNode(node) { + return node.type === "ConditionalExpression" ? node.test : node.left; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "no-mixed-operators", + url: "https://eslint.style/rules/no-mixed-operators", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: "Disallow mixed binary operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-mixed-operators", + }, + + schema: [ + { + type: "object", + properties: { + groups: { + type: "array", + items: { + type: "array", + items: { enum: ALL_OPERATORS }, + minItems: 2, + uniqueItems: true, + }, + uniqueItems: true, + }, + allowSamePrecedence: { + type: "boolean", + default: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedMixedOperator: + "Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'. Use parentheses to clarify the intended order of operations.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = normalizeOptions(context.options[0]); + + /** + * Checks whether a given node should be ignored by options or not. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. This parent node is one of + * them, too. + * @returns {boolean} `true` if the node should be ignored. + */ + function shouldIgnore(node) { + const a = node; + const b = node.parent; + + return ( + !includesBothInAGroup( + options.groups, + a.operator, + b.type === "ConditionalExpression" ? "?:" : b.operator, + ) || + (options.allowSamePrecedence && + astUtils.getPrecedence(a) === astUtils.getPrecedence(b)) + ); + } + + /** + * Checks whether the operator of a given node is mixed with parent + * node's operator or not. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. This parent node is one of + * them, too. + * @returns {boolean} `true` if the node was mixed. + */ + function isMixedWithParent(node) { + return ( + node.operator !== node.parent.operator && + !astUtils.isParenthesised(sourceCode, node) + ); + } + + /** + * Gets the operator token of a given node. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. + * @returns {Token} The operator token of the node. + */ + function getOperatorToken(node) { + return sourceCode.getTokenAfter( + getChildNode(node), + astUtils.isNotClosingParenToken, + ); + } + + /** + * Reports both the operator of a given node and the operator of the + * parent node. + * @param {ASTNode} node A node to check. This is a BinaryExpression + * node or a LogicalExpression node. This parent node is one of + * them, too. + * @returns {void} + */ + function reportBothOperators(node) { + const parent = node.parent; + const left = getChildNode(parent) === node ? node : parent; + const right = getChildNode(parent) !== node ? node : parent; + const data = { + leftOperator: left.operator || "?:", + rightOperator: right.operator || "?:", + }; + + context.report({ + node: left, + loc: getOperatorToken(left).loc, + messageId: "unexpectedMixedOperator", + data, + }); + context.report({ + node: right, + loc: getOperatorToken(right).loc, + messageId: "unexpectedMixedOperator", + data, + }); + } + + /** + * Checks between the operator of this node and the operator of the + * parent node. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function check(node) { + if ( + TARGET_NODE_TYPE.test(node.parent.type) && + isMixedWithParent(node) && + !shouldIgnore(node) + ) { + reportBothOperators(node); + } + } + + return { + BinaryExpression: check, + LogicalExpression: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-mixed-requires.js b/node_modules/eslint/lib/rules/no-mixed-requires.js new file mode 100644 index 0000000000000000000000000000000000000000..0d8bb55863348766bc73b9dac9d6a87cbead55c1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-mixed-requires.js @@ -0,0 +1,267 @@ +/** + * @fileoverview Rule to enforce grouped require statements for Node.JS + * @author Raphael Pigulla + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-mixed-requires", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-mixed-requires.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: + "Disallow `require` calls to be mixed with regular variable declarations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-mixed-requires", + }, + + schema: [ + { + oneOf: [ + { + type: "boolean", + }, + { + type: "object", + properties: { + grouping: { + type: "boolean", + }, + allowCall: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + noMixRequire: "Do not mix 'require' and other declarations.", + noMixCoreModuleFileComputed: + "Do not mix core, module, file and computed requires.", + }, + }, + + create(context) { + const options = context.options[0]; + let grouping = false, + allowCall = false; + + if (typeof options === "object") { + grouping = options.grouping; + allowCall = options.allowCall; + } else { + grouping = !!options; + } + + /** + * Returns the list of built-in modules. + * @returns {string[]} An array of built-in Node.js modules. + */ + function getBuiltinModules() { + /* + * This list is generated using: + * `require("repl")._builtinLibs.concat('repl').sort()` + * This particular list is as per nodejs v0.12.2 and iojs v0.7.1 + */ + return [ + "assert", + "buffer", + "child_process", + "cluster", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "net", + "os", + "path", + "punycode", + "querystring", + "readline", + "repl", + "smalloc", + "stream", + "string_decoder", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib", + ]; + } + + const BUILTIN_MODULES = getBuiltinModules(); + + const DECL_REQUIRE = "require", + DECL_UNINITIALIZED = "uninitialized", + DECL_OTHER = "other"; + + const REQ_CORE = "core", + REQ_FILE = "file", + REQ_MODULE = "module", + REQ_COMPUTED = "computed"; + + /** + * Determines the type of a declaration statement. + * @param {ASTNode} initExpression The init node of the VariableDeclarator. + * @returns {string} The type of declaration represented by the expression. + */ + function getDeclarationType(initExpression) { + if (!initExpression) { + // "var x;" + return DECL_UNINITIALIZED; + } + + if ( + initExpression.type === "CallExpression" && + initExpression.callee.type === "Identifier" && + initExpression.callee.name === "require" + ) { + // "var x = require('util');" + return DECL_REQUIRE; + } + if ( + allowCall && + initExpression.type === "CallExpression" && + initExpression.callee.type === "CallExpression" + ) { + // "var x = require('diagnose')('sub-module');" + return getDeclarationType(initExpression.callee); + } + if (initExpression.type === "MemberExpression") { + // "var x = require('glob').Glob;" + return getDeclarationType(initExpression.object); + } + + // "var x = 42;" + return DECL_OTHER; + } + + /** + * Determines the type of module that is loaded via require. + * @param {ASTNode} initExpression The init node of the VariableDeclarator. + * @returns {string} The module type. + */ + function inferModuleType(initExpression) { + if (initExpression.type === "MemberExpression") { + // "var x = require('glob').Glob;" + return inferModuleType(initExpression.object); + } + if (initExpression.arguments.length === 0) { + // "var x = require();" + return REQ_COMPUTED; + } + + const arg = initExpression.arguments[0]; + + if (arg.type !== "Literal" || typeof arg.value !== "string") { + // "var x = require(42);" + return REQ_COMPUTED; + } + + if (BUILTIN_MODULES.includes(arg.value)) { + // "var fs = require('fs');" + return REQ_CORE; + } + if (/^\.{0,2}\//u.test(arg.value)) { + // "var utils = require('./utils');" + return REQ_FILE; + } + + // "var async = require('async');" + return REQ_MODULE; + } + + /** + * Check if the list of variable declarations is mixed, i.e. whether it + * contains both require and other declarations. + * @param {ASTNode} declarations The list of VariableDeclarators. + * @returns {boolean} True if the declarations are mixed, false if not. + */ + function isMixed(declarations) { + const contains = {}; + + declarations.forEach(declaration => { + const type = getDeclarationType(declaration.init); + + contains[type] = true; + }); + + return !!( + contains[DECL_REQUIRE] && + (contains[DECL_UNINITIALIZED] || contains[DECL_OTHER]) + ); + } + + /** + * Check if all require declarations in the given list are of the same + * type. + * @param {ASTNode} declarations The list of VariableDeclarators. + * @returns {boolean} True if the declarations are grouped, false if not. + */ + function isGrouped(declarations) { + const found = {}; + + declarations.forEach(declaration => { + if (getDeclarationType(declaration.init) === DECL_REQUIRE) { + found[inferModuleType(declaration.init)] = true; + } + }); + + return Object.keys(found).length <= 1; + } + + return { + VariableDeclaration(node) { + if (isMixed(node.declarations)) { + context.report({ + node, + messageId: "noMixRequire", + }); + } else if (grouping && !isGrouped(node.declarations)) { + context.report({ + node, + messageId: "noMixCoreModuleFileComputed", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js b/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js new file mode 100644 index 0000000000000000000000000000000000000000..5983d7cfd00e24be25e24c537cb821aa9953d623 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js @@ -0,0 +1,148 @@ +/** + * @fileoverview Disallow mixed spaces and tabs for indentation + * @author Jary Niebur + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "no-mixed-spaces-and-tabs", + url: "https://eslint.style/rules/no-mixed-spaces-and-tabs", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow mixed spaces and tabs for indentation", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-mixed-spaces-and-tabs", + }, + + schema: [ + { + enum: ["smart-tabs", true, false], + }, + ], + + messages: { + mixedSpacesAndTabs: "Mixed spaces and tabs.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + let smartTabs; + + switch (context.options[0]) { + case true: // Support old syntax, maybe add deprecation warning here + case "smart-tabs": + smartTabs = true; + break; + default: + smartTabs = false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Program:exit"(node) { + const lines = sourceCode.lines, + comments = sourceCode.getAllComments(), + ignoredCommentLines = new Set(); + + // Add all lines except the first ones. + comments.forEach(comment => { + for ( + let i = comment.loc.start.line + 1; + i <= comment.loc.end.line; + i++ + ) { + ignoredCommentLines.add(i); + } + }); + + /* + * At least one space followed by a tab + * or the reverse before non-tab/-space + * characters begin. + */ + let regex = /^(?=( +|\t+))\1(?:\t| )/u; + + if (smartTabs) { + /* + * At least one space followed by a tab + * before non-tab/-space characters begin. + */ + // eslint-disable-next-line regexp/no-empty-lookarounds-assertion -- False positive + regex = /^(?=(\t*))\1(?=( +))\2\t/u; + } + + lines.forEach((line, i) => { + const match = regex.exec(line); + + if (match) { + const lineNumber = i + 1; + const loc = { + start: { + line: lineNumber, + column: match[0].length - 2, + }, + end: { + line: lineNumber, + column: match[0].length, + }, + }; + + if (!ignoredCommentLines.has(lineNumber)) { + const containingNode = + sourceCode.getNodeByRangeIndex( + sourceCode.getIndexFromLoc(loc.start), + ); + + if ( + !( + containingNode && + ["Literal", "TemplateElement"].includes( + containingNode.type, + ) + ) + ) { + context.report({ + node, + loc, + messageId: "mixedSpacesAndTabs", + }); + } + } + } + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-multi-assign.js b/node_modules/eslint/lib/rules/no-multi-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..b4d6ddb4e6a4f76b1470dae89120ca507fc73c78 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multi-assign.js @@ -0,0 +1,66 @@ +/** + * @fileoverview Rule to check use of chained assignment expressions + * @author Stewart Rand + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + ignoreNonDeclaration: false, + }, + ], + + docs: { + description: "Disallow use of chained assignment expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-multi-assign", + }, + + schema: [ + { + type: "object", + properties: { + ignoreNonDeclaration: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedChain: "Unexpected chained assignment.", + }, + }, + + create(context) { + const [{ ignoreNonDeclaration }] = context.options; + const selectors = [ + "VariableDeclarator > AssignmentExpression.init", + "PropertyDefinition > AssignmentExpression.value", + ]; + + if (!ignoreNonDeclaration) { + selectors.push("AssignmentExpression > AssignmentExpression.right"); + } + + return { + [selectors](node) { + context.report({ + node, + messageId: "unexpectedChain", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-multi-spaces.js b/node_modules/eslint/lib/rules/no-multi-spaces.js new file mode 100644 index 0000000000000000000000000000000000000000..93704760a46139b0d872a2366ba5cd38edba3b0b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multi-spaces.js @@ -0,0 +1,179 @@ +/** + * @fileoverview Disallow use of multiple spaces. + * @author Nicholas C. Zakas + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "no-multi-spaces", + url: "https://eslint.style/rules/no-multi-spaces", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow multiple spaces", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-multi-spaces", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "object", + patternProperties: { + "^([A-Z][a-z]*)+$": { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ignoreEOLComments: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + multipleSpaces: "Multiple spaces found before '{{displayValue}}'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = context.options[0] || {}; + const ignoreEOLComments = options.ignoreEOLComments; + const exceptions = Object.assign( + { Property: true }, + options.exceptions, + ); + const hasExceptions = Object.keys(exceptions).some( + key => exceptions[key], + ); + + /** + * Formats value of given comment token for error message by truncating its length. + * @param {Token} token comment token + * @returns {string} formatted value + * @private + */ + function formatReportedCommentValue(token) { + const valueLines = token.value.split("\n"); + const value = valueLines[0]; + const formattedValue = `${value.slice(0, 12)}...`; + + return valueLines.length === 1 && value.length <= 12 + ? value + : formattedValue; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + sourceCode.tokensAndComments.forEach( + (leftToken, leftIndex, tokensAndComments) => { + if (leftIndex === tokensAndComments.length - 1) { + return; + } + const rightToken = tokensAndComments[leftIndex + 1]; + + // Ignore tokens that don't have 2 spaces between them or are on different lines + if ( + !sourceCode.text + .slice(leftToken.range[1], rightToken.range[0]) + .includes(" ") || + leftToken.loc.end.line < rightToken.loc.start.line + ) { + return; + } + + // Ignore comments that are the last token on their line if `ignoreEOLComments` is active. + if ( + ignoreEOLComments && + astUtils.isCommentToken(rightToken) && + (leftIndex === tokensAndComments.length - 2 || + rightToken.loc.end.line < + tokensAndComments[leftIndex + 2].loc.start + .line) + ) { + return; + } + + // Ignore tokens that are in a node in the "exceptions" object + if (hasExceptions) { + const parentNode = sourceCode.getNodeByRangeIndex( + rightToken.range[0] - 1, + ); + + if (parentNode && exceptions[parentNode.type]) { + return; + } + } + + let displayValue; + + if (rightToken.type === "Block") { + displayValue = `/*${formatReportedCommentValue(rightToken)}*/`; + } else if (rightToken.type === "Line") { + displayValue = `//${formatReportedCommentValue(rightToken)}`; + } else { + displayValue = rightToken.value; + } + + context.report({ + node: rightToken, + loc: { + start: leftToken.loc.end, + end: rightToken.loc.start, + }, + messageId: "multipleSpaces", + data: { displayValue }, + fix: fixer => + fixer.replaceTextRange( + [leftToken.range[1], rightToken.range[0]], + " ", + ), + }); + }, + ); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-multi-str.js b/node_modules/eslint/lib/rules/no-multi-str.js new file mode 100644 index 0000000000000000000000000000000000000000..4258dc2e31f09a4cb4745248361606a5309622ac --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multi-str.js @@ -0,0 +1,67 @@ +/** + * @fileoverview Rule to flag when using multiline strings + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow multiline strings", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-multi-str", + }, + + schema: [], + + messages: { + multilineString: + "Multiline support is limited to browsers supporting ES5 only.", + }, + }, + + create(context) { + /** + * Determines if a given node is part of JSX syntax. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a JSX node, false if not. + * @private + */ + function isJSXElement(node) { + return node.type.indexOf("JSX") === 0; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + Literal(node) { + if ( + astUtils.LINEBREAK_MATCHER.test(node.raw) && + !isJSXElement(node.parent) + ) { + context.report({ + node, + messageId: "multilineString", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-multiple-empty-lines.js b/node_modules/eslint/lib/rules/no-multiple-empty-lines.js new file mode 100644 index 0000000000000000000000000000000000000000..1f6d72647d96c7b40b76e11213cad411b6d491f0 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-multiple-empty-lines.js @@ -0,0 +1,210 @@ +/** + * @fileoverview Disallows multiple blank lines. + * implementation adapted from the no-trailing-spaces rule. + * @author Greg Cochard + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "no-multiple-empty-lines", + url: "https://eslint.style/rules/no-multiple-empty-lines", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow multiple empty lines", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-multiple-empty-lines", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + max: { + type: "integer", + minimum: 0, + }, + maxEOF: { + type: "integer", + minimum: 0, + }, + maxBOF: { + type: "integer", + minimum: 0, + }, + }, + required: ["max"], + additionalProperties: false, + }, + ], + + messages: { + blankBeginningOfFile: + "Too many blank lines at the beginning of file. Max of {{max}} allowed.", + blankEndOfFile: + "Too many blank lines at the end of file. Max of {{max}} allowed.", + consecutiveBlank: + "More than {{max}} blank {{pluralizedLines}} not allowed.", + }, + }, + + create(context) { + // Use options.max or 2 as default + let max = 2, + maxEOF = max, + maxBOF = max; + + if (context.options.length) { + max = context.options[0].max; + maxEOF = + typeof context.options[0].maxEOF !== "undefined" + ? context.options[0].maxEOF + : max; + maxBOF = + typeof context.options[0].maxBOF !== "undefined" + ? context.options[0].maxBOF + : max; + } + + const sourceCode = context.sourceCode; + + // Swallow the final newline, as some editors add it automatically and we don't want it to cause an issue + const allLines = + sourceCode.lines.at(-1) === "" + ? sourceCode.lines.slice(0, -1) + : sourceCode.lines; + const templateLiteralLines = new Set(); + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + TemplateLiteral(node) { + node.quasis.forEach(literalPart => { + // Empty lines have a semantic meaning if they're inside template literals. Don't count these as empty lines. + for ( + let ignoredLine = literalPart.loc.start.line; + ignoredLine < literalPart.loc.end.line; + ignoredLine++ + ) { + templateLiteralLines.add(ignoredLine); + } + }); + }, + "Program:exit"(node) { + return ( + allLines + + // Given a list of lines, first get a list of line numbers that are non-empty. + .reduce((nonEmptyLineNumbers, line, index) => { + if ( + line.trim() || + templateLiteralLines.has(index + 1) + ) { + nonEmptyLineNumbers.push(index + 1); + } + return nonEmptyLineNumbers; + }, []) + + // Add a value at the end to allow trailing empty lines to be checked. + .concat(allLines.length + 1) + + // Given two line numbers of non-empty lines, report the lines between if the difference is too large. + .reduce((lastLineNumber, lineNumber) => { + let messageId, maxAllowed; + + if (lastLineNumber === 0) { + messageId = "blankBeginningOfFile"; + maxAllowed = maxBOF; + } else if (lineNumber === allLines.length + 1) { + messageId = "blankEndOfFile"; + maxAllowed = maxEOF; + } else { + messageId = "consecutiveBlank"; + maxAllowed = max; + } + + if (lineNumber - lastLineNumber - 1 > maxAllowed) { + context.report({ + node, + loc: { + start: { + line: + lastLineNumber + maxAllowed + 1, + column: 0, + }, + end: { line: lineNumber, column: 0 }, + }, + messageId, + data: { + max: maxAllowed, + pluralizedLines: + maxAllowed === 1 ? "line" : "lines", + }, + fix(fixer) { + const rangeStart = + sourceCode.getIndexFromLoc({ + line: lastLineNumber + 1, + column: 0, + }); + + /* + * The end of the removal range is usually the start index of the next line. + * However, at the end of the file there is no next line, so the end of the + * range is just the length of the text. + */ + const lineNumberAfterRemovedLines = + lineNumber - maxAllowed; + const rangeEnd = + lineNumberAfterRemovedLines <= + allLines.length + ? sourceCode.getIndexFromLoc({ + line: lineNumberAfterRemovedLines, + column: 0, + }) + : sourceCode.text.length; + + return fixer.removeRange([ + rangeStart, + rangeEnd, + ]); + }, + }); + } + + return lineNumber; + }, 0) + ); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-native-reassign.js b/node_modules/eslint/lib/rules/no-native-reassign.js new file mode 100644 index 0000000000000000000000000000000000000000..f4eef063276b5ad5bd851fb5482f2dcc31ab0f9c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-native-reassign.js @@ -0,0 +1,114 @@ +/** + * @fileoverview Rule to disallow assignments to native objects or read-only global variables + * @author Ilya Volodin + * @deprecated in ESLint v3.3.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow assignments to native objects or read-only global variables", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-native-reassign", + }, + + deprecated: { + message: "Renamed rule.", + url: "https://eslint.org/blog/2016/08/eslint-v3.3.0-released/#deprecated-rules", + deprecatedSince: "3.3.0", + availableUntil: "11.0.0", + replacedBy: [ + { + rule: { + name: "no-global-assign", + url: "https://eslint.org/docs/rules/no-global-assign", + }, + }, + ], + }, + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + nativeReassign: + "Read-only global '{{name}}' should not be modified.", + }, + }, + + create(context) { + const config = context.options[0]; + const exceptions = (config && config.exceptions) || []; + const sourceCode = context.sourceCode; + + /** + * Reports write references. + * @param {Reference} reference A reference to check. + * @param {number} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {void} + */ + function checkReference(reference, index, references) { + const identifier = reference.identifier; + + if ( + reference.init === false && + reference.isWrite() && + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ + (index === 0 || references[index - 1].identifier !== identifier) + ) { + context.report({ + node: identifier, + messageId: "nativeReassign", + data: identifier, + }); + } + } + + /** + * Reports write references if a given variable is read-only builtin. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if ( + variable.writeable === false && + !exceptions.includes(variable.name) + ) { + variable.references.forEach(checkReference); + } + } + + return { + Program(node) { + const globalScope = sourceCode.getScope(node); + + globalScope.variables.forEach(checkVariable); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-negated-condition.js b/node_modules/eslint/lib/rules/no-negated-condition.js new file mode 100644 index 0000000000000000000000000000000000000000..33c150e8909d3ea32b9876f32c3c59747bde4918 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-negated-condition.js @@ -0,0 +1,100 @@ +/** + * @fileoverview Rule to disallow a negated condition + * @author Alberto Rodríguez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow negated conditions", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-negated-condition", + }, + + schema: [], + + messages: { + unexpectedNegated: "Unexpected negated condition.", + }, + }, + + create(context) { + /** + * Determines if a given node is an if-else without a condition on the else + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node has an else without an if. + * @private + */ + function hasElseWithoutCondition(node) { + return node.alternate && node.alternate.type !== "IfStatement"; + } + + /** + * Determines if a given node is a negated unary expression + * @param {Object} test The test object to check. + * @returns {boolean} True if the node is a negated unary expression. + * @private + */ + function isNegatedUnaryExpression(test) { + return test.type === "UnaryExpression" && test.operator === "!"; + } + + /** + * Determines if a given node is a negated binary expression + * @param {Test} test The test to check. + * @returns {boolean} True if the node is a negated binary expression. + * @private + */ + function isNegatedBinaryExpression(test) { + return ( + test.type === "BinaryExpression" && + (test.operator === "!=" || test.operator === "!==") + ); + } + + /** + * Determines if a given node has a negated if expression + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node has a negated if expression. + * @private + */ + function isNegatedIf(node) { + return ( + isNegatedUnaryExpression(node.test) || + isNegatedBinaryExpression(node.test) + ); + } + + return { + IfStatement(node) { + if (!hasElseWithoutCondition(node)) { + return; + } + + if (isNegatedIf(node)) { + context.report({ + node, + messageId: "unexpectedNegated", + }); + } + }, + ConditionalExpression(node) { + if (isNegatedIf(node)) { + context.report({ + node, + messageId: "unexpectedNegated", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-negated-in-lhs.js b/node_modules/eslint/lib/rules/no-negated-in-lhs.js new file mode 100644 index 0000000000000000000000000000000000000000..f003cb30625502b275efa48d9656aefdd759a2b5 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-negated-in-lhs.js @@ -0,0 +1,59 @@ +/** + * @fileoverview A rule to disallow negated left operands of the `in` operator + * @author Michael Ficarra + * @deprecated in ESLint v3.3.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow negating the left operand in `in` expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-negated-in-lhs", + }, + + deprecated: { + message: "Renamed rule.", + url: "https://eslint.org/blog/2016/08/eslint-v3.3.0-released/#deprecated-rules", + deprecatedSince: "3.3.0", + availableUntil: "11.0.0", + replacedBy: [ + { + rule: { + name: "no-unsafe-negation", + url: "https://eslint.org/docs/rules/no-unsafe-negation", + }, + }, + ], + }, + schema: [], + + messages: { + negatedLHS: "The 'in' expression's left operand is negated.", + }, + }, + + create(context) { + return { + BinaryExpression(node) { + if ( + node.operator === "in" && + node.left.type === "UnaryExpression" && + node.left.operator === "!" + ) { + context.report({ node, messageId: "negatedLHS" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-nested-ternary.js b/node_modules/eslint/lib/rules/no-nested-ternary.js new file mode 100644 index 0000000000000000000000000000000000000000..8e5dbb78c849a99f691541990fc48c432cba5897 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-nested-ternary.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Rule to flag nested ternary expressions + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow nested ternary expressions", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-nested-ternary", + }, + + schema: [], + + messages: { + noNestedTernary: "Do not nest ternary expressions.", + }, + }, + + create(context) { + return { + ConditionalExpression(node) { + if ( + node.alternate.type === "ConditionalExpression" || + node.consequent.type === "ConditionalExpression" + ) { + context.report({ + node, + messageId: "noNestedTernary", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-func.js b/node_modules/eslint/lib/rules/no-new-func.js new file mode 100644 index 0000000000000000000000000000000000000000..760dc640f8617595cbd2d37ed9a41a37fd81dc4f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-func.js @@ -0,0 +1,96 @@ +/** + * @fileoverview Rule to flag when using new Function + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const callMethods = new Set(["apply", "bind", "call"]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `new` operators with the `Function` object", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-func", + }, + + schema: [], + + messages: { + noFunctionConstructor: "The Function constructor is eval.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + const variable = globalScope.set.get("Function"); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(ref => { + const idNode = ref.identifier; + const { parent } = idNode; + let evalNode; + + if (parent) { + if ( + idNode === parent.callee && + (parent.type === "NewExpression" || + parent.type === "CallExpression") + ) { + evalNode = parent; + } else if ( + parent.type === "MemberExpression" && + idNode === parent.object && + callMethods.has( + astUtils.getStaticPropertyName(parent), + ) + ) { + const maybeCallee = + parent.parent.type === "ChainExpression" + ? parent.parent + : parent; + + if ( + maybeCallee.parent.type === + "CallExpression" && + maybeCallee.parent.callee === maybeCallee + ) { + evalNode = maybeCallee.parent; + } + } + } + + if (evalNode) { + context.report({ + node: evalNode, + messageId: "noFunctionConstructor", + }); + } + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-native-nonconstructor.js b/node_modules/eslint/lib/rules/no-new-native-nonconstructor.js new file mode 100644 index 0000000000000000000000000000000000000000..0ae892cd53c07e0870342622dd4b71cdfc11a147 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-native-nonconstructor.js @@ -0,0 +1,70 @@ +/** + * @fileoverview Rule to disallow use of the new operator with global non-constructor functions + * @author Sosuke Suzuki + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const nonConstructorGlobalFunctionNames = ["Symbol", "BigInt"]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow `new` operators with global non-constructor functions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-new-native-nonconstructor", + }, + + schema: [], + + messages: { + noNewNonconstructor: + "`{{name}}` cannot be called as a constructor.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + for (const nonConstructorName of nonConstructorGlobalFunctionNames) { + const variable = globalScope.set.get(nonConstructorName); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(ref => { + const idNode = ref.identifier; + const parent = idNode.parent; + + if ( + parent && + parent.type === "NewExpression" && + parent.callee === idNode + ) { + context.report({ + node: idNode, + messageId: "noNewNonconstructor", + data: { name: nonConstructorName }, + }); + } + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-object.js b/node_modules/eslint/lib/rules/no-new-object.js new file mode 100644 index 0000000000000000000000000000000000000000..f18bf974f5f1d57476fc9ebb24772908ccc8d2a9 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-object.js @@ -0,0 +1,76 @@ +/** + * @fileoverview A rule to disallow calls to the Object constructor + * @author Matt DuVall + * @deprecated in ESLint v8.50.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `Object` constructors", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-object", + }, + + deprecated: { + message: + "The new rule flags more situations where object literal syntax can be used, and it does not report a problem when the `Object` constructor is invoked with an argument.", + url: "https://eslint.org/blog/2023/09/eslint-v8.50.0-released/", + deprecatedSince: "8.50.0", + availableUntil: "11.0.0", + replacedBy: [ + { + rule: { + name: "no-object-constructor", + url: "https://eslint.org/docs/rules/no-object-constructor", + }, + }, + ], + }, + + schema: [], + + messages: { + preferLiteral: "The object literal notation {} is preferable.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + NewExpression(node) { + const variable = astUtils.getVariableByName( + sourceCode.getScope(node), + node.callee.name, + ); + + if (variable && variable.identifiers.length > 0) { + return; + } + + if (node.callee.name === "Object") { + context.report({ + node, + messageId: "preferLiteral", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-require.js b/node_modules/eslint/lib/rules/no-new-require.js new file mode 100644 index 0000000000000000000000000000000000000000..09d136c83c43f1f6c3a485374f686ddb5803664d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-require.js @@ -0,0 +1,67 @@ +/** + * @fileoverview Rule to disallow use of new operator with the `require` function + * @author Wil Moore III + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-new-require", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-new-require.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow `new` operators with calls to `require`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-require", + }, + + schema: [], + + messages: { + noNewRequire: "Unexpected use of new with require.", + }, + }, + + create(context) { + return { + NewExpression(node) { + if ( + node.callee.type === "Identifier" && + node.callee.name === "require" + ) { + context.report({ + node, + messageId: "noNewRequire", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-symbol.js b/node_modules/eslint/lib/rules/no-new-symbol.js new file mode 100644 index 0000000000000000000000000000000000000000..838f502f55aab013059c963c4f61f7bc1332d058 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-symbol.js @@ -0,0 +1,74 @@ +/** + * @fileoverview Rule to disallow use of the new operator with the `Symbol` object + * @author Alberto Rodríguez + * @deprecated in ESLint v9.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow `new` operators with the `Symbol` object", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-symbol", + }, + + deprecated: { + message: "The rule was replaced with a more general rule.", + url: "https://eslint.org/docs/latest/use/migrate-to-9.0.0#eslint-recommended", + deprecatedSince: "9.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + rule: { + name: "no-new-native-nonconstructor", + url: "https://eslint.org/docs/latest/rules/no-new-native-nonconstructor", + }, + }, + ], + }, + + schema: [], + + messages: { + noNewSymbol: "`Symbol` cannot be called as a constructor.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + const variable = globalScope.set.get("Symbol"); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(ref => { + const idNode = ref.identifier; + const parent = idNode.parent; + + if ( + parent && + parent.type === "NewExpression" && + parent.callee === idNode + ) { + context.report({ + node: idNode, + messageId: "noNewSymbol", + }); + } + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new-wrappers.js b/node_modules/eslint/lib/rules/no-new-wrappers.js new file mode 100644 index 0000000000000000000000000000000000000000..84025dbf13b749e9a4155096814c152f7e6ffb98 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new-wrappers.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Rule to flag when using constructor for wrapper objects + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getVariableByName } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `new` operators with the `String`, `Number`, and `Boolean` objects", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new-wrappers", + }, + + schema: [], + + messages: { + noConstructor: "Do not use {{fn}} as a constructor.", + }, + }, + + create(context) { + const { sourceCode } = context; + + return { + NewExpression(node) { + const wrapperObjects = ["String", "Number", "Boolean"]; + const { name } = node.callee; + + if (wrapperObjects.includes(name)) { + const variable = getVariableByName( + sourceCode.getScope(node), + name, + ); + + if (variable && variable.identifiers.length === 0) { + context.report({ + node, + messageId: "noConstructor", + data: { fn: name }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-new.js b/node_modules/eslint/lib/rules/no-new.js new file mode 100644 index 0000000000000000000000000000000000000000..8f91835b293b58b4329d4822725aea47f085c420 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-new.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Rule to flag statements with function invocation preceded by + * "new" and not part of assignment + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `new` operators outside of assignments or comparisons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-new", + }, + + schema: [], + + messages: { + noNewStatement: "Do not use 'new' for side effects.", + }, + }, + + create(context) { + return { + "ExpressionStatement > NewExpression"(node) { + context.report({ + node: node.parent, + messageId: "noNewStatement", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-nonoctal-decimal-escape.js b/node_modules/eslint/lib/rules/no-nonoctal-decimal-escape.js new file mode 100644 index 0000000000000000000000000000000000000000..d09b7994b186819d4f0dc48a02e53f4337488f23 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-nonoctal-decimal-escape.js @@ -0,0 +1,176 @@ +/** + * @fileoverview Rule to disallow `\8` and `\9` escape sequences in string literals. + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @import { SourceRange } from "@eslint/core"; + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const QUICK_TEST_REGEX = /\\[89]/u; + +/** + * Returns unicode escape sequence that represents the given character. + * @param {string} character A single code unit. + * @returns {string} "\uXXXX" sequence. + */ +function getUnicodeEscape(character) { + return `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `\\8` and `\\9` escape sequences in string literals", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-nonoctal-decimal-escape", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + decimalEscape: "Don't use '{{decimalEscape}}' escape sequence.", + + // suggestions + refactor: + "Replace '{{original}}' with '{{replacement}}'. This maintains the current functionality.", + escapeBackslash: + "Replace '{{original}}' with '{{replacement}}' to include the actual backslash character.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Creates a new Suggestion object. + * @param {string} messageId "refactor" or "escapeBackslash". + * @param {SourceRange} range The range to replace. + * @param {string} replacement New text for the range. + * @returns {Object} Suggestion + */ + function createSuggestion(messageId, range, replacement) { + return { + messageId, + data: { + original: sourceCode.getText().slice(...range), + replacement, + }, + fix(fixer) { + return fixer.replaceTextRange(range, replacement); + }, + }; + } + + return { + Literal(node) { + if (typeof node.value !== "string") { + return; + } + + if (!QUICK_TEST_REGEX.test(node.raw)) { + return; + } + + const regex = + /(?:[^\\]|(?\\.))*?(?\\[89])/suy; + let match; + + while ((match = regex.exec(node.raw))) { + const { previousEscape, decimalEscape } = match.groups; + const decimalEscapeRangeEnd = + node.range[0] + match.index + match[0].length; + const decimalEscapeRangeStart = + decimalEscapeRangeEnd - decimalEscape.length; + const decimalEscapeRange = [ + decimalEscapeRangeStart, + decimalEscapeRangeEnd, + ]; + const suggest = []; + + // When `regex` is matched, `previousEscape` can only capture characters adjacent to `decimalEscape` + if (previousEscape === "\\0") { + /* + * Now we have a NULL escape "\0" immediately followed by a decimal escape, e.g.: "\0\8". + * Fixing this to "\08" would turn "\0" into a legacy octal escape. To avoid producing + * an octal escape while fixing a decimal escape, we provide different suggestions. + */ + suggest.push( + createSuggestion( + // "\0\8" -> "\u00008" + "refactor", + [ + decimalEscapeRangeStart - + previousEscape.length, + decimalEscapeRangeEnd, + ], + `${getUnicodeEscape("\0")}${decimalEscape[1]}`, + ), + createSuggestion( + // "\8" -> "\u0038" + "refactor", + decimalEscapeRange, + getUnicodeEscape(decimalEscape[1]), + ), + ); + } else { + suggest.push( + createSuggestion( + // "\8" -> "8" + "refactor", + decimalEscapeRange, + decimalEscape[1], + ), + ); + } + + suggest.push( + createSuggestion( + // "\8" -> "\\8" + "escapeBackslash", + decimalEscapeRange, + `\\${decimalEscape}`, + ), + ); + + context.report({ + node, + loc: { + start: sourceCode.getLocFromIndex( + decimalEscapeRangeStart, + ), + end: sourceCode.getLocFromIndex( + decimalEscapeRangeEnd, + ), + }, + messageId: "decimalEscape", + data: { + decimalEscape, + }, + suggest, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-obj-calls.js b/node_modules/eslint/lib/rules/no-obj-calls.js new file mode 100644 index 0000000000000000000000000000000000000000..b999eefb54431f87381c89bf40fcc2bed5c5e947 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-obj-calls.js @@ -0,0 +1,106 @@ +/** + * @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + CALL, + CONSTRUCT, + ReferenceTracker, +} = require("@eslint-community/eslint-utils"); +const getPropertyName = require("./utils/ast-utils").getStaticPropertyName; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const nonCallableGlobals = [ + "Atomics", + "JSON", + "Math", + "Reflect", + "Intl", + "Temporal", +]; + +/** + * Returns the name of the node to report + * @param {ASTNode} node A node to report + * @returns {string} name to report + */ +function getReportNodeName(node) { + if (node.type === "ChainExpression") { + return getReportNodeName(node.expression); + } + if (node.type === "MemberExpression") { + return getPropertyName(node); + } + return node.name; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow calling global object properties as functions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-obj-calls", + }, + + schema: [], + + messages: { + unexpectedCall: "'{{name}}' is not a function.", + unexpectedRefCall: + "'{{name}}' is reference to '{{ref}}', which is not a function.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const traceMap = {}; + + for (const g of nonCallableGlobals) { + traceMap[g] = { + [CALL]: true, + [CONSTRUCT]: true, + }; + } + + for (const { + node: refNode, + path, + } of tracker.iterateGlobalReferences(traceMap)) { + const name = getReportNodeName(refNode.callee); + const ref = path[0]; + const messageId = + name === ref ? "unexpectedCall" : "unexpectedRefCall"; + + context.report({ + node: refNode, + messageId, + data: { name, ref }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-object-constructor.js b/node_modules/eslint/lib/rules/no-object-constructor.js new file mode 100644 index 0000000000000000000000000000000000000000..fffa61227e0848f91544062fba8b99f55028e6f6 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-object-constructor.js @@ -0,0 +1,124 @@ +/** + * @fileoverview Rule to disallow calls to the `Object` constructor without an argument + * @author Francesco Trotta + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + getVariableByName, + isArrowToken, + isStartOfExpressionStatement, + needsPrecedingSemicolon, +} = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow calls to the `Object` constructor without an argument", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-object-constructor", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + preferLiteral: "The object literal notation {} is preferable.", + useLiteral: "Replace with '{{replacement}}'.", + useLiteralAfterSemicolon: + "Replace with '{{replacement}}', add preceding semicolon.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Determines whether or not an object literal that replaces a specified node needs to be enclosed in parentheses. + * @param {ASTNode} node The node to be replaced. + * @returns {boolean} Whether or not parentheses around the object literal are required. + */ + function needsParentheses(node) { + if (isStartOfExpressionStatement(node)) { + return true; + } + + const prevToken = sourceCode.getTokenBefore(node); + + if (prevToken && isArrowToken(prevToken)) { + return true; + } + + return false; + } + + /** + * Reports on nodes where the `Object` constructor is called without arguments. + * @param {ASTNode} node The node to evaluate. + * @returns {void} + */ + function check(node) { + if ( + node.callee.type !== "Identifier" || + node.callee.name !== "Object" || + node.arguments.length + ) { + return; + } + + const variable = getVariableByName( + sourceCode.getScope(node), + "Object", + ); + + if (variable && variable.identifiers.length === 0) { + let replacement; + let fixText; + let messageId = "useLiteral"; + + if (needsParentheses(node)) { + replacement = "({})"; + if (needsPrecedingSemicolon(sourceCode, node)) { + fixText = ";({})"; + messageId = "useLiteralAfterSemicolon"; + } else { + fixText = "({})"; + } + } else { + replacement = fixText = "{}"; + } + + context.report({ + node, + messageId: "preferLiteral", + suggest: [ + { + messageId, + data: { replacement }, + fix: fixer => fixer.replaceText(node, fixText), + }, + ], + }); + } + } + + return { + CallExpression: check, + NewExpression: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-octal-escape.js b/node_modules/eslint/lib/rules/no-octal-escape.js new file mode 100644 index 0000000000000000000000000000000000000000..975b308547ec13b7691ce9f8a8bdcc5fb9d1b71a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-octal-escape.js @@ -0,0 +1,53 @@ +/** + * @fileoverview Rule to flag octal escape sequences in string literals. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow octal escape sequences in string literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-octal-escape", + }, + + schema: [], + + messages: { + octalEscapeSequence: + "Don't use octal: '\\{{sequence}}'. Use '\\u....' instead.", + }, + }, + + create(context) { + return { + Literal(node) { + if (typeof node.value !== "string") { + return; + } + + // \0 represents a valid NULL character if it isn't followed by a digit. + const match = node.raw.match( + /^(?:[^\\]|\\.)*?\\([0-3][0-7]{1,2}|[4-7][0-7]|0(?=[89])|[1-7])/su, + ); + + if (match) { + context.report({ + node, + messageId: "octalEscapeSequence", + data: { sequence: match[1] }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-octal.js b/node_modules/eslint/lib/rules/no-octal.js new file mode 100644 index 0000000000000000000000000000000000000000..e5ea9bda0b01f397cc91b0fd6f3e26959f0332ef --- /dev/null +++ b/node_modules/eslint/lib/rules/no-octal.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Rule to flag when initializing octal literal + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow octal literals", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-octal", + }, + + schema: [], + + messages: { + noOctal: "Octal literals should not be used.", + }, + }, + + create(context) { + return { + Literal(node) { + if (typeof node.value === "number" && /^0\d/u.test(node.raw)) { + context.report({ + node, + messageId: "noOctal", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-param-reassign.js b/node_modules/eslint/lib/rules/no-param-reassign.js new file mode 100644 index 0000000000000000000000000000000000000000..ec22030a718753059bb8f9f6bf96c3070dc7b9d8 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-param-reassign.js @@ -0,0 +1,248 @@ +/** + * @fileoverview Disallow reassigning function parameters. + * @author Nat Burns + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const stopNodePattern = + /(?:Statement|Declaration|Function(?:Expression)?|Program)$/u; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow reassigning function parameters", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-param-reassign", + }, + + schema: [ + { + oneOf: [ + { + type: "object", + properties: { + props: { + enum: [false], + }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + props: { + enum: [true], + }, + ignorePropertyModificationsFor: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + ignorePropertyModificationsForRegex: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + assignmentToFunctionParam: + "Assignment to function parameter '{{name}}'.", + assignmentToFunctionParamProp: + "Assignment to property of function parameter '{{name}}'.", + }, + }, + + create(context) { + const props = context.options[0] && context.options[0].props; + const ignoredPropertyAssignmentsFor = + (context.options[0] && + context.options[0].ignorePropertyModificationsFor) || + []; + const ignoredPropertyAssignmentsForRegex = + (context.options[0] && + context.options[0].ignorePropertyModificationsForRegex) || + []; + const sourceCode = context.sourceCode; + + /** + * Checks whether or not the reference modifies properties of its variable. + * @param {Reference} reference A reference to check. + * @returns {boolean} Whether or not the reference modifies properties of its variable. + */ + function isModifyingProp(reference) { + let node = reference.identifier; + let parent = node.parent; + + while ( + parent && + (!stopNodePattern.test(parent.type) || + parent.type === "ForInStatement" || + parent.type === "ForOfStatement") + ) { + switch (parent.type) { + // e.g. foo.a = 0; + case "AssignmentExpression": + return parent.left === node; + + // e.g. ++foo.a; + case "UpdateExpression": + return true; + + // e.g. delete foo.a; + case "UnaryExpression": + if (parent.operator === "delete") { + return true; + } + break; + + // e.g. for (foo.a in b) {} + case "ForInStatement": + case "ForOfStatement": + if (parent.left === node) { + return true; + } + + // this is a stop node for parent.right and parent.body + return false; + + // EXCLUDES: e.g. cache.get(foo.a).b = 0; + case "CallExpression": + if (parent.callee !== node) { + return false; + } + break; + + // EXCLUDES: e.g. cache[foo.a] = 0; + case "MemberExpression": + if (parent.property === node) { + return false; + } + break; + + // EXCLUDES: e.g. ({ [foo]: a }) = bar; + case "Property": + if (parent.key === node) { + return false; + } + + break; + + // EXCLUDES: e.g. (foo ? a : b).c = bar; + case "ConditionalExpression": + if (parent.test === node) { + return false; + } + + break; + + // no default + } + + node = parent; + parent = node.parent; + } + + return false; + } + + /** + * Tests that an identifier name matches any of the ignored property assignments. + * First we test strings in ignoredPropertyAssignmentsFor. + * Then we instantiate and test RegExp objects from ignoredPropertyAssignmentsForRegex strings. + * @param {string} identifierName A string that describes the name of an identifier to + * ignore property assignments for. + * @returns {boolean} Whether the string matches an ignored property assignment regular expression or not. + */ + function isIgnoredPropertyAssignment(identifierName) { + return ( + ignoredPropertyAssignmentsFor.includes(identifierName) || + ignoredPropertyAssignmentsForRegex.some(ignored => + new RegExp(ignored, "u").test(identifierName), + ) + ); + } + + /** + * Reports a reference if is non initializer and writable. + * @param {Reference} reference A reference to check. + * @param {number} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {void} + */ + function checkReference(reference, index, references) { + const identifier = reference.identifier; + + if ( + identifier && + !reference.init && + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ + (index === 0 || references[index - 1].identifier !== identifier) + ) { + if (reference.isWrite()) { + context.report({ + node: identifier, + messageId: "assignmentToFunctionParam", + data: { name: identifier.name }, + }); + } else if ( + props && + isModifyingProp(reference) && + !isIgnoredPropertyAssignment(identifier.name) + ) { + context.report({ + node: identifier, + messageId: "assignmentToFunctionParamProp", + data: { name: identifier.name }, + }); + } + } + } + + /** + * Finds and reports references that are non initializer and writable. + * @param {Variable} variable A variable to check. + * @returns {void} + */ + function checkVariable(variable) { + if (variable.defs[0].type === "Parameter") { + variable.references.forEach(checkReference); + } + } + + /** + * Checks parameters of a given function node. + * @param {ASTNode} node A function node to check. + * @returns {void} + */ + function checkForFunction(node) { + sourceCode.getDeclaredVariables(node).forEach(checkVariable); + } + + return { + // `:exit` is needed for the `node.parent` property of identifier nodes. + "FunctionDeclaration:exit": checkForFunction, + "FunctionExpression:exit": checkForFunction, + "ArrowFunctionExpression:exit": checkForFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-path-concat.js b/node_modules/eslint/lib/rules/no-path-concat.js new file mode 100644 index 0000000000000000000000000000000000000000..230a39438557ddc891324577197bb3c54d41a069 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-path-concat.js @@ -0,0 +1,79 @@ +/** + * @fileoverview Disallow string concatenation when using __dirname and __filename + * @author Nicholas C. Zakas + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-path-concat", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-path-concat.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: + "Disallow string concatenation with `__dirname` and `__filename`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-path-concat", + }, + + schema: [], + + messages: { + usePathFunctions: + "Use path.join() or path.resolve() instead of + to create paths.", + }, + }, + + create(context) { + const MATCHER = /^__(?:dir|file)name$/u; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + BinaryExpression(node) { + const left = node.left, + right = node.right; + + if ( + node.operator === "+" && + ((left.type === "Identifier" && MATCHER.test(left.name)) || + (right.type === "Identifier" && + MATCHER.test(right.name))) + ) { + context.report({ + node, + messageId: "usePathFunctions", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-plusplus.js b/node_modules/eslint/lib/rules/no-plusplus.js new file mode 100644 index 0000000000000000000000000000000000000000..1f3a9f0f87f842b03ae2cbdb01f8ea19f5e6f40b --- /dev/null +++ b/node_modules/eslint/lib/rules/no-plusplus.js @@ -0,0 +1,102 @@ +/** + * @fileoverview Rule to flag use of unary increment and decrement operators. + * @author Ian Christian Myers + * @author Brody McKee (github.com/mrmckeb) + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given node is the update node of a `ForStatement`. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is `ForStatement` update. + */ +function isForStatementUpdate(node) { + const parent = node.parent; + + return parent.type === "ForStatement" && parent.update === node; +} + +/** + * Determines whether the given node is considered to be a for loop "afterthought" by the logic of this rule. + * In particular, it returns `true` if the given node is either: + * - The update node of a `ForStatement`: for (;; i++) {} + * - An operand of a sequence expression that is the update node: for (;; foo(), i++) {} + * - An operand of a sequence expression that is child of another sequence expression, etc., + * up to the sequence expression that is the update node: for (;; foo(), (bar(), (baz(), i++))) {} + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a for loop afterthought. + */ +function isForLoopAfterthought(node) { + const parent = node.parent; + + if (parent.type === "SequenceExpression") { + return isForLoopAfterthought(parent); + } + + return isForStatementUpdate(node); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowForLoopAfterthoughts: false, + }, + ], + + docs: { + description: "Disallow the unary operators `++` and `--`", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-plusplus", + }, + + schema: [ + { + type: "object", + properties: { + allowForLoopAfterthoughts: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedUnaryOp: "Unary operator '{{operator}}' used.", + }, + }, + + create(context) { + const [{ allowForLoopAfterthoughts }] = context.options; + + return { + UpdateExpression(node) { + if (allowForLoopAfterthoughts && isForLoopAfterthought(node)) { + return; + } + + context.report({ + node, + messageId: "unexpectedUnaryOp", + data: { + operator: node.operator, + }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-process-env.js b/node_modules/eslint/lib/rules/no-process-env.js new file mode 100644 index 0000000000000000000000000000000000000000..c9dc353ff7fc7f79975d376b446c8595c2afbbe9 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-process-env.js @@ -0,0 +1,68 @@ +/** + * @fileoverview Disallow the use of process.env() + * @author Vignesh Anand + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-process-env", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-process-env.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow the use of `process.env`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-process-env", + }, + + schema: [], + + messages: { + unexpectedProcessEnv: "Unexpected use of process.env.", + }, + }, + + create(context) { + return { + MemberExpression(node) { + const objectName = node.object.name, + propertyName = node.property.name; + + if ( + objectName === "process" && + !node.computed && + propertyName && + propertyName === "env" + ) { + context.report({ node, messageId: "unexpectedProcessEnv" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-process-exit.js b/node_modules/eslint/lib/rules/no-process-exit.js new file mode 100644 index 0000000000000000000000000000000000000000..79f8153a636880e86be5729bd831e7e91b234196 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-process-exit.js @@ -0,0 +1,67 @@ +/** + * @fileoverview Disallow the use of process.exit() + * @author Nicholas C. Zakas + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-process-exit", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-process-exit.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow the use of `process.exit()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-process-exit", + }, + + schema: [], + + messages: { + noProcessExit: "Don't use process.exit(); throw an error instead.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "CallExpression > MemberExpression.callee[object.name = 'process'][property.name = 'exit']"( + node, + ) { + context.report({ + node: node.parent, + messageId: "noProcessExit", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-promise-executor-return.js b/node_modules/eslint/lib/rules/no-promise-executor-return.js new file mode 100644 index 0000000000000000000000000000000000000000..647f3ac08469392f526ca5ff9f7cb215fff141dc --- /dev/null +++ b/node_modules/eslint/lib/rules/no-promise-executor-return.js @@ -0,0 +1,264 @@ +/** + * @fileoverview Rule to disallow returning values from Promise executor functions + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const functionTypesToCheck = new Set([ + "ArrowFunctionExpression", + "FunctionExpression", +]); + +/** + * Determines whether the given function node is used as a Promise executor. + * @param {ASTNode} node The node to check. + * @param {SourceCode} sourceCode Source code to which the node belongs. + * @returns {boolean} `true` if the node is a Promise executor. + */ +function isPromiseExecutor(node, sourceCode) { + const parent = node.parent; + + return ( + parent.type === "NewExpression" && + parent.arguments[0] === node && + parent.callee.type === "Identifier" && + parent.callee.name === "Promise" && + sourceCode.isGlobalReference(parent.callee) + ); +} + +/** + * Checks if the given node is a void expression. + * @param {ASTNode} node The node to check. + * @returns {boolean} - `true` if the node is a void expression + */ +function expressionIsVoid(node) { + return node.type === "UnaryExpression" && node.operator === "void"; +} + +/** + * Fixes the linting error by prepending "void " to the given node + * @param {Object} sourceCode context given by context.sourceCode + * @param {ASTNode} node The node to fix. + * @param {Object} fixer The fixer object provided by ESLint. + * @returns {Array} - An array of fix objects to apply to the node. + */ +function voidPrependFixer(sourceCode, node, fixer) { + const requiresParens = + // prepending `void ` will fail if the node has a lower precedence than void + astUtils.getPrecedence(node) < + astUtils.getPrecedence({ + type: "UnaryExpression", + operator: "void", + }) && + // check if there are parentheses around the node to avoid redundant parentheses + !astUtils.isParenthesised(sourceCode, node); + + // avoid parentheses issues + const returnOrArrowToken = sourceCode.getTokenBefore( + node, + node.parent.type === "ArrowFunctionExpression" + ? astUtils.isArrowToken + : // isReturnToken + token => token.type === "Keyword" && token.value === "return", + ); + + const firstToken = sourceCode.getTokenAfter(returnOrArrowToken); + + const prependSpace = + // is return token, as => allows void to be adjacent + returnOrArrowToken.value === "return" && + // If two tokens (return and "(") are adjacent + returnOrArrowToken.range[1] === firstToken.range[0]; + + return [ + fixer.insertTextBefore( + firstToken, + `${prependSpace ? " " : ""}void ${requiresParens ? "(" : ""}`, + ), + fixer.insertTextAfter(node, requiresParens ? ")" : ""), + ]; +} + +/** + * Fixes the linting error by `wrapping {}` around the given node's body. + * @param {Object} sourceCode context given by context.sourceCode + * @param {ASTNode} node The node to fix. + * @param {Object} fixer The fixer object provided by ESLint. + * @returns {Array} - An array of fix objects to apply to the node. + */ +function curlyWrapFixer(sourceCode, node, fixer) { + // https://github.com/eslint/eslint/pull/17282#issuecomment-1592795923 + const arrowToken = sourceCode.getTokenBefore( + node.body, + astUtils.isArrowToken, + ); + const firstToken = sourceCode.getTokenAfter(arrowToken); + const lastToken = sourceCode.getLastToken(node); + + return [ + fixer.insertTextBefore(firstToken, "{"), + fixer.insertTextAfter(lastToken, "}"), + ]; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowVoid: false, + }, + ], + + docs: { + description: + "Disallow returning values from Promise executor functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-promise-executor-return", + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + allowVoid: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + returnsValue: + "Return values from promise executor functions cannot be read.", + + // arrow and function suggestions + prependVoid: "Prepend `void` to the expression.", + + // only arrow suggestions + wrapBraces: "Wrap the expression in `{}`.", + }, + }, + + create(context) { + let funcInfo = null; + const sourceCode = context.sourceCode; + const [{ allowVoid }] = context.options; + + return { + onCodePathStart(_, node) { + funcInfo = { + upper: funcInfo, + shouldCheck: + functionTypesToCheck.has(node.type) && + isPromiseExecutor(node, sourceCode), + }; + + if ( + // Is a Promise executor + funcInfo.shouldCheck && + node.type === "ArrowFunctionExpression" && + node.expression && + // Except void + !(allowVoid && expressionIsVoid(node.body)) + ) { + const suggest = []; + + // prevent useless refactors + if (allowVoid) { + suggest.push({ + messageId: "prependVoid", + fix(fixer) { + return voidPrependFixer( + sourceCode, + node.body, + fixer, + ); + }, + }); + } + + // Do not suggest wrapping an unnamed FunctionExpression in braces as that would be invalid syntax. + if ( + !( + node.body.type === "FunctionExpression" && + !node.body.id + ) + ) { + suggest.push({ + messageId: "wrapBraces", + fix(fixer) { + return curlyWrapFixer(sourceCode, node, fixer); + }, + }); + } + + context.report({ + node: node.body, + messageId: "returnsValue", + suggest, + }); + } + }, + + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + + ReturnStatement(node) { + if (!(funcInfo.shouldCheck && node.argument)) { + return; + } + + // node is `return ` + if (!allowVoid) { + context.report({ node, messageId: "returnsValue" }); + return; + } + + if (expressionIsVoid(node.argument)) { + return; + } + + // allowVoid && !expressionIsVoid + context.report({ + node, + messageId: "returnsValue", + suggest: [ + { + messageId: "prependVoid", + fix(fixer) { + return voidPrependFixer( + sourceCode, + node.argument, + fixer, + ); + }, + }, + ], + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-proto.js b/node_modules/eslint/lib/rules/no-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..d68509e115ed90ba1757c00723a6b64ad1c2d35a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-proto.js @@ -0,0 +1,45 @@ +/** + * @fileoverview Rule to flag usage of __proto__ property + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getStaticPropertyName } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of the `__proto__` property", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-proto", + }, + + schema: [], + + messages: { + unexpectedProto: "The '__proto__' property is deprecated.", + }, + }, + + create(context) { + return { + MemberExpression(node) { + if (getStaticPropertyName(node) === "__proto__") { + context.report({ node, messageId: "unexpectedProto" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-prototype-builtins.js b/node_modules/eslint/lib/rules/no-prototype-builtins.js new file mode 100644 index 0000000000000000000000000000000000000000..c75fdacf8e0e92aed192bd863258b40fc8aa49c9 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-prototype-builtins.js @@ -0,0 +1,181 @@ +/** + * @fileoverview Rule to disallow use of Object.prototype builtins on objects + * @author Andrew Levine + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Returns true if the node or any of the objects + * to the left of it in the member/call chain is optional. + * + * e.g. `a?.b`, `a?.b.c`, `a?.()`, `a()?.()` + * @param {ASTNode} node The expression to check + * @returns {boolean} `true` if there is a short-circuiting optional `?.` + * in the same option chain to the left of this call or member expression, + * or the node itself is an optional call or member `?.`. + */ +function isAfterOptional(node) { + let leftNode; + + if (node.type === "MemberExpression") { + leftNode = node.object; + } else if (node.type === "CallExpression") { + leftNode = node.callee; + } else { + return false; + } + if (node.optional) { + return true; + } + return isAfterOptional(leftNode); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow calling some `Object.prototype` methods directly on objects", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-prototype-builtins", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + prototypeBuildIn: + "Do not access Object.prototype method '{{prop}}' from target object.", + callObjectPrototype: "Call Object.prototype.{{prop}} explicitly.", + }, + }, + + create(context) { + const DISALLOWED_PROPS = new Set([ + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + ]); + + /** + * Reports if a disallowed property is used in a CallExpression + * @param {ASTNode} node The CallExpression node. + * @returns {void} + */ + function disallowBuiltIns(node) { + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type !== "MemberExpression") { + return; + } + + const propName = astUtils.getStaticPropertyName(callee); + + if (propName !== null && DISALLOWED_PROPS.has(propName)) { + context.report({ + messageId: "prototypeBuildIn", + loc: callee.property.loc, + data: { prop: propName }, + node, + suggest: [ + { + messageId: "callObjectPrototype", + data: { prop: propName }, + fix(fixer) { + const sourceCode = context.sourceCode; + + /* + * A call after an optional chain (e.g. a?.b.hasOwnProperty(c)) + * must be fixed manually because the call can be short-circuited + */ + if (isAfterOptional(node)) { + return null; + } + + /* + * A call on a ChainExpression (e.g. (a?.hasOwnProperty)(c)) will trigger + * no-unsafe-optional-chaining which should be fixed before this suggestion + */ + if (node.callee.type === "ChainExpression") { + return null; + } + + const objectVariable = + astUtils.getVariableByName( + sourceCode.getScope(node), + "Object", + ); + + /* + * We can't use Object if the global Object was shadowed, + * or Object does not exist in the global scope for some reason + */ + if ( + !objectVariable || + objectVariable.scope.type !== "global" || + objectVariable.defs.length > 0 + ) { + return null; + } + + let objectText = sourceCode.getText( + callee.object, + ); + + if ( + astUtils.getPrecedence(callee.object) <= + astUtils.getPrecedence({ + type: "SequenceExpression", + }) + ) { + objectText = `(${objectText})`; + } + + const openParenToken = sourceCode.getTokenAfter( + node.callee, + astUtils.isOpeningParenToken, + ); + const isEmptyParameters = + node.arguments.length === 0; + const delim = isEmptyParameters ? "" : ", "; + const fixes = [ + fixer.replaceText( + callee, + `Object.prototype.${propName}.call`, + ), + fixer.insertTextAfter( + openParenToken, + objectText + delim, + ), + ]; + + return fixes; + }, + }, + ], + }); + } + } + + return { + CallExpression: disallowBuiltIns, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-redeclare.js b/node_modules/eslint/lib/rules/no-redeclare.js new file mode 100644 index 0000000000000000000000000000000000000000..4f8c06c97096f7ea3eca4fd29f8e40fdd6c29e16 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-redeclare.js @@ -0,0 +1,173 @@ +/** + * @fileoverview Rule to flag when the same variable is declared more then once. + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{ builtinGlobals: true }], + + docs: { + description: "Disallow variable redeclaration", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-redeclare", + }, + + messages: { + redeclared: "'{{id}}' is already defined.", + redeclaredAsBuiltin: + "'{{id}}' is already defined as a built-in global variable.", + redeclaredBySyntax: + "'{{id}}' is already defined by a variable declaration.", + }, + + schema: [ + { + type: "object", + properties: { + builtinGlobals: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + }, + + create(context) { + const [{ builtinGlobals }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Iterate declarations of a given variable. + * @param {escope.variable} variable The variable object to iterate declarations. + * @returns {IterableIterator<{type:string,node:ASTNode,loc:SourceLocation}>} The declarations. + */ + function* iterateDeclarations(variable) { + if ( + builtinGlobals && + (variable.eslintImplicitGlobalSetting === "readonly" || + variable.eslintImplicitGlobalSetting === "writable") + ) { + yield { type: "builtin" }; + } + + for (const id of variable.identifiers) { + yield { type: "syntax", node: id, loc: id.loc }; + } + + if (variable.eslintExplicitGlobalComments) { + for (const comment of variable.eslintExplicitGlobalComments) { + yield { + type: "comment", + node: comment, + loc: astUtils.getNameLocationInGlobalDirectiveComment( + sourceCode, + comment, + variable.name, + ), + }; + } + } + } + + /** + * Find variables in a given scope and flag redeclared ones. + * @param {Scope} scope An eslint-scope scope object. + * @returns {void} + * @private + */ + function findVariablesInScope(scope) { + for (const variable of scope.variables) { + const [declaration, ...extraDeclarations] = + iterateDeclarations(variable); + + if (extraDeclarations.length === 0) { + continue; + } + + /* + * If the type of a declaration is different from the type of + * the first declaration, it shows the location of the first + * declaration. + */ + const detailMessageId = + declaration.type === "builtin" + ? "redeclaredAsBuiltin" + : "redeclaredBySyntax"; + const data = { id: variable.name }; + + // Report extra declarations. + for (const { type, node, loc } of extraDeclarations) { + const messageId = + type === declaration.type + ? "redeclared" + : detailMessageId; + + context.report({ node, loc, messageId, data }); + } + } + } + + /** + * Find variables in the current scope. + * @param {ASTNode} node The node of the current scope. + * @returns {void} + * @private + */ + function checkForBlock(node) { + const scope = sourceCode.getScope(node); + + /* + * In ES5, some node type such as `BlockStatement` doesn't have that scope. + * `scope.block` is a different node in such a case. + */ + if (scope.block === node) { + findVariablesInScope(scope); + } + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + + findVariablesInScope(scope); + + // Node.js or ES modules has a special scope. + if ( + scope.type === "global" && + scope.childScopes[0] && + // The special scope's block is the Program node. + scope.block === scope.childScopes[0].block + ) { + findVariablesInScope(scope.childScopes[0]); + } + }, + + FunctionDeclaration: checkForBlock, + FunctionExpression: checkForBlock, + ArrowFunctionExpression: checkForBlock, + + StaticBlock: checkForBlock, + + BlockStatement: checkForBlock, + ForStatement: checkForBlock, + ForInStatement: checkForBlock, + ForOfStatement: checkForBlock, + SwitchStatement: checkForBlock, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-regex-spaces.js b/node_modules/eslint/lib/rules/no-regex-spaces.js new file mode 100644 index 0000000000000000000000000000000000000000..71924097573141e2b08bf91021d9aac7ecca75b7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-regex-spaces.js @@ -0,0 +1,219 @@ +/** + * @fileoverview Rule to count multiple spaces in regular expressions + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const regexpp = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const regExpParser = new regexpp.RegExpParser(); +const DOUBLE_SPACE = / {2}/u; + +/** + * Check if node is a string + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if its a string + * @private + */ +function isString(node) { + return node && node.type === "Literal" && typeof node.value === "string"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow multiple spaces in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-regex-spaces", + }, + + schema: [], + fixable: "code", + + messages: { + multipleSpaces: "Spaces are hard to count. Use {{{length}}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Validate regular expression + * @param {ASTNode} nodeToReport Node to report. + * @param {string} pattern Regular expression pattern to validate. + * @param {string} rawPattern Raw representation of the pattern in the source code. + * @param {number} rawPatternStartRange Start range of the pattern in the source code. + * @param {string} flags Regular expression flags. + * @returns {void} + * @private + */ + function checkRegex( + nodeToReport, + pattern, + rawPattern, + rawPatternStartRange, + flags, + ) { + // Skip if there are no consecutive spaces in the source code, to avoid reporting e.g., RegExp(' \ '). + if (!DOUBLE_SPACE.test(rawPattern)) { + return; + } + + const characterClassNodes = []; + let regExpAST; + + try { + regExpAST = regExpParser.parsePattern( + pattern, + 0, + pattern.length, + { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v"), + }, + ); + } catch { + // Ignore regular expressions with syntax errors + return; + } + + regexpp.visitRegExpAST(regExpAST, { + onCharacterClassEnter(ccNode) { + characterClassNodes.push(ccNode); + }, + }); + + const spacesPattern = /( {2,})(?: [+*{?]|[^+*{?]|$)/gu; + let match; + + while ((match = spacesPattern.exec(pattern))) { + const { + 1: { length }, + index, + } = match; + + // Report only consecutive spaces that are not in character classes. + if ( + characterClassNodes.every( + ({ start, end }) => index < start || end <= index, + ) + ) { + context.report({ + node: nodeToReport, + messageId: "multipleSpaces", + data: { length }, + fix(fixer) { + if (pattern !== rawPattern) { + return null; + } + return fixer.replaceTextRange( + [ + rawPatternStartRange + index, + rawPatternStartRange + index + length, + ], + ` {${length}}`, + ); + }, + }); + + // Report only the first occurrence of consecutive spaces + return; + } + } + } + + /** + * Validate regular expression literals + * @param {ASTNode} node node to validate + * @returns {void} + * @private + */ + function checkLiteral(node) { + if (node.regex) { + const pattern = node.regex.pattern; + const rawPattern = node.raw.slice(1, node.raw.lastIndexOf("/")); + const rawPatternStartRange = node.range[0] + 1; + const flags = node.regex.flags; + + checkRegex( + node, + pattern, + rawPattern, + rawPatternStartRange, + flags, + ); + } + } + + /** + * Validate strings passed to the RegExp constructor + * @param {ASTNode} node node to validate + * @returns {void} + * @private + */ + function checkFunction(node) { + const scope = sourceCode.getScope(node); + const regExpVar = astUtils.getVariableByName(scope, "RegExp"); + const shadowed = regExpVar && regExpVar.defs.length > 0; + const patternNode = node.arguments[0]; + + if ( + node.callee.type === "Identifier" && + node.callee.name === "RegExp" && + isString(patternNode) && + !shadowed + ) { + const pattern = patternNode.value; + const rawPattern = patternNode.raw.slice(1, -1); + const rawPatternStartRange = patternNode.range[0] + 1; + let flags; + + if (node.arguments.length < 2) { + // It has no flags. + flags = ""; + } else { + const flagsNode = node.arguments[1]; + + if (isString(flagsNode)) { + flags = flagsNode.value; + } else { + // The flags cannot be determined. + return; + } + } + + checkRegex( + node, + pattern, + rawPattern, + rawPatternStartRange, + flags, + ); + } + } + + return { + Literal: checkLiteral, + CallExpression: checkFunction, + NewExpression: checkFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-exports.js b/node_modules/eslint/lib/rules/no-restricted-exports.js new file mode 100644 index 0000000000000000000000000000000000000000..89c0210591ea8d2423fdc9b8fb7dfbc71c59daa3 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-exports.js @@ -0,0 +1,227 @@ +/** + * @fileoverview Rule to disallow specified names in exports + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified names in exports", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-exports", + }, + + schema: [ + { + anyOf: [ + { + type: "object", + properties: { + restrictedNamedExports: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + restrictedNamedExportsPattern: { type: "string" }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + restrictedNamedExports: { + type: "array", + items: { + type: "string", + pattern: "^(?!default$)", + }, + uniqueItems: true, + }, + restrictedNamedExportsPattern: { type: "string" }, + restrictDefaultExports: { + type: "object", + properties: { + // Allow/Disallow `export default foo; export default 42; export default function foo() {}` format + direct: { + type: "boolean", + }, + + // Allow/Disallow `export { foo as default };` declarations + named: { + type: "boolean", + }, + + // Allow/Disallow `export { default } from "mod"; export { default as default } from "mod";` declarations + defaultFrom: { + type: "boolean", + }, + + // Allow/Disallow `export { foo as default } from "mod";` declarations + namedFrom: { + type: "boolean", + }, + + // Allow/Disallow `export * as default from "mod"`; declarations + namespaceFrom: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + defaultOptions: [{}], + + messages: { + restrictedNamed: + "'{{name}}' is restricted from being used as an exported name.", + restrictedDefault: "Exporting 'default' is restricted.", + }, + }, + + create(context) { + const { + restrictedNamedExports, + restrictedNamedExportsPattern: restrictedNamePattern, + restrictDefaultExports, + } = context.options[0]; + const restrictedNames = new Set(restrictedNamedExports); + const sourceCode = context.sourceCode; + + /** + * Checks and reports given exported name. + * @param {ASTNode} node exported `Identifier` or string `Literal` node to check. + * @returns {void} + */ + function checkExportedName(node) { + const name = astUtils.getModuleExportName(node); + + let matchesRestrictedNamePattern = false; + + if (restrictedNamePattern && name !== "default") { + const patternRegex = new RegExp(restrictedNamePattern, "u"); + + matchesRestrictedNamePattern = patternRegex.test(name); + } + + if (matchesRestrictedNamePattern || restrictedNames.has(name)) { + context.report({ + node, + messageId: "restrictedNamed", + data: { name }, + }); + return; + } + + if (name === "default") { + if (node.parent.type === "ExportAllDeclaration") { + if ( + restrictDefaultExports && + restrictDefaultExports.namespaceFrom + ) { + context.report({ + node, + messageId: "restrictedDefault", + }); + } + } else { + // ExportSpecifier + const isSourceSpecified = !!node.parent.parent.source; + const specifierLocalName = astUtils.getModuleExportName( + node.parent.local, + ); + + if ( + !isSourceSpecified && + restrictDefaultExports && + restrictDefaultExports.named + ) { + context.report({ + node, + messageId: "restrictedDefault", + }); + return; + } + + if (isSourceSpecified && restrictDefaultExports) { + if ( + (specifierLocalName === "default" && + restrictDefaultExports.defaultFrom) || + (specifierLocalName !== "default" && + restrictDefaultExports.namedFrom) + ) { + context.report({ + node, + messageId: "restrictedDefault", + }); + } + } + } + } + } + + return { + ExportAllDeclaration(node) { + if (node.exported) { + checkExportedName(node.exported); + } + }, + + ExportDefaultDeclaration(node) { + if (restrictDefaultExports && restrictDefaultExports.direct) { + context.report({ + node, + messageId: "restrictedDefault", + }); + } + }, + + ExportNamedDeclaration(node) { + const declaration = node.declaration; + + if (declaration) { + if ( + declaration.type === "FunctionDeclaration" || + declaration.type === "ClassDeclaration" + ) { + checkExportedName(declaration.id); + } else if (declaration.type === "VariableDeclaration") { + sourceCode + .getDeclaredVariables(declaration) + .map(v => + v.defs.find(d => d.parent === declaration), + ) + .map(d => d.name) // Identifier nodes + .forEach(checkExportedName); + } + } else { + node.specifiers + .map(s => s.exported) + .forEach(checkExportedName); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-globals.js b/node_modules/eslint/lib/rules/no-restricted-globals.js new file mode 100644 index 0000000000000000000000000000000000000000..26985b77479ccc1330e8f569b545dd4dc8ceadad --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-globals.js @@ -0,0 +1,265 @@ +/** + * @fileoverview Restrict usage of specified globals. + * @author Benoît Zugmeyer + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TYPE_NODES = new Set([ + "TSTypeReference", + "TSInterfaceHeritage", + "TSClassImplements", + "TSTypeQuery", + "TSQualifiedName", +]); + +const GLOBAL_OBJECTS = new Set(["globalThis", "self", "window"]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const arrayOfGlobals = { + type: "array", + items: { + oneOf: [ + { + type: "string", + }, + { + type: "object", + properties: { + name: { type: "string" }, + message: { type: "string" }, + }, + required: ["name"], + additionalProperties: false, + }, + ], + }, + uniqueItems: true, + minItems: 0, +}; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified global variables", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-globals", + }, + + schema: { + anyOf: [ + arrayOfGlobals, + { + type: "array", + items: [ + { + type: "object", + properties: { + globals: arrayOfGlobals, + checkGlobalObject: { + type: "boolean", + }, + globalObjects: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + }, + required: ["globals"], + additionalProperties: false, + }, + ], + additionalItems: false, + }, + ], + }, + + messages: { + defaultMessage: "Unexpected use of '{{name}}'.", + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + customMessage: "Unexpected use of '{{name}}'. {{customMessage}}", + }, + }, + + create(context) { + const { sourceCode, options } = context; + + const isGlobalsObject = + typeof options[0] === "object" && + Object.hasOwn(options[0], "globals"); + + const restrictedGlobals = isGlobalsObject + ? options[0].globals + : options; + const checkGlobalObject = isGlobalsObject + ? options[0].checkGlobalObject + : false; + const userGlobalObjects = isGlobalsObject + ? options[0].globalObjects || [] + : []; + + const globalObjects = new Set([ + ...GLOBAL_OBJECTS, + ...userGlobalObjects, + ]); + + // If no globals are restricted, we don't need to do anything + if (restrictedGlobals.length === 0) { + return {}; + } + + const restrictedGlobalMessages = restrictedGlobals.reduce( + (memo, option) => { + if (typeof option === "string") { + memo[option] = null; + } else { + memo[option.name] = option.message; + } + + return memo; + }, + {}, + ); + + /** + * Report a variable to be used as a restricted global. + * @param {Reference} reference the variable reference + * @returns {void} + * @private + */ + function reportReference(reference) { + const name = reference.identifier.name, + customMessage = restrictedGlobalMessages[name], + messageId = customMessage ? "customMessage" : "defaultMessage"; + + context.report({ + node: reference.identifier, + messageId, + data: { + name, + customMessage, + }, + }); + } + + /** + * Check if the given name is a restricted global name. + * @param {string} name name of a variable + * @returns {boolean} whether the variable is a restricted global or not + * @private + */ + function isRestricted(name) { + return Object.hasOwn(restrictedGlobalMessages, name); + } + + /** + * Check if the given reference occurs within a TypeScript type context. + * @param {Reference} reference The variable reference to check. + * @returns {boolean} Whether the reference is in a type context. + * @private + */ + function isInTypeContext(reference) { + const parent = reference.identifier.parent; + + return TYPE_NODES.has(parent.type); + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + + // Report variables declared elsewhere (ex: variables defined as "global" by eslint) + scope.variables.forEach(variable => { + if (!variable.defs.length && isRestricted(variable.name)) { + variable.references.forEach(reference => { + if (!isInTypeContext(reference)) { + reportReference(reference); + } + }); + } + }); + + // Report variables not declared at all + scope.through.forEach(reference => { + if ( + isRestricted(reference.identifier.name) && + !isInTypeContext(reference) + ) { + reportReference(reference); + } + }); + }, + + "Program:exit"(node) { + if (!checkGlobalObject) { + return; + } + + const globalScope = sourceCode.getScope(node); + globalObjects.forEach(globalObjectName => { + const variable = astUtils.getVariableByName( + globalScope, + globalObjectName, + ); + + if (!variable) { + return; + } + + variable.references.forEach(reference => { + const identifier = reference.identifier; + let parent = identifier.parent; + + // To detect code like `window.window.Promise`. + while ( + astUtils.isSpecificMemberAccess( + parent, + null, + globalObjectName, + ) + ) { + parent = parent.parent; + } + + const propertyName = + astUtils.getStaticPropertyName(parent); + if (propertyName && isRestricted(propertyName)) { + const customMessage = + restrictedGlobalMessages[propertyName]; + const messageId = customMessage + ? "customMessage" + : "defaultMessage"; + + context.report({ + node: parent.property, + messageId, + data: { + name: propertyName, + customMessage, + }, + }); + } + }); + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-imports.js b/node_modules/eslint/lib/rules/no-restricted-imports.js new file mode 100644 index 0000000000000000000000000000000000000000..2df8caa6def341de537db06b4eb248776e340f6f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-imports.js @@ -0,0 +1,891 @@ +/** + * @fileoverview Restrict usage of specified node imports. + * @author Guy Ellis + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Format import names for error messages. + * @param {string[]} importNames The import names to format. + * @returns {string} The formatted import names. + */ +function formatImportNames(importNames) { + return new Intl.ListFormat("en-US").format( + importNames.map(name => `'${name}'`), + ); +} + +/** + * Returns "is" or "are" based on the number of import names. + * @param {string[]} importNames The import names to check. + * @returns {string} "is" if one import name, otherwise "are". + */ +function isOrAre(importNames) { + return importNames.length === 1 ? "is" : "are"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const ignore = require("ignore"); + +const arrayOfStringsOrObjects = { + type: "array", + items: { + anyOf: [ + { type: "string" }, + { + type: "object", + properties: { + name: { type: "string" }, + message: { + type: "string", + minLength: 1, + }, + importNames: { + type: "array", + items: { + type: "string", + }, + }, + allowImportNames: { + type: "array", + items: { + type: "string", + }, + }, + allowTypeImports: { + type: "boolean", + description: + "Whether to allow type-only imports for a path.", + }, + }, + additionalProperties: false, + required: ["name"], + not: { required: ["importNames", "allowImportNames"] }, + }, + ], + }, + uniqueItems: true, +}; + +const arrayOfStringsOrObjectPatterns = { + anyOf: [ + { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + { + type: "array", + items: { + type: "object", + properties: { + importNames: { + type: "array", + items: { + type: "string", + }, + minItems: 1, + uniqueItems: true, + }, + allowImportNames: { + type: "array", + items: { + type: "string", + }, + minItems: 1, + uniqueItems: true, + }, + group: { + type: "array", + items: { + type: "string", + }, + minItems: 1, + uniqueItems: true, + }, + regex: { + type: "string", + }, + importNamePattern: { + type: "string", + }, + allowImportNamePattern: { + type: "string", + }, + message: { + type: "string", + minLength: 1, + }, + caseSensitive: { + type: "boolean", + }, + allowTypeImports: { + type: "boolean", + description: + "Whether to allow type-only imports for a pattern.", + }, + }, + additionalProperties: false, + not: { + anyOf: [ + { required: ["importNames", "allowImportNames"] }, + { + required: [ + "importNamePattern", + "allowImportNamePattern", + ], + }, + { required: ["importNames", "allowImportNamePattern"] }, + { required: ["importNamePattern", "allowImportNames"] }, + { + required: [ + "allowImportNames", + "allowImportNamePattern", + ], + }, + ], + }, + oneOf: [{ required: ["group"] }, { required: ["regex"] }], + }, + uniqueItems: true, + }, + ], +}; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified modules when loaded by `import`", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-imports", + }, + + messages: { + path: "'{{importSource}}' import is restricted from being used.", + pathWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importSource}}' import is restricted from being used. {{customMessage}}", + + patterns: + "'{{importSource}}' import is restricted from being used by a pattern.", + patternWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importSource}}' import is restricted from being used by a pattern. {{customMessage}}", + + patternAndImportName: + "'{{importName}}' import from '{{importSource}}' is restricted from being used by a pattern.", + patternAndImportNameWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importName}}' import from '{{importSource}}' is restricted from being used by a pattern. {{customMessage}}", + + patternAndEverything: + "* import is invalid because {{importNames}} from '{{importSource}}' {{isOrAre}} restricted from being used by a pattern.", + + patternAndEverythingWithRegexImportName: + "* import is invalid because import name matching '{{importNames}}' pattern from '{{importSource}}' is restricted from being used.", + patternAndEverythingWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "* import is invalid because {{importNames}} from '{{importSource}}' {{isOrAre}} restricted from being used by a pattern. {{customMessage}}", + patternAndEverythingWithRegexImportNameAndCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "* import is invalid because import name matching '{{importNames}}' pattern from '{{importSource}}' is restricted from being used. {{customMessage}}", + + everything: + "* import is invalid because {{importNames}} from '{{importSource}}' {{isOrAre}} restricted.", + everythingWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "* import is invalid because {{importNames}} from '{{importSource}}' {{isOrAre}} restricted. {{customMessage}}", + + importName: + "'{{importName}}' import from '{{importSource}}' is restricted.", + importNameWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importName}}' import from '{{importSource}}' is restricted. {{customMessage}}", + + allowedImportName: + "'{{importName}}' import from '{{importSource}}' is restricted because only {{allowedImportNames}} {{isOrAre}} allowed.", + allowedImportNameWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importName}}' import from '{{importSource}}' is restricted because only {{allowedImportNames}} {{isOrAre}} allowed. {{customMessage}}", + + everythingWithAllowImportNames: + "* import is invalid because only {{allowedImportNames}} from '{{importSource}}' {{isOrAre}} allowed.", + everythingWithAllowImportNamesAndCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "* import is invalid because only {{allowedImportNames}} from '{{importSource}}' {{isOrAre}} allowed. {{customMessage}}", + + allowedImportNamePattern: + "'{{importName}}' import from '{{importSource}}' is restricted because only imports that match the pattern '{{allowedImportNamePattern}}' are allowed from '{{importSource}}'.", + allowedImportNamePatternWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{importName}}' import from '{{importSource}}' is restricted because only imports that match the pattern '{{allowedImportNamePattern}}' are allowed from '{{importSource}}'. {{customMessage}}", + + everythingWithAllowedImportNamePattern: + "* import is invalid because only imports that match the pattern '{{allowedImportNamePattern}}' from '{{importSource}}' are allowed.", + everythingWithAllowedImportNamePatternWithCustomMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "* import is invalid because only imports that match the pattern '{{allowedImportNamePattern}}' from '{{importSource}}' are allowed. {{customMessage}}", + }, + + schema: { + anyOf: [ + arrayOfStringsOrObjects, + { + type: "array", + items: [ + { + type: "object", + properties: { + paths: arrayOfStringsOrObjects, + patterns: arrayOfStringsOrObjectPatterns, + }, + additionalProperties: false, + }, + ], + additionalItems: false, + }, + ], + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = Array.isArray(context.options) ? context.options : []; + const isPathAndPatternsObject = + typeof options[0] === "object" && + (Object.hasOwn(options[0], "paths") || + Object.hasOwn(options[0], "patterns")); + + const restrictedPaths = + (isPathAndPatternsObject ? options[0].paths : context.options) || + []; + const groupedRestrictedPaths = restrictedPaths.reduce( + (memo, importSource) => { + const path = + typeof importSource === "string" + ? importSource + : importSource.name; + + if (!memo[path]) { + memo[path] = []; + } + + if (typeof importSource === "string") { + memo[path].push({}); + } else { + memo[path].push({ + message: importSource.message, + importNames: importSource.importNames, + allowImportNames: importSource.allowImportNames, + allowTypeImports: importSource.allowTypeImports, + }); + } + return memo; + }, + Object.create(null), + ); + + // Handle patterns too, either as strings or groups + let restrictedPatterns = + (isPathAndPatternsObject ? options[0].patterns : []) || []; + + // standardize to array of objects if we have an array of strings + if ( + restrictedPatterns.length > 0 && + typeof restrictedPatterns[0] === "string" + ) { + restrictedPatterns = [{ group: restrictedPatterns }]; + } + + // relative paths are supported for this rule + const restrictedPatternGroups = restrictedPatterns.map( + ({ + group, + regex, + message, + caseSensitive, + importNames, + importNamePattern, + allowImportNames, + allowImportNamePattern, + allowTypeImports, + }) => ({ + ...(group + ? { + matcher: ignore({ + allowRelativePaths: true, + ignorecase: !caseSensitive, + }).add(group), + } + : {}), + ...(typeof regex === "string" + ? { + regexMatcher: new RegExp( + regex, + caseSensitive ? "u" : "iu", + ), + } + : {}), + customMessage: message, + importNames, + importNamePattern, + allowImportNames, + allowImportNamePattern, + allowTypeImports, + }), + ); + + // if no imports are restricted we don't need to check + if ( + Object.keys(restrictedPaths).length === 0 && + restrictedPatternGroups.length === 0 + ) { + return {}; + } + + /** + * Check if the node is a type-only import + * @param {ASTNode} node The node to check + * @returns {boolean} Whether the node is a type-only import + */ + function isTypeOnlyImport(node) { + return ( + node.importKind === "type" || + (node.specifiers?.length > 0 && + node.specifiers.every( + specifier => specifier.importKind === "type", + )) + ); + } + + /** + * Check if a specifier is type-only + * @param {ASTNode} specifier The specifier to check + * @returns {boolean} Whether the specifier is type-only + */ + function isTypeOnlySpecifier(specifier) { + return ( + specifier.importKind === "type" || + specifier.exportKind === "type" + ); + } + + /** + * Check if the node is a type-only export + * @param {ASTNode} node The node to check + * @returns {boolean} Whether the node is a type-only export + */ + function isTypeOnlyExport(node) { + return ( + node.exportKind === "type" || + (node.specifiers?.length > 0 && + node.specifiers.every( + specifier => specifier.exportKind === "type", + )) + ); + } + + /** + * Report a restricted path. + * @param {string} importSource path of the import + * @param {Map} importNames Map of import names that are being imported + * @param {node} node representing the restricted path reference + * @returns {void} + * @private + */ + function checkRestrictedPathAndReport(importSource, importNames, node) { + if (!Object.hasOwn(groupedRestrictedPaths, importSource)) { + return; + } + + groupedRestrictedPaths[importSource].forEach( + restrictedPathEntry => { + const customMessage = restrictedPathEntry.message; + const restrictedImportNames = + restrictedPathEntry.importNames; + const allowedImportNames = + restrictedPathEntry.allowImportNames; + const allowTypeImports = + restrictedPathEntry.allowTypeImports; + + // Skip if this is a type-only import and it's allowed for this specific entry + if ( + allowTypeImports && + (node.type === "ImportDeclaration" || + node.type === "TSImportEqualsDeclaration") && + isTypeOnlyImport(node) + ) { + return; + } + + // Skip if this is a type-only export and it's allowed for this specific entry + if ( + allowTypeImports && + (node.type === "ExportNamedDeclaration" || + node.type === "ExportAllDeclaration") && + isTypeOnlyExport(node) + ) { + return; + } + + if (!restrictedImportNames && !allowedImportNames) { + context.report({ + node, + messageId: customMessage + ? "pathWithCustomMessage" + : "path", + data: { + importSource, + customMessage, + }, + }); + + return; + } + + importNames.forEach((specifiers, importName) => { + if (importName === "*") { + const [specifier] = specifiers; + + if (restrictedImportNames) { + context.report({ + node, + messageId: customMessage + ? "everythingWithCustomMessage" + : "everything", + loc: specifier.loc, + data: { + importSource, + importNames: formatImportNames( + restrictedImportNames, + ), + isOrAre: isOrAre(restrictedImportNames), + customMessage, + }, + }); + } else if (allowedImportNames) { + context.report({ + node, + messageId: customMessage + ? "everythingWithAllowImportNamesAndCustomMessage" + : "everythingWithAllowImportNames", + loc: specifier.loc, + data: { + importSource, + allowedImportNames: + formatImportNames( + allowedImportNames, + ), + isOrAre: isOrAre(allowedImportNames), + customMessage, + }, + }); + } + + return; + } + + if ( + restrictedImportNames && + restrictedImportNames.includes(importName) + ) { + specifiers.forEach(specifier => { + // Skip if this is a type-only import specifier and type imports are allowed + if ( + allowTypeImports && + isTypeOnlySpecifier(specifier.specifier) + ) { + return; + } + + context.report({ + node, + messageId: customMessage + ? "importNameWithCustomMessage" + : "importName", + loc: specifier.loc, + data: { + importSource, + customMessage, + importName, + }, + }); + }); + } + + if ( + allowedImportNames && + !allowedImportNames.includes(importName) + ) { + specifiers.forEach(specifier => { + // Skip if this is a type-only import specifier and type imports are allowed + if ( + allowTypeImports && + isTypeOnlySpecifier(specifier.specifier) + ) { + return; + } + + context.report({ + node, + loc: specifier.loc, + messageId: customMessage + ? "allowedImportNameWithCustomMessage" + : "allowedImportName", + data: { + importSource, + customMessage, + importName, + allowedImportNames: + formatImportNames( + allowedImportNames, + ), + isOrAre: isOrAre(allowedImportNames), + }, + }); + }); + } + }); + }, + ); + } + + /** + * Report a restricted path specifically for patterns. + * @param {node} node representing the restricted path reference + * @param {Object} group contains an Ignore instance for paths, the customMessage to show on failure, + * and any restricted import names that have been specified in the config + * @param {Map} importNames Map of import names that are being imported + * @param {string} importSource the import source string + * @returns {void} + * @private + */ + function reportPathForPatterns(node, group, importNames, importSource) { + // Skip if this is a type-only import and it's allowed + if ( + group.allowTypeImports && + (node.type === "ImportDeclaration" || + node.type === "TSImportEqualsDeclaration") && + isTypeOnlyImport(node) + ) { + return; + } + + // Skip if this is a type-only export and it's allowed + if ( + group.allowTypeImports && + (node.type === "ExportNamedDeclaration" || + node.type === "ExportAllDeclaration") && + isTypeOnlyExport(node) + ) { + return; + } + + const customMessage = group.customMessage; + const restrictedImportNames = group.importNames; + const restrictedImportNamePattern = group.importNamePattern + ? new RegExp(group.importNamePattern, "u") + : null; + const allowedImportNames = group.allowImportNames; + const allowedImportNamePattern = group.allowImportNamePattern + ? new RegExp(group.allowImportNamePattern, "u") + : null; + + /** + * If we are not restricting to any specific import names and just the pattern itself, + * report the error and move on + */ + if ( + !restrictedImportNames && + !allowedImportNames && + !restrictedImportNamePattern && + !allowedImportNamePattern + ) { + context.report({ + node, + messageId: customMessage + ? "patternWithCustomMessage" + : "patterns", + data: { + importSource, + customMessage, + }, + }); + return; + } + + importNames.forEach((specifiers, importName) => { + if (importName === "*") { + const [specifier] = specifiers; + + if (restrictedImportNames) { + context.report({ + node, + messageId: customMessage + ? "patternAndEverythingWithCustomMessage" + : "patternAndEverything", + loc: specifier.loc, + data: { + importSource, + importNames: formatImportNames( + restrictedImportNames, + ), + isOrAre: isOrAre(restrictedImportNames), + customMessage, + }, + }); + } else if (allowedImportNames) { + context.report({ + node, + messageId: customMessage + ? "everythingWithAllowImportNamesAndCustomMessage" + : "everythingWithAllowImportNames", + loc: specifier.loc, + data: { + importSource, + allowedImportNames: + formatImportNames(allowedImportNames), + isOrAre: isOrAre(allowedImportNames), + customMessage, + }, + }); + } else if (allowedImportNamePattern) { + context.report({ + node, + messageId: customMessage + ? "everythingWithAllowedImportNamePatternWithCustomMessage" + : "everythingWithAllowedImportNamePattern", + loc: specifier.loc, + data: { + importSource, + allowedImportNamePattern, + customMessage, + }, + }); + } else { + context.report({ + node, + messageId: customMessage + ? "patternAndEverythingWithRegexImportNameAndCustomMessage" + : "patternAndEverythingWithRegexImportName", + loc: specifier.loc, + data: { + importSource, + importNames: restrictedImportNamePattern, + customMessage, + }, + }); + } + + return; + } + + if ( + (restrictedImportNames && + restrictedImportNames.includes(importName)) || + (restrictedImportNamePattern && + restrictedImportNamePattern.test(importName)) + ) { + specifiers.forEach(specifier => { + // Skip if this is a type-only import specifier and type imports are allowed + if ( + group.allowTypeImports && + isTypeOnlySpecifier(specifier.specifier) + ) { + return; + } + + context.report({ + node, + messageId: customMessage + ? "patternAndImportNameWithCustomMessage" + : "patternAndImportName", + loc: specifier.loc, + data: { + importSource, + customMessage, + importName, + }, + }); + }); + } + + if ( + allowedImportNames && + !allowedImportNames.includes(importName) + ) { + specifiers.forEach(specifier => { + // Skip if this is a type-only import specifier and type imports are allowed + if ( + group.allowTypeImports && + isTypeOnlySpecifier(specifier.specifier) + ) { + return; + } + + context.report({ + node, + messageId: customMessage + ? "allowedImportNameWithCustomMessage" + : "allowedImportName", + loc: specifier.loc, + data: { + importSource, + customMessage, + importName, + allowedImportNames: + formatImportNames(allowedImportNames), + isOrAre: isOrAre(allowedImportNames), + }, + }); + }); + } else if ( + allowedImportNamePattern && + !allowedImportNamePattern.test(importName) + ) { + specifiers.forEach(specifier => { + // Skip if this is a type-only import specifier and type imports are allowed + if ( + group.allowTypeImports && + isTypeOnlySpecifier(specifier.specifier) + ) { + return; + } + + context.report({ + node, + messageId: customMessage + ? "allowedImportNamePatternWithCustomMessage" + : "allowedImportNamePattern", + loc: specifier.loc, + data: { + importSource, + customMessage, + importName, + allowedImportNamePattern, + }, + }); + }); + } + }); + } + + /** + * Check if the given importSource is restricted by a pattern. + * @param {string} importSource path of the import + * @param {Object} group contains a Ignore instance for paths, and the customMessage to show if it fails + * @returns {boolean} whether the variable is a restricted pattern or not + * @private + */ + function isRestrictedPattern(importSource, group) { + return group.regexMatcher + ? group.regexMatcher.test(importSource) + : group.matcher.ignores(importSource); + } + + /** + * Checks a node to see if any problems should be reported. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkNode(node) { + const importSource = node.source.value.trim(); + const importNames = new Map(); + + if (node.type === "ExportAllDeclaration") { + const starToken = sourceCode.getFirstToken(node, 1); + + importNames.set("*", [{ loc: starToken.loc }]); + } else if (node.specifiers) { + for (const specifier of node.specifiers) { + let name; + const specifierData = { loc: specifier.loc, specifier }; + + if (specifier.type === "ImportDefaultSpecifier") { + name = "default"; + } else if (specifier.type === "ImportNamespaceSpecifier") { + name = "*"; + } else if (specifier.imported) { + name = astUtils.getModuleExportName(specifier.imported); + } else if (specifier.local) { + name = astUtils.getModuleExportName(specifier.local); + } + + if (typeof name === "string") { + if (importNames.has(name)) { + importNames.get(name).push(specifierData); + } else { + importNames.set(name, [specifierData]); + } + } + } + } + + checkRestrictedPathAndReport(importSource, importNames, node); + restrictedPatternGroups.forEach(group => { + if (isRestrictedPattern(importSource, group)) { + reportPathForPatterns( + node, + group, + importNames, + importSource, + ); + } + }); + } + + return { + ImportDeclaration: checkNode, + ExportNamedDeclaration(node) { + if (node.source) { + checkNode(node); + } + }, + ExportAllDeclaration: checkNode, + // Add support for TypeScript import equals declarations + TSImportEqualsDeclaration(node) { + if (node.moduleReference.type === "TSExternalModuleReference") { + const importSource = node.moduleReference.expression.value; + const importNames = new Map(); + + // Use existing logic with the actual node + checkRestrictedPathAndReport( + importSource, + importNames, + node, + ); + restrictedPatternGroups.forEach(group => { + if (isRestrictedPattern(importSource, group)) { + reportPathForPatterns( + node, + group, + importNames, + importSource, + ); + } + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-modules.js b/node_modules/eslint/lib/rules/no-restricted-modules.js new file mode 100644 index 0000000000000000000000000000000000000000..c09cb7d9e6bb6a2a36a0c8c2e501924459830f0a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-modules.js @@ -0,0 +1,249 @@ +/** + * @fileoverview Restrict usage of specified node modules. + * @author Christian Schulz + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const ignore = require("ignore"); + +const arrayOfStrings = { + type: "array", + items: { type: "string" }, + uniqueItems: true, +}; + +const arrayOfStringsOrObjects = { + type: "array", + items: { + anyOf: [ + { type: "string" }, + { + type: "object", + properties: { + name: { type: "string" }, + message: { + type: "string", + minLength: 1, + }, + }, + additionalProperties: false, + required: ["name"], + }, + ], + }, + uniqueItems: true, +}; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-restricted-require", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-restricted-require.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow specified modules when loaded by `require`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-modules", + }, + + schema: { + anyOf: [ + arrayOfStringsOrObjects, + { + type: "array", + items: { + type: "object", + properties: { + paths: arrayOfStringsOrObjects, + patterns: arrayOfStrings, + }, + additionalProperties: false, + }, + additionalItems: false, + }, + ], + }, + + messages: { + defaultMessage: "'{{name}}' module is restricted from being used.", + customMessage: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{name}}' module is restricted from being used. {{customMessage}}", + patternMessage: + "'{{name}}' module is restricted from being used by a pattern.", + }, + }, + + create(context) { + const options = Array.isArray(context.options) ? context.options : []; + const isPathAndPatternsObject = + typeof options[0] === "object" && + (Object.hasOwn(options[0], "paths") || + Object.hasOwn(options[0], "patterns")); + + const restrictedPaths = + (isPathAndPatternsObject ? options[0].paths : context.options) || + []; + const restrictedPatterns = + (isPathAndPatternsObject ? options[0].patterns : []) || []; + + const restrictedPathMessages = restrictedPaths.reduce( + (memo, importName) => { + if (typeof importName === "string") { + memo[importName] = null; + } else { + memo[importName.name] = importName.message; + } + return memo; + }, + {}, + ); + + // if no imports are restricted we don't need to check + if ( + Object.keys(restrictedPaths).length === 0 && + restrictedPatterns.length === 0 + ) { + return {}; + } + + // relative paths are supported for this rule + const ig = ignore({ allowRelativePaths: true }).add(restrictedPatterns); + + /** + * Function to check if a node is a string literal. + * @param {ASTNode} node The node to check. + * @returns {boolean} If the node is a string literal. + */ + function isStringLiteral(node) { + return ( + node && + node.type === "Literal" && + typeof node.value === "string" + ); + } + + /** + * Function to check if a node is a require call. + * @param {ASTNode} node The node to check. + * @returns {boolean} If the node is a require call. + */ + function isRequireCall(node) { + return ( + node.callee.type === "Identifier" && + node.callee.name === "require" + ); + } + + /** + * Extract string from Literal or TemplateLiteral node + * @param {ASTNode} node The node to extract from + * @returns {string|null} Extracted string or null if node doesn't represent a string + */ + function getFirstArgumentString(node) { + if (isStringLiteral(node)) { + return node.value.trim(); + } + + if (astUtils.isStaticTemplateLiteral(node)) { + return node.quasis[0].value.cooked.trim(); + } + + return null; + } + + /** + * Report a restricted path. + * @param {node} node representing the restricted path reference + * @param {string} name restricted path + * @returns {void} + * @private + */ + function reportPath(node, name) { + const customMessage = restrictedPathMessages[name]; + const messageId = customMessage + ? "customMessage" + : "defaultMessage"; + + context.report({ + node, + messageId, + data: { + name, + customMessage, + }, + }); + } + + /** + * Check if the given name is a restricted path name + * @param {string} name name of a variable + * @returns {boolean} whether the variable is a restricted path or not + * @private + */ + function isRestrictedPath(name) { + return Object.hasOwn(restrictedPathMessages, name); + } + + return { + CallExpression(node) { + if (isRequireCall(node)) { + // node has arguments + if (node.arguments.length) { + const name = getFirstArgumentString(node.arguments[0]); + + // if first argument is a string literal or a static string template literal + if (name) { + // check if argument value is in restricted modules array + if (isRestrictedPath(name)) { + reportPath(node, name); + } + + if ( + restrictedPatterns.length > 0 && + ig.ignores(name) + ) { + context.report({ + node, + messageId: "patternMessage", + data: { name }, + }); + } + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-properties.js b/node_modules/eslint/lib/rules/no-restricted-properties.js new file mode 100644 index 0000000000000000000000000000000000000000..8a671e0ecf1acbecff76fac5b978c81f7ad82eeb --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-properties.js @@ -0,0 +1,235 @@ +/** + * @fileoverview Rule to disallow certain object properties + * @author Will Klein & Eli White + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow certain properties on certain objects", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-properties", + }, + + schema: { + type: "array", + items: { + type: "object", + properties: { + object: { + type: "string", + }, + property: { + type: "string", + }, + allowObjects: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + allowProperties: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + message: { + type: "string", + }, + }, + anyOf: [ + { + required: ["object"], + }, + { + required: ["property"], + }, + ], + not: { + anyOf: [ + { required: ["allowObjects", "object"] }, + { required: ["allowProperties", "property"] }, + ], + }, + additionalProperties: false, + }, + uniqueItems: true, + }, + + defaultOptions: [], + + messages: { + restrictedObjectProperty: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{objectName}}.{{propertyName}}' is restricted from being used.{{allowedPropertiesMessage}}{{message}}", + restrictedProperty: + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + "'{{propertyName}}' is restricted from being used.{{allowedObjectsMessage}}{{message}}", + }, + }, + + create(context) { + const restrictedCalls = context.options; + + if (restrictedCalls.length === 0) { + return {}; + } + + const restrictedProperties = new Map(); + const globallyRestrictedObjects = new Map(); + const globallyRestrictedProperties = new Map(); + + restrictedCalls.forEach(option => { + const objectName = option.object; + const propertyName = option.property; + + if (typeof objectName === "undefined") { + globallyRestrictedProperties.set(propertyName, { + allowObjects: option.allowObjects, + message: option.message, + }); + } else if (typeof propertyName === "undefined") { + globallyRestrictedObjects.set(objectName, { + allowProperties: option.allowProperties, + message: option.message, + }); + } else { + if (!restrictedProperties.has(objectName)) { + restrictedProperties.set(objectName, new Map()); + } + + restrictedProperties.get(objectName).set(propertyName, { + message: option.message, + }); + } + }); + + /** + * Checks if a name is in the allowed list. + * @param {string} name The name to check + * @param {string[]} [allowedList] The list of allowed names + * @returns {boolean} True if the name is allowed, false otherwise + */ + function isAllowed(name, allowedList) { + if (!allowedList) { + return false; + } + + return allowedList.includes(name); + } + + /** + * Checks to see whether a property access is restricted, and reports it if so. + * @param {ASTNode} node The node to report + * @param {string} objectName The name of the object + * @param {string} propertyName The name of the property + * @returns {undefined} + */ + function checkPropertyAccess(node, objectName, propertyName) { + if (propertyName === null) { + return; + } + const matchedObject = restrictedProperties.get(objectName); + const matchedObjectProperty = matchedObject + ? matchedObject.get(propertyName) + : globallyRestrictedObjects.get(objectName); + const globalMatchedProperty = + globallyRestrictedProperties.get(propertyName); + + if ( + matchedObjectProperty && + !isAllowed(propertyName, matchedObjectProperty.allowProperties) + ) { + const message = matchedObjectProperty.message + ? ` ${matchedObjectProperty.message}` + : ""; + const allowedPropertiesMessage = + matchedObjectProperty.allowProperties + ? ` Only these properties are allowed: ${matchedObjectProperty.allowProperties.join(", ")}.` + : ""; + + context.report({ + node, + messageId: "restrictedObjectProperty", + data: { + objectName, + propertyName, + message, + allowedPropertiesMessage, + }, + }); + } else if ( + globalMatchedProperty && + !isAllowed(objectName, globalMatchedProperty.allowObjects) + ) { + const message = globalMatchedProperty.message + ? ` ${globalMatchedProperty.message}` + : ""; + const allowedObjectsMessage = globalMatchedProperty.allowObjects + ? ` Property '${propertyName}' is only allowed on these objects: ${globalMatchedProperty.allowObjects.join(", ")}.` + : ""; + + context.report({ + node, + messageId: "restrictedProperty", + data: { + propertyName, + message, + allowedObjectsMessage, + }, + }); + } + } + + return { + MemberExpression(node) { + checkPropertyAccess( + node, + node.object && node.object.name, + astUtils.getStaticPropertyName(node), + ); + }, + ObjectPattern(node) { + let objectName = null; + + if (node.parent.type === "VariableDeclarator") { + if ( + node.parent.init && + node.parent.init.type === "Identifier" + ) { + objectName = node.parent.init.name; + } + } else if ( + node.parent.type === "AssignmentExpression" || + node.parent.type === "AssignmentPattern" + ) { + if (node.parent.right.type === "Identifier") { + objectName = node.parent.right.name; + } + } + + node.properties.forEach(property => { + checkPropertyAccess( + node, + objectName, + astUtils.getStaticPropertyName(property), + ); + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-restricted-syntax.js b/node_modules/eslint/lib/rules/no-restricted-syntax.js new file mode 100644 index 0000000000000000000000000000000000000000..c9453df9ec2f98e2be575b2fd05accd40acb1f5c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-restricted-syntax.js @@ -0,0 +1,76 @@ +/** + * @fileoverview Rule to flag use of certain node types + * @author Burak Yigit Kaya + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow specified syntax", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-restricted-syntax", + }, + + schema: { + type: "array", + items: { + oneOf: [ + { + type: "string", + }, + { + type: "object", + properties: { + selector: { type: "string" }, + message: { type: "string" }, + }, + required: ["selector"], + additionalProperties: false, + }, + ], + }, + uniqueItems: true, + minItems: 0, + }, + + defaultOptions: [], + + messages: { + // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period + restrictedSyntax: "{{message}}", + }, + }, + + create(context) { + return context.options.reduce((result, selectorOrObject) => { + const isStringFormat = typeof selectorOrObject === "string"; + const hasCustomMessage = + !isStringFormat && Boolean(selectorOrObject.message); + + const selector = isStringFormat + ? selectorOrObject + : selectorOrObject.selector; + const message = hasCustomMessage + ? selectorOrObject.message + : `Using '${selector}' is not allowed.`; + + return Object.assign(result, { + [selector](node) { + context.report({ + node, + messageId: "restrictedSyntax", + data: { message }, + }); + }, + }); + }, {}); + }, +}; diff --git a/node_modules/eslint/lib/rules/no-return-assign.js b/node_modules/eslint/lib/rules/no-return-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..92999ddf2b61bdcae561ed450c5d6e3387614ddc --- /dev/null +++ b/node_modules/eslint/lib/rules/no-return-assign.js @@ -0,0 +1,87 @@ +/** + * @fileoverview Rule to flag when return statement contains assignment + * @author Ilya Volodin + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_TYPE = + /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/u; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: ["except-parens"], + + docs: { + description: "Disallow assignment operators in `return` statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-return-assign", + }, + + schema: [ + { + enum: ["except-parens", "always"], + }, + ], + + messages: { + returnAssignment: "Return statement should not contain assignment.", + arrowAssignment: "Arrow function should not return assignment.", + }, + }, + + create(context) { + const always = context.options[0] !== "except-parens"; + const sourceCode = context.sourceCode; + + return { + AssignmentExpression(node) { + if (!always && astUtils.isParenthesised(sourceCode, node)) { + return; + } + + let currentChild = node; + let parent = currentChild.parent; + + // Find ReturnStatement or ArrowFunctionExpression in ancestors. + while (parent && !SENTINEL_TYPE.test(parent.type)) { + currentChild = parent; + parent = parent.parent; + } + + // Reports. + if (parent && parent.type === "ReturnStatement") { + context.report({ + node: parent, + messageId: "returnAssignment", + }); + } else if ( + parent && + parent.type === "ArrowFunctionExpression" && + parent.body === currentChild + ) { + context.report({ + node: parent, + messageId: "arrowAssignment", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-return-await.js b/node_modules/eslint/lib/rules/no-return-await.js new file mode 100644 index 0000000000000000000000000000000000000000..21627eddf7f7d796d072392d7fdd7d3a48542702 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-return-await.js @@ -0,0 +1,162 @@ +/** + * @fileoverview Disallows unnecessary `return await` + * @author Jordan Harband + * @deprecated in ESLint v8.46.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "suggestion", + + docs: { + description: "Disallow unnecessary `return await`", + + recommended: false, + + url: "https://eslint.org/docs/latest/rules/no-return-await", + }, + + fixable: null, + + deprecated: { + message: + "The original assumption of the rule no longer holds true because of engine optimization.", + deprecatedSince: "8.46.0", + availableUntil: null, + replacedBy: [], + }, + + schema: [], + + messages: { + removeAwait: "Remove redundant `await`.", + redundantUseOfAwait: "Redundant use of `await` on a return value.", + }, + }, + + create(context) { + /** + * Reports a found unnecessary `await` expression. + * @param {ASTNode} node The node representing the `await` expression to report + * @returns {void} + */ + function reportUnnecessaryAwait(node) { + context.report({ + node: context.sourceCode.getFirstToken(node), + loc: node.loc, + messageId: "redundantUseOfAwait", + suggest: [ + { + messageId: "removeAwait", + fix(fixer) { + const sourceCode = context.sourceCode; + const [awaitToken, tokenAfterAwait] = + sourceCode.getFirstTokens(node, 2); + + const areAwaitAndAwaitedExpressionOnTheSameLine = + awaitToken.loc.start.line === + tokenAfterAwait.loc.start.line; + + if (!areAwaitAndAwaitedExpressionOnTheSameLine) { + return null; + } + + const [startOfAwait, endOfAwait] = awaitToken.range; + + const characterAfterAwait = + sourceCode.text[endOfAwait]; + const trimLength = + characterAfterAwait === " " ? 1 : 0; + + const range = [ + startOfAwait, + endOfAwait + trimLength, + ]; + + return fixer.removeRange(range); + }, + }, + ], + }); + } + + /** + * Determines whether a thrown error from this node will be caught/handled within this function rather than immediately halting + * this function. For example, a statement in a `try` block will always have an error handler. A statement in + * a `catch` block will only have an error handler if there is also a `finally` block. + * @param {ASTNode} node A node representing a location where an could be thrown + * @returns {boolean} `true` if a thrown error will be caught/handled in this function + */ + function hasErrorHandler(node) { + let ancestor = node; + + while ( + !astUtils.isFunction(ancestor) && + ancestor.type !== "Program" + ) { + if ( + ancestor.parent.type === "TryStatement" && + (ancestor === ancestor.parent.block || + (ancestor === ancestor.parent.handler && + ancestor.parent.finalizer)) + ) { + return true; + } + ancestor = ancestor.parent; + } + return false; + } + + /** + * Checks if a node is placed in tail call position. Once `return` arguments (or arrow function expressions) can be a complex expression, + * an `await` expression could or could not be unnecessary by the definition of this rule. So we're looking for `await` expressions that are in tail position. + * @param {ASTNode} node A node representing the `await` expression to check + * @returns {boolean} The checking result + */ + function isInTailCallPosition(node) { + if (node.parent.type === "ArrowFunctionExpression") { + return true; + } + if (node.parent.type === "ReturnStatement") { + return !hasErrorHandler(node.parent); + } + if ( + node.parent.type === "ConditionalExpression" && + (node === node.parent.consequent || + node === node.parent.alternate) + ) { + return isInTailCallPosition(node.parent); + } + if ( + node.parent.type === "LogicalExpression" && + node === node.parent.right + ) { + return isInTailCallPosition(node.parent); + } + if ( + node.parent.type === "SequenceExpression" && + node === node.parent.expressions.at(-1) + ) { + return isInTailCallPosition(node.parent); + } + return false; + } + + return { + AwaitExpression(node) { + if (isInTailCallPosition(node) && !hasErrorHandler(node)) { + reportUnnecessaryAwait(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-script-url.js b/node_modules/eslint/lib/rules/no-script-url.js new file mode 100644 index 0000000000000000000000000000000000000000..fe550b6dec00933df2a2e4b5d92b89f51bc35021 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-script-url.js @@ -0,0 +1,68 @@ +/** + * @fileoverview Rule to disallow `javascript:` URLs + * @author Ilya Volodin + */ +/* eslint no-script-url: 0 -- Code is checking to report such URLs */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `javascript:` URLs", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-script-url", + }, + + schema: [], + + messages: { + unexpectedScriptURL: "Script URL is a form of eval.", + }, + }, + + create(context) { + /** + * Check whether a node's static value starts with `javascript:` or not. + * And report an error for unexpected script URL. + * @param {ASTNode} node node to check + * @returns {void} + */ + function check(node) { + const value = astUtils.getStaticStringValue(node); + + if ( + typeof value === "string" && + value.toLowerCase().indexOf("javascript:") === 0 + ) { + context.report({ node, messageId: "unexpectedScriptURL" }); + } + } + return { + Literal(node) { + if (node.value && typeof node.value === "string") { + check(node); + } + }, + TemplateLiteral(node) { + if ( + !( + node.parent && + node.parent.type === "TaggedTemplateExpression" + ) + ) { + check(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-self-assign.js b/node_modules/eslint/lib/rules/no-self-assign.js new file mode 100644 index 0000000000000000000000000000000000000000..c1831bb03a5dd7c1eea4d14d1244c129915561d9 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-self-assign.js @@ -0,0 +1,186 @@ +/** + * @fileoverview Rule to disallow assignments where both sides are exactly the same + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SPACES = /\s+/gu; + +/** + * Traverses 2 Pattern nodes in parallel, then reports self-assignments. + * @param {ASTNode|null} left A left node to traverse. This is a Pattern or + * a Property. + * @param {ASTNode|null} right A right node to traverse. This is a Pattern or + * a Property. + * @param {boolean} props The flag to check member expressions as well. + * @param {Function} report A callback function to report. + * @returns {void} + */ +function eachSelfAssignment(left, right, props, report) { + if (!left || !right) { + // do nothing + } else if ( + left.type === "Identifier" && + right.type === "Identifier" && + left.name === right.name + ) { + report(right); + } else if ( + left.type === "ArrayPattern" && + right.type === "ArrayExpression" + ) { + const end = Math.min(left.elements.length, right.elements.length); + + for (let i = 0; i < end; ++i) { + const leftElement = left.elements[i]; + const rightElement = right.elements[i]; + + // Avoid cases such as [...a] = [...a, 1] + if ( + leftElement && + leftElement.type === "RestElement" && + i < right.elements.length - 1 + ) { + break; + } + + eachSelfAssignment(leftElement, rightElement, props, report); + + // After a spread element, those indices are unknown. + if (rightElement && rightElement.type === "SpreadElement") { + break; + } + } + } else if (left.type === "RestElement" && right.type === "SpreadElement") { + eachSelfAssignment(left.argument, right.argument, props, report); + } else if ( + left.type === "ObjectPattern" && + right.type === "ObjectExpression" && + right.properties.length >= 1 + ) { + /* + * Gets the index of the last spread property. + * It's possible to overwrite properties followed by it. + */ + let startJ = 0; + + for (let i = right.properties.length - 1; i >= 0; --i) { + const propType = right.properties[i].type; + + if ( + propType === "SpreadElement" || + propType === "ExperimentalSpreadProperty" + ) { + startJ = i + 1; + break; + } + } + + for (let i = 0; i < left.properties.length; ++i) { + for (let j = startJ; j < right.properties.length; ++j) { + eachSelfAssignment( + left.properties[i], + right.properties[j], + props, + report, + ); + } + } + } else if ( + left.type === "Property" && + right.type === "Property" && + right.kind === "init" && + !right.method + ) { + const leftName = astUtils.getStaticPropertyName(left); + + if ( + leftName !== null && + leftName === astUtils.getStaticPropertyName(right) + ) { + eachSelfAssignment(left.value, right.value, props, report); + } + } else if ( + props && + astUtils.skipChainExpression(left).type === "MemberExpression" && + astUtils.skipChainExpression(right).type === "MemberExpression" && + astUtils.isSameReference(left, right) + ) { + report(right); + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [{ props: true }], + + docs: { + description: + "Disallow assignments where both sides are exactly the same", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-self-assign", + }, + + schema: [ + { + type: "object", + properties: { + props: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + selfAssignment: "'{{name}}' is assigned to itself.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ props }] = context.options; + + /** + * Reports a given node as self assignments. + * @param {ASTNode} node A node to report. This is an Identifier node. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "selfAssignment", + data: { + name: sourceCode.getText(node).replace(SPACES, ""), + }, + }); + } + + return { + AssignmentExpression(node) { + if (["=", "&&=", "||=", "??="].includes(node.operator)) { + eachSelfAssignment(node.left, node.right, props, report); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-self-compare.js b/node_modules/eslint/lib/rules/no-self-compare.js new file mode 100644 index 0000000000000000000000000000000000000000..ee05d3a6028b9b5c84d20cbc4f7666b0a3b71bf4 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-self-compare.js @@ -0,0 +1,77 @@ +/** + * @fileoverview Rule to flag comparison where left part is the same as the right + * part. + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow comparisons where both sides are exactly the same", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-self-compare", + }, + + schema: [], + + messages: { + comparingToSelf: "Comparing to itself is potentially pointless.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Determines whether two nodes are composed of the same tokens. + * @param {ASTNode} nodeA The first node + * @param {ASTNode} nodeB The second node + * @returns {boolean} true if the nodes have identical token representations + */ + function hasSameTokens(nodeA, nodeB) { + const tokensA = sourceCode.getTokens(nodeA); + const tokensB = sourceCode.getTokens(nodeB); + + return ( + tokensA.length === tokensB.length && + tokensA.every( + (token, index) => + token.type === tokensB[index].type && + token.value === tokensB[index].value, + ) + ); + } + + return { + BinaryExpression(node) { + const operators = new Set([ + "===", + "==", + "!==", + "!=", + ">", + "<", + ">=", + "<=", + ]); + + if ( + operators.has(node.operator) && + hasSameTokens(node.left, node.right) + ) { + context.report({ node, messageId: "comparingToSelf" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-sequences.js b/node_modules/eslint/lib/rules/no-sequences.js new file mode 100644 index 0000000000000000000000000000000000000000..96a8ba4e33a6a2178448247e16907f5cbc726d8d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-sequences.js @@ -0,0 +1,158 @@ +/** + * @fileoverview Rule to flag use of comma operator + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow comma operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-sequences", + }, + + schema: [ + { + type: "object", + properties: { + allowInParentheses: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [ + { + allowInParentheses: true, + }, + ], + + messages: { + unexpectedCommaExpression: "Unexpected use of comma operator.", + }, + }, + + create(context) { + const [{ allowInParentheses }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Parts of the grammar that are required to have parens. + */ + const parenthesized = { + DoWhileStatement: "test", + IfStatement: "test", + SwitchStatement: "discriminant", + WhileStatement: "test", + WithStatement: "object", + ArrowFunctionExpression: "body", + + /* + * Omitting CallExpression - commas are parsed as argument separators + * Omitting NewExpression - commas are parsed as argument separators + * Omitting ForInStatement - parts aren't individually parenthesised + * Omitting ForStatement - parts aren't individually parenthesised + */ + }; + + /** + * Determines whether a node is required by the grammar to be wrapped in + * parens, e.g. the test of an if statement. + * @param {ASTNode} node The AST node + * @returns {boolean} True if parens around node belong to parent node. + */ + function requiresExtraParens(node) { + return ( + node.parent && + parenthesized[node.parent.type] && + node === node.parent[parenthesized[node.parent.type]] + ); + } + + /** + * Check if a node is wrapped in parens. + * @param {ASTNode} node The AST node + * @returns {boolean} True if the node has a paren on each side. + */ + function isParenthesised(node) { + return astUtils.isParenthesised(sourceCode, node); + } + + /** + * Check if a node is wrapped in two levels of parens. + * @param {ASTNode} node The AST node + * @returns {boolean} True if two parens surround the node on each side. + */ + function isParenthesisedTwice(node) { + const previousToken = sourceCode.getTokenBefore(node, 1), + nextToken = sourceCode.getTokenAfter(node, 1); + + return ( + isParenthesised(node) && + previousToken && + nextToken && + astUtils.isOpeningParenToken(previousToken) && + previousToken.range[1] <= node.range[0] && + astUtils.isClosingParenToken(nextToken) && + nextToken.range[0] >= node.range[1] + ); + } + + return { + SequenceExpression(node) { + // Always allow sequences in for statement update + if ( + node.parent.type === "ForStatement" && + (node === node.parent.init || node === node.parent.update) + ) { + return; + } + + // Wrapping a sequence in extra parens indicates intent + if (allowInParentheses) { + if (requiresExtraParens(node)) { + if (isParenthesisedTwice(node)) { + return; + } + } else { + if (isParenthesised(node)) { + return; + } + } + } + + const firstCommaToken = sourceCode.getTokenAfter( + node.expressions[0], + astUtils.isCommaToken, + ); + + context.report({ + node, + loc: firstCommaToken.loc, + messageId: "unexpectedCommaExpression", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-setter-return.js b/node_modules/eslint/lib/rules/no-setter-return.js new file mode 100644 index 0000000000000000000000000000000000000000..63e0de53bfa46c767564303a3bd25aeb4f678c65 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-setter-return.js @@ -0,0 +1,224 @@ +/** + * @fileoverview Rule to disallow returning values from setters + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given node is an argument of the specified global method call, at the given `index` position. + * E.g., for given `index === 1`, this function checks for `objectName.methodName(foo, node)`, where objectName is a global variable. + * @param {ASTNode} node The node to check. + * @param {SourceCode} sourceCode Source code to which the node belongs. + * @param {string} objectName Name of the global object. + * @param {string} methodName Name of the method. + * @param {number} index The given position. + * @returns {boolean} `true` if the node is argument at the given position. + */ +function isArgumentOfGlobalMethodCall( + node, + sourceCode, + objectName, + methodName, + index, +) { + const callNode = node.parent; + + return ( + callNode.type === "CallExpression" && + callNode.arguments[index] === node && + astUtils.isSpecificMemberAccess( + callNode.callee, + objectName, + methodName, + ) && + sourceCode.isGlobalReference( + astUtils.skipChainExpression(callNode.callee).object, + ) + ); +} + +/** + * Determines whether the given node is used as a property descriptor. + * @param {ASTNode} node The node to check. + * @param {SourceCode} sourceCode Source code to which the node belongs. + * @returns {boolean} `true` if the node is a property descriptor. + */ +function isPropertyDescriptor(node, sourceCode) { + if ( + isArgumentOfGlobalMethodCall( + node, + sourceCode, + "Object", + "defineProperty", + 2, + ) || + isArgumentOfGlobalMethodCall( + node, + sourceCode, + "Reflect", + "defineProperty", + 2, + ) + ) { + return true; + } + + const parent = node.parent; + + if (parent.type === "Property" && parent.value === node) { + const grandparent = parent.parent; + + if ( + grandparent.type === "ObjectExpression" && + (isArgumentOfGlobalMethodCall( + grandparent, + sourceCode, + "Object", + "create", + 1, + ) || + isArgumentOfGlobalMethodCall( + grandparent, + sourceCode, + "Object", + "defineProperties", + 1, + )) + ) { + return true; + } + } + + return false; +} + +/** + * Determines whether the given function node is used as a setter function. + * @param {ASTNode} node The node to check. + * @param {SourceCode} sourceCode Source code to which the node belongs. + * @returns {boolean} `true` if the node is a setter. + */ +function isSetter(node, sourceCode) { + const parent = node.parent; + + if ( + (parent.type === "Property" || parent.type === "MethodDefinition") && + parent.kind === "set" && + parent.value === node + ) { + // Setter in an object literal or in a class + return true; + } + + if ( + parent.type === "Property" && + parent.value === node && + astUtils.getStaticPropertyName(parent) === "set" && + parent.parent.type === "ObjectExpression" && + isPropertyDescriptor(parent.parent, sourceCode) + ) { + // Setter in a property descriptor + return true; + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow returning values from setters", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-setter-return", + }, + + schema: [], + + messages: { + returnsValue: "Setter cannot return a value.", + }, + }, + + create(context) { + let funcInfo = null; + const sourceCode = context.sourceCode; + + /** + * Creates and pushes to the stack a function info object for the given function node. + * @param {ASTNode} node The function node. + * @returns {void} + */ + function enterFunction(node) { + funcInfo = { + upper: funcInfo, + isSetter: isSetter(node, sourceCode), + }; + } + + /** + * Pops the current function info object from the stack. + * @returns {void} + */ + function exitFunction() { + funcInfo = funcInfo.upper; + } + + /** + * Reports the given node. + * @param {ASTNode} node Node to report. + * @returns {void} + */ + function report(node) { + context.report({ node, messageId: "returnsValue" }); + } + + return { + /* + * Function declarations cannot be setters, but we still have to track them in the `funcInfo` stack to avoid + * false positives, because a ReturnStatement node can belong to a function declaration inside a setter. + * + * Note: A previously declared function can be referenced and actually used as a setter in a property descriptor, + * but that's out of scope for this rule. + */ + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + ArrowFunctionExpression(node) { + enterFunction(node); + + if (funcInfo.isSetter && node.expression) { + // { set: foo => bar } property descriptor. Report implicit return 'bar' as the equivalent for a return statement. + report(node.body); + } + }, + + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + "ArrowFunctionExpression:exit": exitFunction, + + ReturnStatement(node) { + // Global returns (e.g., at the top level of a Node module) don't have `funcInfo`. + if (funcInfo && funcInfo.isSetter && node.argument) { + report(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-shadow-restricted-names.js b/node_modules/eslint/lib/rules/no-shadow-restricted-names.js new file mode 100644 index 0000000000000000000000000000000000000000..4436c342e58886185f181fdf762c75057bed3420 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-shadow-restricted-names.js @@ -0,0 +1,113 @@ +/** + * @fileoverview Disallow shadowing of globalThis, NaN, undefined, and Infinity (ES2020 section 18.1) + * @author Michael Ficarra + */ +"use strict"; + +/** + * Determines if a variable safely shadows undefined. + * This is the case when a variable named `undefined` is never assigned to a value (i.e. it always shares the same value + * as the global). + * @param {eslintScope.Variable} variable The variable to check + * @returns {boolean} true if this variable safely shadows `undefined` + */ +function safelyShadowsUndefined(variable) { + return ( + variable.name === "undefined" && + variable.references.every(ref => !ref.isWrite()) && + variable.defs.every( + def => + def.node.type === "VariableDeclarator" && + def.node.init === null, + ) + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + reportGlobalThis: true, + }, + ], + + docs: { + description: "Disallow identifiers from shadowing restricted names", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-shadow-restricted-names", + }, + + schema: [ + { + type: "object", + properties: { + reportGlobalThis: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + shadowingRestrictedName: "Shadowing of global property '{{name}}'.", + }, + }, + + create(context) { + const [{ reportGlobalThis }] = context.options; + + const RESTRICTED = new Set([ + "undefined", + "NaN", + "Infinity", + "arguments", + "eval", + ]); + + if (reportGlobalThis) { + RESTRICTED.add("globalThis"); + } + + const sourceCode = context.sourceCode; + + // Track reported nodes to avoid duplicate reports. For example, on class declarations. + const reportedNodes = new Set(); + + return { + "VariableDeclaration, :function, CatchClause, ImportDeclaration, ClassDeclaration, ClassExpression"( + node, + ) { + for (const variable of sourceCode.getDeclaredVariables(node)) { + if ( + variable.defs.length > 0 && + RESTRICTED.has(variable.name) && + !safelyShadowsUndefined(variable) + ) { + for (const def of variable.defs) { + const nodeToReport = def.name; + + if (!reportedNodes.has(nodeToReport)) { + reportedNodes.add(nodeToReport); + context.report({ + node: nodeToReport, + messageId: "shadowingRestrictedName", + data: { + name: variable.name, + }, + }); + } + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-shadow.js b/node_modules/eslint/lib/rules/no-shadow.js new file mode 100644 index 0000000000000000000000000000000000000000..dbed9114f97084fe10475d3c44eb51ee5af6d2a7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-shadow.js @@ -0,0 +1,694 @@ +/** + * @fileoverview Rule to flag on declaring variables already declared in the outer scope + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Variable} Variable */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const FUNC_EXPR_NODE_TYPES = new Set([ + "ArrowFunctionExpression", + "FunctionExpression", +]); +const CALL_EXPR_NODE_TYPE = new Set(["CallExpression"]); +const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/u; +const SENTINEL_TYPE = + /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/u; + +// TS-specific node types +const TYPES_HOISTED_NODES = new Set([ + "TSInterfaceDeclaration", + "TSTypeAliasDeclaration", +]); + +// TS-specific function variable def types +const ALLOWED_FUNCTION_VARIABLE_DEF_TYPES = new Set([ + "TSCallSignatureDeclaration", + "TSFunctionType", + "TSMethodSignature", + "TSEmptyBodyFunctionExpression", + "TSDeclareFunction", + "TSConstructSignatureDeclaration", + "TSConstructorType", +]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allow: [], + builtinGlobals: false, + hoist: "functions", + ignoreOnInitialization: false, + ignoreTypeValueShadow: true, + ignoreFunctionTypeParameterNameValueShadow: true, + }, + ], + + docs: { + description: + "Disallow variable declarations from shadowing variables declared in the outer scope", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-shadow", + }, + + schema: [ + { + type: "object", + properties: { + builtinGlobals: { type: "boolean" }, + hoist: { + enum: [ + "all", + "functions", + "never", + "types", + "functions-and-types", + ], + }, + allow: { + type: "array", + items: { + type: "string", + }, + }, + ignoreOnInitialization: { type: "boolean" }, + ignoreTypeValueShadow: { type: "boolean" }, + ignoreFunctionTypeParameterNameValueShadow: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + noShadow: + "'{{name}}' is already declared in the upper scope on line {{shadowedLine}} column {{shadowedColumn}}.", + noShadowGlobal: "'{{name}}' is already a global variable.", + }, + }, + + create(context) { + const [ + { + builtinGlobals, + hoist, + allow, + ignoreOnInitialization, + ignoreTypeValueShadow, + ignoreFunctionTypeParameterNameValueShadow, + }, + ] = context.options; + const sourceCode = context.sourceCode; + + /** + * Check if a scope is a TypeScript module augmenting the global namespace. + * @param {Scope} scope The scope to check + * @returns {boolean} Whether the scope is a global augmentation + */ + function isGlobalAugmentation(scope) { + return ( + scope.block.kind === "global" || + (!!scope.upper && isGlobalAugmentation(scope.upper)) + ); + } + + /** + * Check if variable is a `this` parameter. + * @param {Object} variable The variable to check + * @returns {boolean} Whether the variable is a this parameter + */ + function isThisParam(variable) { + return variable.name === "this"; + } + + /** + * Checks if type and value shadows each other + * @param {Object} variable The variable to check + * @param {Object} shadowedVariable The shadowed variable + * @returns {boolean} Whether it's a type/value shadow case to ignore + */ + function isTypeValueShadow(variable, shadowedVariable) { + if (ignoreTypeValueShadow !== true) { + return false; + } + + if (!("isValueVariable" in variable)) { + return false; + } + + const firstDefinition = shadowedVariable.defs[0]; + + // Check if shadowedVariable is a type import + const isTypeImport = + firstDefinition && + firstDefinition.parent?.type === "ImportDeclaration" && + (firstDefinition.parent.importKind === "type" || + firstDefinition.parent.specifiers.some( + s => s.importKind === "type", + )); + + const isShadowedValue = + !firstDefinition || + (isTypeImport ? false : shadowedVariable.isValueVariable); + + return variable.isValueVariable !== isShadowedValue; + } + + /** + * Checks if it's a function type parameter shadow + * @param {Object} variable The variable to check + * @returns {boolean} Whether it's a function type parameter shadow case to ignore + */ + function isFunctionTypeParameterNameValueShadow(variable) { + if (ignoreFunctionTypeParameterNameValueShadow !== true) { + return false; + } + + return variable.defs.some(def => + ALLOWED_FUNCTION_VARIABLE_DEF_TYPES.has(def.node.type), + ); + } + + /** + * Checks if the variable is a generic of a static method + * @param {Object} variable The variable to check + * @returns {boolean} Whether the variable is a generic of a static method + */ + function isTypeParameterOfStaticMethod(variable) { + const typeParameter = variable.identifiers[0].parent; + const typeParameterDecl = typeParameter.parent; + if (typeParameterDecl.type !== "TSTypeParameterDeclaration") { + return false; + } + const functionExpr = typeParameterDecl.parent; + const methodDefinition = functionExpr.parent; + return methodDefinition.static; + } + + /** + * Checks for static method generic shadowing class generic + * @param {Object} variable The variable to check + * @returns {boolean} Whether it's a static method generic shadowing class generic + */ + function isGenericOfAStaticMethodShadow(variable) { + return isTypeParameterOfStaticMethod(variable); + } + + /** + * Checks whether or not a given location is inside of the range of a given node. + * @param {ASTNode} node An node to check. + * @param {number} location A location to check. + * @returns {boolean} `true` if the location is inside of the range of the node. + */ + function isInRange(node, location) { + return ( + node && node.range[0] <= location && location <= node.range[1] + ); + } + + /** + * Searches from the current node through its ancestry to find a matching node. + * @param {ASTNode} node a node to get. + * @param {(node: ASTNode) => boolean} match a callback that checks whether or not the node verifies its condition or not. + * @returns {ASTNode|null} the matching node. + */ + function findSelfOrAncestor(node, match) { + let currentNode = node; + + while (currentNode && !match(currentNode)) { + currentNode = currentNode.parent; + } + return currentNode; + } + + /** + * Finds function's outer scope. + * @param {Scope} scope Function's own scope. + * @returns {Scope} Function's outer scope. + */ + function getOuterScope(scope) { + const upper = scope.upper; + + if (upper && upper.type === "function-expression-name") { + return upper.upper; + } + return upper; + } + + /** + * Checks if a variable and a shadowedVariable have the same init pattern ancestor. + * @param {Object} variable a variable to check. + * @param {Object} shadowedVariable a shadowedVariable to check. + * @returns {boolean} Whether or not the variable and the shadowedVariable have the same init pattern ancestor. + */ + function isInitPatternNode(variable, shadowedVariable) { + const outerDef = shadowedVariable.defs[0]; + + if (!outerDef) { + return false; + } + + const { variableScope } = variable.scope; + + if ( + !( + FUNC_EXPR_NODE_TYPES.has(variableScope.block.type) && + getOuterScope(variableScope) === shadowedVariable.scope + ) + ) { + return false; + } + + const fun = variableScope.block; + const { parent } = fun; + + const callExpression = findSelfOrAncestor(parent, node => + CALL_EXPR_NODE_TYPE.has(node.type), + ); + + if (!callExpression) { + return false; + } + + let node = outerDef.name; + const location = callExpression.range[1]; + + while (node) { + if (node.type === "VariableDeclarator") { + if (isInRange(node.init, location)) { + return true; + } + if ( + FOR_IN_OF_TYPE.test(node.parent.parent.type) && + isInRange(node.parent.parent.right, location) + ) { + return true; + } + break; + } else if (node.type === "AssignmentPattern") { + if (isInRange(node.right, location)) { + return true; + } + } else if (SENTINEL_TYPE.test(node.type)) { + break; + } + + node = node.parent; + } + + return false; + } + + /** + * Check if variable name is allowed. + * @param {ASTNode} variable The variable to check. + * @returns {boolean} Whether or not the variable name is allowed. + */ + function isAllowed(variable) { + return allow.includes(variable.name); + } + + /** + * Checks if a variable of the class name in the class scope of ClassDeclaration. + * + * ClassDeclaration creates two variables of its name into its outer scope and its class scope. + * So we should ignore the variable in the class scope. + * @param {Object} variable The variable to check. + * @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration. + */ + function isDuplicatedClassNameVariable(variable) { + const block = variable.scope.block; + + return ( + block.type === "ClassDeclaration" && + block.id === variable.identifiers[0] + ); + } + + /** + * Finds the uppermost expression node that can evaluate to the given one. + * + * Examples: + * If given `a` in `a || foo`, it returns the `a || foo` node. + * If given `a` in `foo ? a : bar`, it returns the `foo ? a : bar` node. + * If given `a` in `foo ? bar : (baz && a)`, it returns the `foo ? bar : (baz && a)` node. + * If given `a` in `a ? foo : bar`, it returns the `a` node. + * If given `a` in `foo(a)`, it returns the `a` node. + * @param {ASTNode} expression The expression node to unwrap. + * @returns {ASTNode} The uppermost ancestor that can evaluate to the given node + * or the given node if there is no such ancestor. + */ + function unwrapExpression(expression) { + const { parent } = expression; + + const shouldUnwrap = + parent.type === "LogicalExpression" || + (parent.type === "ConditionalExpression" && + parent.test !== expression); + + return shouldUnwrap ? unwrapExpression(parent) : expression; + } + + /** + * Checks if inner variable is the name of a function or class + * that is assigned to outer variable as its initializer. + * + * To avoid reporting at declarations such as: + * var a = function a() {}; + * var A = class A {}; + * var a = foo || function a() {}; + * var a = foo ? function a() {} : bar; + * var { a = function a() {} } = foo; + * + * But it should report at declarations such as: + * var a = function(a) {}; + * var a = function() { function a() {} }; + * var a = wrap(function a() {}); + * @param {Object} innerVariable The inner variable to check. + * @param {Object} outerVariable The outer variable. + * @returns {boolean} Whether or not inner variable is the name of a + * function or class that is assigned to outer variable as its initializer. + */ + function isFunctionNameInitializerException( + innerVariable, + outerVariable, + ) { + const outerDef = outerVariable.defs[0]; + const innerDef = innerVariable.defs[0]; + + if (!outerDef || !innerDef) { + return false; + } + + if ( + !( + (innerDef.type === "FunctionName" && + innerDef.node.type === "FunctionExpression") || + (innerDef.type === "ClassName" && + innerDef.node.type === "ClassExpression") + ) + ) { + return false; + } + + const outerIdentifier = outerDef.name; + let initializerNode; + + if (outerIdentifier.parent.type === "VariableDeclarator") { + initializerNode = outerIdentifier.parent.init; + } else if (outerIdentifier.parent.type === "AssignmentPattern") { + initializerNode = outerIdentifier.parent.right; + } + + if (!initializerNode) { + return false; + } + + const nodeToCheck = innerDef.node; // FunctionExpression or ClassExpression node + + // Exit early if the node to check isn't inside the initializer + if ( + !( + initializerNode.range[0] <= nodeToCheck.range[0] && + nodeToCheck.range[1] <= initializerNode.range[1] + ) + ) { + return false; + } + + return initializerNode === unwrapExpression(nodeToCheck); + } + + /** + * Get a range of a variable's identifier node. + * @param {Object} variable The variable to get. + * @returns {Array|undefined} The range of the variable's identifier node. + */ + function getNameRange(variable) { + const def = variable.defs[0]; + + return def && def.name.range; + } + + /** + * Get declared line and column of a variable. + * @param {Variable} variable The variable to get. + * @returns {Object} The declared line and column of the variable. + */ + function getDeclaredLocation(variable) { + const identifier = variable.identifiers[0]; + let obj; + + if (identifier) { + obj = { + global: false, + line: identifier.loc.start.line, + column: identifier.loc.start.column + 1, + }; + } else { + obj = { + global: true, + }; + } + return obj; + } + + /** + * Checks if a variable is in TDZ of scopeVar. + * @param {Object} variable The variable to check. + * @param {Object} scopeVar The variable of TDZ. + * @returns {boolean} Whether or not the variable is in TDZ of scopeVar. + */ + function isInTdz(variable, scopeVar) { + const outerDef = scopeVar.defs[0]; + const inner = getNameRange(variable); + const outer = getNameRange(scopeVar); + + if (!outer || inner[1] >= outer[0]) { + return false; + } + + if (hoist === "types") { + return !TYPES_HOISTED_NODES.has(outerDef.node.type); + } + + if (hoist === "functions-and-types") { + return ( + outerDef.node.type !== "FunctionDeclaration" && + !TYPES_HOISTED_NODES.has(outerDef.node.type) + ); + } + + return ( + inner && + outer && + inner[1] < outer[0] && + // Excepts FunctionDeclaration if is {"hoist":"function"}. + (hoist !== "functions" || + !outerDef || + outerDef.node.type !== "FunctionDeclaration") + ); + } + + /** + * Checks if the initialization of a variable has the declare modifier in a + * definition file. + * @param {Object} variable The variable to check + * @returns {boolean} Whether the variable is declared in a definition file + */ + function isDeclareInDTSFile(variable) { + const fileName = context.filename; + if ( + !fileName.endsWith(".d.ts") && + !fileName.endsWith(".d.cts") && + !fileName.endsWith(".d.mts") + ) { + return false; + } + return variable.defs.some( + def => + (def.type === "Variable" && def.parent.declare) || + (def.type === "ClassName" && def.node.declare) || + (def.type === "TSEnumName" && def.node.declare) || + (def.type === "TSModuleName" && def.node.declare), + ); + } + + /** + * Checks if a variable is a duplicate of an enum name in the enum scope + * @param {Object} variable The variable to check + * @returns {boolean} Whether it's a duplicate enum name variable + */ + function isDuplicatedEnumNameVariable(variable) { + const block = variable.scope.block; + + return ( + block.type === "TSEnumDeclaration" && + block.id === variable.identifiers[0] + ); + } + + /** + * Check if this is an external module declaration merging with a type import + * @param {Scope} scope Current scope + * @param {Object} variable Current variable + * @param {Object} shadowedVariable Shadowed variable + * @returns {boolean} Whether it's an external declaration merging + */ + function isExternalDeclarationMerging( + scope, + variable, + shadowedVariable, + ) { + const firstDefinition = shadowedVariable.defs[0]; + + if (!firstDefinition || !firstDefinition.parent) { + return false; + } + + // Check if the shadowed variable is a type import + const isTypeImport = + firstDefinition.parent.type === "ImportDeclaration" && + (firstDefinition.parent.importKind === "type" || + firstDefinition.parent.specifiers?.some( + s => + s.type === "ImportSpecifier" && + s.importKind === "type" && + s.local.name === shadowedVariable.name, + )); + + if (!isTypeImport) { + return false; + } + + // Check if the current variable is within a module declaration + const moduleDecl = findSelfOrAncestor( + variable.identifiers[0]?.parent, + node => node.type === "TSModuleDeclaration", + ); + + if (!moduleDecl) { + return false; + } + + /* + * Module declaration merging should only happen within the same module + * Check if the module name matches the import source + */ + const importSource = firstDefinition.parent.source.value; + const moduleName = + moduleDecl.id.type === "Literal" + ? moduleDecl.id.value + : moduleDecl.id.name; + + return importSource === moduleName; + } + + /** + * Checks the current context for shadowed variables. + * @param {Scope} scope The scope to check for shadowed variables. + * @returns {void} + */ + function checkForShadows(scope) { + // ignore global augmentation + if (isGlobalAugmentation(scope)) { + return; + } + + const variables = scope.variables; + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + + // Skips "arguments" or variables of a class name in the class scope of ClassDeclaration. + if ( + variable.identifiers.length === 0 || + isDuplicatedClassNameVariable(variable) || + isDuplicatedEnumNameVariable(variable) || + isAllowed(variable) || + isDeclareInDTSFile(variable) || + isThisParam(variable) + ) { + continue; + } + + // Gets shadowed variable. + const shadowed = astUtils.getVariableByName( + scope.upper, + variable.name, + ); + + if ( + shadowed && + (shadowed.identifiers.length > 0 || + (builtinGlobals && "writeable" in shadowed)) && + !isFunctionNameInitializerException(variable, shadowed) && + !( + ignoreOnInitialization && + isInitPatternNode(variable, shadowed) + ) && + !(hoist !== "all" && isInTdz(variable, shadowed)) && + !isTypeValueShadow(variable, shadowed) && + !isFunctionTypeParameterNameValueShadow(variable) && + !isGenericOfAStaticMethodShadow(variable, shadowed) && + !isExternalDeclarationMerging(scope, variable, shadowed) + ) { + const location = getDeclaredLocation(shadowed); + const messageId = location.global + ? "noShadowGlobal" + : "noShadow"; + const data = { name: variable.name }; + + if (!location.global) { + data.shadowedLine = location.line; + data.shadowedColumn = location.column; + } + context.report({ + node: variable.identifiers[0], + messageId, + data, + }); + } + } + } + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + const stack = globalScope.childScopes.slice(); + + while (stack.length) { + const scope = stack.pop(); + + stack.push(...scope.childScopes); + checkForShadows(scope); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-spaced-func.js b/node_modules/eslint/lib/rules/no-spaced-func.js new file mode 100644 index 0000000000000000000000000000000000000000..7d8cad6051aa75322de18e9209f66ff9eb01f584 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-spaced-func.js @@ -0,0 +1,105 @@ +/** + * @fileoverview Rule to check that spaced function application + * @author Matt DuVall + * @deprecated in ESLint v3.3.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: + "Disallow spacing between function identifiers and their applications (deprecated)", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-spaced-func", + }, + + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2016/08/eslint-v3.3.0-released/#deprecated-rules", + deprecatedSince: "3.3.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "function-call-spacing", + url: "https://eslint.style/rules/function-call-spacing", + }, + }, + ], + }, + + fixable: "whitespace", + schema: [], + + messages: { + noSpacedFunction: + "Unexpected space between function name and paren.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Check if open space is present in a function name + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function detectOpenSpaces(node) { + const lastCalleeToken = sourceCode.getLastToken(node.callee); + let prevToken = lastCalleeToken, + parenToken = sourceCode.getTokenAfter(lastCalleeToken); + + // advances to an open parenthesis. + while ( + parenToken && + parenToken.range[1] < node.range[1] && + parenToken.value !== "(" + ) { + prevToken = parenToken; + parenToken = sourceCode.getTokenAfter(parenToken); + } + + // look for a space between the callee and the open paren + if ( + parenToken && + parenToken.range[1] < node.range[1] && + sourceCode.isSpaceBetween(prevToken, parenToken) + ) { + context.report({ + node, + loc: lastCalleeToken.loc.start, + messageId: "noSpacedFunction", + fix(fixer) { + return fixer.removeRange([ + prevToken.range[1], + parenToken.range[0], + ]); + }, + }); + } + } + + return { + CallExpression: detectOpenSpaces, + NewExpression: detectOpenSpaces, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-sparse-arrays.js b/node_modules/eslint/lib/rules/no-sparse-arrays.js new file mode 100644 index 0000000000000000000000000000000000000000..f805ecef3e09c21734a65277fcc4e1cff31d19f5 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-sparse-arrays.js @@ -0,0 +1,68 @@ +/** + * @fileoverview Disallow sparse arrays + * @author Nicholas C. Zakas + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow sparse arrays", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-sparse-arrays", + }, + + schema: [], + + messages: { + unexpectedSparseArray: "Unexpected comma in middle of array.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ArrayExpression(node) { + if (!node.elements.includes(null)) { + return; + } + + const { sourceCode } = context; + let commaToken; + + for (const [index, element] of node.elements.entries()) { + if (index === node.elements.length - 1 && element) { + return; + } + + commaToken = sourceCode.getTokenAfter( + element ?? commaToken ?? sourceCode.getFirstToken(node), + astUtils.isCommaToken, + ); + + if (element) { + continue; + } + + context.report({ + node, + loc: commaToken.loc, + messageId: "unexpectedSparseArray", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-sync.js b/node_modules/eslint/lib/rules/no-sync.js new file mode 100644 index 0000000000000000000000000000000000000000..50b5860ee1ed90057e10b32e75b19a30d8c472c7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-sync.js @@ -0,0 +1,81 @@ +/** + * @fileoverview Rule to check for properties whose identifier ends with the string Sync + * @author Matt DuVall + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "no-sync", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-sync.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow synchronous methods", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-sync", + }, + + schema: [ + { + type: "object", + properties: { + allowAtRootLevel: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + noSync: "Unexpected sync method: '{{propertyName}}'.", + }, + }, + + create(context) { + const selector = + context.options[0] && context.options[0].allowAtRootLevel + ? ":function MemberExpression[property.name=/.*Sync$/]" + : "MemberExpression[property.name=/.*Sync$/]"; + + return { + [selector](node) { + context.report({ + node, + messageId: "noSync", + data: { + propertyName: node.property.name, + }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-tabs.js b/node_modules/eslint/lib/rules/no-tabs.js new file mode 100644 index 0000000000000000000000000000000000000000..f35f4da0d09b3249b59dc9665e2948f01290647d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-tabs.js @@ -0,0 +1,110 @@ +/** + * @fileoverview Rule to check for tabs inside a file + * @author Gyandeep Singh + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const tabRegex = /\t+/gu; +const anyNonWhitespaceRegex = /\S/u; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "no-tabs", + url: "https://eslint.style/rules/no-tabs", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow all tabs", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-tabs", + }, + schema: [ + { + type: "object", + properties: { + allowIndentationTabs: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedTab: "Unexpected tab character.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const allowIndentationTabs = + context.options && + context.options[0] && + context.options[0].allowIndentationTabs; + + return { + Program(node) { + sourceCode.getLines().forEach((line, index) => { + let match; + + while ((match = tabRegex.exec(line)) !== null) { + if ( + allowIndentationTabs && + !anyNonWhitespaceRegex.test( + line.slice(0, match.index), + ) + ) { + continue; + } + + context.report({ + node, + loc: { + start: { + line: index + 1, + column: match.index, + }, + end: { + line: index + 1, + column: match.index + match[0].length, + }, + }, + messageId: "unexpectedTab", + }); + } + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-template-curly-in-string.js b/node_modules/eslint/lib/rules/no-template-curly-in-string.js new file mode 100644 index 0000000000000000000000000000000000000000..901e1aeadfd267b644722365b3462451f0ebea98 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-template-curly-in-string.js @@ -0,0 +1,45 @@ +/** + * @fileoverview Warn when using template string syntax in regular strings + * @author Jeroen Engels + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow template literal placeholder syntax in regular strings", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-template-curly-in-string", + }, + + schema: [], + + messages: { + unexpectedTemplateExpression: + "Unexpected template string expression.", + }, + }, + + create(context) { + const regex = /\$\{[^}]+\}/u; + + return { + Literal(node) { + if (typeof node.value === "string" && regex.test(node.value)) { + context.report({ + node, + messageId: "unexpectedTemplateExpression", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-ternary.js b/node_modules/eslint/lib/rules/no-ternary.js new file mode 100644 index 0000000000000000000000000000000000000000..f58136d5e650dba11091cc45d0c3692fb556ab6d --- /dev/null +++ b/node_modules/eslint/lib/rules/no-ternary.js @@ -0,0 +1,38 @@ +/** + * @fileoverview Rule to flag use of ternary operators. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow ternary operators", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-ternary", + }, + + schema: [], + + messages: { + noTernaryOperator: "Ternary operator used.", + }, + }, + + create(context) { + return { + ConditionalExpression(node) { + context.report({ node, messageId: "noTernaryOperator" }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-this-before-super.js b/node_modules/eslint/lib/rules/no-this-before-super.js new file mode 100644 index 0000000000000000000000000000000000000000..27ba94a2715a41991c021a87b921579e2102e2a8 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-this-before-super.js @@ -0,0 +1,363 @@ +/** + * @fileoverview A rule to disallow using `this`/`super` before `super()`. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a constructor. + * @param {ASTNode} node A node to check. This node type is one of + * `Program`, `FunctionDeclaration`, `FunctionExpression`, and + * `ArrowFunctionExpression`. + * @returns {boolean} `true` if the node is a constructor. + */ +function isConstructorFunction(node) { + return ( + node.type === "FunctionExpression" && + node.parent.type === "MethodDefinition" && + node.parent.kind === "constructor" + ); +} + +/* + * Information for each code path segment. + * - superCalled: The flag which shows `super()` called in all code paths. + * - invalidNodes: The array of invalid ThisExpression and Super nodes. + */ +/** + * + */ +class SegmentInfo { + /** + * Indicates whether `super()` is called in all code paths. + * @type {boolean} + */ + superCalled = false; + + /** + * The array of invalid ThisExpression and Super nodes. + * @type {ASTNode[]} + */ + invalidNodes = []; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow `this`/`super` before calling `super()` in constructors", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-this-before-super", + }, + + schema: [], + + messages: { + noBeforeSuper: "'{{kind}}' is not allowed before 'super()'.", + }, + }, + + create(context) { + /* + * Information for each constructor. + * - upper: Information of the upper constructor. + * - hasExtends: A flag which shows whether the owner class has a valid + * `extends` part. + * - scope: The scope of the owner class. + * - codePath: The code path of this constructor. + */ + let funcInfo = null; + + /** @type {Record} */ + let segInfoMap = Object.create(null); + + /** + * Gets whether or not `super()` is called in a given code path segment. + * @param {CodePathSegment} segment A code path segment to get. + * @returns {boolean} `true` if `super()` is called. + */ + function isCalled(segment) { + return !segment.reachable || segInfoMap[segment.id]?.superCalled; + } + + /** + * Checks whether or not this is in a constructor. + * @returns {boolean} `true` if this is in a constructor. + */ + function isInConstructorOfDerivedClass() { + return Boolean( + funcInfo && funcInfo.isConstructor && funcInfo.hasExtends, + ); + } + + /** + * Determines if every segment in a set has been called. + * @param {Set} segments The segments to search. + * @returns {boolean} True if every segment has been called; false otherwise. + */ + function isEverySegmentCalled(segments) { + for (const segment of segments) { + if (!isCalled(segment)) { + return false; + } + } + + return true; + } + + /** + * Checks whether or not this is before `super()` is called. + * @returns {boolean} `true` if this is before `super()` is called. + */ + function isBeforeCallOfSuper() { + return ( + isInConstructorOfDerivedClass() && + !isEverySegmentCalled(funcInfo.currentSegments) + ); + } + + /** + * Sets a given node as invalid. + * @param {ASTNode} node A node to set as invalid. This is one of + * a ThisExpression and a Super. + * @returns {void} + */ + function setInvalid(node) { + const segments = funcInfo.currentSegments; + + for (const segment of segments) { + if (segment.reachable) { + segInfoMap[segment.id].invalidNodes.push(node); + } + } + } + + /** + * Sets the current segment as `super` was called. + * @returns {void} + */ + function setSuperCalled() { + const segments = funcInfo.currentSegments; + + for (const segment of segments) { + if (segment.reachable) { + segInfoMap[segment.id].superCalled = true; + } + } + } + + return { + /** + * Adds information of a constructor into the stack. + * @param {CodePath} codePath A code path which was started. + * @param {ASTNode} node The current node. + * @returns {void} + */ + onCodePathStart(codePath, node) { + if (isConstructorFunction(node)) { + // Class > ClassBody > MethodDefinition > FunctionExpression + const classNode = node.parent.parent.parent; + + funcInfo = { + upper: funcInfo, + isConstructor: true, + hasExtends: Boolean( + classNode.superClass && + !astUtils.isNullOrUndefined(classNode.superClass), + ), + codePath, + currentSegments: new Set(), + }; + } else { + funcInfo = { + upper: funcInfo, + isConstructor: false, + hasExtends: false, + codePath, + currentSegments: new Set(), + }; + } + }, + + /** + * Removes the top of stack item. + * + * And this traverses all segments of this code path then reports every + * invalid node. + * @param {CodePath} codePath A code path which was ended. + * @returns {void} + */ + onCodePathEnd(codePath) { + const isDerivedClass = funcInfo.hasExtends; + + funcInfo = funcInfo.upper; + if (!isDerivedClass) { + return; + } + + /** + * A collection of nodes to avoid duplicate reports. + * @type {Set} + */ + const reported = new Set(); + + codePath.traverseSegments((segment, controller) => { + const info = segInfoMap[segment.id]; + const invalidNodes = info.invalidNodes.filter( + /* + * Avoid duplicate reports. + * When there is a `finally`, invalidNodes may contain already reported node. + */ + node => !reported.has(node), + ); + + for (const invalidNode of invalidNodes) { + reported.add(invalidNode); + + context.report({ + messageId: "noBeforeSuper", + node: invalidNode, + data: { + kind: + invalidNode.type === "Super" + ? "super" + : "this", + }, + }); + } + + if (info.superCalled) { + controller.skip(); + } + }); + }, + + /** + * Initialize information of a given code path segment. + * @param {CodePathSegment} segment A code path segment to initialize. + * @returns {void} + */ + onCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + + if (!isInConstructorOfDerivedClass()) { + return; + } + + // Initialize info. + segInfoMap[segment.id] = { + superCalled: + segment.prevSegments.length > 0 && + segment.prevSegments.every(isCalled), + invalidNodes: [], + }; + }, + + onUnreachableCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + /** + * Update information of the code path segment when a code path was + * looped. + * @param {CodePathSegment} fromSegment The code path segment of the + * end of a loop. + * @param {CodePathSegment} toSegment A code path segment of the head + * of a loop. + * @returns {void} + */ + onCodePathSegmentLoop(fromSegment, toSegment) { + if (!isInConstructorOfDerivedClass()) { + return; + } + + // Update information inside of the loop. + funcInfo.codePath.traverseSegments( + { first: toSegment, last: fromSegment }, + (segment, controller) => { + const info = + segInfoMap[segment.id] ?? new SegmentInfo(); + + if (info.superCalled) { + controller.skip(); + } else if ( + segment.prevSegments.length > 0 && + segment.prevSegments.every(isCalled) + ) { + info.superCalled = true; + } + + segInfoMap[segment.id] = info; + }, + ); + }, + + /** + * Reports if this is before `super()`. + * @param {ASTNode} node A target node. + * @returns {void} + */ + ThisExpression(node) { + if (isBeforeCallOfSuper()) { + setInvalid(node); + } + }, + + /** + * Reports if this is before `super()`. + * @param {ASTNode} node A target node. + * @returns {void} + */ + Super(node) { + if (!astUtils.isCallee(node) && isBeforeCallOfSuper()) { + setInvalid(node); + } + }, + + /** + * Marks `super()` called. + * @param {ASTNode} node A target node. + * @returns {void} + */ + "CallExpression:exit"(node) { + if (node.callee.type === "Super" && isBeforeCallOfSuper()) { + setSuperCalled(); + } + }, + + /** + * Resets state. + * @returns {void} + */ + "Program:exit"() { + segInfoMap = Object.create(null); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-throw-literal.js b/node_modules/eslint/lib/rules/no-throw-literal.js new file mode 100644 index 0000000000000000000000000000000000000000..877224be1a723f7cc4e8011a5e9a59bf13fa4047 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-throw-literal.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Rule to restrict what can be thrown as an exception. + * @author Dieter Oberkofler + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow throwing literals as exceptions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-throw-literal", + }, + + schema: [], + + messages: { + object: "Expected an error object to be thrown.", + undef: "Do not throw undefined.", + }, + }, + + create(context) { + return { + ThrowStatement(node) { + if (!astUtils.couldBeError(node.argument)) { + context.report({ node, messageId: "object" }); + } else if (node.argument.type === "Identifier") { + if (node.argument.name === "undefined") { + context.report({ node, messageId: "undef" }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-trailing-spaces.js b/node_modules/eslint/lib/rules/no-trailing-spaces.js new file mode 100644 index 0000000000000000000000000000000000000000..14c66db4ae377cf6bf7c522576dfa30676291efa --- /dev/null +++ b/node_modules/eslint/lib/rules/no-trailing-spaces.js @@ -0,0 +1,227 @@ +/** + * @fileoverview Disallow trailing spaces at the end of lines. + * @author Nodeca Team + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @import { SourceLocation, SourceRange } from "@eslint/core"; + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "no-trailing-spaces", + url: "https://eslint.style/rules/no-trailing-spaces", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow trailing whitespace at the end of lines", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-trailing-spaces", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + skipBlankLines: { + type: "boolean", + default: false, + }, + ignoreComments: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + trailingSpace: "Trailing spaces not allowed.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const BLANK_CLASS = + "[ \t\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u3000]", + SKIP_BLANK = `^${BLANK_CLASS}*$`, + NONBLANK = `${BLANK_CLASS}+$`; + + const options = context.options[0] || {}, + skipBlankLines = options.skipBlankLines || false, + ignoreComments = options.ignoreComments || false; + + /** + * Report the error message + * @param {ASTNode} node node to report + * @param {SourceLocation} location range information + * @param {SourceRange} fixRange Range based on the whole program + * @returns {void} + */ + function report(node, location, fixRange) { + /* + * Passing node is a bit dirty, because message data will contain big + * text in `source`. But... who cares :) ? + * One more kludge will not make worse the bloody wizardry of this + * plugin. + */ + context.report({ + node, + loc: location, + messageId: "trailingSpace", + fix(fixer) { + return fixer.removeRange(fixRange); + }, + }); + } + + /** + * Given a list of comment nodes, return the line numbers for those comments. + * @param {Array} comments An array of comment nodes. + * @returns {number[]} An array of line numbers containing comments. + */ + function getCommentLineNumbers(comments) { + const lines = new Set(); + + comments.forEach(comment => { + const endLine = + comment.type === "Block" + ? comment.loc.end.line - 1 + : comment.loc.end.line; + + for (let i = comment.loc.start.line; i <= endLine; i++) { + lines.add(i); + } + }); + + return lines; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkTrailingSpaces(node) { + /* + * Let's hack. Since Espree does not return whitespace nodes, + * fetch the source code and do matching via regexps. + */ + + const re = new RegExp(NONBLANK, "u"), + skipMatch = new RegExp(SKIP_BLANK, "u"), + lines = sourceCode.lines, + linebreaks = sourceCode + .getText() + .match(astUtils.createGlobalLinebreakMatcher()), + comments = sourceCode.getAllComments(), + commentLineNumbers = getCommentLineNumbers(comments); + + let totalLength = 0; + + for (let i = 0, ii = lines.length; i < ii; i++) { + const lineNumber = i + 1; + + /* + * Always add linebreak length to line length to accommodate for line break (\n or \r\n) + * Because during the fix time they also reserve one spot in the array. + * Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF) + */ + const linebreakLength = + linebreaks && linebreaks[i] ? linebreaks[i].length : 1; + const lineLength = lines[i].length + linebreakLength; + + const matches = re.exec(lines[i]); + + if (matches) { + const location = { + start: { + line: lineNumber, + column: matches.index, + }, + end: { + line: lineNumber, + column: lineLength - linebreakLength, + }, + }; + + const rangeStart = totalLength + location.start.column; + const rangeEnd = totalLength + location.end.column; + const containingNode = + sourceCode.getNodeByRangeIndex(rangeStart); + + if ( + containingNode && + containingNode.type === "TemplateElement" && + rangeStart > containingNode.parent.range[0] && + rangeEnd < containingNode.parent.range[1] + ) { + totalLength += lineLength; + continue; + } + + /* + * If the line has only whitespace, and skipBlankLines + * is true, don't report it + */ + if (skipBlankLines && skipMatch.test(lines[i])) { + totalLength += lineLength; + continue; + } + + const fixRange = [rangeStart, rangeEnd]; + + if ( + !ignoreComments || + !commentLineNumbers.has(lineNumber) + ) { + report(node, location, fixRange); + } + } + + totalLength += lineLength; + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unassigned-vars.js b/node_modules/eslint/lib/rules/no-unassigned-vars.js new file mode 100644 index 0000000000000000000000000000000000000000..24053b3f0c787a9f19e560dcf2e92f468fd7cf3a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unassigned-vars.js @@ -0,0 +1,79 @@ +/** + * @fileoverview Rule to flag variables that are never assigned + * @author Jacob Bandes-Storch + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow `let` or `var` variables that are read but never assigned", + dialects: ["JavaScript", "TypeScript"], + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unassigned-vars", + }, + + schema: [], + messages: { + unassigned: + "'{{name}}' is always 'undefined' because it's never assigned.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + let insideDeclareModule = false; + + return { + "TSModuleDeclaration[declare=true]"() { + insideDeclareModule = true; + }, + "TSModuleDeclaration[declare=true]:exit"() { + insideDeclareModule = false; + }, + VariableDeclarator(node) { + /** @type {import('estree').VariableDeclaration} */ + const declaration = node.parent; + const shouldSkip = + node.init || + node.id.type !== "Identifier" || + declaration.kind === "const" || + declaration.declare || + insideDeclareModule; + if (shouldSkip) { + return; + } + const [variable] = sourceCode.getDeclaredVariables(node); + if (!variable) { + return; + } + let hasRead = false; + for (const reference of variable.references) { + if (reference.isWrite()) { + return; + } + if (reference.isRead()) { + hasRead = true; + } + } + if (!hasRead) { + // Variables that are never read should be flagged by no-unused-vars instead + return; + } + context.report({ + node, + messageId: "unassigned", + data: { name: node.id.name }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-undef-init.js b/node_modules/eslint/lib/rules/no-undef-init.js new file mode 100644 index 0000000000000000000000000000000000000000..77a120043e2c7c9bae5d219acc5885aa11e27b14 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-undef-init.js @@ -0,0 +1,101 @@ +/** + * @fileoverview Rule to flag when initializing to undefined + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const CONSTANT_BINDINGS = new Set(["const", "using", "await using"]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow initializing variables to `undefined`", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-undef-init", + }, + + schema: [], + fixable: "code", + + messages: { + unnecessaryUndefinedInit: + "It's not necessary to initialize '{{name}}' to undefined.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + VariableDeclarator(node) { + const name = sourceCode.getText(node.id), + init = node.init && node.init.name, + scope = sourceCode.getScope(node), + undefinedVar = astUtils.getVariableByName( + scope, + "undefined", + ), + shadowed = undefinedVar && undefinedVar.defs.length > 0, + lastToken = sourceCode.getLastToken(node); + + if ( + init === "undefined" && + !CONSTANT_BINDINGS.has(node.parent.kind) && + !shadowed + ) { + context.report({ + node, + messageId: "unnecessaryUndefinedInit", + data: { name }, + fix(fixer) { + if (node.parent.kind === "var") { + return null; + } + + if ( + node.id.type === "ArrayPattern" || + node.id.type === "ObjectPattern" + ) { + // Don't fix destructuring assignment to `undefined`. + return null; + } + + if ( + sourceCode.commentsExistBetween( + node.id, + lastToken, + ) + ) { + return null; + } + + return fixer.removeRange([ + node.id.range[1], + node.range[1], + ]); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-undef.js b/node_modules/eslint/lib/rules/no-undef.js new file mode 100644 index 0000000000000000000000000000000000000000..fbda877330743a65d7c55438dbbafd247d21f155 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-undef.js @@ -0,0 +1,84 @@ +/** + * @fileoverview Rule to flag references to undeclared variables. + * @author Mark Macdonald + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks if the given node is the argument of a typeof operator. + * @param {ASTNode} node The AST node being checked. + * @returns {boolean} Whether or not the node is the argument of a typeof operator. + */ +function hasTypeOfOperator(node) { + const parent = node.parent; + + return parent.type === "UnaryExpression" && parent.operator === "typeof"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + typeof: false, + }, + ], + + docs: { + description: + "Disallow the use of undeclared variables unless mentioned in `/*global */` comments", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-undef", + }, + + schema: [ + { + type: "object", + properties: { + typeof: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + messages: { + undef: "'{{name}}' is not defined.", + }, + }, + + create(context) { + const [{ typeof: considerTypeOf }] = context.options; + const sourceCode = context.sourceCode; + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + globalScope.through.forEach(ref => { + const identifier = ref.identifier; + + if (!considerTypeOf && hasTypeOfOperator(identifier)) { + return; + } + + context.report({ + node: identifier, + messageId: "undef", + data: identifier, + }); + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-undefined.js b/node_modules/eslint/lib/rules/no-undefined.js new file mode 100644 index 0000000000000000000000000000000000000000..e728e19901ef17e4f1f1efc17d07baac224fb177 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-undefined.js @@ -0,0 +1,91 @@ +/** + * @fileoverview Rule to flag references to the undefined variable. + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Scope} Scope */ + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow the use of `undefined` as an identifier", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-undefined", + }, + + schema: [], + + messages: { + unexpectedUndefined: "Unexpected use of undefined.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Report an invalid "undefined" identifier node. + * @param {ASTNode} node The node to report. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "unexpectedUndefined", + }); + } + + /** + * Checks the given scope for references to `undefined` and reports + * all references found. + * @param {Scope} scope The scope to check. + * @returns {void} + */ + function checkScope(scope) { + const undefinedVar = scope.set.get("undefined"); + + if (!undefinedVar) { + return; + } + + const references = undefinedVar.references; + + const defs = undefinedVar.defs; + + // Report non-initializing references (those are covered in defs below) + references + .filter(ref => !ref.init) + .forEach(ref => report(ref.identifier)); + + defs.forEach(def => report(def.name)); + } + + return { + "Program:exit"(node) { + const globalScope = sourceCode.getScope(node); + + const stack = [globalScope]; + + while (stack.length) { + const scope = stack.pop(); + + stack.push(...scope.childScopes); + checkScope(scope); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-underscore-dangle.js b/node_modules/eslint/lib/rules/no-underscore-dangle.js new file mode 100644 index 0000000000000000000000000000000000000000..24b7237098832943ec1e6e1dd7e98b301363e3f1 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-underscore-dangle.js @@ -0,0 +1,383 @@ +/** + * @fileoverview Rule to flag dangling underscores in variable declarations. + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allow: [], + allowAfterSuper: false, + allowAfterThis: false, + allowAfterThisConstructor: false, + allowFunctionParams: true, + allowInArrayDestructuring: true, + allowInObjectDestructuring: true, + enforceInClassFields: false, + enforceInMethodNames: false, + }, + ], + + docs: { + description: "Disallow dangling underscores in identifiers", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-underscore-dangle", + }, + + schema: [ + { + type: "object", + properties: { + allow: { + type: "array", + items: { + type: "string", + }, + }, + allowAfterThis: { + type: "boolean", + }, + allowAfterSuper: { + type: "boolean", + }, + allowAfterThisConstructor: { + type: "boolean", + }, + enforceInMethodNames: { + type: "boolean", + }, + allowFunctionParams: { + type: "boolean", + }, + enforceInClassFields: { + type: "boolean", + }, + allowInArrayDestructuring: { + type: "boolean", + }, + allowInObjectDestructuring: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedUnderscore: + "Unexpected dangling '_' in '{{identifier}}'.", + }, + }, + + create(context) { + const [ + { + allow, + allowAfterSuper, + allowAfterThis, + allowAfterThisConstructor, + allowFunctionParams, + allowInArrayDestructuring, + allowInObjectDestructuring, + enforceInClassFields, + enforceInMethodNames, + }, + ] = context.options; + const sourceCode = context.sourceCode; + + //------------------------------------------------------------------------- + // Helpers + //------------------------------------------------------------------------- + + /** + * Check if identifier is present inside the allowed option + * @param {string} identifier name of the node + * @returns {boolean} true if its is present + * @private + */ + function isAllowed(identifier) { + return allow.includes(identifier); + } + + /** + * Check if identifier has a dangling underscore + * @param {string} identifier name of the node + * @returns {boolean} true if its is present + * @private + */ + function hasDanglingUnderscore(identifier) { + const len = identifier.length; + + return ( + identifier !== "_" && + (identifier[0] === "_" || identifier[len - 1] === "_") + ); + } + + /** + * Check if identifier is a special case member expression + * @param {string} identifier name of the node + * @returns {boolean} true if its is a special case + * @private + */ + function isSpecialCaseIdentifierForMemberExpression(identifier) { + return identifier === "__proto__"; + } + + /** + * Check if identifier is a special case variable expression + * @param {string} identifier name of the node + * @returns {boolean} true if its is a special case + * @private + */ + function isSpecialCaseIdentifierInVariableExpression(identifier) { + // Checks for the underscore library usage here + return identifier === "_"; + } + + /** + * Check if a node is a member reference of this.constructor + * @param {ASTNode} node node to evaluate + * @returns {boolean} true if it is a reference on this.constructor + * @private + */ + function isThisConstructorReference(node) { + return ( + node.object.type === "MemberExpression" && + node.object.property.name === "constructor" && + node.object.object.type === "ThisExpression" + ); + } + + /** + * Check if function parameter has a dangling underscore. + * @param {ASTNode} node function node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInFunctionParameters(node) { + if (!allowFunctionParams) { + node.params.forEach(param => { + const { type } = param; + let nodeToCheck; + + if (type === "RestElement") { + nodeToCheck = param.argument; + } else if (type === "AssignmentPattern") { + nodeToCheck = param.left; + } else { + nodeToCheck = param; + } + + if (nodeToCheck.type === "Identifier") { + const identifier = nodeToCheck.name; + + if ( + hasDanglingUnderscore(identifier) && + !isAllowed(identifier) + ) { + context.report({ + node: param, + messageId: "unexpectedUnderscore", + data: { + identifier, + }, + }); + } + } + }); + } + } + + /** + * Check if function has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInFunction(node) { + if (node.type === "FunctionDeclaration" && node.id) { + const identifier = node.id.name; + + if ( + typeof identifier !== "undefined" && + hasDanglingUnderscore(identifier) && + !isAllowed(identifier) + ) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier, + }, + }); + } + } + checkForDanglingUnderscoreInFunctionParameters(node); + } + + /** + * Check if variable expression has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInVariableExpression(node) { + sourceCode.getDeclaredVariables(node).forEach(variable => { + const definition = variable.defs.find(def => def.node === node); + const identifierNode = definition.name; + const identifier = identifierNode.name; + let parent = identifierNode.parent; + + while ( + ![ + "VariableDeclarator", + "ArrayPattern", + "ObjectPattern", + ].includes(parent.type) + ) { + parent = parent.parent; + } + + if ( + hasDanglingUnderscore(identifier) && + !isSpecialCaseIdentifierInVariableExpression(identifier) && + !isAllowed(identifier) && + !( + allowInArrayDestructuring && + parent.type === "ArrayPattern" + ) && + !( + allowInObjectDestructuring && + parent.type === "ObjectPattern" + ) + ) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier, + }, + }); + } + }); + } + + /** + * Check if member expression has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInMemberExpression(node) { + const identifier = node.property.name, + isMemberOfThis = node.object.type === "ThisExpression", + isMemberOfSuper = node.object.type === "Super", + isMemberOfThisConstructor = isThisConstructorReference(node); + + if ( + typeof identifier !== "undefined" && + hasDanglingUnderscore(identifier) && + !(isMemberOfThis && allowAfterThis) && + !(isMemberOfSuper && allowAfterSuper) && + !(isMemberOfThisConstructor && allowAfterThisConstructor) && + !isSpecialCaseIdentifierForMemberExpression(identifier) && + !isAllowed(identifier) + ) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier, + }, + }); + } + } + + /** + * Check if method declaration or method property has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInMethod(node) { + const identifier = node.key.name; + const isMethod = + node.type === "MethodDefinition" || + (node.type === "Property" && node.method); + + if ( + typeof identifier !== "undefined" && + enforceInMethodNames && + isMethod && + hasDanglingUnderscore(identifier) && + !isAllowed(identifier) + ) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier: + node.key.type === "PrivateIdentifier" + ? `#${identifier}` + : identifier, + }, + }); + } + } + + /** + * Check if a class field has a dangling underscore + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkForDanglingUnderscoreInClassField(node) { + const identifier = node.key.name; + + if ( + typeof identifier !== "undefined" && + hasDanglingUnderscore(identifier) && + enforceInClassFields && + !isAllowed(identifier) + ) { + context.report({ + node, + messageId: "unexpectedUnderscore", + data: { + identifier: + node.key.type === "PrivateIdentifier" + ? `#${identifier}` + : identifier, + }, + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + FunctionDeclaration: checkForDanglingUnderscoreInFunction, + VariableDeclarator: checkForDanglingUnderscoreInVariableExpression, + MemberExpression: checkForDanglingUnderscoreInMemberExpression, + MethodDefinition: checkForDanglingUnderscoreInMethod, + PropertyDefinition: checkForDanglingUnderscoreInClassField, + Property: checkForDanglingUnderscoreInMethod, + FunctionExpression: checkForDanglingUnderscoreInFunction, + ArrowFunctionExpression: checkForDanglingUnderscoreInFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unexpected-multiline.js b/node_modules/eslint/lib/rules/no-unexpected-multiline.js new file mode 100644 index 0000000000000000000000000000000000000000..0e91cdca8e7b807683a0292432e2db5fe7e6b50f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unexpected-multiline.js @@ -0,0 +1,130 @@ +/** + * @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not. + * @author Glen Mailer + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow confusing multiline expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unexpected-multiline", + }, + + schema: [], + messages: { + function: + "Unexpected newline between function and ( of function call.", + property: + "Unexpected newline between object and [ of property access.", + taggedTemplate: + "Unexpected newline between template tag and template literal.", + division: + "Unexpected newline between numerator and division operator.", + }, + }, + + create(context) { + const REGEX_FLAG_MATCHER = /^[gimsuy]+$/u; + + const sourceCode = context.sourceCode; + + /** + * Check to see if there is a newline between the node and the following open bracket + * line's expression + * @param {ASTNode} node The node to check. + * @param {string} messageId The error messageId to use. + * @returns {void} + * @private + */ + function checkForBreakAfter(node, messageId) { + const openParen = sourceCode.getTokenAfter( + node, + astUtils.isNotClosingParenToken, + ); + const nodeExpressionEnd = sourceCode.getTokenBefore(openParen); + + if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) { + context.report({ + node, + loc: openParen.loc, + messageId, + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + MemberExpression(node) { + if (!node.computed || node.optional) { + return; + } + checkForBreakAfter(node.object, "property"); + }, + + TaggedTemplateExpression(node) { + const { quasi } = node; + + // handles common tags, parenthesized tags, and typescript's generic type arguments + const tokenBefore = sourceCode.getTokenBefore(quasi); + + if (tokenBefore.loc.end.line !== quasi.loc.start.line) { + context.report({ + node, + loc: { + start: quasi.loc.start, + end: { + line: quasi.loc.start.line, + column: quasi.loc.start.column + 1, + }, + }, + messageId: "taggedTemplate", + }); + } + }, + + CallExpression(node) { + if (node.arguments.length === 0 || node.optional) { + return; + } + checkForBreakAfter(node.callee, "function"); + }, + + "BinaryExpression[operator='/'] > BinaryExpression[operator='/'].left"( + node, + ) { + const secondSlash = sourceCode.getTokenAfter( + node, + token => token.value === "/", + ); + const tokenAfterOperator = + sourceCode.getTokenAfter(secondSlash); + + if ( + tokenAfterOperator.type === "Identifier" && + REGEX_FLAG_MATCHER.test(tokenAfterOperator.value) && + secondSlash.range[1] === tokenAfterOperator.range[0] + ) { + checkForBreakAfter(node.left, "division"); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js b/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js new file mode 100644 index 0000000000000000000000000000000000000000..a159889a719ffd998f568ca0e3de6bbfc43402aa --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js @@ -0,0 +1,378 @@ +/** + * @fileoverview Rule to disallow use of unmodified expressions in loop conditions + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Traverser = require("../shared/traverser"), + astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Variable} Variable */ +/** @typedef {import("eslint-scope").Reference} Reference */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_PATTERN = + /(?:(?:Call|Class|Function|Member|New|Yield)Expression|Statement|Declaration)$/u; +const LOOP_PATTERN = /^(?:DoWhile|For|While)Statement$/u; // for-in/of statements don't have `test` property. +const GROUP_PATTERN = /^(?:BinaryExpression|ConditionalExpression)$/u; +const SKIP_PATTERN = /^(?:ArrowFunction|Class|Function)Expression$/u; +const DYNAMIC_PATTERN = /^(?:Call|Member|New|TaggedTemplate|Yield)Expression$/u; + +/** + * @typedef {Object} LoopConditionInfo + * @property {Reference} reference - The reference. + * @property {ASTNode} group - BinaryExpression or ConditionalExpression nodes + * that the reference is belonging to. + * @property {Function} isInLoop - The predicate which checks a given reference + * is in this loop. + * @property {boolean} modified - The flag that the reference is modified in + * this loop. + */ + +/** + * Checks whether or not a given reference is a write reference. + * @param {Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is a write reference. + */ +function isWriteReference(reference) { + if (reference.init) { + const def = reference.resolved && reference.resolved.defs[0]; + + if (!def || def.type !== "Variable" || def.parent.kind !== "var") { + return false; + } + } + return reference.isWrite(); +} + +/** + * Checks whether or not a given loop condition info does not have the modified + * flag. + * @param {LoopConditionInfo} condition A loop condition info to check. + * @returns {boolean} `true` if the loop condition info is "unmodified". + */ +function isUnmodified(condition) { + return !condition.modified; +} + +/** + * Checks whether or not a given loop condition info does not have the modified + * flag and does not have the group this condition belongs to. + * @param {LoopConditionInfo} condition A loop condition info to check. + * @returns {boolean} `true` if the loop condition info is "unmodified". + */ +function isUnmodifiedAndNotBelongToGroup(condition) { + return !(condition.modified || condition.group); +} + +/** + * Checks whether or not a given reference is inside of a given node. + * @param {ASTNode} node A node to check. + * @param {Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is inside of the node. + */ +function isInRange(node, reference) { + const or = node.range; + const ir = reference.identifier.range; + + return or[0] <= ir[0] && ir[1] <= or[1]; +} + +/** + * Checks whether or not a given reference is inside of a loop node's condition. + * @param {ASTNode} node A node to check. + * @param {Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is inside of the loop node's + * condition. + */ +const isInLoop = { + WhileStatement: isInRange, + DoWhileStatement: isInRange, + ForStatement(node, reference) { + return ( + isInRange(node, reference) && + !(node.init && isInRange(node.init, reference)) + ); + }, +}; + +/** + * Gets the function which encloses a given reference. + * This supports only FunctionDeclaration. + * @param {Reference} reference A reference to get. + * @returns {ASTNode|null} The function node or null. + */ +function getEncloseFunctionDeclaration(reference) { + let node = reference.identifier; + + while (node) { + if (node.type === "FunctionDeclaration") { + return node.id ? node : null; + } + + node = node.parent; + } + + return null; +} + +/** + * Checks whether a given modifier is in a loop. + * + * Besides checking for the condition being in the loop, this also checks + * whether the function that this modifier is belonging to is called + * in the loop. + * @param {LoopConditionInfo} condition The condition to check. + * @param {Reference} modifier The modifier to check. + * @returns {boolean} `true` if the modifier is in a loop. + */ +function hasModifierInLoop(condition, modifier) { + if (condition.isInLoop(modifier)) { + return true; + } + + const funcNode = getEncloseFunctionDeclaration(modifier); + + if (!funcNode) { + return false; + } + + const funcVar = astUtils.getVariableByName( + modifier.from.upper, + funcNode.id.name, + ); + + return Boolean(funcVar && funcVar.references.some(condition.isInLoop)); +} + +/** + * Updates the "modified" flags of given loop conditions with given modifiers. + * @param {LoopConditionInfo[]} conditions The loop conditions to be updated. + * @param {Reference[]} modifiers The references to update. + * @returns {void} + */ +function updateModifiedFlag(conditions, modifiers) { + for (let i = 0; i < conditions.length; ++i) { + const condition = conditions[i]; + + for (let j = 0; !condition.modified && j < modifiers.length; ++j) { + const modifier = modifiers[j]; + + condition.modified = hasModifierInLoop(condition, modifier); + } + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow unmodified loop conditions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unmodified-loop-condition", + }, + + schema: [], + + messages: { + loopConditionNotModified: + "'{{name}}' is not modified in this loop.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + let groupMap = null; + + /** + * Reports a given condition info. + * @param {LoopConditionInfo} condition A loop condition info to report. + * @returns {void} + */ + function report(condition) { + const node = condition.reference.identifier; + + context.report({ + node, + messageId: "loopConditionNotModified", + data: node, + }); + } + + /** + * Registers given conditions to the group the condition belongs to. + * @param {LoopConditionInfo[]} conditions A loop condition info to + * register. + * @returns {void} + */ + function registerConditionsToGroup(conditions) { + for (let i = 0; i < conditions.length; ++i) { + const condition = conditions[i]; + + if (condition.group) { + let group = groupMap.get(condition.group); + + if (!group) { + group = []; + groupMap.set(condition.group, group); + } + group.push(condition); + } + } + } + + /** + * Reports references which are inside of unmodified groups. + * @param {LoopConditionInfo[]} conditions A loop condition info to report. + * @returns {void} + */ + function checkConditionsInGroup(conditions) { + if (conditions.every(isUnmodified)) { + conditions.forEach(report); + } + } + + /** + * Checks whether or not a given group node has any dynamic elements. + * @param {ASTNode} root A node to check. + * This node is one of BinaryExpression or ConditionalExpression. + * @returns {boolean} `true` if the node is dynamic. + */ + function hasDynamicExpressions(root) { + let retv = false; + + Traverser.traverse(root, { + visitorKeys: sourceCode.visitorKeys, + enter(node) { + if (DYNAMIC_PATTERN.test(node.type)) { + retv = true; + this.break(); + } else if (SKIP_PATTERN.test(node.type)) { + this.skip(); + } + }, + }); + + return retv; + } + + /** + * Creates the loop condition information from a given reference. + * @param {Reference} reference A reference to create. + * @returns {LoopConditionInfo|null} Created loop condition info, or null. + */ + function toLoopCondition(reference) { + if (reference.init) { + return null; + } + + let group = null; + let child = reference.identifier; + let node = child.parent; + + while (node) { + if (SENTINEL_PATTERN.test(node.type)) { + if (LOOP_PATTERN.test(node.type) && node.test === child) { + // This reference is inside of a loop condition. + return { + reference, + group, + isInLoop: isInLoop[node.type].bind(null, node), + modified: false, + }; + } + + // This reference is outside of a loop condition. + break; + } + + /* + * If it's inside of a group, OK if either operand is modified. + * So stores the group this reference belongs to. + */ + if (GROUP_PATTERN.test(node.type)) { + // If this expression is dynamic, no need to check. + if (hasDynamicExpressions(node)) { + break; + } else { + group = node; + } + } + + child = node; + node = node.parent; + } + + return null; + } + + /** + * Finds unmodified references which are inside of a loop condition. + * Then reports the references which are outside of groups. + * @param {Variable} variable A variable to report. + * @returns {void} + */ + function checkReferences(variable) { + // Gets references that exist in loop conditions. + const conditions = variable.references + .map(toLoopCondition) + .filter(Boolean); + + if (conditions.length === 0) { + return; + } + + // Registers the conditions to belonging groups. + registerConditionsToGroup(conditions); + + // Check the conditions are modified. + const modifiers = variable.references.filter(isWriteReference); + + if (modifiers.length > 0) { + updateModifiedFlag(conditions, modifiers); + } + + /* + * Reports the conditions which are not belonging to groups. + * Others will be reported after all variables are done. + */ + conditions.filter(isUnmodifiedAndNotBelongToGroup).forEach(report); + } + + return { + "Program:exit"(node) { + const queue = [sourceCode.getScope(node)]; + + groupMap = new Map(); + + let scope; + + while ((scope = queue.pop())) { + queue.push(...scope.childScopes); + scope.variables.forEach(checkReferences); + } + + groupMap.forEach(checkConditionsInGroup); + groupMap = null; + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unneeded-ternary.js b/node_modules/eslint/lib/rules/no-unneeded-ternary.js new file mode 100644 index 0000000000000000000000000000000000000000..24e65b67e1db7cf080eabcc9661aad37b0a69d81 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unneeded-ternary.js @@ -0,0 +1,232 @@ +/** + * @fileoverview Rule to flag no-unneeded-ternary + * @author Gyandeep Singh + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +// Operators that always result in a boolean value +const BOOLEAN_OPERATORS = new Set([ + "==", + "===", + "!=", + "!==", + ">", + ">=", + "<", + "<=", + "in", + "instanceof", +]); +const OPERATOR_INVERSES = { + "==": "!=", + "!=": "==", + "===": "!==", + "!==": "===", + + // Operators like < and >= are not true inverses, since both will return false with NaN. +}; +const OR_PRECEDENCE = astUtils.getPrecedence({ + type: "LogicalExpression", + operator: "||", +}); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{ defaultAssignment: true }], + + docs: { + description: + "Disallow ternary operators when simpler alternatives exist", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-unneeded-ternary", + }, + + schema: [ + { + type: "object", + properties: { + defaultAssignment: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + unnecessaryConditionalExpression: + "Unnecessary use of boolean literals in conditional expression.", + unnecessaryConditionalAssignment: + "Unnecessary use of conditional expression for default assignment.", + }, + }, + + create(context) { + const [{ defaultAssignment }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Test if the node is a boolean literal + * @param {ASTNode} node The node to report. + * @returns {boolean} True if the its a boolean literal + * @private + */ + function isBooleanLiteral(node) { + return node.type === "Literal" && typeof node.value === "boolean"; + } + + /** + * Creates an expression that represents the boolean inverse of the expression represented by the original node + * @param {ASTNode} node A node representing an expression + * @returns {string} A string representing an inverted expression + */ + function invertExpression(node) { + if ( + node.type === "BinaryExpression" && + Object.hasOwn(OPERATOR_INVERSES, node.operator) + ) { + const operatorToken = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + const text = sourceCode.getText(); + + return ( + text.slice(node.range[0], operatorToken.range[0]) + + OPERATOR_INVERSES[node.operator] + + text.slice(operatorToken.range[1], node.range[1]) + ); + } + + if ( + astUtils.getPrecedence(node) < + astUtils.getPrecedence({ type: "UnaryExpression" }) + ) { + return `!(${astUtils.getParenthesisedText(sourceCode, node)})`; + } + return `!${astUtils.getParenthesisedText(sourceCode, node)}`; + } + + /** + * Tests if a given node always evaluates to a boolean value + * @param {ASTNode} node An expression node + * @returns {boolean} True if it is determined that the node will always evaluate to a boolean value + */ + function isBooleanExpression(node) { + return ( + (node.type === "BinaryExpression" && + BOOLEAN_OPERATORS.has(node.operator)) || + (node.type === "UnaryExpression" && node.operator === "!") + ); + } + + /** + * Test if the node matches the pattern id ? id : expression + * @param {ASTNode} node The ConditionalExpression to check. + * @returns {boolean} True if the pattern is matched, and false otherwise + * @private + */ + function matchesDefaultAssignment(node) { + return ( + node.test.type === "Identifier" && + node.consequent.type === "Identifier" && + node.test.name === node.consequent.name + ); + } + + return { + ConditionalExpression(node) { + if ( + isBooleanLiteral(node.alternate) && + isBooleanLiteral(node.consequent) + ) { + context.report({ + node, + messageId: "unnecessaryConditionalExpression", + fix(fixer) { + if ( + node.consequent.value === node.alternate.value + ) { + // Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true` + return node.test.type === "Identifier" + ? fixer.replaceText( + node, + node.consequent.value.toString(), + ) + : null; + } + if (node.alternate.value) { + // Replace `foo() ? false : true` with `!(foo())` + return fixer.replaceText( + node, + invertExpression(node.test), + ); + } + + // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise. + + return fixer.replaceText( + node, + isBooleanExpression(node.test) + ? astUtils.getParenthesisedText( + sourceCode, + node.test, + ) + : `!${invertExpression(node.test)}`, + ); + }, + }); + } else if ( + !defaultAssignment && + matchesDefaultAssignment(node) + ) { + context.report({ + node, + messageId: "unnecessaryConditionalAssignment", + fix(fixer) { + const shouldParenthesizeAlternate = + (astUtils.getPrecedence(node.alternate) < + OR_PRECEDENCE || + astUtils.isCoalesceExpression( + node.alternate, + )) && + !astUtils.isParenthesised( + sourceCode, + node.alternate, + ); + const alternateText = shouldParenthesizeAlternate + ? `(${sourceCode.getText(node.alternate)})` + : astUtils.getParenthesisedText( + sourceCode, + node.alternate, + ); + const testText = astUtils.getParenthesisedText( + sourceCode, + node.test, + ); + + return fixer.replaceText( + node, + `${testText} || ${alternateText}`, + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unreachable-loop.js b/node_modules/eslint/lib/rules/no-unreachable-loop.js new file mode 100644 index 0000000000000000000000000000000000000000..200da8bd691f19a60f3a62d8f6770e32ddf930c4 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unreachable-loop.js @@ -0,0 +1,177 @@ +/** + * @fileoverview Rule to disallow loops with a body that allows only one iteration + * @author Milos Djermanovic + */ + +"use strict"; + +const { isAnySegmentReachable } = require("./utils/code-path-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const allLoopTypes = [ + "WhileStatement", + "DoWhileStatement", + "ForStatement", + "ForInStatement", + "ForOfStatement", +]; + +/** + * Determines whether the given node is the first node in the code path to which a loop statement + * 'loops' for the next iteration. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a looping target. + */ +function isLoopingTarget(node) { + const parent = node.parent; + + if (parent) { + switch (parent.type) { + case "WhileStatement": + return node === parent.test; + case "DoWhileStatement": + return node === parent.body; + case "ForStatement": + return node === (parent.update || parent.test || parent.body); + case "ForInStatement": + case "ForOfStatement": + return node === parent.left; + + // no default + } + } + + return false; +} + +/** + * Creates an array with elements from the first given array that are not included in the second given array. + * @param {Array} arrA The array to compare from. + * @param {Array} arrB The array to compare against. + * @returns {Array} a new array that represents `arrA \ arrB`. + */ +function getDifference(arrA, arrB) { + return arrA.filter(a => !arrB.includes(a)); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [{ ignore: [] }], + + docs: { + description: + "Disallow loops with a body that allows only one iteration", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unreachable-loop", + }, + + schema: [ + { + type: "object", + properties: { + ignore: { + type: "array", + items: { + enum: allLoopTypes, + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + invalid: "Invalid loop. Its body allows only one iteration.", + }, + }, + + create(context) { + const [{ ignore: ignoredLoopTypes }] = context.options; + const loopTypesToCheck = getDifference(allLoopTypes, ignoredLoopTypes), + loopSelector = loopTypesToCheck.join(","), + loopsByTargetSegments = new Map(), + loopsToReport = new Set(); + + const codePathSegments = []; + let currentCodePathSegments = new Set(); + + return { + onCodePathStart() { + codePathSegments.push(currentCodePathSegments); + currentCodePathSegments = new Set(); + }, + + onCodePathEnd() { + currentCodePathSegments = codePathSegments.pop(); + }, + + onUnreachableCodePathSegmentStart(segment) { + currentCodePathSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + onCodePathSegmentStart(segment, node) { + currentCodePathSegments.add(segment); + + if (isLoopingTarget(node)) { + const loop = node.parent; + + loopsByTargetSegments.set(segment, loop); + } + }, + + onCodePathSegmentLoop(_, toSegment, node) { + const loop = loopsByTargetSegments.get(toSegment); + + /** + * The second iteration is reachable, meaning that the loop is valid by the logic of this rule, + * only if there is at least one loop event with the appropriate target (which has been already + * determined in the `loopsByTargetSegments` map), raised from either: + * + * - the end of the loop's body (in which case `node === loop`) + * - a `continue` statement + * + * This condition skips loop events raised from `ForInStatement > .right` and `ForOfStatement > .right` nodes. + */ + if (node === loop || node.type === "ContinueStatement") { + // Removes loop if it exists in the set. Otherwise, `Set#delete` has no effect and doesn't throw. + loopsToReport.delete(loop); + } + }, + + [loopSelector](node) { + /** + * Ignore unreachable loop statements to avoid unnecessary complexity in the implementation, or false positives otherwise. + * For unreachable segments, the code path analysis does not raise events required for this implementation. + */ + if (isAnySegmentReachable(currentCodePathSegments)) { + loopsToReport.add(node); + } + }, + + "Program:exit"() { + loopsToReport.forEach(node => + context.report({ node, messageId: "invalid" }), + ); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unreachable.js b/node_modules/eslint/lib/rules/no-unreachable.js new file mode 100644 index 0000000000000000000000000000000000000000..32571a1f6f5a05028bbcd84c13ab14165587828e --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unreachable.js @@ -0,0 +1,291 @@ +/** + * @fileoverview Checks for unreachable code due to return, throws, break, and continue. + * @author Joel Feenstra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { isAnySegmentReachable } = require("./utils/code-path-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * @typedef {Object} ConstructorInfo + * @property {ConstructorInfo | null} upper Info about the constructor that encloses this constructor. + * @property {boolean} hasSuperCall The flag about having `super()` expressions. + */ + +/** + * Checks whether or not a given variable declarator has the initializer. + * @param {ASTNode} node A VariableDeclarator node to check. + * @returns {boolean} `true` if the node has the initializer. + */ +function isInitialized(node) { + return Boolean(node.init); +} + +/** + * The class to distinguish consecutive unreachable statements. + */ +class ConsecutiveRange { + constructor(sourceCode) { + this.sourceCode = sourceCode; + this.startNode = null; + this.endNode = null; + } + + /** + * The location object of this range. + * @type {Object} + */ + get location() { + return { + start: this.startNode.loc.start, + end: this.endNode.loc.end, + }; + } + + /** + * `true` if this range is empty. + * @type {boolean} + */ + get isEmpty() { + return !(this.startNode && this.endNode); + } + + /** + * Checks whether the given node is inside of this range. + * @param {ASTNode|Token} node The node to check. + * @returns {boolean} `true` if the node is inside of this range. + */ + contains(node) { + return ( + node.range[0] >= this.startNode.range[0] && + node.range[1] <= this.endNode.range[1] + ); + } + + /** + * Checks whether the given node is consecutive to this range. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is consecutive to this range. + */ + isConsecutive(node) { + return this.contains(this.sourceCode.getTokenBefore(node)); + } + + /** + * Merges the given node to this range. + * @param {ASTNode} node The node to merge. + * @returns {void} + */ + merge(node) { + this.endNode = node; + } + + /** + * Resets this range by the given node or null. + * @param {ASTNode|null} node The node to reset, or null. + * @returns {void} + */ + reset(node) { + this.startNode = this.endNode = node; + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow unreachable code after `return`, `throw`, `continue`, and `break` statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unreachable", + }, + + schema: [], + + messages: { + unreachableCode: "Unreachable code.", + }, + }, + + create(context) { + /** @type {ConstructorInfo | null} */ + let constructorInfo = null; + + /** @type {ConsecutiveRange} */ + const range = new ConsecutiveRange(context.sourceCode); + + /** @type {Array>} */ + const codePathSegments = []; + + /** @type {Set} */ + let currentCodePathSegments = new Set(); + + /** + * Reports a given node if it's unreachable. + * @param {ASTNode} node A statement node to report. + * @returns {void} + */ + function reportIfUnreachable(node) { + let nextNode = null; + + if ( + node && + (node.type === "PropertyDefinition" || + !isAnySegmentReachable(currentCodePathSegments)) + ) { + // Store this statement to distinguish consecutive statements. + if (range.isEmpty) { + range.reset(node); + return; + } + + // Skip if this statement is inside of the current range. + if (range.contains(node)) { + return; + } + + // Merge if this statement is consecutive to the current range. + if (range.isConsecutive(node)) { + range.merge(node); + return; + } + + nextNode = node; + } + + /* + * Report the current range since this statement is reachable or is + * not consecutive to the current range. + */ + if (!range.isEmpty) { + context.report({ + messageId: "unreachableCode", + loc: range.location, + node: range.startNode, + }); + } + + // Update the current range. + range.reset(nextNode); + } + + return { + // Manages the current code path. + onCodePathStart() { + codePathSegments.push(currentCodePathSegments); + currentCodePathSegments = new Set(); + }, + + onCodePathEnd() { + currentCodePathSegments = codePathSegments.pop(); + }, + + onUnreachableCodePathSegmentStart(segment) { + currentCodePathSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + currentCodePathSegments.delete(segment); + }, + + onCodePathSegmentStart(segment) { + currentCodePathSegments.add(segment); + }, + + // Registers for all statement nodes (excludes FunctionDeclaration). + BlockStatement: reportIfUnreachable, + BreakStatement: reportIfUnreachable, + ClassDeclaration: reportIfUnreachable, + ContinueStatement: reportIfUnreachable, + DebuggerStatement: reportIfUnreachable, + DoWhileStatement: reportIfUnreachable, + ExpressionStatement: reportIfUnreachable, + ForInStatement: reportIfUnreachable, + ForOfStatement: reportIfUnreachable, + ForStatement: reportIfUnreachable, + IfStatement: reportIfUnreachable, + ImportDeclaration: reportIfUnreachable, + LabeledStatement: reportIfUnreachable, + ReturnStatement: reportIfUnreachable, + SwitchStatement: reportIfUnreachable, + ThrowStatement: reportIfUnreachable, + TryStatement: reportIfUnreachable, + + VariableDeclaration(node) { + if ( + node.kind !== "var" || + node.declarations.some(isInitialized) + ) { + reportIfUnreachable(node); + } + }, + + WhileStatement: reportIfUnreachable, + WithStatement: reportIfUnreachable, + ExportNamedDeclaration: reportIfUnreachable, + ExportDefaultDeclaration: reportIfUnreachable, + ExportAllDeclaration: reportIfUnreachable, + + "Program:exit"() { + reportIfUnreachable(); + }, + + /* + * Instance fields defined in a subclass are never created if the constructor of the subclass + * doesn't call `super()`, so their definitions are unreachable code. + */ + "MethodDefinition[kind='constructor']"() { + constructorInfo = { + upper: constructorInfo, + hasSuperCall: false, + }; + }, + "MethodDefinition[kind='constructor']:exit"(node) { + const { hasSuperCall } = constructorInfo; + + constructorInfo = constructorInfo.upper; + + // skip typescript constructors without the body + if (!node.value.body) { + return; + } + + const classDefinition = node.parent.parent; + + if (classDefinition.superClass && !hasSuperCall) { + for (const element of classDefinition.body.body) { + if ( + element.type === "PropertyDefinition" && + !element.static + ) { + reportIfUnreachable(element); + } + } + } + }, + "CallExpression > Super.callee"() { + if (constructorInfo) { + constructorInfo.hasSuperCall = true; + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unsafe-finally.js b/node_modules/eslint/lib/rules/no-unsafe-finally.js new file mode 100644 index 0000000000000000000000000000000000000000..4c6393e60ef352a11dcb68c1af110c30fe808da4 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unsafe-finally.js @@ -0,0 +1,119 @@ +/** + * @fileoverview Rule to flag unsafe statements in finally block + * @author Onur Temizkan + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_NODE_TYPE_RETURN_THROW = + /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression)$/u; +const SENTINEL_NODE_TYPE_BREAK = + /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement|SwitchStatement)$/u; +const SENTINEL_NODE_TYPE_CONTINUE = + /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement)$/u; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow control flow statements in `finally` blocks", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unsafe-finally", + }, + + schema: [], + + messages: { + unsafeUsage: "Unsafe usage of {{nodeType}}.", + }, + }, + create(context) { + /** + * Checks if the node is the finalizer of a TryStatement + * @param {ASTNode} node node to check. + * @returns {boolean} - true if the node is the finalizer of a TryStatement + */ + function isFinallyBlock(node) { + return ( + node.parent.type === "TryStatement" && + node.parent.finalizer === node + ); + } + + /** + * Climbs up the tree if the node is not a sentinel node + * @param {ASTNode} node node to check. + * @param {string} label label of the break or continue statement + * @returns {boolean} - return whether the node is a finally block or a sentinel node + */ + function isInFinallyBlock(node, label) { + let labelInside = false; + let sentinelNodeType; + + if (node.type === "BreakStatement" && !node.label) { + sentinelNodeType = SENTINEL_NODE_TYPE_BREAK; + } else if (node.type === "ContinueStatement") { + sentinelNodeType = SENTINEL_NODE_TYPE_CONTINUE; + } else { + sentinelNodeType = SENTINEL_NODE_TYPE_RETURN_THROW; + } + + for ( + let currentNode = node; + currentNode && !sentinelNodeType.test(currentNode.type); + currentNode = currentNode.parent + ) { + if ( + currentNode.parent.label && + label && + currentNode.parent.label.name === label.name + ) { + labelInside = true; + } + if (isFinallyBlock(currentNode)) { + if (label && labelInside) { + return false; + } + return true; + } + } + return false; + } + + /** + * Checks whether the possibly-unsafe statement is inside a finally block. + * @param {ASTNode} node node to check. + * @returns {void} + */ + function check(node) { + if (isInFinallyBlock(node, node.label)) { + context.report({ + messageId: "unsafeUsage", + data: { + nodeType: node.type, + }, + node, + line: node.loc.line, + column: node.loc.column, + }); + } + } + + return { + ReturnStatement: check, + ThrowStatement: check, + BreakStatement: check, + ContinueStatement: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unsafe-negation.js b/node_modules/eslint/lib/rules/no-unsafe-negation.js new file mode 100644 index 0000000000000000000000000000000000000000..17e0271068e29ca9350040e06ca6c55063786fc7 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unsafe-negation.js @@ -0,0 +1,152 @@ +/** + * @fileoverview Rule to disallow negating the left operand of relational operators + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given operator is `in` or `instanceof` + * @param {string} op The operator type to check. + * @returns {boolean} `true` if the operator is `in` or `instanceof` + */ +function isInOrInstanceOfOperator(op) { + return op === "in" || op === "instanceof"; +} + +/** + * Checks whether the given operator is an ordering relational operator or not. + * @param {string} op The operator type to check. + * @returns {boolean} `true` if the operator is an ordering relational operator. + */ +function isOrderingRelationalOperator(op) { + return op === "<" || op === ">" || op === ">=" || op === "<="; +} + +/** + * Checks whether the given node is a logical negation expression or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a logical negation expression. + */ +function isNegation(node) { + return node.type === "UnaryExpression" && node.operator === "!"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + enforceForOrderingRelations: false, + }, + ], + + docs: { + description: + "Disallow negating the left operand of relational operators", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unsafe-negation", + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + enforceForOrderingRelations: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: null, + + messages: { + unexpected: + "Unexpected negating the left operand of '{{operator}}' operator.", + suggestNegatedExpression: + "Negate '{{operator}}' expression instead of its left operand. This changes the current behavior.", + suggestParenthesisedNegation: + "Wrap negation in '()' to make the intention explicit. This preserves the current behavior.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ enforceForOrderingRelations }] = context.options; + + return { + BinaryExpression(node) { + const operator = node.operator; + const orderingRelationRuleApplies = + enforceForOrderingRelations && + isOrderingRelationalOperator(operator); + + if ( + (isInOrInstanceOfOperator(operator) || + orderingRelationRuleApplies) && + isNegation(node.left) && + !astUtils.isParenthesised(sourceCode, node.left) + ) { + context.report({ + node, + loc: node.left.loc, + messageId: "unexpected", + data: { operator }, + suggest: [ + { + messageId: "suggestNegatedExpression", + data: { operator }, + fix(fixer) { + const negationToken = + sourceCode.getFirstToken(node.left); + const fixRange = [ + negationToken.range[1], + node.range[1], + ]; + const text = sourceCode.text.slice( + fixRange[0], + fixRange[1], + ); + + return fixer.replaceTextRange( + fixRange, + `(${text})`, + ); + }, + }, + { + messageId: "suggestParenthesisedNegation", + fix(fixer) { + return fixer.replaceText( + node.left, + `(${sourceCode.getText(node.left)})`, + ); + }, + }, + ], + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unsafe-optional-chaining.js b/node_modules/eslint/lib/rules/no-unsafe-optional-chaining.js new file mode 100644 index 0000000000000000000000000000000000000000..95875b7ebf75ec38376c4cc4c0f164bb737cd755 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unsafe-optional-chaining.js @@ -0,0 +1,221 @@ +/** + * @fileoverview Rule to disallow unsafe optional chaining + * @author Yeon JuAn + */ + +"use strict"; + +const UNSAFE_ARITHMETIC_OPERATORS = new Set(["+", "-", "/", "*", "%", "**"]); +const UNSAFE_ASSIGNMENT_OPERATORS = new Set([ + "+=", + "-=", + "/=", + "*=", + "%=", + "**=", +]); +const UNSAFE_RELATIONAL_OPERATORS = new Set(["in", "instanceof"]); + +/** + * Checks whether a node is a destructuring pattern or not + * @param {ASTNode} node node to check + * @returns {boolean} `true` if a node is a destructuring pattern, otherwise `false` + */ +function isDestructuringPattern(node) { + return node.type === "ObjectPattern" || node.type === "ArrayPattern"; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + disallowArithmeticOperators: false, + }, + ], + + docs: { + description: + "Disallow use of optional chaining in contexts where the `undefined` value is not allowed", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unsafe-optional-chaining", + }, + schema: [ + { + type: "object", + properties: { + disallowArithmeticOperators: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + fixable: null, + messages: { + unsafeOptionalChain: + "Unsafe usage of optional chaining. If it short-circuits with 'undefined' the evaluation will throw TypeError.", + unsafeArithmetic: + "Unsafe arithmetic operation on optional chaining. It can result in NaN.", + }, + }, + + create(context) { + const [{ disallowArithmeticOperators }] = context.options; + + /** + * Reports unsafe usage of optional chaining + * @param {ASTNode} node node to report + * @returns {void} + */ + function reportUnsafeUsage(node) { + context.report({ + messageId: "unsafeOptionalChain", + node, + }); + } + + /** + * Reports unsafe arithmetic operation on optional chaining + * @param {ASTNode} node node to report + * @returns {void} + */ + function reportUnsafeArithmetic(node) { + context.report({ + messageId: "unsafeArithmetic", + node, + }); + } + + /** + * Checks and reports if a node can short-circuit with `undefined` by optional chaining. + * @param {ASTNode} [node] node to check + * @param {Function} reportFunc report function + * @returns {void} + */ + function checkUndefinedShortCircuit(node, reportFunc) { + if (!node) { + return; + } + switch (node.type) { + case "LogicalExpression": + if (node.operator === "||" || node.operator === "??") { + checkUndefinedShortCircuit(node.right, reportFunc); + } else if (node.operator === "&&") { + checkUndefinedShortCircuit(node.left, reportFunc); + checkUndefinedShortCircuit(node.right, reportFunc); + } + break; + case "SequenceExpression": + checkUndefinedShortCircuit( + node.expressions.at(-1), + reportFunc, + ); + break; + case "ConditionalExpression": + checkUndefinedShortCircuit(node.consequent, reportFunc); + checkUndefinedShortCircuit(node.alternate, reportFunc); + break; + case "AwaitExpression": + checkUndefinedShortCircuit(node.argument, reportFunc); + break; + case "ChainExpression": + reportFunc(node); + break; + default: + break; + } + } + + /** + * Checks unsafe usage of optional chaining + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkUnsafeUsage(node) { + checkUndefinedShortCircuit(node, reportUnsafeUsage); + } + + /** + * Checks unsafe arithmetic operations on optional chaining + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkUnsafeArithmetic(node) { + checkUndefinedShortCircuit(node, reportUnsafeArithmetic); + } + + return { + "AssignmentExpression, AssignmentPattern"(node) { + if (isDestructuringPattern(node.left)) { + checkUnsafeUsage(node.right); + } + }, + "ClassDeclaration, ClassExpression"(node) { + checkUnsafeUsage(node.superClass); + }, + CallExpression(node) { + if (!node.optional) { + checkUnsafeUsage(node.callee); + } + }, + NewExpression(node) { + checkUnsafeUsage(node.callee); + }, + VariableDeclarator(node) { + if (isDestructuringPattern(node.id)) { + checkUnsafeUsage(node.init); + } + }, + MemberExpression(node) { + if (!node.optional) { + checkUnsafeUsage(node.object); + } + }, + TaggedTemplateExpression(node) { + checkUnsafeUsage(node.tag); + }, + ForOfStatement(node) { + checkUnsafeUsage(node.right); + }, + SpreadElement(node) { + if (node.parent && node.parent.type !== "ObjectExpression") { + checkUnsafeUsage(node.argument); + } + }, + BinaryExpression(node) { + if (UNSAFE_RELATIONAL_OPERATORS.has(node.operator)) { + checkUnsafeUsage(node.right); + } + if ( + disallowArithmeticOperators && + UNSAFE_ARITHMETIC_OPERATORS.has(node.operator) + ) { + checkUnsafeArithmetic(node.right); + checkUnsafeArithmetic(node.left); + } + }, + WithStatement(node) { + checkUnsafeUsage(node.object); + }, + UnaryExpression(node) { + if ( + disallowArithmeticOperators && + UNSAFE_ARITHMETIC_OPERATORS.has(node.operator) + ) { + checkUnsafeArithmetic(node.argument); + } + }, + AssignmentExpression(node) { + if ( + disallowArithmeticOperators && + UNSAFE_ASSIGNMENT_OPERATORS.has(node.operator) + ) { + checkUnsafeArithmetic(node.right); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unused-expressions.js b/node_modules/eslint/lib/rules/no-unused-expressions.js new file mode 100644 index 0000000000000000000000000000000000000000..26fe2b944f38a3890dd1c35d5d78110a3ea97a19 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-expressions.js @@ -0,0 +1,226 @@ +/** + * @fileoverview Flag expressions in statement position that do not side effect + * @author Michael Ficarra + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Returns `true`. + * @returns {boolean} `true`. + */ +function alwaysTrue() { + return true; +} + +/** + * Returns `false`. + * @returns {boolean} `false`. + */ +function alwaysFalse() { + return false; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unused expressions", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-unused-expressions", + }, + + schema: [ + { + type: "object", + properties: { + allowShortCircuit: { + type: "boolean", + }, + allowTernary: { + type: "boolean", + }, + allowTaggedTemplates: { + type: "boolean", + }, + enforceForJSX: { + type: "boolean", + }, + ignoreDirectives: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [ + { + allowShortCircuit: false, + allowTernary: false, + allowTaggedTemplates: false, + enforceForJSX: false, + ignoreDirectives: false, + }, + ], + + messages: { + unusedExpression: + "Expected an assignment or function call and instead saw an expression.", + }, + }, + + create(context) { + const [ + { + allowShortCircuit, + allowTernary, + allowTaggedTemplates, + enforceForJSX, + ignoreDirectives, + }, + ] = context.options; + + /** + * Has AST suggesting a directive. + * @param {ASTNode} node any node + * @returns {boolean} whether the given node structurally represents a directive + */ + function looksLikeDirective(node) { + return ( + node.type === "ExpressionStatement" && + node.expression.type === "Literal" && + typeof node.expression.value === "string" + ); + } + + /** + * Gets the leading sequence of members in a list that pass the predicate. + * @param {Function} predicate ([a] -> Boolean) the function used to make the determination + * @param {a[]} list the input list + * @returns {a[]} the leading sequence of members in the given list that pass the given predicate + */ + function takeWhile(predicate, list) { + for (let i = 0; i < list.length; ++i) { + if (!predicate(list[i])) { + return list.slice(0, i); + } + } + return list.slice(); + } + + /** + * Gets leading directives nodes in a Node body. + * @param {ASTNode} node a Program or BlockStatement node + * @returns {ASTNode[]} the leading sequence of directive nodes in the given node's body + */ + function directives(node) { + return takeWhile(looksLikeDirective, node.body); + } + + /** + * Detect if a Node is a directive. + * @param {ASTNode} node any node + * @returns {boolean} whether the given node is considered a directive in its current position + */ + function isDirective(node) { + /** + * https://tc39.es/ecma262/#directive-prologue + * + * Only `FunctionBody`, `ScriptBody` and `ModuleBody` can have directive prologue. + * Class static blocks do not have directive prologue. + */ + return ( + astUtils.isTopLevelExpressionStatement(node) && + directives(node.parent).includes(node) + ); + } + + /** + * The member functions return `true` if the type has no side-effects. + * Unknown nodes are handled as `false`, then this rule ignores those. + */ + const Checker = Object.assign(Object.create(null), { + isDisallowed(node) { + return (Checker[node.type] || alwaysFalse)(node); + }, + + ArrayExpression: alwaysTrue, + ArrowFunctionExpression: alwaysTrue, + BinaryExpression: alwaysTrue, + ChainExpression(node) { + return Checker.isDisallowed(node.expression); + }, + ClassExpression: alwaysTrue, + ConditionalExpression(node) { + if (allowTernary) { + return ( + Checker.isDisallowed(node.consequent) || + Checker.isDisallowed(node.alternate) + ); + } + return true; + }, + FunctionExpression: alwaysTrue, + Identifier: alwaysTrue, + JSXElement() { + return enforceForJSX; + }, + JSXFragment() { + return enforceForJSX; + }, + Literal: alwaysTrue, + LogicalExpression(node) { + if (allowShortCircuit) { + return Checker.isDisallowed(node.right); + } + return true; + }, + MemberExpression: alwaysTrue, + MetaProperty: alwaysTrue, + ObjectExpression: alwaysTrue, + SequenceExpression: alwaysTrue, + TaggedTemplateExpression() { + return !allowTaggedTemplates; + }, + TemplateLiteral: alwaysTrue, + ThisExpression: alwaysTrue, + UnaryExpression(node) { + return node.operator !== "void" && node.operator !== "delete"; + }, + // TypeScript-specific node types + TSAsExpression(node) { + return Checker.isDisallowed(node.expression); + }, + TSTypeAssertion(node) { + return Checker.isDisallowed(node.expression); + }, + TSNonNullExpression(node) { + return Checker.isDisallowed(node.expression); + }, + TSInstantiationExpression(node) { + return Checker.isDisallowed(node.expression); + }, + }); + + return { + ExpressionStatement(node) { + if ( + Checker.isDisallowed(node.expression) && + !astUtils.isDirective(node) && + !(ignoreDirectives && isDirective(node)) + ) { + context.report({ node, messageId: "unusedExpression" }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unused-labels.js b/node_modules/eslint/lib/rules/no-unused-labels.js new file mode 100644 index 0000000000000000000000000000000000000000..d7fe3e42749577c2b5f8167ba447ad89bb18de09 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-labels.js @@ -0,0 +1,158 @@ +/** + * @fileoverview Rule to disallow unused labels. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unused labels", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unused-labels", + }, + + schema: [], + + fixable: "code", + + messages: { + unused: "'{{name}}:' is defined but never used.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Adds a scope info to the stack. + * @param {ASTNode} node A node to add. This is a LabeledStatement. + * @returns {void} + */ + function enterLabeledScope(node) { + scopeInfo = { + label: node.label.name, + used: false, + upper: scopeInfo, + }; + } + + /** + * Checks if a `LabeledStatement` node is fixable. + * For a node to be fixable, there must be no comments between the label and the body. + * Furthermore, is must be possible to remove the label without turning the body statement into a + * directive after other fixes are applied. + * @param {ASTNode} node The node to evaluate. + * @returns {boolean} Whether or not the node is fixable. + */ + function isFixable(node) { + /* + * Only perform a fix if there are no comments between the label and the body. This will be the case + * when there is exactly one token/comment (the ":") between the label and the body. + */ + if ( + sourceCode.getTokenAfter(node.label, { + includeComments: true, + }) !== + sourceCode.getTokenBefore(node.body, { includeComments: true }) + ) { + return false; + } + + // Looking for the node's deepest ancestor which is not a `LabeledStatement`. + let ancestor = node.parent; + + while (ancestor.type === "LabeledStatement") { + ancestor = ancestor.parent; + } + + if ( + ancestor.type === "Program" || + (ancestor.type === "BlockStatement" && + astUtils.isFunction(ancestor.parent)) + ) { + const { body } = node; + + if ( + body.type === "ExpressionStatement" && + ((body.expression.type === "Literal" && + typeof body.expression.value === "string") || + astUtils.isStaticTemplateLiteral(body.expression)) + ) { + return false; // potential directive + } + } + return true; + } + + /** + * Removes the top of the stack. + * At the same time, this reports the label if it's never used. + * @param {ASTNode} node A node to report. This is a LabeledStatement. + * @returns {void} + */ + function exitLabeledScope(node) { + if (!scopeInfo.used) { + context.report({ + node: node.label, + messageId: "unused", + data: node.label, + fix: isFixable(node) + ? fixer => + fixer.removeRange([ + node.range[0], + node.body.range[0], + ]) + : null, + }); + } + + scopeInfo = scopeInfo.upper; + } + + /** + * Marks the label of a given node as used. + * @param {ASTNode} node A node to mark. This is a BreakStatement or + * ContinueStatement. + * @returns {void} + */ + function markAsUsed(node) { + if (!node.label) { + return; + } + + const label = node.label.name; + let info = scopeInfo; + + while (info) { + if (info.label === label) { + info.used = true; + break; + } + info = info.upper; + } + } + + return { + LabeledStatement: enterLabeledScope, + "LabeledStatement:exit": exitLabeledScope, + BreakStatement: markAsUsed, + ContinueStatement: markAsUsed, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unused-private-class-members.js b/node_modules/eslint/lib/rules/no-unused-private-class-members.js new file mode 100644 index 0000000000000000000000000000000000000000..3fd4e1d2f61af832f5f69c6966da5ce9b621f53a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-private-class-members.js @@ -0,0 +1,419 @@ +/** + * @fileoverview Rule to flag declared but unused private class members + * @author Tim van der Lippe + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + hasSuggestions: true, + + docs: { + description: "Disallow unused private class members", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unused-private-class-members", + }, + + schema: [], + + messages: { + unusedPrivateClassMember: + "'{{classMemberName}}' is defined but never used.", + removeUnusedPrivateClassMember: + "Remove unused private class member '{{classMemberName}}'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const trackedClasses = []; + + /** + * Gets the start index of the line that contains a given token or node. + * @param {ASTNode|Token|Comment} nodeOrToken The token or node to check + * @returns {number} The line start index + */ + function getLineStartIndex(nodeOrToken) { + return nodeOrToken.range[0] - nodeOrToken.loc.start.column; + } + + /** + * Checks whether a token or node starts on its own line, preceded only by whitespace. + * @param {ASTNode|Token|Comment} nodeOrToken The token or node to check + * @returns {boolean} Whether the token or node starts on its own line + */ + function startsOnOwnLine(nodeOrToken) { + return ( + sourceCode.getTokenBefore(nodeOrToken, { + includeComments: true, + }).loc.end.line !== nodeOrToken.loc.start.line + ); + } + + /** + * Gets leading comments that are directly attached to a class member. + * @param {ASTNode} classMemberNode The class member node + * @returns {Comment[]} Leading comments to remove with the member + */ + function getLeadingComments(classMemberNode) { + const commentsBefore = + sourceCode.getCommentsBefore(classMemberNode); + const lastNonLeadingCommentIndex = commentsBefore.findLastIndex( + (comment, index, self) => { + const next = + index < self.length - 1 + ? self[index + 1] + : classMemberNode; + + return ( + !startsOnOwnLine(comment) || + next.loc.start.line - comment.loc.end.line > 1 + ); + }, + ); + + return commentsBefore.slice(lastNonLeadingCommentIndex + 1); + } + + /** + * Checks whether a class member shares its line with another token. + * @param {ASTNode} classMemberNode The class member node + * @returns {boolean} Whether the member shares its line with another token + */ + function sharesLineWithAnotherToken(classMemberNode) { + const previousToken = sourceCode.getTokenBefore(classMemberNode); + const nextToken = sourceCode.getTokenAfter(classMemberNode); + + return ( + previousToken.loc.end.line === classMemberNode.loc.start.line || + nextToken.loc.start.line === classMemberNode.loc.end.line + ); + } + + /** + * Gets trailing comments that are directly attached to a class member. + * Same-line trailing comments are preserved when another token shares + * the line, because the comment might describe the remaining code rather + * than the unused member alone. + * @param {ASTNode} classMemberNode The class member node + * @returns {Comment[]} Trailing comments to remove with the member + */ + function getTrailingComments(classMemberNode) { + if (sharesLineWithAnotherToken(classMemberNode)) { + return []; + } + + return sourceCode + .getCommentsAfter(classMemberNode) + .filter( + comment => + comment.loc.start.line === classMemberNode.loc.end.line, + ); + } + + /** + * Gets the token after which a semicolon should be inserted when removing a class member. + * @param {ASTNode} classMemberNode The member that would be removed + * @returns {Token|null} The token after which a semicolon should be inserted, or null if no semicolon is needed + */ + function getSemicolonInsertionToken(classMemberNode) { + const nextToken = sourceCode.getTokenAfter(classMemberNode); + + if ( + astUtils.canContinueExpressionInClassBody(nextToken) && + astUtils.needsPrecedingSemicolon(sourceCode, classMemberNode) + ) { + return sourceCode.getTokenBefore(classMemberNode); + } + + return null; + } + + /** + * Gets the replacement range for removing an unused class member. + * @param {ASTNode} classMemberNode The member that would be removed + * @returns {number[]} The text range to remove + */ + function getMemberRemovalRange(classMemberNode) { + const leadingComments = getLeadingComments(classMemberNode); + const trailingComments = getTrailingComments(classMemberNode); + const shouldRemoveLeadingComments = + leadingComments.length > 0 && + !sharesLineWithAnotherToken(classMemberNode); + const lastItemToRemove = + trailingComments.length > 0 + ? trailingComments.at(-1) + : classMemberNode; + + const previousToken = sourceCode.getTokenBefore(classMemberNode); + const nextToken = sourceCode.getTokenAfter(lastItemToRemove, { + includeComments: true, + }); + const nextTokenStartsOnNewLine = + nextToken.loc.start.line > lastItemToRemove.loc.end.line; + const shouldRemoveOwnLine = + !shouldRemoveLeadingComments && + startsOnOwnLine(classMemberNode) && + nextTokenStartsOnNewLine; + let start = classMemberNode.range[0]; + let end = lastItemToRemove.range[1]; + + if (shouldRemoveLeadingComments) { + start = nextTokenStartsOnNewLine + ? getLineStartIndex(leadingComments[0]) + : leadingComments[0].range[0]; + end = nextTokenStartsOnNewLine + ? getLineStartIndex(nextToken) + : nextToken.range[0]; + } else if (shouldRemoveOwnLine) { + start = getLineStartIndex(classMemberNode); + end = getLineStartIndex(nextToken); + } else if ( + previousToken.loc.end.line === classMemberNode.loc.start.line + ) { + start = previousToken.range[1]; + } else if ( + nextToken.loc.start.line === lastItemToRemove.loc.end.line + ) { + end = nextToken.range[0]; + } + + return [start, end]; + } + + /** + * Check whether the current node is in a write only assignment. + * @param {ASTNode} privateIdentifierNode Node referring to a private identifier + * @returns {boolean} Whether the node is in a write only assignment + * @private + */ + function isWriteOnlyAssignment(privateIdentifierNode) { + const parentStatement = privateIdentifierNode.parent.parent; + const isAssignmentExpression = + parentStatement.type === "AssignmentExpression"; + + if ( + !isAssignmentExpression && + parentStatement.type !== "ForInStatement" && + parentStatement.type !== "ForOfStatement" && + parentStatement.type !== "AssignmentPattern" + ) { + return false; + } + + // It is a write-only usage, since we still allow usages on the right for reads + if (parentStatement.left !== privateIdentifierNode.parent) { + return false; + } + + // For any other operator (such as '+=') we still consider it a read operation + if (isAssignmentExpression && parentStatement.operator !== "=") { + /* + * However, if the read operation is "discarded" in an empty statement, then + * we consider it write only. + */ + return parentStatement.parent.type === "ExpressionStatement"; + } + + return true; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + // Collect all declared members up front and assume they are all unused + ClassBody(classBodyNode) { + const privateMembers = new Map(); + + trackedClasses.unshift(privateMembers); + for (const bodyMember of classBodyNode.body) { + if ( + bodyMember.type === "PropertyDefinition" || + bodyMember.type === "MethodDefinition" + ) { + if (bodyMember.key.type === "PrivateIdentifier") { + privateMembers.set(bodyMember.key.name, { + declaredNode: bodyMember, + hasReference: false, + isAccessor: + bodyMember.type === "MethodDefinition" && + (bodyMember.kind === "set" || + bodyMember.kind === "get"), + }); + } + } + } + }, + + /* + * Process all usages of the private identifier and remove a member from + * `declaredAndUnusedPrivateMembers` if we deem it used. + */ + PrivateIdentifier(privateIdentifierNode) { + const classBody = trackedClasses.find(classProperties => + classProperties.has(privateIdentifierNode.name), + ); + + // Can't happen, as it is a parser to have a missing class body, but let's code defensively here. + if (!classBody) { + return; + } + + // In case any other usage was already detected, we can short circuit the logic here. + const memberDefinition = classBody.get( + privateIdentifierNode.name, + ); + + if (memberDefinition.isUsed) { + return; + } + + // The definition of the class member itself + if ( + privateIdentifierNode.parent.type === + "PropertyDefinition" || + privateIdentifierNode.parent.type === "MethodDefinition" + ) { + return; + } + + memberDefinition.hasReference = true; + + /* + * Any usage of an accessor is considered a read, as the getter/setter can have + * side-effects in its definition. + */ + if (memberDefinition.isAccessor) { + memberDefinition.isUsed = true; + return; + } + + // Any assignments to this member, except for assignments that also read + if (isWriteOnlyAssignment(privateIdentifierNode)) { + return; + } + + const wrappingExpressionType = + privateIdentifierNode.parent.parent.type; + const parentOfWrappingExpressionType = + privateIdentifierNode.parent.parent.parent.type; + + // A statement which only increments (`this.#x++;`) + if ( + wrappingExpressionType === "UpdateExpression" && + parentOfWrappingExpressionType === "ExpressionStatement" + ) { + return; + } + + /* + * ({ x: this.#usedInDestructuring } = bar); + * + * But should treat the following as a read: + * ({ [this.#x]: a } = foo); + */ + if ( + wrappingExpressionType === "Property" && + parentOfWrappingExpressionType === "ObjectPattern" && + privateIdentifierNode.parent.parent.value === + privateIdentifierNode.parent + ) { + return; + } + + // [...this.#unusedInRestPattern] = bar; + if (wrappingExpressionType === "RestElement") { + return; + } + + // [this.#unusedInAssignmentPattern] = bar; + if (wrappingExpressionType === "ArrayPattern") { + return; + } + + /* + * We can't delete the memberDefinition, as we need to keep track of which member we are marking as used. + * In the case of nested classes, we only mark the first member we encounter as used. If you were to delete + * the member, then any subsequent usage could incorrectly mark the member of an encapsulating parent class + * as used, which is incorrect. + */ + memberDefinition.isUsed = true; + }, + + /* + * Post-process the class members and report any remaining members. + * Since private members can only be accessed in the current class context, + * we can safely assume that all usages are within the current class body. + */ + "ClassBody:exit"() { + const unusedPrivateMembers = trackedClasses.shift(); + + for (const [ + classMemberName, + { declaredNode, hasReference, isUsed }, + ] of unusedPrivateMembers.entries()) { + if (isUsed) { + continue; + } + + context.report({ + node: declaredNode, + loc: declaredNode.key.loc, + messageId: "unusedPrivateClassMember", + data: { + classMemberName: `#${classMemberName}`, + }, + suggest: [ + { + messageId: "removeUnusedPrivateClassMember", + data: { + classMemberName: `#${classMemberName}`, + }, + *fix(fixer) { + if (hasReference) { + return; + } + + const removalRange = + getMemberRemovalRange(declaredNode); + const semicolonInsertionToken = + getSemicolonInsertionToken( + declaredNode, + ); + const removalFix = fixer.replaceTextRange( + removalRange, + "", + ); + + yield removalFix; + + if (semicolonInsertionToken) { + yield fixer.insertTextAfter( + semicolonInsertionToken, + ";", + ); + } + }, + }, + ], + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-unused-vars.js b/node_modules/eslint/lib/rules/no-unused-vars.js new file mode 100644 index 0000000000000000000000000000000000000000..cb33993a3a19e81a8d11de46a223dca95a0b0eaa --- /dev/null +++ b/node_modules/eslint/lib/rules/no-unused-vars.js @@ -0,0 +1,1743 @@ +/** + * @fileoverview Rule to flag declared but unused variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Variable} Variable */ +/** @typedef {import("eslint-scope").Reference} Reference */ + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * A simple name for the types of variables that this rule supports + * @typedef {'array-destructure'|'catch-clause'|'parameter'|'variable'} VariableType + */ + +/** + * Bag of data used for formatting the `unusedVar` lint message. + * @typedef {Object} UnusedVarMessageData + * @property {string} varName The name of the unused var. + * @property {'defined'|'assigned a value'} action Description of the vars state. + * @property {string} additional Any additional info to be appended at the end. + */ + +/** + * Bag of data used for formatting the `usedIgnoredVar` lint message. + * @typedef {Object} UsedIgnoredVarMessageData + * @property {string} varName The name of the unused var. + * @property {string} additional Any additional info to be appended at the end. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_OPTIONS = { + vars: "all", + args: "after-used", + ignoreRestSiblings: false, + caughtErrors: "all", + ignoreClassWithStaticInitBlock: false, + ignoreUsingDeclarations: false, + reportUsedIgnorePattern: false, +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Disallow unused variables", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-unused-vars", + }, + + hasSuggestions: true, + + schema: [ + { + oneOf: [ + { + enum: ["all", "local"], + }, + { + type: "object", + properties: { + vars: { + enum: ["all", "local"], + }, + varsIgnorePattern: { + type: "string", + }, + args: { + enum: ["all", "after-used", "none"], + }, + ignoreRestSiblings: { + type: "boolean", + }, + argsIgnorePattern: { + type: "string", + }, + caughtErrors: { + enum: ["all", "none"], + }, + caughtErrorsIgnorePattern: { + type: "string", + }, + destructuredArrayIgnorePattern: { + type: "string", + }, + ignoreClassWithStaticInitBlock: { + type: "boolean", + }, + ignoreUsingDeclarations: { + type: "boolean", + }, + reportUsedIgnorePattern: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + defaultOptions: [DEFAULT_OPTIONS], + + messages: { + unusedVar: + "'{{varName}}' is {{action}} but never used{{additional}}.", + usedIgnoredVar: + "'{{varName}}' is marked as ignored but is used{{additional}}.", + removeVar: "Remove unused variable '{{varName}}'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const REST_PROPERTY_TYPE = + /^(?:RestElement|(?:Experimental)?RestProperty)$/u; + + let config; + + const firstOption = context.options[0]; + + if (typeof firstOption === "string") { + config = { + ...DEFAULT_OPTIONS, + vars: firstOption, + }; + } else { + config = { + ...firstOption, + }; + + if (firstOption.varsIgnorePattern) { + config.varsIgnorePattern = new RegExp( + firstOption.varsIgnorePattern, + "u", + ); + } + + if (firstOption.argsIgnorePattern) { + config.argsIgnorePattern = new RegExp( + firstOption.argsIgnorePattern, + "u", + ); + } + + if (firstOption.caughtErrorsIgnorePattern) { + config.caughtErrorsIgnorePattern = new RegExp( + firstOption.caughtErrorsIgnorePattern, + "u", + ); + } + + if (firstOption.destructuredArrayIgnorePattern) { + config.destructuredArrayIgnorePattern = new RegExp( + firstOption.destructuredArrayIgnorePattern, + "u", + ); + } + } + + /** + * Determines what variable type a def is. + * @param {Object} def the declaration to check + * @returns {VariableType} a simple name for the types of variables that this rule supports + */ + function defToVariableType(def) { + /* + * This `destructuredArrayIgnorePattern` error report works differently from the catch + * clause and parameter error reports. _Both_ the `varsIgnorePattern` and the + * `destructuredArrayIgnorePattern` will be checked for array destructuring. However, + * for the purposes of the report, the currently defined behavior is to only inform the + * user of the `destructuredArrayIgnorePattern` if it's present (regardless of the fact + * that the `varsIgnorePattern` would also apply). If it's not present, the user will be + * informed of the `varsIgnorePattern`, assuming that's present. + */ + if ( + config.destructuredArrayIgnorePattern && + def.name.parent.type === "ArrayPattern" + ) { + return "array-destructure"; + } + + switch (def.type) { + case "CatchClause": + return "catch-clause"; + case "Parameter": + return "parameter"; + + default: + return "variable"; + } + } + + /** + * Gets a given variable's description and configured ignore pattern + * based on the provided variableType + * @param {VariableType} variableType a simple name for the types of variables that this rule supports + * @throws {Error} (Unreachable) + * @returns {[string | undefined, string | undefined]} the given variable's description and + * ignore pattern + */ + function getVariableDescription(variableType) { + let pattern; + let variableDescription; + + switch (variableType) { + case "array-destructure": + pattern = config.destructuredArrayIgnorePattern; + variableDescription = "elements of array destructuring"; + break; + + case "catch-clause": + pattern = config.caughtErrorsIgnorePattern; + variableDescription = "caught errors"; + break; + + case "parameter": + pattern = config.argsIgnorePattern; + variableDescription = "args"; + break; + + case "variable": + pattern = config.varsIgnorePattern; + variableDescription = "vars"; + break; + + default: + throw new Error( + `Unexpected variable type: ${variableType}`, + ); + } + + if (pattern) { + pattern = pattern.toString(); + } + + return [variableDescription, pattern]; + } + + /** + * Generates the message data about the variable being defined and unused, + * including the ignore pattern if configured. + * @param {Variable} unusedVar eslint-scope variable object. + * @returns {UnusedVarMessageData} The message data to be used with this unused variable. + */ + function getDefinedMessageData(unusedVar) { + const def = unusedVar.defs && unusedVar.defs[0]; + let additionalMessageData = ""; + + if (def) { + const [variableDescription, pattern] = getVariableDescription( + defToVariableType(def), + ); + + if (pattern && variableDescription) { + additionalMessageData = `. Allowed unused ${variableDescription} must match ${pattern}`; + } + } + + return { + varName: unusedVar.name, + action: "defined", + additional: additionalMessageData, + }; + } + + /** + * Generate the warning message about the variable being + * assigned and unused, including the ignore pattern if configured. + * @param {Variable} unusedVar eslint-scope variable object. + * @returns {UnusedVarMessageData} The message data to be used with this unused variable. + */ + function getAssignedMessageData(unusedVar) { + const def = unusedVar.defs && unusedVar.defs[0]; + let additionalMessageData = ""; + + if (def) { + const [variableDescription, pattern] = getVariableDescription( + defToVariableType(def), + ); + + if (pattern && variableDescription) { + additionalMessageData = `. Allowed unused ${variableDescription} must match ${pattern}`; + } + } + + return { + varName: unusedVar.name, + action: "assigned a value", + additional: additionalMessageData, + }; + } + + /** + * Generate the warning message about a variable being used even though + * it is marked as being ignored. + * @param {Variable} variable eslint-scope variable object + * @param {VariableType} variableType a simple name for the types of variables that this rule supports + * @returns {UsedIgnoredVarMessageData} The message data to be used with + * this used ignored variable. + */ + function getUsedIgnoredMessageData(variable, variableType) { + const [variableDescription, pattern] = + getVariableDescription(variableType); + + let additionalMessageData = ""; + + if (pattern && variableDescription) { + additionalMessageData = `. Used ${variableDescription} must not match ${pattern}`; + } + + return { + varName: variable.name, + additional: additionalMessageData, + }; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const STATEMENT_TYPE = /(?:Statement|Declaration)$/u; + + /** + * Determines if a given variable is being exported from a module. + * @param {Variable} variable eslint-scope variable object. + * @returns {boolean} True if the variable is exported, false if not. + * @private + */ + function isExported(variable) { + const definition = variable.defs[0]; + + if (definition) { + let node = definition.node; + + if (node.type === "VariableDeclarator") { + node = node.parent; + } else if (definition.type === "Parameter") { + return false; + } + + return node.parent.type.indexOf("Export") === 0; + } + return false; + } + + /** + * Determines if a given variable uses the explicit resource management protocol. + * @param {Variable} variable eslint-scope variable object. + * @returns {boolean} True if the variable is declared with "using" or "await using" + * @private + */ + function usesExplicitResourceManagement(variable) { + const [definition] = variable.defs; + + return ( + definition?.type === "Variable" && + (definition.parent.kind === "using" || + definition.parent.kind === "await using") + ); + } + + /** + * Checks whether a node is a sibling of the rest property or not. + * @param {ASTNode} node a node to check + * @returns {boolean} True if the node is a sibling of the rest property, otherwise false. + */ + function hasRestSibling(node) { + return ( + node.type === "Property" && + node.parent.type === "ObjectPattern" && + REST_PROPERTY_TYPE.test(node.parent.properties.at(-1).type) + ); + } + + /** + * Determines if a variable has a sibling rest property + * @param {Variable} variable eslint-scope variable object. + * @returns {boolean} True if the variable has a sibling rest property, false if not. + * @private + */ + function hasRestSpreadSibling(variable) { + if (config.ignoreRestSiblings) { + const hasRestSiblingDefinition = variable.defs.some(def => + hasRestSibling(def.name.parent), + ); + const hasRestSiblingReference = variable.references.some(ref => + hasRestSibling(ref.identifier.parent), + ); + + return hasRestSiblingDefinition || hasRestSiblingReference; + } + + return false; + } + + /** + * Determines if a reference is a read operation. + * @param {Reference} ref An eslint-scope Reference + * @returns {boolean} whether the given reference represents a read operation + * @private + */ + function isReadRef(ref) { + return ref.isRead(); + } + + /** + * Determine if an identifier is referencing an enclosing function name. + * @param {Reference} ref The reference to check. + * @param {ASTNode[]} nodes The candidate function nodes. + * @returns {boolean} True if it's a self-reference, false if not. + * @private + */ + function isSelfReference(ref, nodes) { + let scope = ref.from; + + while (scope) { + if (nodes.includes(scope.block)) { + return true; + } + + scope = scope.upper; + } + + return false; + } + + /** + * Gets a list of function definitions for a specified variable. + * @param {Variable} variable eslint-scope variable object. + * @returns {ASTNode[]} Function nodes. + * @private + */ + function getFunctionDefinitions(variable) { + const functionDefinitions = []; + + variable.defs.forEach(def => { + const { type, node } = def; + + // FunctionDeclarations + if (type === "FunctionName") { + functionDefinitions.push(node); + } + + // FunctionExpressions + if ( + type === "Variable" && + node.init && + (node.init.type === "FunctionExpression" || + node.init.type === "ArrowFunctionExpression") + ) { + functionDefinitions.push(node.init); + } + }); + return functionDefinitions; + } + + /** + * Checks the position of given nodes. + * @param {ASTNode} inner A node which is expected as inside. + * @param {ASTNode} outer A node which is expected as outside. + * @returns {boolean} `true` if the `inner` node exists in the `outer` node. + * @private + */ + function isInside(inner, outer) { + return ( + inner.range[0] >= outer.range[0] && + inner.range[1] <= outer.range[1] + ); + } + + /** + * Checks whether a given node is unused expression or not. + * @param {ASTNode} node The node itself + * @returns {boolean} The node is an unused expression. + * @private + */ + function isUnusedExpression(node) { + const parent = node.parent; + + if (parent.type === "ExpressionStatement") { + return true; + } + + if (parent.type === "SequenceExpression") { + const isLastExpression = parent.expressions.at(-1) === node; + + if (!isLastExpression) { + return true; + } + return isUnusedExpression(parent); + } + + return false; + } + + /** + * If a given reference is left-hand side of an assignment, this gets + * the right-hand side node of the assignment. + * + * In the following cases, this returns null. + * + * - The reference is not the LHS of an assignment expression. + * - The reference is inside of a loop. + * - The reference is inside of a function scope which is different from + * the declaration. + * @param {Reference} ref A reference to check. + * @param {ASTNode} prevRhsNode The previous RHS node. + * @returns {ASTNode|null} The RHS node or null. + * @private + */ + function getRhsNode(ref, prevRhsNode) { + const id = ref.identifier; + const parent = id.parent; + const refScope = ref.from.variableScope; + const varScope = ref.resolved.scope.variableScope; + const canBeUsedLater = + refScope !== varScope || astUtils.isInLoop(id); + + /* + * Inherits the previous node if this reference is in the node. + * This is for `a = a + a`-like code. + */ + if (prevRhsNode && isInside(id, prevRhsNode)) { + return prevRhsNode; + } + + if ( + parent.type === "AssignmentExpression" && + isUnusedExpression(parent) && + id === parent.left && + !canBeUsedLater + ) { + return parent.right; + } + return null; + } + + /** + * Checks whether a given function node is stored to somewhere or not. + * If the function node is stored, the function can be used later. + * @param {ASTNode} funcNode A function node to check. + * @param {ASTNode} rhsNode The RHS node of the previous assignment. + * @returns {boolean} `true` if under the following conditions: + * - the funcNode is assigned to a variable. + * - the funcNode is bound as an argument of a function call. + * - the function is bound to a property and the object satisfies above conditions. + * @private + */ + function isStorableFunction(funcNode, rhsNode) { + let node = funcNode; + let parent = funcNode.parent; + + while (parent && isInside(parent, rhsNode)) { + switch (parent.type) { + case "SequenceExpression": + if (parent.expressions.at(-1) !== node) { + return false; + } + break; + + case "CallExpression": + case "NewExpression": + return parent.callee !== node; + + case "AssignmentExpression": + case "TaggedTemplateExpression": + case "YieldExpression": + return true; + + default: + if (STATEMENT_TYPE.test(parent.type)) { + /* + * If it encountered statements, this is a complex pattern. + * Since analyzing complex patterns is hard, this returns `true` to avoid false positive. + */ + return true; + } + } + + node = parent; + parent = parent.parent; + } + + return false; + } + + /** + * Checks whether a given Identifier node exists inside of a function node which can be used later. + * + * "can be used later" means: + * - the function is assigned to a variable. + * - the function is bound to a property and the object can be used later. + * - the function is bound as an argument of a function call. + * + * If a reference exists in a function which can be used later, the reference is read when the function is called. + * @param {ASTNode} id An Identifier node to check. + * @param {ASTNode} rhsNode The RHS node of the previous assignment. + * @returns {boolean} `true` if the `id` node exists inside of a function node which can be used later. + * @private + */ + function isInsideOfStorableFunction(id, rhsNode) { + const funcNode = astUtils.getUpperFunction(id); + + return ( + funcNode && + isInside(funcNode, rhsNode) && + isStorableFunction(funcNode, rhsNode) + ); + } + + /** + * Checks whether a given reference is a read to update itself or not. + * @param {Reference} ref A reference to check. + * @param {ASTNode} rhsNode The RHS node of the previous assignment. + * @returns {boolean} The reference is a read to update itself. + * @private + */ + function isReadForItself(ref, rhsNode) { + const id = ref.identifier; + const parent = id.parent; + + return ( + ref.isRead() && + // self update. e.g. `a += 1`, `a++` + ((parent.type === "AssignmentExpression" && + parent.left === id && + isUnusedExpression(parent) && + !astUtils.isLogicalAssignmentOperator(parent.operator)) || + (parent.type === "UpdateExpression" && + isUnusedExpression(parent)) || + // in RHS of an assignment for itself. e.g. `a = a + 1` + (rhsNode && + isInside(id, rhsNode) && + !isInsideOfStorableFunction(id, rhsNode))) + ); + } + + /** + * Determine if an identifier is used either in for-in or for-of loops. + * @param {Reference} ref The reference to check. + * @returns {boolean} whether reference is used in the for-in loops + * @private + */ + function isForInOfRef(ref) { + let target = ref.identifier.parent; + + // "for (var ...) { return; }" + if (target.type === "VariableDeclarator") { + target = target.parent.parent; + } + + if ( + target.type !== "ForInStatement" && + target.type !== "ForOfStatement" + ) { + return false; + } + + // "for (...) { return; }" + if (target.body.type === "BlockStatement") { + target = target.body.body[0]; + + // "for (...) return;" + } else { + target = target.body; + } + + // For empty loop body + if (!target) { + return false; + } + + return target.type === "ReturnStatement"; + } + + /** + * Determines if the variable is used. + * @param {Variable} variable The variable to check. + * @returns {boolean} True if the variable is used + * @private + */ + function isUsedVariable(variable) { + if (variable.eslintUsed) { + return true; + } + + const functionNodes = getFunctionDefinitions(variable); + const isFunctionDefinition = functionNodes.length > 0; + + let rhsNode = null; + + return variable.references.some(ref => { + if (isForInOfRef(ref)) { + return true; + } + + const forItself = isReadForItself(ref, rhsNode); + + rhsNode = getRhsNode(ref, rhsNode); + + return ( + isReadRef(ref) && + !forItself && + !( + isFunctionDefinition && + isSelfReference(ref, functionNodes) + ) + ); + }); + } + + /** + * Checks whether the given variable is after the last used parameter. + * @param {Variable} variable The variable to check. + * @returns {boolean} `true` if the variable is defined after the last + * used parameter. + */ + function isAfterLastUsedArg(variable) { + const def = variable.defs[0]; + const params = sourceCode.getDeclaredVariables(def.node); + const posteriorParams = params.slice(params.indexOf(variable) + 1); + + // If any used parameters occur after this parameter, do not report. + return !posteriorParams.some( + v => v.references.length > 0 || v.eslintUsed, + ); + } + + /** + * Gets an array of variables without read references. + * @param {Scope} scope an eslint-scope Scope object. + * @param {Variable[]} unusedVars an array that saving result. + * @returns {Variable[]} unused variables of the scope and descendant scopes. + * @private + */ + function collectUnusedVariables(scope, unusedVars) { + const variables = scope.variables; + const childScopes = scope.childScopes; + let i, l; + + if (scope.type !== "global" || config.vars === "all") { + for (i = 0, l = variables.length; i < l; ++i) { + const variable = variables[i]; + + // skip a variable of class itself name in the class scope + if ( + scope.type === "class" && + scope.block.id === variable.identifiers[0] + ) { + continue; + } + + // skip function expression names + if (scope.functionExpressionScope) { + continue; + } + + // skip variables marked with markVariableAsUsed() + if ( + !config.reportUsedIgnorePattern && + variable.eslintUsed + ) { + continue; + } + + // skip implicit "arguments" variable + if ( + scope.type === "function" && + variable.name === "arguments" && + variable.identifiers.length === 0 + ) { + continue; + } + + // explicit global variables don't have definitions. + const def = variable.defs[0]; + + if (def) { + const type = def.type; + const refUsedInArrayPatterns = variable.references.some( + ref => + ref.identifier.parent.type === "ArrayPattern", + ); + + // skip elements of array destructuring patterns + if ( + (def.name.parent.type === "ArrayPattern" || + refUsedInArrayPatterns) && + config.destructuredArrayIgnorePattern && + config.destructuredArrayIgnorePattern.test( + def.name.name, + ) + ) { + if ( + config.reportUsedIgnorePattern && + isUsedVariable(variable) + ) { + context.report({ + node: def.name, + messageId: "usedIgnoredVar", + data: getUsedIgnoredMessageData( + variable, + "array-destructure", + ), + }); + } + + continue; + } + + if (type === "ClassName") { + const hasStaticBlock = def.node.body.body.some( + node => node.type === "StaticBlock", + ); + + if ( + config.ignoreClassWithStaticInitBlock && + hasStaticBlock + ) { + continue; + } + } + + // skip catch variables + if (type === "CatchClause") { + if (config.caughtErrors === "none") { + continue; + } + + // skip ignored parameters + if ( + config.caughtErrorsIgnorePattern && + config.caughtErrorsIgnorePattern.test( + def.name.name, + ) + ) { + if ( + config.reportUsedIgnorePattern && + isUsedVariable(variable) + ) { + context.report({ + node: def.name, + messageId: "usedIgnoredVar", + data: getUsedIgnoredMessageData( + variable, + "catch-clause", + ), + }); + } + + continue; + } + } else if (type === "Parameter") { + // skip any setter argument + if ( + (def.node.parent.type === "Property" || + def.node.parent.type === + "MethodDefinition") && + def.node.parent.kind === "set" + ) { + continue; + } + + // if "args" option is "none", skip any parameter + if (config.args === "none") { + continue; + } + + // skip ignored parameters + if ( + config.argsIgnorePattern && + config.argsIgnorePattern.test(def.name.name) + ) { + if ( + config.reportUsedIgnorePattern && + isUsedVariable(variable) + ) { + context.report({ + node: def.name, + messageId: "usedIgnoredVar", + data: getUsedIgnoredMessageData( + variable, + "parameter", + ), + }); + } + + continue; + } + + // if "args" option is "after-used", skip used variables + if ( + config.args === "after-used" && + astUtils.isFunction(def.name.parent) && + !isAfterLastUsedArg(variable) + ) { + continue; + } + } else { + // skip ignored variables + if ( + config.varsIgnorePattern && + config.varsIgnorePattern.test(def.name.name) + ) { + if ( + config.reportUsedIgnorePattern && + isUsedVariable(variable) + ) { + context.report({ + node: def.name, + messageId: "usedIgnoredVar", + data: getUsedIgnoredMessageData( + variable, + "variable", + ), + }); + } + + continue; + } + } + } + + if ( + !isUsedVariable(variable) && + !isExported(variable) && + !( + config.ignoreUsingDeclarations && + usesExplicitResourceManagement(variable) + ) && + !hasRestSpreadSibling(variable) + ) { + unusedVars.push(variable); + } + } + } + + for (i = 0, l = childScopes.length; i < l; ++i) { + collectUnusedVariables(childScopes[i], unusedVars); + } + + return unusedVars; + } + + /** + * fixes unused variables + * @param {Object} fixer fixer object + * @param {Object} unusedVar unused variable to fix + * @returns {Object} fixer object + */ + function handleFixes(fixer, unusedVar) { + const id = unusedVar.identifiers[0]; + const parent = id.parent; + const parentType = parent.type; + const tokenBefore = sourceCode.getTokenBefore(id); + const tokenAfter = sourceCode.getTokenAfter(id); + const isFunction = astUtils.isFunction; + const isLoop = astUtils.isLoop; + const allWriteReferences = unusedVar.references.filter(ref => + ref.isWrite(), + ); + + /** + * get range from token before of a given node + * @param {ASTNode} node node of identifier + * @param {number} skips number of token to skip + * @returns {number} start range of token before the identifier + */ + function getPreviousTokenStart(node, skips) { + return sourceCode.getTokenBefore(node, skips).range[0]; + } + + /** + * get range to token after of a given node + * @param {ASTNode} node node of identifier + * @param {number} skips number of token to skip + * @returns {number} end range of token after the identifier + */ + function getNextTokenEnd(node, skips) { + return sourceCode.getTokenAfter(node, skips).range[1]; + } + + /** + * get the value of token before of a given node + * @param {ASTNode} node node of identifier + * @returns {string} value of token before the identifier + */ + function getTokenBeforeValue(node) { + return sourceCode.getTokenBefore(node).value; + } + + /** + * get the value of token after of a given node + * @param {ASTNode} node node of identifier + * @returns {string} value of token after the identifier + */ + function getTokenAfterValue(node) { + return sourceCode.getTokenAfter(node).value; + } + + /** + * Check if an array has a single element with null as other element. + * @param {ASTNode} node ArrayPattern node + * @returns {boolean} true if array has single element with other null elements + */ + function hasSingleElement(node) { + return node.elements.filter(e => e !== null).length === 1; + } + + /** + * check whether import specifier has an import of particular type + * @param {ASTNode} node ImportDeclaration node + * @param {string} type type of import to check + * @returns {boolean} true if import specifier has import of specified type + */ + function hasImportOfCertainType(node, type) { + return node.specifiers.some(e => e.type === type); + } + + /** + * Check whether declaration is safe to remove or not + * @param {ASTNode} nextToken next token of unused variable + * @param {ASTNode} prevToken previous token of unused variable + * @returns {boolean} true if declaration is not safe to remove + */ + function isDeclarationNotSafeToRemove(nextToken, prevToken) { + return ( + nextToken.type === "String" || + (prevToken && + !astUtils.isSemicolonToken(prevToken) && + !astUtils.isOpeningBraceToken(prevToken)) + ); + } + + /** + * give fixes for unused variables in function parameters + * @param {ASTNode} node node to check + * @returns {Object} fixer object + */ + function fixFunctionParameters(node) { + const parentNode = node.parent; + + if (isFunction(parentNode)) { + // remove unused function parameter if there is only a single parameter + if (parentNode.params.length === 1) { + return fixer.removeRange(node.range); + } + + // remove first unused function parameter when there are multiple parameters + if ( + getTokenBeforeValue(node) === "(" && + getTokenAfterValue(node) === "," + ) { + return fixer.removeRange([ + node.range[0], + getNextTokenEnd(node), + ]); + } + + // remove unused function parameters except first one when there are multiple parameters + return fixer.removeRange([ + getPreviousTokenStart(node), + node.range[1], + ]); + } + + return null; + } + + /** + * fix unused variable declarations and function parameters + * @param {ASTNode} node parent node to identifier + * @returns {Object} fixer object + */ + function fixVariables(node) { + const parentNode = node.parent; + + // remove unused declared variables such as var a = b; or var a = b, c; + if (parentNode.type === "VariableDeclarator") { + // skip variable in for (const [ foo ] of bar); + if (isLoop(parentNode.parent.parent)) { + return null; + } + + /* + * remove unused declared variable with single declaration such as 'var a = b;' + * remove complete declaration when there is an unused variable in 'const { a } = foo;', same for arrays. + */ + if (parentNode.parent.declarations.length === 1) { + // if next token is a string it could become a directive if node is removed -> no suggestion. + const nextToken = sourceCode.getTokenAfter( + parentNode.parent, + ); + + // if previous token exists and is not ";" or "{" not sure about ASI rules -> no suggestion. + const prevToken = sourceCode.getTokenBefore( + parentNode.parent, + ); + + if ( + nextToken && + isDeclarationNotSafeToRemove(nextToken, prevToken) + ) { + return null; + } + + return fixer.removeRange(parentNode.parent.range); + } + + /* + * remove unused declared variable with multiple declaration except first one such as 'var a = b, c = d;' + * fix 'let bar = "hello", { a } = foo;' to 'let bar = "hello";' if 'a' is unused, same for arrays. + */ + if (getTokenBeforeValue(parentNode) === ",") { + return fixer.removeRange([ + getPreviousTokenStart(parentNode), + parentNode.range[1], + ]); + } + + /* + * remove first unused declared variable when there are multiple declarations + * fix 'let { a } = foo, bar = "hello";' to 'let bar = "hello";' if 'a' is unused, same for arrays. + */ + return fixer.removeRange([ + parentNode.range[0], + getNextTokenEnd(parentNode), + ]); + } + + // fixes [{a: {k}}], [{a: [k]}] + if (getTokenBeforeValue(node) === ":") { + if (parentNode.parent.type === "ObjectPattern") { + // eslint-disable-next-line no-use-before-define -- due to interdependency of functions + return fixObjectWithValueSeparator(node); + } + } + + // fix unused function parameters + return fixFunctionParameters(node); + } + + /** + * fix nested object like { a: { b } } + * @param {ASTNode} node parent node to check + * @returns {Object} fixer object + */ + function fixNestedObjectVariable(node) { + const parentNode = node.parent; + + // fix for { a: { b: { c: { d } } } } + if ( + parentNode.parent.parent.parent.type === "ObjectPattern" && + parentNode.parent.properties.length === 1 + ) { + return fixNestedObjectVariable(parentNode.parent); + } + + // fix for { a: { b } } + if (parentNode.parent.type === "ObjectPattern") { + // fix for unused variables in destructured object with single property in variable declaration and function parameter + if (parentNode.parent.properties.length === 1) { + return fixVariables(parentNode.parent); + } + + // fix for first unused property when there are multiple properties such as '{ a: { b }, c }' + if (getTokenBeforeValue(parentNode) === "{") { + return fixer.removeRange([ + parentNode.range[0], + getNextTokenEnd(parentNode), + ]); + } + + // fix for unused property except first one when there are multiple properties such as '{ k, a: { b } }' + return fixer.removeRange([ + getPreviousTokenStart(parentNode), + parentNode.range[1], + ]); + } + + return null; + } + + /** + * fix unused variables in array and nested array + * @param {ASTNode} node parent node to check + * @returns {Object} fixer object + */ + function fixNestedArrayVariable(node) { + const parentNode = node.parent; + + // fix for nested arrays [[ a ]] + if ( + parentNode.parent.type === "ArrayPattern" && + hasSingleElement(parentNode) + ) { + return fixNestedArrayVariable(parentNode); + } + + if (hasSingleElement(parentNode)) { + // fixes { a: [{ b }] } or { a: [[ b ]] } + if (getTokenBeforeValue(parentNode) === ":") { + return fixVariables(parentNode); + } + + // fixes [a, ...[[ b ]]] or [a, ...[{ b }]] + if (parentNode.parent.type === "RestElement") { + // eslint-disable-next-line no-use-before-define -- due to interdependency of functions + return fixRestInPattern(parentNode.parent); + } + + // fix unused variables in destructured array in variable declaration or function parameter + return fixVariables(parentNode); + } + + // remove last unused array element + if ( + getTokenBeforeValue(node) === "," && + getTokenAfterValue(node) === "]" + ) { + return fixer.removeRange([ + getPreviousTokenStart(node), + node.range[1], + ]); + } + + // remove unused array element + return fixer.removeRange(node.range); + } + + /** + * fix cases like {a: {k}} or {a: [k]} + * @param {ASTNode} node parent node to check + * @returns {Object} fixer object + */ + function fixObjectWithValueSeparator(node) { + const parentNode = node.parent.parent; + + // fix cases like [{a : { b }}] or [{a : [ b ]}] + if ( + parentNode.parent.type === "ArrayPattern" && + parentNode.properties.length === 1 + ) { + return fixNestedArrayVariable(parentNode); + } + + // fix cases like {a: {k}} or {a: [k]} + return fixNestedObjectVariable(node); + } + + /** + * fix ...[[a]] or ...[{a}] like patterns + * @param {ASTNode} node parent node to check + * @returns {Object} fixer object + */ + function fixRestInPattern(node) { + const parentNode = node.parent; + + // fix ...[[a]] or ...[{a}] in function parameters + if (isFunction(parentNode)) { + if (parentNode.params.length === 1) { + return fixer.removeRange(node.range); + } + + return fixer.removeRange([ + getPreviousTokenStart(node), + node.range[1], + ]); + } + + // fix rest in nested array pattern like [[a, ...[b]]] + if (parentNode.type === "ArrayPattern") { + // fix [[...[b]]] + if (hasSingleElement(parentNode)) { + if (parentNode.parent.type === "ArrayPattern") { + return fixNestedArrayVariable(parentNode); + } + + // fix 'const [...[b]] = foo; and function foo([...[b]]) {} + return fixVariables(parentNode); + } + + // fix [[a, ...[b]]] + return fixer.removeRange([ + getPreviousTokenStart(node), + node.range[1], + ]); + } + + return null; + } + + // skip fix when variable has references that would be left behind + if ( + allWriteReferences.some( + ref => ref.identifier.range[0] !== id.range[0], + ) + ) { + return null; + } + + // remove declared variables such as var a; or var a, b; + if (parentType === "VariableDeclarator") { + if (parent.parent.declarations.length === 1) { + // prevent fix of variable in forOf and forIn loops. + if ( + isLoop(parent.parent.parent) && + parent.parent.parent.body !== parent.parent + ) { + return null; + } + + // removes only variable not semicolon in 'if (foo()) var bar;' or in 'loops' or in 'with' statement. + if ( + parent.parent.parent.type === "IfStatement" || + isLoop(parent.parent.parent) || + (parent.parent.parent.type === "WithStatement" && + parent.parent.parent.body === parent.parent) + ) { + return fixer.replaceText(parent.parent, ";"); + } + + // if next token is a string it could become a directive if node is removed -> no suggestion. + const nextToken = sourceCode.getTokenAfter(parent.parent); + + // if previous token exists and is not ";" or "{" not sure about ASI rules -> no suggestion. + const prevToken = sourceCode.getTokenBefore(parent.parent); + + if ( + nextToken && + isDeclarationNotSafeToRemove(nextToken, prevToken) + ) { + return null; + } + + // remove unused declared variable with single declaration like 'var a = b;' + return fixer.removeRange(parent.parent.range); + } + + // remove unused declared variable with multiple declaration except first one like 'var a = b, c = d;' + if (tokenBefore.value === ",") { + return fixer.removeRange([ + tokenBefore.range[0], + parent.range[1], + ]); + } + + // remove first unused declared variable when there are multiple declarations + return fixer.removeRange([ + parent.range[0], + getNextTokenEnd(parent), + ]); + } + + // remove variables in object patterns + if (parent.parent.type === "ObjectPattern") { + if (parent.parent.properties.length === 1) { + // fix [a, ...{b}] + if (parent.parent.parent.type === "RestElement") { + return fixRestInPattern(parent.parent.parent); + } + + // fix [{ a }] + if (parent.parent.parent.type === "ArrayPattern") { + return fixNestedArrayVariable(parent.parent); + } + + /* + * var {a} = foo; + * function a({a}) {} + * fix const { a: { b } } = foo; + */ + return fixVariables(parent.parent); + } + + // fix const { a:b } = foo; + if (tokenBefore.value === ":") { + // remove first unused variable in const { a:b } = foo; + if ( + getTokenBeforeValue(parent) === "{" && + getTokenAfterValue(parent) === "," + ) { + return fixer.removeRange([ + parent.range[0], + getNextTokenEnd(parent), + ]); + } + + // remove unused variables in const { a: b, c: d } = foo; except first one + return fixer.removeRange([ + getPreviousTokenStart(parent), + id.range[1], + ]); + } + } + + // remove unused variables inside an array + if (parentType === "ArrayPattern") { + if (hasSingleElement(parent)) { + // fix [a, ...[b]] + if (parent.parent.type === "RestElement") { + return fixRestInPattern(parent.parent); + } + + // fix [ [a] ] + if (parent.parent.type === "ArrayPattern") { + return fixNestedArrayVariable(parent); + } + + /* + * fix var [a] = foo; + * fix function foo([a]) {} + * fix const { a: [b] } = foo; + */ + return fixVariables(parent); + } + + // if "a" is unused in [a, b ,c] fixes to [, b, c] + if (tokenBefore.value === "," && tokenAfter.value === ",") { + return fixer.removeRange(id.range); + } + } + + // remove unused rest elements + if (parentType === "RestElement") { + // fix [a, ...rest] + if (parent.parent.type === "ArrayPattern") { + if (hasSingleElement(parent.parent)) { + // fix [[...rest]] when there is only rest element + if (parent.parent.parent.type === "ArrayPattern") { + return fixNestedArrayVariable(parent.parent); + } + + // fix 'const [...rest] = foo;' and 'function foo([...rest]) {}' + return fixVariables(parent.parent); + } + + // fix [a, ...rest] + return fixer.removeRange([ + getPreviousTokenStart(id, 1), + id.range[1], + ]); + } + + // fix { a, ...rest} + if (parent.parent.type === "ObjectPattern") { + // fix 'const {...rest} = foo;' and 'function foo({...rest}) {}' + if (parent.parent.properties.length === 1) { + return fixVariables(parent.parent); + } + + // fix { a, ...rest} when there are multiple properties + return fixer.removeRange([ + getPreviousTokenStart(id, 1), + id.range[1], + ]); + } + + // fix function foo(...rest) {} + if (isFunction(parent.parent)) { + // remove unused rest in function parameter if there is only single parameter + if (parent.parent.params.length === 1) { + return fixer.removeRange(parent.range); + } + + // remove unused rest in function parameter if there multiple parameter + return fixer.removeRange([ + getPreviousTokenStart(parent), + parent.range[1], + ]); + } + } + + if (parentType === "AssignmentPattern") { + // fix [a = aDefault] + if (parent.parent.type === "ArrayPattern") { + return fixNestedArrayVariable(parent); + } + + // fix {a = aDefault} + if (parent.parent.parent.type === "ObjectPattern") { + if (parent.parent.parent.properties.length === 1) { + // fixes [{a = aDefault}] + if ( + parent.parent.parent.parent.type === "ArrayPattern" + ) { + return fixNestedArrayVariable(parent.parent.parent); + } + + // fix 'const {a = aDefault} = foo;' and 'function foo({a = aDefault}) {}' + return fixVariables(parent.parent.parent); + } + + // fix unused 'a' in {a = aDefault} if it is the first property + if ( + getTokenBeforeValue(parent.parent) === "{" && + getTokenAfterValue(parent.parent) === "," + ) { + return fixer.removeRange([ + parent.parent.range[0], + getNextTokenEnd(parent.parent), + ]); + } + + // fix unused 'b' in {a, b = aDefault} if it is not the first property + return fixer.removeRange([ + getPreviousTokenStart(parent.parent), + parent.parent.range[1], + ]); + } + + // fix unused assignment patterns in function parameters + if (isFunction(parent.parent)) { + return fixFunctionParameters(parent); + } + } + + // remove unused functions + if (parentType === "FunctionDeclaration" && parent.id === id) { + return fixer.removeRange(parent.range); + } + + // remove unused default import + if (parentType === "ImportDefaultSpecifier") { + // remove unused default import when there are not other imports + if ( + !hasImportOfCertainType(parent.parent, "ImportSpecifier") && + !hasImportOfCertainType( + parent.parent, + "ImportNamespaceSpecifier", + ) + ) { + return fixer.removeRange([ + parent.range[0], + parent.parent.source.range[0], + ]); + } + + // remove unused default import when there are other imports also + return fixer.removeRange([id.range[0], tokenAfter.range[1]]); + } + + if (parentType === "ImportSpecifier") { + // remove unused imports when there is a single import + if ( + parent.parent.specifiers.filter( + e => e.type === "ImportSpecifier", + ).length === 1 + ) { + // remove unused import when there is no default import + if ( + !hasImportOfCertainType( + parent.parent, + "ImportDefaultSpecifier", + ) + ) { + return fixer.removeRange(parent.parent.range); + } + + // fixes "import foo from 'module';" to "import 'module';" + return fixer.removeRange([ + getPreviousTokenStart(parent, 1), + tokenAfter.range[1], + ]); + } + + if (getTokenBeforeValue(parent) === "{") { + return fixer.removeRange([ + parent.range[0], + getNextTokenEnd(parent), + ]); + } + + return fixer.removeRange([ + getPreviousTokenStart(parent), + parent.range[1], + ]); + } + + if (parentType === "ImportNamespaceSpecifier") { + if ( + hasImportOfCertainType( + parent.parent, + "ImportDefaultSpecifier", + ) + ) { + return fixer.removeRange([ + getPreviousTokenStart(parent), + parent.range[1], + ]); + } + + // fixes "import * as foo from 'module';" to "import 'module';" + return fixer.removeRange([ + parent.range[0], + parent.parent.source.range[0], + ]); + } + + // skip error in catch(error) variable + if (parentType === "CatchClause") { + return null; + } + + // remove unused declared classes + if (parentType === "ClassDeclaration") { + return fixer.removeRange(parent.range); + } + + // remove unused variable that is in a sequence [a,b] fixes to [a] + if (tokenBefore?.value === ",") { + return fixer.removeRange([tokenBefore.range[0], id.range[1]]); + } + + // remove unused variable that is in a sequence inside function arguments and object pattern + if (tokenAfter.value === ",") { + // fix function foo(a, b) {} + if (tokenBefore.value === "(") { + return fixer.removeRange([ + id.range[0], + tokenAfter.range[1], + ]); + } + + // fix const {a, b} = foo; + if (tokenBefore.value === "{") { + return fixer.removeRange([ + id.range[0], + tokenAfter.range[1], + ]); + } + } + + if ( + parentType === "ArrowFunctionExpression" && + parent.params.length === 1 && + tokenAfter?.value !== ")" + ) { + return fixer.replaceText(id, "()"); + } + + return fixer.removeRange(id.range); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Program:exit"(programNode) { + const unusedVars = collectUnusedVariables( + sourceCode.getScope(programNode), + [], + ); + + for (let i = 0, l = unusedVars.length; i < l; ++i) { + const unusedVar = unusedVars[i]; + + // Report the first declaration. + if (unusedVar.defs.length > 0) { + // report last write reference, https://github.com/eslint/eslint/issues/14324 + const writeReferences = unusedVar.references.filter( + ref => + ref.isWrite() && + ref.from.variableScope === + unusedVar.scope.variableScope, + ); + + let referenceToReport; + + if (writeReferences.length > 0) { + referenceToReport = writeReferences.at(-1); + } + + context.report({ + node: referenceToReport + ? referenceToReport.identifier + : unusedVar.identifiers[0], + messageId: "unusedVar", + data: unusedVar.references.some(ref => + ref.isWrite(), + ) + ? getAssignedMessageData(unusedVar) + : getDefinedMessageData(unusedVar), + suggest: [ + { + messageId: "removeVar", + data: { + varName: unusedVar.name, + }, + fix(fixer) { + return handleFixes(fixer, unusedVar); + }, + }, + ], + }); + + // If there are no regular declaration, report the first `/*globals*/` comment directive. + } else if (unusedVar.eslintExplicitGlobalComments) { + const directiveComment = + unusedVar.eslintExplicitGlobalComments[0]; + + context.report({ + node: programNode, + loc: astUtils.getNameLocationInGlobalDirectiveComment( + sourceCode, + directiveComment, + unusedVar.name, + ), + messageId: "unusedVar", + data: getDefinedMessageData(unusedVar), + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-use-before-define.js b/node_modules/eslint/lib/rules/no-use-before-define.js new file mode 100644 index 0000000000000000000000000000000000000000..19f36c4bf72ae671625f7f17d104cf5e2de4e539 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-use-before-define.js @@ -0,0 +1,452 @@ +/** + * @fileoverview Rule to flag use of variables before they are defined + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("eslint-scope").Reference} Reference */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SENTINEL_TYPE = + /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/u; +const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/u; + +/** + * Parses a given value as options. + * @param {any} options A value to parse. + * @returns {Object} The parsed options. + */ +function parseOptions(options) { + if (typeof options === "object" && options !== null) { + return options; + } + + const functions = typeof options === "string" ? options !== "nofunc" : true; + + return { + functions, + classes: true, + variables: true, + allowNamedExports: false, + enums: true, + typedefs: true, + ignoreTypeReferences: true, + }; +} + +/** + * Checks whether or not a given location is inside of the range of a given node. + * @param {ASTNode} node An node to check. + * @param {number} location A location to check. + * @returns {boolean} `true` if the location is inside of the range of the node. + */ +function isInRange(node, location) { + return node && node.range[0] <= location && location <= node.range[1]; +} + +/** + * Checks whether or not a given location is inside of the range of a class static initializer. + * Static initializers are static blocks and initializers of static fields. + * @param {ASTNode} node `ClassBody` node to check static initializers. + * @param {number} location A location to check. + * @returns {boolean} `true` if the location is inside of a class static initializer. + */ +function isInClassStaticInitializerRange(node, location) { + return node.body.some( + classMember => + (classMember.type === "StaticBlock" && + isInRange(classMember, location)) || + (classMember.type === "PropertyDefinition" && + classMember.static && + classMember.value && + isInRange(classMember.value, location)), + ); +} + +/** + * Checks whether a given scope is the scope of a class static initializer. + * Static initializers are static blocks and initializers of static fields. + * @param {Scope} scope A scope to check. + * @returns {boolean} `true` if the scope is a class static initializer scope. + */ +function isClassStaticInitializerScope(scope) { + if (scope.type === "class-static-block") { + return true; + } + + if (scope.type === "class-field-initializer") { + // `scope.block` is PropertyDefinition#value node + const propertyDefinition = scope.block.parent; + + return propertyDefinition.static; + } + + return false; +} + +/** + * Checks whether a given reference is evaluated in an execution context + * that isn't the one where the variable it refers to is defined. + * Execution contexts are: + * - top-level + * - functions + * - class field initializers (implicit functions) + * - class static blocks (implicit functions) + * Static class field initializers and class static blocks are automatically run during the class definition evaluation, + * and therefore we'll consider them as a part of the parent execution context. + * Example: + * + * const x = 1; + * + * x; // returns `false` + * () => x; // returns `true` + * + * class C { + * field = x; // returns `true` + * static field = x; // returns `false` + * + * method() { + * x; // returns `true` + * } + * + * static method() { + * x; // returns `true` + * } + * + * static { + * x; // returns `false` + * } + * } + * @param {Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is from a separate execution context. + */ +function isFromSeparateExecutionContext(reference) { + const variable = reference.resolved; + let scope = reference.from; + + // Scope#variableScope represents execution context + while (variable.scope.variableScope !== scope.variableScope) { + if (isClassStaticInitializerScope(scope.variableScope)) { + scope = scope.variableScope.upper; + } else { + return true; + } + } + + return false; +} + +/** + * Checks whether or not a given reference is evaluated during the initialization of its variable. + * + * This returns `true` in the following cases: + * + * var a = a + * var [a = a] = list + * var {a = a} = obj + * for (var a in a) {} + * for (var a of a) {} + * var C = class { [C]; }; + * var C = class { static foo = C; }; + * var C = class { static { foo = C; } }; + * class C extends C {} + * class C extends (class { static foo = C; }) {} + * class C { [C]; } + * @param {Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is evaluated during the initialization. + */ +function isEvaluatedDuringInitialization(reference) { + if (isFromSeparateExecutionContext(reference)) { + /* + * Even if the reference appears in the initializer, it isn't evaluated during the initialization. + * For example, `const x = () => x;` is valid. + */ + return false; + } + + const location = reference.identifier.range[1]; + const definition = reference.resolved.defs[0]; + + if (definition.type === "ClassName") { + // `ClassDeclaration` or `ClassExpression` + const classDefinition = definition.node; + + return ( + isInRange(classDefinition, location) && + /* + * Class binding is initialized before running static initializers. + * For example, `class C { static foo = C; static { bar = C; } }` is valid. + */ + !isInClassStaticInitializerRange(classDefinition.body, location) + ); + } + + let node = definition.name.parent; + + while (node) { + if (node.type === "VariableDeclarator") { + if (isInRange(node.init, location)) { + return true; + } + if ( + FOR_IN_OF_TYPE.test(node.parent.parent.type) && + isInRange(node.parent.parent.right, location) + ) { + return true; + } + break; + } else if (node.type === "AssignmentPattern") { + if (isInRange(node.right, location)) { + return true; + } + } else if (SENTINEL_TYPE.test(node.type)) { + break; + } + + node = node.parent; + } + + return false; +} + +/** + * check whether the reference contains a type query. + * @param {ASTNode} node Identifier node to check. + * @returns {boolean} true if reference contains type query. + */ +function referenceContainsTypeQuery(node) { + switch (node.type) { + case "TSTypeQuery": + return true; + + case "TSQualifiedName": + case "Identifier": + return referenceContainsTypeQuery(node.parent); + + default: + // if we find a different node, there's no chance that we're in a TSTypeQuery + return false; + } +} + +/** + * Decorators are transpiled such that the decorator is placed after the class declaration + * So it is considered safe + * @param {Variable} variable The variable to check. + * @param {Reference} reference The reference to check. + * @returns {boolean} `true` if the reference is in a class decorator. + */ +function isClassRefInClassDecorator(variable, reference) { + if (variable.defs[0].type !== "ClassName") { + return false; + } + + if ( + !variable.defs[0].node.decorators || + variable.defs[0].node.decorators.length === 0 + ) { + return false; + } + + for (const deco of variable.defs[0].node.decorators) { + if ( + reference.identifier.range[0] >= deco.range[0] && + reference.identifier.range[1] <= deco.range[1] + ) { + return true; + } + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow the use of variables before they are defined", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-use-before-define", + }, + + schema: [ + { + oneOf: [ + { + enum: ["nofunc"], + }, + { + type: "object", + properties: { + functions: { type: "boolean" }, + classes: { type: "boolean" }, + variables: { type: "boolean" }, + allowNamedExports: { type: "boolean" }, + enums: { type: "boolean" }, + typedefs: { type: "boolean" }, + ignoreTypeReferences: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + }, + ], + + defaultOptions: [ + { + classes: true, + functions: true, + variables: true, + allowNamedExports: false, + enums: true, + typedefs: true, + ignoreTypeReferences: true, + }, + ], + + messages: { + usedBeforeDefined: "'{{name}}' was used before it was defined.", + }, + }, + + create(context) { + const options = parseOptions(context.options[0]); + const sourceCode = context.sourceCode; + + /** + * Determines whether a given reference should be checked. + * + * Returns `false` if the reference is: + * - initialization's (e.g., `let a = 1`). + * - referring to an undefined variable (i.e., if it's an unresolved reference). + * - referring to a variable that is defined, but not in the given source code + * (e.g., global environment variable or `arguments` in functions). + * - allowed by options. + * @param {Reference} reference The reference + * @returns {boolean} `true` if the reference should be checked + */ + function shouldCheck(reference) { + if (reference.init) { + return false; + } + + const { identifier } = reference; + + if ( + options.allowNamedExports && + identifier.parent.type === "ExportSpecifier" && + identifier.parent.local === identifier + ) { + return false; + } + + const variable = reference.resolved; + + if (!variable || variable.defs.length === 0) { + return false; + } + + const definitionType = variable.defs[0].type; + + if (!options.functions && definitionType === "FunctionName") { + return false; + } + + if ( + ((!options.variables && definitionType === "Variable") || + (!options.classes && definitionType === "ClassName")) && + // don't skip checking the reference if it's in the same execution context, because of TDZ + isFromSeparateExecutionContext(reference) + ) { + return false; + } + + if (!options.enums && definitionType === "TSEnumName") { + return false; + } + + if (!options.typedefs && definitionType === "Type") { + return false; + } + + if ( + options.ignoreTypeReferences && + (referenceContainsTypeQuery(identifier) || + identifier.parent.type === "TSTypeReference") + ) { + return false; + } + + // skip nested namespace aliases as variable references + if (identifier.parent.type === "TSQualifiedName") { + let currentNode = identifier.parent; + + while (currentNode.type === "TSQualifiedName") { + currentNode = currentNode.left; + } + + if (currentNode === identifier) { + return true; + } + + return false; + } + + if (isClassRefInClassDecorator(variable, reference)) { + return false; + } + + return true; + } + + /** + * Finds and validates all references in a given scope and its child scopes. + * @param {Scope} scope The scope object. + * @returns {void} + */ + function checkReferencesInScope(scope) { + scope.references.filter(shouldCheck).forEach(reference => { + const variable = reference.resolved; + const definitionIdentifier = variable.defs[0].name; + + if ( + reference.identifier.range[1] < + definitionIdentifier.range[1] || + (isEvaluatedDuringInitialization(reference) && + reference.identifier.parent.type !== "TSTypeReference") + ) { + context.report({ + node: reference.identifier, + messageId: "usedBeforeDefined", + data: reference.identifier, + }); + } + }); + + scope.childScopes.forEach(checkReferencesInScope); + } + + return { + Program(node) { + checkReferencesInScope(sourceCode.getScope(node)); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-assignment.js b/node_modules/eslint/lib/rules/no-useless-assignment.js new file mode 100644 index 0000000000000000000000000000000000000000..d5cca1e4db52d184a428a885c01443bcf1f0d886 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-assignment.js @@ -0,0 +1,658 @@ +/** + * @fileoverview A rule to disallow unnecessary assignments`. + * @author Yosuke Ota + */ + +"use strict"; + +const { findVariable } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("estree").Node} ASTNode */ +/** @typedef {import("estree").Pattern} Pattern */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").VariableDeclarator} VariableDeclarator */ +/** @typedef {import("estree").AssignmentExpression} AssignmentExpression */ +/** @typedef {import("estree").UpdateExpression} UpdateExpression */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("eslint-scope").Variable} Variable */ +/** @typedef {import("../linter/code-path-analysis/code-path")} CodePath */ +/** @typedef {import("../linter/code-path-analysis/code-path-segment")} CodePathSegment */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Extract identifier from the given pattern node used on the left-hand side of the assignment. + * @param {Pattern} pattern The pattern node to extract identifier + * @returns {Iterable} The extracted identifier + */ +function* extractIdentifiersFromPattern(pattern) { + switch (pattern.type) { + case "Identifier": + yield pattern; + return; + case "ObjectPattern": + for (const property of pattern.properties) { + yield* extractIdentifiersFromPattern( + property.type === "Property" ? property.value : property, + ); + } + return; + case "ArrayPattern": + for (const element of pattern.elements) { + if (!element) { + continue; + } + yield* extractIdentifiersFromPattern(element); + } + return; + case "RestElement": + yield* extractIdentifiersFromPattern(pattern.argument); + return; + case "AssignmentPattern": + yield* extractIdentifiersFromPattern(pattern.left); + + // no default + } +} + +/** + * Checks whether the given identifier node is evaluated after the assignment identifier. + * @param {AssignmentInfo} assignment The assignment info. + * @param {Identifier} identifier The identifier to check. + * @returns {boolean} `true` if the given identifier node is evaluated after the assignment identifier. + */ +function isIdentifierEvaluatedAfterAssignment(assignment, identifier) { + if (identifier.range[0] < assignment.identifier.range[1]) { + return false; + } + if ( + assignment.expression && + assignment.expression.range[0] <= identifier.range[0] && + identifier.range[1] <= assignment.expression.range[1] + ) { + /* + * The identifier node is in an expression that is evaluated before the assignment. + * e.g. x = id; + * ^^ identifier to check + * ^ assignment identifier + */ + return false; + } + + /* + * e.g. + * x = 42; id; + * ^^ identifier to check + * ^ assignment identifier + * let { x, y = id } = obj; + * ^^ identifier to check + * ^ assignment identifier + */ + return true; +} + +/** + * Checks whether the given identifier node is used between the assigned identifier and the equal sign. + * + * e.g. let { x, y = x } = obj; + * ^ identifier to check + * ^ assigned identifier + * @param {AssignmentInfo} assignment The assignment info. + * @param {Identifier} identifier The identifier to check. + * @returns {boolean} `true` if the given identifier node is used between the assigned identifier and the equal sign. + */ +function isIdentifierUsedBetweenAssignedAndEqualSign(assignment, identifier) { + if (!assignment.expression) { + return false; + } + return ( + assignment.identifier.range[1] <= identifier.range[0] && + identifier.range[1] <= assignment.expression.range[0] + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow variable assignments when the value is not used", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-useless-assignment", + }, + + schema: [], + + messages: { + unnecessaryAssignment: + "The value assigned to '{{name}}' is not used in subsequent statements.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * @typedef {Object} ScopeStack + * @property {CodePath} codePath The code path of this scope stack. + * @property {Scope} scope The scope of this scope stack. + * @property {ScopeStack} upper The upper scope stack. + * @property {Record} segments The map of ScopeStackSegmentInfo. + * @property {Set} currentSegments The current CodePathSegments. + * @property {Map} assignments The map of list of AssignmentInfo for each variable. + * @property {Array} tryStatementBlocks The array of TryStatement block nodes in this scope stack. + */ + /** + * @typedef {Object} ScopeStackSegmentInfo + * @property {CodePathSegment} segment The code path segment. + * @property {Identifier|null} first The first identifier that appears within the segment. + * @property {Identifier|null} last The last identifier that appears within the segment. + * `first` and `last` are used to determine whether an identifier exists within the segment position range. + * Since it is used as a range of segments, we should originally hold all nodes, not just identifiers, + * but since the only nodes to be judged are identifiers, it is sufficient to have a range of identifiers. + */ + /** + * @typedef {Object} AssignmentInfo + * @property {Variable} variable The variable that is assigned. + * @property {Identifier} identifier The identifier that is assigned. + * @property {VariableDeclarator|AssignmentExpression|UpdateExpression} node The node where the variable was updated. + * @property {Expression|null} expression The expression that is evaluated before the assignment. + * @property {CodePathSegment[]} segments The code path segments where the assignment was made. + */ + + /** @type {ScopeStack} */ + let scopeStack = null; + + /** @type {Set} */ + const codePathStartScopes = new Set(); + + /** + * Gets the scope of code path start from given scope + * @param {Scope} scope The initial scope + * @returns {Scope} The scope of code path start + * @throws {Error} Unexpected error + */ + function getCodePathStartScope(scope) { + let target = scope; + + while (target) { + if (codePathStartScopes.has(target)) { + return target; + } + target = target.upper; + } + + // Should be unreachable + return null; + } + + /** + * Verify the given scope stack. + * @param {ScopeStack} target The scope stack to verify. + * @returns {void} + */ + function verify(target) { + /** + * Checks whether the given identifier is used in the segment. + * @param {CodePathSegment} segment The code path segment. + * @param {Identifier} identifier The identifier to check. + * @returns {boolean} `true` if the identifier is used in the segment. + */ + function isIdentifierUsedInSegment(segment, identifier) { + const segmentInfo = target.segments[segment.id]; + + return ( + segmentInfo.first && + segmentInfo.last && + segmentInfo.first.range[0] <= identifier.range[0] && + identifier.range[1] <= segmentInfo.last.range[1] + ); + } + + /** + * Verifies whether the given assignment info is an used assignment. + * Report if it is an unused assignment. + * @param {AssignmentInfo} targetAssignment The assignment info to verify. + * @param {AssignmentInfo[]} allAssignments The list of all assignment info for variables. + * @returns {void} + */ + function verifyAssignmentIsUsed(targetAssignment, allAssignments) { + // Skip assignment if it is in a try block. + const isAssignmentInTryBlock = target.tryStatementBlocks.some( + tryBlock => + tryBlock.range[0] <= + targetAssignment.identifier.range[0] && + targetAssignment.identifier.range[1] <= + tryBlock.range[1], + ); + + if (isAssignmentInTryBlock) { + return; + } + + /** + * @typedef {Object} SubsequentSegmentData + * @property {CodePathSegment} segment The code path segment + * @property {AssignmentInfo} [assignment] The first occurrence of the assignment within the segment. + * There is no need to check if the variable is used after this assignment, + * as the value it was assigned will be used. + */ + + /** + * Information used in `getSubsequentSegments()`. + * To avoid unnecessary iterations, cache information that has already been iterated over, + * and if additional iterations are needed, start iterating from the retained position. + */ + const subsequentSegmentData = { + /** + * Cache of subsequent segment information list that have already been iterated. + * @type {SubsequentSegmentData[]} + */ + results: [], + + /** + * Subsequent segments that have already been iterated on. Used to avoid infinite loops. + * @type {Set} + */ + subsequentSegments: new Set(), + + /** + * Unexplored code path segment. + * If additional iterations are needed, consume this information and iterate. + * @type {CodePathSegment[]} + */ + queueSegments: targetAssignment.segments.flatMap( + segment => segment.nextSegments, + ), + }; + + /** + * Gets the subsequent segments from the segment of + * the assignment currently being validated (targetAssignment). + * @returns {Iterable} the subsequent segments + */ + function* getSubsequentSegments() { + yield* subsequentSegmentData.results; + + while (subsequentSegmentData.queueSegments.length > 0) { + const nextSegment = + subsequentSegmentData.queueSegments.shift(); + + if ( + subsequentSegmentData.subsequentSegments.has( + nextSegment, + ) + ) { + continue; + } + subsequentSegmentData.subsequentSegments.add( + nextSegment, + ); + + const assignmentInSegment = allAssignments.find( + otherAssignment => + otherAssignment.segments.includes( + nextSegment, + ) && + !isIdentifierUsedBetweenAssignedAndEqualSign( + otherAssignment, + targetAssignment.identifier, + ), + ); + + if (!assignmentInSegment) { + /* + * Stores the next segment to explore. + * If `assignmentInSegment` exists, + * we are guarding it because we don't need to explore the next segment. + */ + subsequentSegmentData.queueSegments.push( + ...nextSegment.nextSegments, + ); + } + + /** @type {SubsequentSegmentData} */ + const result = { + segment: nextSegment, + assignment: assignmentInSegment, + }; + + subsequentSegmentData.results.push(result); + yield result; + } + } + + if ( + targetAssignment.variable.references.some(ref => { + const type = ref.identifier.type; + return ( + type !== "Identifier" && type !== "JSXIdentifier" + ); + }) + ) { + /** + * Skip checking for a variable that has at least one non-identifier reference. + * It's generated by plugins and cannot be handled reliably in the core rule. + */ + return; + } + + const readReferences = + targetAssignment.variable.references.filter(reference => + reference.isRead(), + ); + + if (!readReferences.length) { + /* + * It is not just an unnecessary assignment, but an unnecessary (unused) variable + * and thus should not be reported by this rule because it is reported by `no-unused-vars`. + */ + return; + } + + /** + * Other assignment on the current segment and after current assignment. + */ + const otherAssignmentAfterTargetAssignment = + allAssignments.find(assignment => { + if ( + assignment === targetAssignment || + (assignment.segments.length && + assignment.segments.every( + segment => + !targetAssignment.segments.includes( + segment, + ), + )) + ) { + return false; + } + if ( + isIdentifierEvaluatedAfterAssignment( + targetAssignment, + assignment.identifier, + ) + ) { + return true; + } + if ( + assignment.expression && + assignment.expression.range[0] <= + targetAssignment.identifier.range[0] && + targetAssignment.identifier.range[1] <= + assignment.expression.range[1] + ) { + /* + * The target assignment is in an expression that is evaluated before the assignment. + * e.g. x=(x=1); + * ^^^ targetAssignment + * ^^^^^^^ assignment + */ + return true; + } + + return false; + }); + + for (const reference of readReferences) { + /* + * If the scope of the reference is outside the current code path scope, + * we cannot track whether this assignment is not used. + * For example, it can also be called asynchronously. + */ + if ( + target.scope !== getCodePathStartScope(reference.from) + ) { + return; + } + + // Checks if it is used in the same segment as the target assignment. + if ( + isIdentifierEvaluatedAfterAssignment( + targetAssignment, + reference.identifier, + ) && + (isIdentifierUsedBetweenAssignedAndEqualSign( + targetAssignment, + reference.identifier, + ) || + targetAssignment.segments.some(segment => + isIdentifierUsedInSegment( + segment, + reference.identifier, + ), + )) + ) { + if ( + otherAssignmentAfterTargetAssignment && + isIdentifierEvaluatedAfterAssignment( + otherAssignmentAfterTargetAssignment, + reference.identifier, + ) + ) { + // There was another assignment before the reference. Therefore, it has not been used yet. + continue; + } + + // Uses in statements after the written identifier. + return; + } + + if (otherAssignmentAfterTargetAssignment) { + /* + * The assignment was followed by another assignment in the same segment. + * Therefore, there is no need to check the next segment. + */ + continue; + } + + // Check subsequent segments. + for (const subsequentSegment of getSubsequentSegments()) { + if ( + isIdentifierUsedInSegment( + subsequentSegment.segment, + reference.identifier, + ) + ) { + if ( + subsequentSegment.assignment && + isIdentifierEvaluatedAfterAssignment( + subsequentSegment.assignment, + reference.identifier, + ) + ) { + // There was another assignment before the reference. Therefore, it has not been used yet. + continue; + } + + // It is used + return; + } + } + } + context.report({ + node: targetAssignment.identifier, + messageId: "unnecessaryAssignment", + data: { name: targetAssignment.identifier.name }, + }); + } + + // Verify that each assignment in the code path is used. + for (const assignments of target.assignments.values()) { + assignments.sort( + (a, b) => a.identifier.range[0] - b.identifier.range[0], + ); + for (const assignment of assignments) { + verifyAssignmentIsUsed(assignment, assignments); + } + } + } + + return { + onCodePathStart(codePath, node) { + const scope = sourceCode.getScope(node); + + scopeStack = { + upper: scopeStack, + codePath, + scope, + segments: Object.create(null), + currentSegments: new Set(), + assignments: new Map(), + tryStatementBlocks: [], + }; + codePathStartScopes.add(scopeStack.scope); + }, + onCodePathEnd() { + verify(scopeStack); + + scopeStack = scopeStack.upper; + }, + onCodePathSegmentStart(segment) { + const segmentInfo = { segment, first: null, last: null }; + + scopeStack.segments[segment.id] = segmentInfo; + scopeStack.currentSegments.add(segment); + }, + onCodePathSegmentEnd(segment) { + scopeStack.currentSegments.delete(segment); + }, + TryStatement(node) { + scopeStack.tryStatementBlocks.push(node.block); + }, + "Identifier, JSXIdentifier"(node) { + for (const segment of scopeStack.currentSegments) { + const segmentInfo = scopeStack.segments[segment.id]; + + if (!segmentInfo.first) { + segmentInfo.first = node; + } + segmentInfo.last = node; + } + }, + "VariableDeclarator[init!=null], AssignmentExpression, UpdateExpression:exit"( + node, + ) { + if (scopeStack.currentSegments.size === 0) { + // Ignore unreachable segments + return; + } + + const assignments = scopeStack.assignments; + + let pattern; + let expression = null; + + if (node.type === "VariableDeclarator") { + pattern = node.id; + expression = node.init; + } else if (node.type === "AssignmentExpression") { + pattern = node.left; + expression = node.right; + } else { + // UpdateExpression + pattern = node.argument; + } + + for (const identifier of extractIdentifiersFromPattern( + pattern, + )) { + const scope = sourceCode.getScope(identifier); + + /** @type {Variable} */ + const variable = findVariable(scope, identifier); + + if (!variable) { + continue; + } + + // We don't know where global variables are used. + if ( + variable.scope.type === "global" && + variable.defs.length === 0 + ) { + continue; + } + + /* + * If the scope of the variable is outside the current code path scope, + * we cannot track whether this assignment is not used. + */ + if ( + scopeStack.scope !== + getCodePathStartScope(variable.scope) + ) { + continue; + } + + // Variables marked by `markVariableAsUsed()` or + // exported by "exported" block comment. + if (variable.eslintUsed) { + continue; + } + + // Variables exported by ESM export syntax + if (variable.scope.type === "module") { + if ( + variable.defs.some( + def => + (def.type === "Variable" && + def.parent.parent.type === + "ExportNamedDeclaration") || + (def.type === "FunctionName" && + (def.node.parent.type === + "ExportNamedDeclaration" || + def.node.parent.type === + "ExportDefaultDeclaration")) || + (def.type === "ClassName" && + (def.node.parent.type === + "ExportNamedDeclaration" || + def.node.parent.type === + "ExportDefaultDeclaration")), + ) + ) { + continue; + } + if ( + variable.references.some( + reference => + reference.identifier.parent.type === + "ExportSpecifier", + ) + ) { + // It have `export { ... }` reference. + continue; + } + } + + let list = assignments.get(variable); + + if (!list) { + list = []; + assignments.set(variable, list); + } + list.push({ + variable, + identifier, + node, + expression, + segments: [...scopeStack.currentSegments], + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-backreference.js b/node_modules/eslint/lib/rules/no-useless-backreference.js new file mode 100644 index 0000000000000000000000000000000000000000..73cce577a2fc779ea855e4897b06462dac22cb97 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-backreference.js @@ -0,0 +1,263 @@ +/** + * @fileoverview Rule to disallow useless backreferences in regular expressions + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + CALL, + CONSTRUCT, + ReferenceTracker, + getStringIfConstant, +} = require("@eslint-community/eslint-utils"); +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const parser = new RegExpParser(); + +/** + * Finds the path from the given `regexpp` AST node to the root node. + * @param {regexpp.Node} node Node. + * @returns {regexpp.Node[]} Array that starts with the given node and ends with the root node. + */ +function getPathToRoot(node) { + const path = []; + let current = node; + + do { + path.push(current); + current = current.parent; + } while (current); + + return path; +} + +/** + * Determines whether the given `regexpp` AST node is a lookaround node. + * @param {regexpp.Node} node Node. + * @returns {boolean} `true` if it is a lookaround node. + */ +function isLookaround(node) { + return ( + node.type === "Assertion" && + (node.kind === "lookahead" || node.kind === "lookbehind") + ); +} + +/** + * Determines whether the given `regexpp` AST node is a negative lookaround node. + * @param {regexpp.Node} node Node. + * @returns {boolean} `true` if it is a negative lookaround node. + */ +function isNegativeLookaround(node) { + return isLookaround(node) && node.negate; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Disallow useless backreferences in regular expressions", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-useless-backreference", + }, + + schema: [], + + messages: { + nested: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}'{{ otherGroups }} from within that group.", + forward: + "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}'{{ otherGroups }} which appears later in the pattern.", + backward: + "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}'{{ otherGroups }} which appears before in the same lookbehind.", + disjunctive: + "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}'{{ otherGroups }} which is in another alternative.", + intoNegativeLookaround: + "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}'{{ otherGroups }} which is in a negative lookaround.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Checks and reports useless backreferences in the given regular expression. + * @param {ASTNode} node Node that represents regular expression. A regex literal or RegExp constructor call. + * @param {string} pattern Regular expression pattern. + * @param {string} flags Regular expression flags. + * @returns {void} + */ + function checkRegex(node, pattern, flags) { + let regExpAST; + + try { + regExpAST = parser.parsePattern(pattern, 0, pattern.length, { + unicode: flags.includes("u"), + unicodeSets: flags.includes("v"), + }); + } catch { + // Ignore regular expressions with syntax errors + return; + } + + visitRegExpAST(regExpAST, { + onBackreferenceEnter(bref) { + const groups = [bref.resolved].flat(), + brefPath = getPathToRoot(bref); + + const problems = groups.map(group => { + const groupPath = getPathToRoot(group); + + if (brefPath.includes(group)) { + // group is bref's ancestor => bref is nested ('nested reference') => group hasn't matched yet when bref starts to match. + return { + messageId: "nested", + group, + }; + } + + // Start from the root to find the lowest common ancestor. + let i = brefPath.length - 1, + j = groupPath.length - 1; + + do { + i--; + j--; + } while (brefPath[i] === groupPath[j]); + + const indexOfLowestCommonAncestor = j + 1, + groupCut = groupPath.slice( + 0, + indexOfLowestCommonAncestor, + ), + commonPath = groupPath.slice( + indexOfLowestCommonAncestor, + ), + lowestCommonLookaround = + commonPath.find(isLookaround), + isMatchingBackward = + lowestCommonLookaround && + lowestCommonLookaround.kind === "lookbehind"; + + if (groupCut.at(-1).type === "Alternative") { + // group's and bref's ancestor nodes below the lowest common ancestor are sibling alternatives => they're disjunctive. + return { + messageId: "disjunctive", + group, + }; + } + if (!isMatchingBackward && bref.end <= group.start) { + // bref is left, group is right ('forward reference') => group hasn't matched yet when bref starts to match. + return { + messageId: "forward", + group, + }; + } + if (isMatchingBackward && group.end <= bref.start) { + // the opposite of the previous when the regex is matching backward in a lookbehind context. + return { + messageId: "backward", + group, + }; + } + if (groupCut.some(isNegativeLookaround)) { + // group is in a negative lookaround which isn't bref's ancestor => group has already failed when bref starts to match. + return { + messageId: "intoNegativeLookaround", + group, + }; + } + + return null; + }); + + if ( + problems.length === 0 || + problems.some(problem => !problem) + ) { + // If there are no problems or no problems with any group then do not report it. + return; + } + + let problemsToReport; + + // Gets problems that appear in the same disjunction. + const problemsInSameDisjunction = problems.filter( + problem => problem.messageId !== "disjunctive", + ); + + if (problemsInSameDisjunction.length) { + // Only report problems that appear in the same disjunction. + problemsToReport = problemsInSameDisjunction; + } else { + // If all groups appear in different disjunctions, report it. + problemsToReport = problems; + } + + const [{ messageId, group }, ...other] = problemsToReport; + let otherGroups = ""; + + if (other.length === 1) { + otherGroups = " and another group"; + } else if (other.length > 1) { + otherGroups = ` and other ${other.length} groups`; + } + context.report({ + node, + messageId, + data: { + bref: bref.raw, + group: group.raw, + otherGroups, + }, + }); + }, + }); + } + + return { + "Literal[regex]"(node) { + const { pattern, flags } = node.regex; + + checkRegex(node, pattern, flags); + }, + Program(node) { + const scope = sourceCode.getScope(node), + tracker = new ReferenceTracker(scope), + traceMap = { + RegExp: { + [CALL]: true, + [CONSTRUCT]: true, + }, + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences( + traceMap, + )) { + const [patternNode, flagsNode] = refNode.arguments, + pattern = getStringIfConstant(patternNode, scope), + flags = getStringIfConstant(flagsNode, scope); + + if (typeof pattern === "string") { + checkRegex(refNode, pattern, flags || ""); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-call.js b/node_modules/eslint/lib/rules/no-useless-call.js new file mode 100644 index 0000000000000000000000000000000000000000..2a04ad2909229d6bb11735bd5bb603cb488777ef --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-call.js @@ -0,0 +1,95 @@ +/** + * @fileoverview A rule to disallow unnecessary `.call()` and `.apply()`. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a node is a `.call()`/`.apply()`. + * @param {ASTNode} node A CallExpression node to check. + * @returns {boolean} Whether or not the node is a `.call()`/`.apply()`. + */ +function isCallOrNonVariadicApply(node) { + const callee = astUtils.skipChainExpression(node.callee); + + return ( + callee.type === "MemberExpression" && + callee.property.type === "Identifier" && + callee.computed === false && + ((callee.property.name === "call" && node.arguments.length >= 1) || + (callee.property.name === "apply" && + node.arguments.length === 2 && + node.arguments[1].type === "ArrayExpression")) + ); +} + +/** + * Checks whether or not `thisArg` is not changed by `.call()`/`.apply()`. + * @param {ASTNode|null} expectedThis The node that is the owner of the applied function. + * @param {ASTNode} thisArg The node that is given to the first argument of the `.call()`/`.apply()`. + * @param {SourceCode} sourceCode The ESLint source code object. + * @returns {boolean} Whether or not `thisArg` is not changed by `.call()`/`.apply()`. + */ +function isValidThisArg(expectedThis, thisArg, sourceCode) { + if (!expectedThis) { + return astUtils.isNullOrUndefined(thisArg); + } + return astUtils.equalTokens(expectedThis, thisArg, sourceCode); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow unnecessary calls to `.call()` and `.apply()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-call", + }, + + schema: [], + + messages: { + unnecessaryCall: "Unnecessary '.{{name}}()'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + if (!isCallOrNonVariadicApply(node)) { + return; + } + + const callee = astUtils.skipChainExpression(node.callee); + const applied = astUtils.skipChainExpression(callee.object); + const expectedThis = + applied.type === "MemberExpression" ? applied.object : null; + const thisArg = node.arguments[0]; + + if (isValidThisArg(expectedThis, thisArg, sourceCode)) { + context.report({ + node, + messageId: "unnecessaryCall", + data: { name: callee.property.name }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-catch.js b/node_modules/eslint/lib/rules/no-useless-catch.js new file mode 100644 index 0000000000000000000000000000000000000000..e3df3093cbedceefbed7ebe858c18fa9dec5d57f --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-catch.js @@ -0,0 +1,57 @@ +/** + * @fileoverview Reports useless `catch` clauses that just rethrow their error. + * @author Teddy Katz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary `catch` clauses", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-useless-catch", + }, + + schema: [], + + messages: { + unnecessaryCatchClause: "Unnecessary catch clause.", + unnecessaryCatch: "Unnecessary try/catch wrapper.", + }, + }, + + create(context) { + return { + CatchClause(node) { + if ( + node.param && + node.param.type === "Identifier" && + node.body.body.length && + node.body.body[0].type === "ThrowStatement" && + node.body.body[0].argument.type === "Identifier" && + node.body.body[0].argument.name === node.param.name + ) { + if (node.parent.finalizer) { + context.report({ + node, + messageId: "unnecessaryCatchClause", + }); + } else { + context.report({ + node: node.parent, + messageId: "unnecessaryCatch", + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-computed-key.js b/node_modules/eslint/lib/rules/no-useless-computed-key.js new file mode 100644 index 0000000000000000000000000000000000000000..3c61c767216b63d518a0522006aa8802f2efe8d3 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-computed-key.js @@ -0,0 +1,204 @@ +/** + * @fileoverview Rule to disallow unnecessary computed property keys in object literals + * @author Burak Yigit Kaya + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the computed key syntax is unnecessarily used for the given node. + * In particular, it determines whether removing the square brackets and using the content between them + * directly as the key (e.g. ['foo'] -> 'foo') would produce valid syntax and preserve the same behavior. + * Valid non-computed keys are only: identifiers, number literals and string literals. + * Only literals can preserve the same behavior, with a few exceptions for specific node types: + * Property + * - { ["__proto__"]: foo } defines a property named "__proto__" + * { "__proto__": foo } defines object's prototype + * PropertyDefinition + * - class C { ["constructor"]; } defines an instance field named "constructor" + * class C { "constructor"; } produces a parsing error + * - class C { static ["constructor"]; } defines a static field named "constructor" + * class C { static "constructor"; } produces a parsing error + * - class C { static ["prototype"]; } produces a runtime error (doesn't break the whole script) + * class C { static "prototype"; } produces a parsing error (breaks the whole script) + * MethodDefinition + * - class C { ["constructor"]() {} } defines a prototype method named "constructor" + * class C { "constructor"() {} } defines the constructor + * - class C { static ["prototype"]() {} } produces a runtime error (doesn't break the whole script) + * class C { static "prototype"() {} } produces a parsing error (breaks the whole script) + * @param {ASTNode} node The node to check. It can be `Property`, `PropertyDefinition` or `MethodDefinition`. + * @throws {Error} (Unreachable.) + * @returns {void} `true` if the node has useless computed key. + */ +function hasUselessComputedKey(node) { + if (!node.computed) { + return false; + } + + const { key } = node; + + if (key.type !== "Literal") { + return false; + } + + const { value } = key; + + if (typeof value !== "number" && typeof value !== "string") { + return false; + } + + switch (node.type) { + case "Property": + if (node.parent.type === "ObjectExpression") { + return value !== "__proto__"; + } + return true; + + case "PropertyDefinition": + if (node.static) { + return value !== "constructor" && value !== "prototype"; + } + + return value !== "constructor"; + + case "MethodDefinition": + if (node.static) { + return value !== "prototype"; + } + + return value !== "constructor"; + + /* c8 ignore next */ + default: + throw new Error(`Unexpected node type: ${node.type}`); + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + enforceForClassMembers: true, + }, + ], + + docs: { + description: + "Disallow unnecessary computed property keys in objects and classes", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-useless-computed-key", + }, + + schema: [ + { + type: "object", + properties: { + enforceForClassMembers: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + fixable: "code", + + messages: { + unnecessarilyComputedProperty: + "Unnecessarily computed property [{{property}}] found.", + }, + }, + create(context) { + const sourceCode = context.sourceCode; + const [{ enforceForClassMembers }] = context.options; + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function check(node) { + if (hasUselessComputedKey(node)) { + const { key } = node; + + context.report({ + node, + messageId: "unnecessarilyComputedProperty", + data: { property: sourceCode.getText(key) }, + fix(fixer) { + const leftSquareBracket = sourceCode.getTokenBefore( + key, + astUtils.isOpeningBracketToken, + ); + const rightSquareBracket = sourceCode.getTokenAfter( + key, + astUtils.isClosingBracketToken, + ); + + // If there are comments between the brackets and the property name, don't do a fix. + if ( + sourceCode.commentsExistBetween( + leftSquareBracket, + rightSquareBracket, + ) + ) { + return null; + } + + const tokenBeforeLeftBracket = + sourceCode.getTokenBefore(leftSquareBracket); + + // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} }) + const needsSpaceBeforeKey = + tokenBeforeLeftBracket.range[1] === + leftSquareBracket.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBeforeLeftBracket, + sourceCode.getFirstToken(key), + ); + + const replacementKey = + (needsSpaceBeforeKey ? " " : "") + key.raw; + + return fixer.replaceTextRange( + [ + leftSquareBracket.range[0], + rightSquareBracket.range[1], + ], + replacementKey, + ); + }, + }); + } + } + + /** + * A no-op function to act as placeholder for checking a node when the `enforceForClassMembers` option is `false`. + * @returns {void} + * @private + */ + function noop() {} + + return { + Property: check, + MethodDefinition: enforceForClassMembers ? check : noop, + PropertyDefinition: enforceForClassMembers ? check : noop, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-concat.js b/node_modules/eslint/lib/rules/no-useless-concat.js new file mode 100644 index 0000000000000000000000000000000000000000..a4846e0100db82a76d9edb81036215c3943cebc5 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-concat.js @@ -0,0 +1,121 @@ +/** + * @fileoverview disallow unnecessary concatenation of template strings + * @author Henry Zhu + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a concatenation. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a concatenation. + */ +function isConcatenation(node) { + return node.type === "BinaryExpression" && node.operator === "+"; +} + +/** + * Checks if the given token is a `+` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a `+` token. + */ +function isConcatOperatorToken(token) { + return token.value === "+" && token.type === "Punctuator"; +} + +/** + * Gets the right most node on the left side of a BinaryExpression with + operator. + * @param {ASTNode} node A BinaryExpression node to check. + * @returns {ASTNode} node + */ +function getLeft(node) { + let left = node.left; + + while (isConcatenation(left)) { + left = left.right; + } + return left; +} + +/** + * Gets the left most node on the right side of a BinaryExpression with + operator. + * @param {ASTNode} node A BinaryExpression node to check. + * @returns {ASTNode} node + */ +function getRight(node) { + let right = node.right; + + while (isConcatenation(right)) { + right = right.left; + } + return right; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow unnecessary concatenation of literals or template literals", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-useless-concat", + }, + + schema: [], + + messages: { + unexpectedConcat: "Unexpected string concatenation of literals.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + BinaryExpression(node) { + // check if not concatenation + if (node.operator !== "+") { + return; + } + + // account for the `foo + "a" + "b"` case + const left = getLeft(node); + const right = getRight(node); + + if ( + astUtils.isStringLiteral(left) && + astUtils.isStringLiteral(right) && + astUtils.isTokenOnSameLine(left, right) + ) { + const operatorToken = sourceCode.getFirstTokenBetween( + left, + right, + isConcatOperatorToken, + ); + + context.report({ + node, + loc: operatorToken.loc, + messageId: "unexpectedConcat", + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-constructor.js b/node_modules/eslint/lib/rules/no-useless-constructor.js new file mode 100644 index 0000000000000000000000000000000000000000..d81cb6c27451b1971238339b207d4afd662c597a --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-constructor.js @@ -0,0 +1,262 @@ +/** + * @fileoverview Rule to flag the use of redundant constructors in classes. + * @author Alberto Rodríguez + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether any of a method's parameters have a decorator or are a parameter property. + * @param {ASTNode} node A method definition node. + * @returns {boolean} `true` if any parameter had a decorator or is a parameter property. + */ +function hasDecoratorsOrParameterProperty(node) { + return node.value.params.some( + param => + param.decorators?.length || param.type === "TSParameterProperty", + ); +} + +/** + * Checks whether a node's accessibility makes it not useless. + * @param {ASTNode} node A method definition node. + * @returns {boolean} `true` if the node has a useful accessibility. + */ +function hasUsefulAccessibility(node) { + switch (node.accessibility) { + case "protected": + case "private": + return true; + case "public": + return !!node.parent.parent.superClass; + default: + return false; + } +} + +/** + * Checks whether a given array of statements is a single call of `super`. + * @param {ASTNode[]} body An array of statements to check. + * @returns {boolean} `true` if the body is a single call of `super`. + */ +function isSingleSuperCall(body) { + return ( + body.length === 1 && + body[0].type === "ExpressionStatement" && + body[0].expression.type === "CallExpression" && + body[0].expression.callee.type === "Super" + ); +} + +/** + * Checks whether a given node is a pattern which doesn't have any side effects. + * Default parameters and Destructuring parameters can have side effects. + * @param {ASTNode} node A pattern node. + * @returns {boolean} `true` if the node doesn't have any side effects. + */ +function isSimple(node) { + return node.type === "Identifier" || node.type === "RestElement"; +} + +/** + * Checks whether a given array of expressions is `...arguments` or not. + * `super(...arguments)` passes all arguments through. + * @param {ASTNode[]} superArgs An array of expressions to check. + * @returns {boolean} `true` if the superArgs is `...arguments`. + */ +function isSpreadArguments(superArgs) { + return ( + superArgs.length === 1 && + superArgs[0].type === "SpreadElement" && + superArgs[0].argument.type === "Identifier" && + superArgs[0].argument.name === "arguments" + ); +} + +/** + * Checks whether given 2 nodes are identifiers which have the same name or not. + * @param {ASTNode} ctorParam A node to check. + * @param {ASTNode} superArg A node to check. + * @returns {boolean} `true` if the nodes are identifiers which have the same + * name. + */ +function isValidIdentifierPair(ctorParam, superArg) { + return ( + ctorParam.type === "Identifier" && + superArg.type === "Identifier" && + ctorParam.name === superArg.name + ); +} + +/** + * Checks whether given 2 nodes are a rest/spread pair which has the same values. + * @param {ASTNode} ctorParam A node to check. + * @param {ASTNode} superArg A node to check. + * @returns {boolean} `true` if the nodes are a rest/spread pair which has the + * same values. + */ +function isValidRestSpreadPair(ctorParam, superArg) { + return ( + ctorParam.type === "RestElement" && + superArg.type === "SpreadElement" && + isValidIdentifierPair(ctorParam.argument, superArg.argument) + ); +} + +/** + * Checks whether given 2 nodes have the same value or not. + * @param {ASTNode} ctorParam A node to check. + * @param {ASTNode} superArg A node to check. + * @returns {boolean} `true` if the nodes have the same value or not. + */ +function isValidPair(ctorParam, superArg) { + return ( + isValidIdentifierPair(ctorParam, superArg) || + isValidRestSpreadPair(ctorParam, superArg) + ); +} + +/** + * Checks whether the parameters of a constructor and the arguments of `super()` + * have the same values or not. + * @param {ASTNode} ctorParams The parameters of a constructor to check. + * @param {ASTNode} superArgs The arguments of `super()` to check. + * @returns {boolean} `true` if those have the same values. + */ +function isPassingThrough(ctorParams, superArgs) { + if (ctorParams.length !== superArgs.length) { + return false; + } + + for (let i = 0; i < ctorParams.length; ++i) { + if (!isValidPair(ctorParams[i], superArgs[i])) { + return false; + } + } + + return true; +} + +/** + * Checks whether the constructor body is a redundant super call. + * @param {Array} body constructor body content. + * @param {Array} ctorParams The params to check against super call. + * @returns {boolean} true if the constructor body is redundant + */ +function isRedundantSuperCall(body, ctorParams) { + return ( + isSingleSuperCall(body) && + ctorParams.every(isSimple) && + (isSpreadArguments(body[0].expression.arguments) || + isPassingThrough(ctorParams, body[0].expression.arguments)) + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow unnecessary constructors", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-constructor", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + noUselessConstructor: "Useless constructor.", + removeConstructor: "Remove the constructor.", + }, + }, + + create(context) { + const { sourceCode } = context; + + /** + * Checks whether a node is a redundant constructor + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkForConstructor(node) { + if ( + node.kind !== "constructor" || + node.value.type !== "FunctionExpression" || + hasDecoratorsOrParameterProperty(node) || + hasUsefulAccessibility(node) + ) { + return; + } + + /* + * Prevent crashing on parsers which do not require class constructor + * to have a body, e.g. typescript and flow + */ + if (!node.value.body) { + return; + } + + const body = node.value.body.body; + const ctorParams = node.value.params; + const superClass = node.parent.parent.superClass; + const parenToken = sourceCode.getFirstToken( + node, + astUtils.isOpeningParenToken, + ); + const loc = { + start: node.loc.start, + end: sourceCode.getTokenBefore(parenToken).loc.end, + }; + + if ( + superClass + ? isRedundantSuperCall(body, ctorParams) + : body.length === 0 + ) { + context.report({ + loc, + messageId: "noUselessConstructor", + suggest: [ + { + messageId: "removeConstructor", + *fix(fixer) { + const nextToken = + sourceCode.getTokenAfter(node); + const addSemiColon = + astUtils.canContinueExpressionInClassBody( + nextToken, + ) && + astUtils.needsPrecedingSemicolon( + sourceCode, + node, + ); + + yield fixer.replaceText( + node, + addSemiColon ? ";" : "", + ); + }, + }, + ], + }); + } + } + + return { + MethodDefinition: checkForConstructor, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-escape.js b/node_modules/eslint/lib/rules/no-useless-escape.js new file mode 100644 index 0000000000000000000000000000000000000000..480b5159773ac9ddd1d248f29243b1de8ff6eb80 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-escape.js @@ -0,0 +1,406 @@ +/** + * @fileoverview Look for useless escapes in strings and regexes + * @author Onur Temizkan + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); +const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp"); + +/** + * @typedef {import('@eslint-community/regexpp').AST.CharacterClass} CharacterClass + * @typedef {import('@eslint-community/regexpp').AST.ExpressionCharacterClass} ExpressionCharacterClass + */ +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Returns the union of two sets. + * @param {Set} setA The first set + * @param {Set} setB The second set + * @returns {Set} The union of the two sets + */ +function union(setA, setB) { + return new Set( + (function* () { + yield* setA; + yield* setB; + })(), + ); +} + +const VALID_STRING_ESCAPES = union(new Set("\\nrvtbfux"), astUtils.LINEBREAKS); +const REGEX_GENERAL_ESCAPES = new Set("\\bcdDfnpPrsStvwWxu0123456789]"); +const REGEX_NON_CHARCLASS_ESCAPES = union( + REGEX_GENERAL_ESCAPES, + new Set("^/.$*+?[{}|()Bk"), +); + +/* + * Set of characters that require escaping in character classes in `unicodeSets` mode. + * ( ) [ ] { } / - \ | are ClassSetSyntaxCharacter + */ +const REGEX_CLASSSET_CHARACTER_ESCAPES = union( + REGEX_GENERAL_ESCAPES, + new Set("q/[{}|()-"), +); + +/* + * A single character set of ClassSetReservedDoublePunctuator. + * && !! ## $$ %% ** ++ ,, .. :: ;; << == >> ?? @@ ^^ `` ~~ are ClassSetReservedDoublePunctuator + */ +const REGEX_CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR = new Set( + "!#$%&*+,.:;<=>?@^`~", +); + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowRegexCharacters: [], + }, + ], + + docs: { + description: "Disallow unnecessary escape characters", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-useless-escape", + }, + + hasSuggestions: true, + + messages: { + unnecessaryEscape: "Unnecessary escape character: \\{{character}}.", + removeEscape: + "Remove the `\\`. This maintains the current functionality.", + removeEscapeDoNotKeepSemantics: + "Remove the `\\` if it was inserted by mistake.", + escapeBackslash: + "Replace the `\\` with `\\\\` to include the actual backslash character.", + }, + + schema: [ + { + type: "object", + properties: { + allowRegexCharacters: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ allowRegexCharacters }] = context.options; + const parser = new RegExpParser(); + + /** + * Reports a node + * @param {ASTNode} node The node to report + * @param {number} startOffset The backslash's offset from the start of the node + * @param {string} character The uselessly escaped character (not including the backslash) + * @param {boolean} [disableEscapeBackslashSuggest] `true` if escapeBackslash suggestion should be turned off. + * @returns {void} + */ + function report( + node, + startOffset, + character, + disableEscapeBackslashSuggest, + ) { + const rangeStart = node.range[0] + startOffset; + const range = [rangeStart, rangeStart + 1]; + const start = sourceCode.getLocFromIndex(rangeStart); + + context.report({ + node, + loc: { + start, + end: { line: start.line, column: start.column + 1 }, + }, + messageId: "unnecessaryEscape", + data: { character }, + suggest: [ + { + // Removing unnecessary `\` characters in a directive is not guaranteed to maintain functionality. + messageId: astUtils.isDirective(node.parent) + ? "removeEscapeDoNotKeepSemantics" + : "removeEscape", + fix(fixer) { + return fixer.removeRange(range); + }, + }, + ...(disableEscapeBackslashSuggest + ? [] + : [ + { + messageId: "escapeBackslash", + fix(fixer) { + return fixer.insertTextBeforeRange( + range, + "\\", + ); + }, + }, + ]), + ], + }); + } + + /** + * Checks if the escape character in given string slice is unnecessary. + * @private + * @param {ASTNode} node node to validate. + * @param {string} match string slice to validate. + * @returns {void} + */ + function validateString(node, match) { + const isTemplateElement = node.type === "TemplateElement"; + const escapedChar = match[0][1]; + let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar); + let isQuoteEscape; + + if (isTemplateElement) { + isQuoteEscape = escapedChar === "`"; + + if (escapedChar === "$") { + // Warn if `\$` is not followed by `{` + isUnnecessaryEscape = match.input[match.index + 2] !== "{"; + } else if (escapedChar === "{") { + /* + * Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping + * is necessary and the rule should not warn. If preceded by `/$`, the rule + * will warn for the `/$` instead, as it is the first unnecessarily escaped character. + */ + isUnnecessaryEscape = match.input[match.index - 1] !== "$"; + } + } else { + isQuoteEscape = escapedChar === node.raw[0]; + } + + if (isUnnecessaryEscape && !isQuoteEscape) { + report(node, match.index, match[0].slice(1)); + } + } + + /** + * Checks if the escape character in given regexp is unnecessary. + * @private + * @param {ASTNode} node node to validate. + * @returns {void} + */ + function validateRegExp(node) { + const { pattern, flags } = node.regex; + let patternNode; + const unicode = flags.includes("u"); + const unicodeSets = flags.includes("v"); + + try { + patternNode = parser.parsePattern(pattern, 0, pattern.length, { + unicode, + unicodeSets, + }); + } catch { + // Ignore regular expressions with syntax errors + return; + } + + /** @type {(CharacterClass | ExpressionCharacterClass)[]} */ + const characterClassStack = []; + + visitRegExpAST(patternNode, { + onCharacterClassEnter: characterClassNode => + characterClassStack.unshift(characterClassNode), + onCharacterClassLeave: () => characterClassStack.shift(), + onExpressionCharacterClassEnter: characterClassNode => + characterClassStack.unshift(characterClassNode), + onExpressionCharacterClassLeave: () => + characterClassStack.shift(), + onCharacterEnter(characterNode) { + if (!characterNode.raw.startsWith("\\")) { + // It's not an escaped character. + return; + } + + const escapedChar = characterNode.raw.slice(1); + + if ( + escapedChar !== + String.fromCodePoint(characterNode.value) || + allowRegexCharacters.includes(escapedChar) + ) { + // It's a valid escape. + return; + } + let allowedEscapes; + + if (characterClassStack.length) { + allowedEscapes = unicodeSets + ? REGEX_CLASSSET_CHARACTER_ESCAPES + : REGEX_GENERAL_ESCAPES; + } else { + allowedEscapes = REGEX_NON_CHARCLASS_ESCAPES; + } + if (allowedEscapes.has(escapedChar)) { + return; + } + + const reportedIndex = characterNode.start + 1; + let disableEscapeBackslashSuggest = false; + + if (characterClassStack.length) { + const characterClassNode = characterClassStack[0]; + + if (escapedChar === "^") { + /* + * The '^' character is also a special case; it must always be escaped outside of character classes, but + * it only needs to be escaped in character classes if it's at the beginning of the character class. To + * account for this, consider it to be a valid escape character outside of character classes, and filter + * out '^' characters that appear at the start of a character class. + */ + if ( + characterClassNode.start + 1 === + characterNode.start + ) { + return; + } + } + if (!unicodeSets) { + if (escapedChar === "-") { + /* + * The '-' character is a special case, because it's only valid to escape it if it's in a character + * class, and is not at either edge of the character class. To account for this, don't consider '-' + * characters to be valid in general, and filter out '-' characters that appear in the middle of a + * character class. + */ + if ( + characterClassNode.start + 1 !== + characterNode.start && + characterNode.end !== + characterClassNode.end - 1 + ) { + return; + } + } + } else { + // unicodeSets mode + if ( + REGEX_CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR.has( + escapedChar, + ) + ) { + // Escaping is valid if it is a ClassSetReservedDoublePunctuator. + if ( + pattern[characterNode.end] === escapedChar + ) { + return; + } + if ( + pattern[characterNode.start - 1] === + escapedChar + ) { + if (escapedChar !== "^") { + return; + } + + // If the previous character is a `negate` caret(`^`), escape to caret is unnecessary. + + if (!characterClassNode.negate) { + return; + } + const negateCaretIndex = + characterClassNode.start + 1; + + if ( + negateCaretIndex < + characterNode.start - 1 + ) { + return; + } + } + } + + if ( + characterNode.parent.type === + "ClassIntersection" || + characterNode.parent.type === "ClassSubtraction" + ) { + disableEscapeBackslashSuggest = true; + } + } + } + + report( + node, + reportedIndex, + escapedChar, + disableEscapeBackslashSuggest, + ); + }, + }); + } + + /** + * Checks if a node has an escape. + * @param {ASTNode} node node to check. + * @returns {void} + */ + function check(node) { + const isTemplateElement = node.type === "TemplateElement"; + + if ( + isTemplateElement && + node.parent && + node.parent.parent && + node.parent.parent.type === "TaggedTemplateExpression" && + node.parent === node.parent.parent.quasi + ) { + // Don't report tagged template literals, because the backslash character is accessible to the tag function. + return; + } + + if (typeof node.value === "string" || isTemplateElement) { + /* + * JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/. + * In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25. + */ + if ( + node.parent.type === "JSXAttribute" || + node.parent.type === "JSXElement" || + node.parent.type === "JSXFragment" + ) { + return; + } + + const value = isTemplateElement + ? sourceCode.getText(node) + : node.raw; + const pattern = /\\\D/gu; + let match; + + while ((match = pattern.exec(value))) { + validateString(node, match); + } + } else if (node.regex) { + validateRegExp(node); + } + } + + return { + Literal: check, + TemplateElement: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-rename.js b/node_modules/eslint/lib/rules/no-useless-rename.js new file mode 100644 index 0000000000000000000000000000000000000000..13c76861c9649b7a00b55723acfb2241d8edceef --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-rename.js @@ -0,0 +1,202 @@ +/** + * @fileoverview Disallow renaming import, export, and destructured assignments to the same name. + * @author Kai Cataldo + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + ignoreDestructuring: false, + ignoreImport: false, + ignoreExport: false, + }, + ], + + docs: { + description: + "Disallow renaming import, export, and destructured assignments to the same name", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-rename", + }, + + fixable: "code", + + schema: [ + { + type: "object", + properties: { + ignoreDestructuring: { type: "boolean" }, + ignoreImport: { type: "boolean" }, + ignoreExport: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + + messages: { + unnecessarilyRenamed: "{{type}} {{name}} unnecessarily renamed.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ ignoreDestructuring, ignoreImport, ignoreExport }] = + context.options; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports error for unnecessarily renamed assignments + * @param {ASTNode} node node to report + * @param {ASTNode} initial node with initial name value + * @param {string} type the type of the offending node + * @returns {void} + */ + function reportError(node, initial, type) { + const name = + initial.type === "Identifier" ? initial.name : initial.value; + + return context.report({ + node, + messageId: "unnecessarilyRenamed", + data: { + name, + type, + }, + fix(fixer) { + const replacementNode = + node.type === "Property" ? node.value : node.local; + + if ( + sourceCode.getCommentsInside(node).length > + sourceCode.getCommentsInside(replacementNode).length + ) { + return null; + } + + // Don't autofix code such as `({foo: (foo) = a} = obj);`, parens are not allowed in shorthand properties. + if ( + replacementNode.type === "AssignmentPattern" && + astUtils.isParenthesised( + sourceCode, + replacementNode.left, + ) + ) { + return null; + } + + return fixer.replaceText( + node, + sourceCode.getText(replacementNode), + ); + }, + }); + } + + /** + * Checks whether a destructured assignment is unnecessarily renamed + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkDestructured(node) { + if (ignoreDestructuring) { + return; + } + + for (const property of node.properties) { + /** + * Properties using shorthand syntax and rest elements can not be renamed. + * If the property is computed, we have no idea if a rename is useless or not. + */ + if ( + property.type !== "Property" || + property.shorthand || + property.computed + ) { + continue; + } + + const key = + (property.key.type === "Identifier" && property.key.name) || + (property.key.type === "Literal" && property.key.value); + const renamedKey = + property.value.type === "AssignmentPattern" + ? property.value.left.name + : property.value.name; + + if (key === renamedKey) { + reportError( + property, + property.key, + "Destructuring assignment", + ); + } + } + } + + /** + * Checks whether an import is unnecessarily renamed + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkImport(node) { + if (ignoreImport) { + return; + } + + if ( + node.imported.range[0] !== node.local.range[0] && + astUtils.getModuleExportName(node.imported) === node.local.name + ) { + reportError(node, node.imported, "Import"); + } + } + + /** + * Checks whether an export is unnecessarily renamed + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkExport(node) { + if (ignoreExport) { + return; + } + + if ( + node.local.range[0] !== node.exported.range[0] && + astUtils.getModuleExportName(node.local) === + astUtils.getModuleExportName(node.exported) + ) { + reportError(node, node.local, "Export"); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ObjectPattern: checkDestructured, + ImportSpecifier: checkImport, + ExportSpecifier: checkExport, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-useless-return.js b/node_modules/eslint/lib/rules/no-useless-return.js new file mode 100644 index 0000000000000000000000000000000000000000..a2f0380d563d783c793e653b0b940b5e0bd5f36c --- /dev/null +++ b/node_modules/eslint/lib/rules/no-useless-return.js @@ -0,0 +1,387 @@ +/** + * @fileoverview Disallow redundant return statements + * @author Teddy Katz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"), + FixTracker = require("./utils/fix-tracker"); +const { isAnySegmentReachable } = require("./utils/code-path-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Removes the given element from the array. + * @param {Array} array The source array to remove. + * @param {any} element The target item to remove. + * @returns {void} + */ +function remove(array, element) { + const index = array.indexOf(element); + + if (index !== -1) { + array.splice(index, 1); + } +} + +/** + * Checks whether it can remove the given return statement or not. + * @param {ASTNode} node The return statement node to check. + * @returns {boolean} `true` if the node is removable. + */ +function isRemovable(node) { + return astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type); +} + +/** + * Checks whether the given return statement is in a `finally` block or not. + * @param {ASTNode} node The return statement node to check. + * @returns {boolean} `true` if the node is in a `finally` block. + */ +function isInFinally(node) { + for ( + let currentNode = node; + currentNode && currentNode.parent && !astUtils.isFunction(currentNode); + currentNode = currentNode.parent + ) { + if ( + currentNode.parent.type === "TryStatement" && + currentNode.parent.finalizer === currentNode + ) { + return true; + } + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow redundant return statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-useless-return", + }, + + fixable: "code", + schema: [], + + messages: { + unnecessaryReturn: "Unnecessary return statement.", + }, + }, + + create(context) { + const segmentInfoMap = new WeakMap(); + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Checks whether the given segment is terminated by a return statement or not. + * @param {CodePathSegment} segment The segment to check. + * @returns {boolean} `true` if the segment is terminated by a return statement, or if it's still a part of unreachable. + */ + function isReturned(segment) { + const info = segmentInfoMap.get(segment); + + return !info || info.returned; + } + + /** + * Collects useless return statements from the given previous segments. + * + * A previous segment may be an unreachable segment. + * In that case, the information object of the unreachable segment is not + * initialized because `onCodePathSegmentStart` event is not notified for + * unreachable segments. + * This goes to the previous segments of the unreachable segment recursively + * if the unreachable segment was generated by a return statement. Otherwise, + * this ignores the unreachable segment. + * + * This behavior would simulate code paths for the case that the return + * statement does not exist. + * @param {ASTNode[]} uselessReturns The collected return statements. + * @param {CodePathSegment[]} prevSegments The previous segments to traverse. + * @param {WeakSet} [providedTraversedSegments] A set of segments that have already been traversed in this call + * @returns {ASTNode[]} `uselessReturns`. + */ + function getUselessReturns( + uselessReturns, + prevSegments, + providedTraversedSegments, + ) { + const traversedSegments = + providedTraversedSegments || new WeakSet(); + + for (const segment of prevSegments) { + if (!segment.reachable) { + if (!traversedSegments.has(segment)) { + traversedSegments.add(segment); + getUselessReturns( + uselessReturns, + segment.allPrevSegments.filter(isReturned), + traversedSegments, + ); + } + continue; + } + + if (segmentInfoMap.has(segment)) { + uselessReturns.push( + ...segmentInfoMap.get(segment).uselessReturns, + ); + } + } + + return uselessReturns; + } + + /** + * Removes the return statements on the given segment from the useless return + * statement list. + * + * This segment may be an unreachable segment. + * In that case, the information object of the unreachable segment is not + * initialized because `onCodePathSegmentStart` event is not notified for + * unreachable segments. + * This goes to the previous segments of the unreachable segment recursively + * if the unreachable segment was generated by a return statement. Otherwise, + * this ignores the unreachable segment. + * + * This behavior would simulate code paths for the case that the return + * statement does not exist. + * @param {CodePathSegment} segment The segment to get return statements. + * @param {Set} usedUnreachableSegments A set of segments that have already been traversed in this call. + * @returns {void} + */ + function markReturnStatementsOnSegmentAsUsed( + segment, + usedUnreachableSegments, + ) { + if (!segment.reachable) { + usedUnreachableSegments.add(segment); + segment.allPrevSegments + .filter(isReturned) + .filter( + prevSegment => + !usedUnreachableSegments.has(prevSegment), + ) + .forEach(prevSegment => + markReturnStatementsOnSegmentAsUsed( + prevSegment, + usedUnreachableSegments, + ), + ); + return; + } + + const info = segmentInfoMap.get(segment); + + if (!info) { + return; + } + + info.uselessReturns = info.uselessReturns.filter(node => { + if ( + scopeInfo.traversedTryBlockStatements && + scopeInfo.traversedTryBlockStatements.length > 0 + ) { + const returnInitialRange = node.range[0]; + const returnFinalRange = node.range[1]; + + const areBlocksInRange = + scopeInfo.traversedTryBlockStatements.some( + tryBlockStatement => { + const blockInitialRange = + tryBlockStatement.range[0]; + const blockFinalRange = + tryBlockStatement.range[1]; + + return ( + returnInitialRange >= blockInitialRange && + returnFinalRange <= blockFinalRange + ); + }, + ); + + if (areBlocksInRange) { + return true; + } + } + + remove(scopeInfo.uselessReturns, node); + return false; + }); + } + + /** + * Removes the return statements on the current segments from the useless + * return statement list. + * + * This function will be called at every statement except FunctionDeclaration, + * BlockStatement, and BreakStatement. + * + * - FunctionDeclarations are always executed whether it's returned or not. + * - BlockStatements do nothing. + * - BreakStatements go the next merely. + * @returns {void} + */ + function markReturnStatementsOnCurrentSegmentsAsUsed() { + scopeInfo.currentSegments.forEach(segment => + markReturnStatementsOnSegmentAsUsed(segment, new Set()), + ); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + // Makes and pushes a new scope information. + onCodePathStart(codePath) { + scopeInfo = { + upper: scopeInfo, + uselessReturns: [], + traversedTryBlockStatements: [], + codePath, + currentSegments: new Set(), + }; + }, + + // Reports useless return statements if exist. + onCodePathEnd() { + for (const node of scopeInfo.uselessReturns) { + context.report({ + node, + loc: node.loc, + messageId: "unnecessaryReturn", + fix(fixer) { + if ( + isRemovable(node) && + !sourceCode.getCommentsInside(node).length + ) { + /* + * Extend the replacement range to include the + * entire function to avoid conflicting with + * no-else-return. + * https://github.com/eslint/eslint/issues/8026 + */ + return new FixTracker(fixer, sourceCode) + .retainEnclosingFunction(node) + .remove(node); + } + return null; + }, + }); + } + + scopeInfo = scopeInfo.upper; + }, + + /* + * Initializes segments. + * NOTE: This event is notified for only reachable segments. + */ + onCodePathSegmentStart(segment) { + scopeInfo.currentSegments.add(segment); + + const info = { + uselessReturns: getUselessReturns( + [], + segment.allPrevSegments, + ), + returned: false, + }; + + // Stores the info. + segmentInfoMap.set(segment, info); + }, + + onUnreachableCodePathSegmentStart(segment) { + scopeInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + scopeInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + scopeInfo.currentSegments.delete(segment); + }, + + // Adds ReturnStatement node to check whether it's useless or not. + ReturnStatement(node) { + if (node.argument) { + markReturnStatementsOnCurrentSegmentsAsUsed(); + } + if ( + node.argument || + astUtils.isInLoop(node) || + isInFinally(node) || + // Ignore `return` statements in unreachable places (https://github.com/eslint/eslint/issues/11647). + !isAnySegmentReachable(scopeInfo.currentSegments) + ) { + return; + } + + for (const segment of scopeInfo.currentSegments) { + const info = segmentInfoMap.get(segment); + + if (info) { + info.uselessReturns.push(node); + info.returned = true; + } + } + scopeInfo.uselessReturns.push(node); + }, + + "TryStatement > BlockStatement.block:exit"(node) { + scopeInfo.traversedTryBlockStatements.push(node); + }, + + "TryStatement:exit"() { + scopeInfo.traversedTryBlockStatements.pop(); + }, + + /* + * Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement. + * Removes return statements of the current segments from the useless return statement list. + */ + ClassDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ContinueStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + DebuggerStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + DoWhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + EmptyStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ExpressionStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForInStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForOfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + IfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ImportDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + LabeledStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + SwitchStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ThrowStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + TryStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + VariableDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + WhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + WithStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportNamedDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportDefaultDeclaration: + markReturnStatementsOnCurrentSegmentsAsUsed, + ExportAllDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-var.js b/node_modules/eslint/lib/rules/no-var.js new file mode 100644 index 0000000000000000000000000000000000000000..1839dbb22c3ee45336ca8b519baeb19d4289f383 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-var.js @@ -0,0 +1,402 @@ +/** + * @fileoverview Rule to check for the usage of var. + * @author Jamund Ferguson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("eslint-scope").Variable} Variable */ +/** @typedef {import("eslint-scope").Reference} Reference */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Check whether a given variable is a global variable or not. + * @param {Variable} variable The variable to check. + * @returns {boolean} `true` if the variable is a global variable. + */ +function isGlobal(variable) { + return Boolean(variable.scope) && variable.scope.type === "global"; +} + +/** + * Finds the nearest function scope or global scope walking up the scope + * hierarchy. + * @param {Scope} scope The scope to traverse. + * @returns {Scope} a function scope or global scope containing the given + * scope. + */ +function getEnclosingFunctionScope(scope) { + let currentScope = scope; + + while (currentScope.type !== "function" && currentScope.type !== "global") { + currentScope = currentScope.upper; + } + return currentScope; +} + +/** + * Checks whether the given variable has any references from a more specific + * function expression (i.e. a closure). + * @param {Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is used from a closure. + */ +function isReferencedInClosure(variable) { + const enclosingFunctionScope = getEnclosingFunctionScope(variable.scope); + + return variable.references.some( + reference => + getEnclosingFunctionScope(reference.from) !== + enclosingFunctionScope, + ); +} + +/** + * Checks whether the given node is the assignee of a loop. + * @param {ASTNode} node A VariableDeclaration node to check. + * @returns {boolean} `true` if the declaration is assigned as part of loop + * iteration. + */ +function isLoopAssignee(node) { + return ( + (node.parent.type === "ForOfStatement" || + node.parent.type === "ForInStatement") && + node === node.parent.left + ); +} + +/** + * Checks whether the given variable declaration is immediately initialized. + * @param {ASTNode} node A VariableDeclaration node to check. + * @returns {boolean} `true` if the declaration has an initializer. + */ +function isDeclarationInitialized(node) { + return node.declarations.every(declarator => declarator.init !== null); +} + +const SCOPE_NODE_TYPE = + /^(?:Program|BlockStatement|SwitchStatement|ForStatement|ForInStatement|ForOfStatement)$/u; + +/** + * Gets the scope node which directly contains a given node. + * @param {ASTNode} node A node to get. This is a `VariableDeclaration` or + * an `Identifier`. + * @returns {ASTNode} A scope node. This is one of `Program`, `BlockStatement`, + * `SwitchStatement`, `ForStatement`, `ForInStatement`, and + * `ForOfStatement`. + */ +function getScopeNode(node) { + for ( + let currentNode = node; + currentNode; + currentNode = currentNode.parent + ) { + if (SCOPE_NODE_TYPE.test(currentNode.type)) { + return currentNode; + } + } + + /* c8 ignore next */ + return null; +} + +/** + * Checks whether a given variable is redeclared or not. + * @param {Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is redeclared. + */ +function isRedeclared(variable) { + return variable.defs.length >= 2; +} + +/** + * Checks whether a given variable is used from outside of the specified scope. + * @param {ASTNode} scopeNode A scope node to check. + * @returns {Function} The predicate function which checks whether a given + * variable is used from outside of the specified scope. + */ +function isUsedFromOutsideOf(scopeNode) { + /** + * Checks whether a given reference is inside of the specified scope or not. + * @param {Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is inside of the specified + * scope. + */ + function isOutsideOfScope(reference) { + const scope = scopeNode.range; + const id = reference.identifier.range; + + return id[0] < scope[0] || id[1] > scope[1]; + } + + return function (variable) { + return variable.references.some(isOutsideOfScope); + }; +} + +/** + * Creates the predicate function which checks whether a variable has their references in TDZ. + * + * The predicate function would return `true`: + * + * - if a reference is before the declarator. E.g. (var a = b, b = 1;)(var {a = b, b} = {};) + * - if a reference is in the expression of their default value. E.g. (var {a = a} = {};) + * - if a reference is in the expression of their initializer. E.g. (var a = a;) + * @param {ASTNode} node The initializer node of VariableDeclarator. + * @returns {Function} The predicate function. + * @private + */ +function hasReferenceInTDZ(node) { + const initStart = node.range[0]; + const initEnd = node.range[1]; + + return variable => { + const id = variable.defs[0].name; + const idStart = id.range[0]; + const defaultValue = + id.parent.type === "AssignmentPattern" ? id.parent.right : null; + const defaultStart = defaultValue && defaultValue.range[0]; + const defaultEnd = defaultValue && defaultValue.range[1]; + + return variable.references.some(reference => { + const start = reference.identifier.range[0]; + const end = reference.identifier.range[1]; + + return ( + !reference.init && + (start < idStart || + (defaultValue !== null && + start >= defaultStart && + end <= defaultEnd) || + (!astUtils.isFunction(node) && + start >= initStart && + end <= initEnd)) + ); + }); + }; +} + +/** + * Checks whether a given variable has name that is allowed for 'var' declarations, + * but disallowed for `let` declarations. + * @param {Variable} variable The variable to check. + * @returns {boolean} `true` if the variable has a disallowed name. + */ +function hasNameDisallowedForLetDeclarations(variable) { + return variable.name === "let"; +} + +/** + * Checks whether a given variable has any references before its declaration. + * This is important because var allows hoisting, but let/const do not. + * @param {Variable} variable The variable to check. + * @returns {boolean} `true` if the variable is referenced before its declaration. + */ +function hasReferenceBeforeDeclaration(variable) { + const declarationStart = variable.defs[0].node.range[0]; + + return variable.references.some(reference => { + const referenceStart = reference.identifier.range[0]; + + /* + * Check if the reference occurs before the declaration. + * We don't need to check scopes because all references to this variable + * are already in variable.references (which only includes references + * that resolve to this specific variable binding). + */ + return !reference.init && referenceStart < declarationStart; + }); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `let` or `const` instead of `var`", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-var", + }, + + schema: [], + fixable: "code", + + messages: { + unexpectedVar: "Unexpected var, use let or const instead.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Checks whether the variables which are defined by the given declarator node have their references in TDZ. + * @param {ASTNode} declarator The VariableDeclarator node to check. + * @returns {boolean} `true` if one of the variables which are defined by the given declarator node have their references in TDZ. + */ + function hasSelfReferenceInTDZ(declarator) { + if (!declarator.init) { + return false; + } + const variables = sourceCode.getDeclaredVariables(declarator); + + return variables.some(hasReferenceInTDZ(declarator.init)); + } + + /** + * Checks whether it can fix a given variable declaration or not. + * It cannot fix if the following cases: + * + * - A variable is a global variable. + * - A variable is declared on a SwitchCase node. + * - A variable is redeclared. + * - A variable is used from outside the scope. + * - A variable is used from a closure within a loop. + * - A variable might be used before it is assigned within a loop. + * - A variable might be used in TDZ. + * - A variable is referenced before its declaration. + * - A variable is declared in statement position (e.g. a single-line `IfStatement`) + * - A variable has name that is disallowed for `let` declarations. + * + * ## A variable is declared on a SwitchCase node. + * + * If this rule modifies 'var' declarations on a SwitchCase node, it + * would generate the warnings of 'no-case-declarations' rule. And the + * 'eslint:recommended' preset includes 'no-case-declarations' rule, so + * this rule doesn't modify those declarations. + * + * ## A variable is redeclared. + * + * The language spec disallows redeclarations of `let` declarations. + * Those variables would cause syntax errors. + * + * ## A variable is used from outside the scope. + * + * The language spec disallows accesses from outside of the scope for + * `let` declarations. Those variables would cause reference errors. + * + * ## A variable is used from a closure within a loop. + * + * A `var` declaration within a loop shares the same variable instance + * across all loop iterations, while a `let` declaration creates a new + * instance for each iteration. This means if a variable in a loop is + * referenced by any closure, changing it from `var` to `let` would + * change the behavior in a way that is generally unsafe. + * + * ## A variable might be used before it is assigned within a loop. + * + * Within a loop, a `let` declaration without an initializer will be + * initialized to null, while a `var` declaration will retain its value + * from the previous iteration, so it is only safe to change `var` to + * `let` if we can statically determine that the variable is always + * assigned a value before its first access in the loop body. To keep + * the implementation simple, we only convert `var` to `let` within + * loops when the variable is a loop assignee or the declaration has an + * initializer. + * @param {ASTNode} node A variable declaration node to check. + * @returns {boolean} `true` if it can fix the node. + */ + function canFix(node) { + const variables = sourceCode.getDeclaredVariables(node); + const scopeNode = getScopeNode(node); + const parentStatementList = new Set([ + ...astUtils.STATEMENT_LIST_PARENTS, + "TSModuleBlock", + ]); + + if ( + node.parent.type === "SwitchCase" || + node.declarations.some(hasSelfReferenceInTDZ) || + variables.some(isGlobal) || + variables.some(isRedeclared) || + variables.some(isUsedFromOutsideOf(scopeNode)) || + variables.some(hasNameDisallowedForLetDeclarations) || + variables.some(hasReferenceBeforeDeclaration) + ) { + return false; + } + + if (astUtils.isInLoop(node)) { + if (variables.some(isReferencedInClosure)) { + return false; + } + if (!isLoopAssignee(node) && !isDeclarationInitialized(node)) { + return false; + } + } + + if ( + !isLoopAssignee(node) && + !( + node.parent.type === "ForStatement" && + node.parent.init === node + ) && + !parentStatementList.has(node.parent.type) + ) { + // If the declaration is not in a block, e.g. `if (foo) var bar = 1;`, then it can't be fixed. + return false; + } + + return true; + } + + /** + * Reports a given variable declaration node. + * @param {ASTNode} node A variable declaration node to report. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "unexpectedVar", + + fix(fixer) { + const varToken = sourceCode.getFirstToken(node, { + filter: t => t.value === "var", + }); + + return canFix(node) + ? fixer.replaceText(varToken, "let") + : null; + }, + }); + } + + return { + "VariableDeclaration:exit"(node) { + if (node.kind !== "var") { + return; + } + + if ( + node.parent.type === "TSModuleBlock" && + node.parent.parent.type === "TSModuleDeclaration" && + node.parent.parent.global + ) { + return; + } + + report(node); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-void.js b/node_modules/eslint/lib/rules/no-void.js new file mode 100644 index 0000000000000000000000000000000000000000..7e99fd3c14887e4e603b43d39ba8fafeebcbcf92 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-void.js @@ -0,0 +1,69 @@ +/** + * @fileoverview Rule to disallow use of void operator. + * @author Mike Sidorov + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowAsStatement: false, + }, + ], + + docs: { + description: "Disallow `void` operators", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-void", + }, + + messages: { + noVoid: "Expected 'undefined' and instead saw 'void'.", + }, + + schema: [ + { + type: "object", + properties: { + allowAsStatement: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + + create(context) { + const [{ allowAsStatement }] = context.options; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + 'UnaryExpression[operator="void"]'(node) { + if ( + allowAsStatement && + node.parent && + node.parent.type === "ExpressionStatement" + ) { + return; + } + context.report({ + node, + messageId: "noVoid", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-warning-comments.js b/node_modules/eslint/lib/rules/no-warning-comments.js new file mode 100644 index 0000000000000000000000000000000000000000..8f1a7c36b488c4fddce510676ad7f24c334c8584 --- /dev/null +++ b/node_modules/eslint/lib/rules/no-warning-comments.js @@ -0,0 +1,209 @@ +/** + * @fileoverview Rule that warns about used warning comments + * @author Alexander Schmidt + */ + +"use strict"; + +const escapeRegExp = require("escape-string-regexp"); +const astUtils = require("./utils/ast-utils"); + +const CHAR_LIMIT = 40; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + location: "start", + terms: ["todo", "fixme", "xxx"], + }, + ], + + docs: { + description: "Disallow specified warning terms in comments", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/no-warning-comments", + }, + + schema: [ + { + type: "object", + properties: { + terms: { + type: "array", + items: { + type: "string", + }, + }, + location: { + enum: ["start", "anywhere"], + }, + decoration: { + type: "array", + items: { + type: "string", + pattern: "^\\S$", + }, + minItems: 1, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedComment: + "Unexpected '{{matchedTerm}}' comment: '{{comment}}'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ decoration, location, terms: warningTerms }] = context.options; + const escapedDecoration = escapeRegExp( + decoration ? decoration.join("") : "", + ); + const selfConfigRegEx = /\bno-warning-comments\b/u; + + /** + * Convert a warning term into a RegExp which will match a comment containing that whole word in the specified + * location ("start" or "anywhere"). If the term starts or ends with non word characters, then the match will not + * require word boundaries on that side. + * @param {string} term A term to convert to a RegExp + * @returns {RegExp} The term converted to a RegExp + */ + function convertToRegExp(term) { + const escaped = escapeRegExp(term); + + /* + * When matching at the start, ignore leading whitespace, and + * there's no need to worry about word boundaries. + * + * These expressions for the prefix and suffix are designed as follows: + * ^ handles any terms at the beginning of a comment. + * e.g. terms ["TODO"] matches `//TODO something` + * $ handles any terms at the end of a comment + * e.g. terms ["TODO"] matches `// something TODO` + * \b handles terms preceded/followed by word boundary + * e.g. terms: ["!FIX", "FIX!"] matches `// FIX!something` or `// something!FIX` + * terms: ["FIX"] matches `// FIX!` or `// !FIX`, but not `// fixed or affix` + * + * For location start: + * [\s]* handles optional leading spaces + * e.g. terms ["TODO"] matches `// TODO something` + * [\s\*]* (where "\*" is the escaped string of decoration) + * handles optional leading spaces or decoration characters (for "start" location only) + * e.g. terms ["TODO"] matches `/**** TODO something ... ` + */ + const wordBoundary = "\\b"; + + let prefix = ""; + + if (location === "start") { + prefix = `^[\\s${escapedDecoration}]*`; + } else if (/^\w/u.test(term)) { + prefix = wordBoundary; + } + + const suffix = /\w$/u.test(term) ? wordBoundary : ""; + const flags = "iu"; // Case-insensitive with Unicode case folding. + + /* + * For location "start", the typical regex is: + * /^[\s]*ESCAPED_TERM\b/iu. + * Or if decoration characters are specified (e.g. "*"), then any of + * those characters may appear in any order at the start: + * /^[\s\*]*ESCAPED_TERM\b/iu. + * + * For location "anywhere" the typical regex is + * /\bESCAPED_TERM\b/iu + * + * If it starts or ends with non-word character, the prefix and suffix are empty, respectively. + */ + return new RegExp(`${prefix}${escaped}${suffix}`, flags); + } + + const warningRegExps = warningTerms.map(convertToRegExp); + + /** + * Checks the specified comment for matches of the configured warning terms and returns the matches. + * @param {string} comment The comment which is checked. + * @returns {Array} All matched warning terms for this comment. + */ + function commentContainsWarningTerm(comment) { + const matches = []; + + warningRegExps.forEach((regex, index) => { + if (regex.test(comment)) { + matches.push(warningTerms[index]); + } + }); + + return matches; + } + + /** + * Checks the specified node for matching warning comments and reports them. + * @param {ASTNode} node The AST node being checked. + * @returns {void} undefined. + */ + function checkComment(node) { + const comment = node.value; + + if ( + astUtils.isDirectiveComment(node) && + selfConfigRegEx.test(comment) + ) { + return; + } + + const matches = commentContainsWarningTerm(comment); + + matches.forEach(matchedTerm => { + let commentToDisplay = ""; + let truncated = false; + + for (const c of comment.trim().split(/\s+/u)) { + const tmp = commentToDisplay + ? `${commentToDisplay} ${c}` + : c; + + if (tmp.length <= CHAR_LIMIT) { + commentToDisplay = tmp; + } else { + truncated = true; + break; + } + } + + context.report({ + node, + messageId: "unexpectedComment", + data: { + matchedTerm, + comment: `${commentToDisplay}${truncated ? "..." : ""}`, + }, + }); + }); + } + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments + .filter(token => token.type !== "Shebang") + .forEach(checkComment); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-whitespace-before-property.js b/node_modules/eslint/lib/rules/no-whitespace-before-property.js new file mode 100644 index 0000000000000000000000000000000000000000..137d8fcf98967860cc7b85f6d7454f0c1f3aa5af --- /dev/null +++ b/node_modules/eslint/lib/rules/no-whitespace-before-property.js @@ -0,0 +1,150 @@ +/** + * @fileoverview Rule to disallow whitespace before properties + * @author Kai Cataldo + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "no-whitespace-before-property", + url: "https://eslint.style/rules/no-whitespace-before-property", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Disallow whitespace before properties", + recommended: false, + url: "https://eslint.org/docs/latest/rules/no-whitespace-before-property", + }, + + fixable: "whitespace", + schema: [], + + messages: { + unexpectedWhitespace: + "Unexpected whitespace before property {{propName}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports whitespace before property token + * @param {ASTNode} node the node to report in the event of an error + * @param {Token} leftToken the left token + * @param {Token} rightToken the right token + * @returns {void} + * @private + */ + function reportError(node, leftToken, rightToken) { + context.report({ + node, + messageId: "unexpectedWhitespace", + data: { + propName: sourceCode.getText(node.property), + }, + fix(fixer) { + let replacementText = ""; + + if ( + !node.computed && + !node.optional && + astUtils.isDecimalInteger(node.object) + ) { + /* + * If the object is a number literal, fixing it to something like 5.toString() would cause a SyntaxError. + * Don't fix this case. + */ + return null; + } + + // Don't fix if comments exist. + if ( + sourceCode.commentsExistBetween(leftToken, rightToken) + ) { + return null; + } + + if (node.optional) { + replacementText = "?."; + } else if (!node.computed) { + replacementText = "."; + } + + return fixer.replaceTextRange( + [leftToken.range[1], rightToken.range[0]], + replacementText, + ); + }, + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + MemberExpression(node) { + let rightToken; + let leftToken; + + if (!astUtils.isTokenOnSameLine(node.object, node.property)) { + return; + } + + if (node.computed) { + rightToken = sourceCode.getTokenBefore( + node.property, + astUtils.isOpeningBracketToken, + ); + leftToken = sourceCode.getTokenBefore( + rightToken, + node.optional ? 1 : 0, + ); + } else { + rightToken = sourceCode.getFirstToken(node.property); + leftToken = sourceCode.getTokenBefore(rightToken, 1); + } + + if (sourceCode.isSpaceBetween(leftToken, rightToken)) { + reportError(node, leftToken, rightToken); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/no-with.js b/node_modules/eslint/lib/rules/no-with.js new file mode 100644 index 0000000000000000000000000000000000000000..f0461180a2b7bcc8ca7bd0134b9a0efa627f8daa --- /dev/null +++ b/node_modules/eslint/lib/rules/no-with.js @@ -0,0 +1,43 @@ +/** + * @fileoverview Rule to flag use of with statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Disallow `with` statements", + recommended: true, + url: "https://eslint.org/docs/latest/rules/no-with", + }, + + schema: [], + + messages: { + unexpectedWith: "Unexpected use of 'with' statement.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + WithStatement(node) { + context.report({ + node, + loc: sourceCode.getFirstToken(node).loc, + messageId: "unexpectedWith", + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/nonblock-statement-body-position.js b/node_modules/eslint/lib/rules/nonblock-statement-body-position.js new file mode 100644 index 0000000000000000000000000000000000000000..dbfd1063fbabcd92411eef19722c4858c4d633f3 --- /dev/null +++ b/node_modules/eslint/lib/rules/nonblock-statement-body-position.js @@ -0,0 +1,164 @@ +/** + * @fileoverview enforce the location of single-line statements + * @author Teddy Katz + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const POSITION_SCHEMA = { enum: ["beside", "below", "any"] }; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "nonblock-statement-body-position", + url: "https://eslint.style/rules/nonblock-statement-body-position", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce the location of single-line statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/nonblock-statement-body-position", + }, + + fixable: "whitespace", + + schema: [ + POSITION_SCHEMA, + { + properties: { + overrides: { + properties: { + if: POSITION_SCHEMA, + else: POSITION_SCHEMA, + while: POSITION_SCHEMA, + do: POSITION_SCHEMA, + for: POSITION_SCHEMA, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + expectNoLinebreak: "Expected no linebreak before this statement.", + expectLinebreak: "Expected a linebreak before this statement.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Gets the applicable preference for a particular keyword + * @param {string} keywordName The name of a keyword, e.g. 'if' + * @returns {string} The applicable option for the keyword, e.g. 'beside' + */ + function getOption(keywordName) { + return ( + (context.options[1] && + context.options[1].overrides && + context.options[1].overrides[keywordName]) || + context.options[0] || + "beside" + ); + } + + /** + * Validates the location of a single-line statement + * @param {ASTNode} node The single-line statement + * @param {string} keywordName The applicable keyword name for the single-line statement + * @returns {void} + */ + function validateStatement(node, keywordName) { + const option = getOption(keywordName); + + if (node.type === "BlockStatement" || option === "any") { + return; + } + + const tokenBefore = sourceCode.getTokenBefore(node); + + if ( + tokenBefore.loc.end.line === node.loc.start.line && + option === "below" + ) { + context.report({ + node, + messageId: "expectLinebreak", + fix: fixer => fixer.insertTextBefore(node, "\n"), + }); + } else if ( + tokenBefore.loc.end.line !== node.loc.start.line && + option === "beside" + ) { + context.report({ + node, + messageId: "expectNoLinebreak", + fix(fixer) { + if ( + sourceCode + .getText() + .slice(tokenBefore.range[1], node.range[0]) + .trim() + ) { + return null; + } + return fixer.replaceTextRange( + [tokenBefore.range[1], node.range[0]], + " ", + ); + }, + }); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + IfStatement(node) { + validateStatement(node.consequent, "if"); + + // Check the `else` node, but don't check 'else if' statements. + if (node.alternate && node.alternate.type !== "IfStatement") { + validateStatement(node.alternate, "else"); + } + }, + WhileStatement: node => validateStatement(node.body, "while"), + DoWhileStatement: node => validateStatement(node.body, "do"), + ForStatement: node => validateStatement(node.body, "for"), + ForInStatement: node => validateStatement(node.body, "for"), + ForOfStatement: node => validateStatement(node.body, "for"), + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/object-curly-newline.js b/node_modules/eslint/lib/rules/object-curly-newline.js new file mode 100644 index 0000000000000000000000000000000000000000..e0b860b3d3936e9003c03e3962628c205ddf1ea0 --- /dev/null +++ b/node_modules/eslint/lib/rules/object-curly-newline.js @@ -0,0 +1,383 @@ +/** + * @fileoverview Rule to require or disallow line breaks inside braces. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// Schema objects. +const OPTION_VALUE = { + oneOf: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + multiline: { + type: "boolean", + }, + minProperties: { + type: "integer", + minimum: 0, + }, + consistent: { + type: "boolean", + }, + }, + additionalProperties: false, + minProperties: 1, + }, + ], +}; + +/** + * Normalizes a given option value. + * @param {string|Object|undefined} value An option value to parse. + * @returns {{multiline: boolean, minProperties: number, consistent: boolean}} Normalized option object. + */ +function normalizeOptionValue(value) { + let multiline = false; + let minProperties = Number.POSITIVE_INFINITY; + let consistent = false; + + if (value) { + if (value === "always") { + minProperties = 0; + } else if (value === "never") { + minProperties = Number.POSITIVE_INFINITY; + } else { + multiline = Boolean(value.multiline); + minProperties = value.minProperties || Number.POSITIVE_INFINITY; + consistent = Boolean(value.consistent); + } + } else { + consistent = true; + } + + return { multiline, minProperties, consistent }; +} + +/** + * Checks if a value is an object. + * @param {any} value The value to check + * @returns {boolean} `true` if the value is an object, otherwise `false` + */ +function isObject(value) { + return typeof value === "object" && value !== null; +} + +/** + * Checks if an option is a node-specific option + * @param {any} option The option to check + * @returns {boolean} `true` if the option is node-specific, otherwise `false` + */ +function isNodeSpecificOption(option) { + return isObject(option) || typeof option === "string"; +} + +/** + * Normalizes a given option value. + * @param {string|Object|undefined} options An option value to parse. + * @returns {{ + * ObjectExpression: {multiline: boolean, minProperties: number, consistent: boolean}, + * ObjectPattern: {multiline: boolean, minProperties: number, consistent: boolean}, + * ImportDeclaration: {multiline: boolean, minProperties: number, consistent: boolean}, + * ExportNamedDeclaration : {multiline: boolean, minProperties: number, consistent: boolean} + * }} Normalized option object. + */ +function normalizeOptions(options) { + if ( + isObject(options) && + Object.values(options).some(isNodeSpecificOption) + ) { + return { + ObjectExpression: normalizeOptionValue(options.ObjectExpression), + ObjectPattern: normalizeOptionValue(options.ObjectPattern), + ImportDeclaration: normalizeOptionValue(options.ImportDeclaration), + ExportNamedDeclaration: normalizeOptionValue( + options.ExportDeclaration, + ), + }; + } + + const value = normalizeOptionValue(options); + + return { + ObjectExpression: value, + ObjectPattern: value, + ImportDeclaration: value, + ExportNamedDeclaration: value, + }; +} + +/** + * Determines if ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration + * node needs to be checked for missing line breaks + * @param {ASTNode} node Node under inspection + * @param {Object} options option specific to node type + * @param {Token} first First object property + * @param {Token} last Last object property + * @returns {boolean} `true` if node needs to be checked for missing line breaks + */ +function areLineBreaksRequired(node, options, first, last) { + let objectProperties; + + if (node.type === "ObjectExpression" || node.type === "ObjectPattern") { + objectProperties = node.properties; + } else { + // is ImportDeclaration or ExportNamedDeclaration + objectProperties = node.specifiers.filter( + s => s.type === "ImportSpecifier" || s.type === "ExportSpecifier", + ); + } + + return ( + objectProperties.length >= options.minProperties || + (options.multiline && + objectProperties.length > 0 && + first.loc.start.line !== last.loc.end.line) + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "object-curly-newline", + url: "https://eslint.style/rules/object-curly-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent line breaks after opening and before closing braces", + recommended: false, + url: "https://eslint.org/docs/latest/rules/object-curly-newline", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + OPTION_VALUE, + { + type: "object", + properties: { + ObjectExpression: OPTION_VALUE, + ObjectPattern: OPTION_VALUE, + ImportDeclaration: OPTION_VALUE, + ExportDeclaration: OPTION_VALUE, + }, + additionalProperties: false, + minProperties: 1, + }, + ], + }, + ], + + messages: { + unexpectedLinebreakBeforeClosingBrace: + "Unexpected line break before this closing brace.", + unexpectedLinebreakAfterOpeningBrace: + "Unexpected line break after this opening brace.", + expectedLinebreakBeforeClosingBrace: + "Expected a line break before this closing brace.", + expectedLinebreakAfterOpeningBrace: + "Expected a line break after this opening brace.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const normalizedOptions = normalizeOptions(context.options[0]); + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node A node to check. This is an ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration node. + * @returns {void} + */ + function check(node) { + const options = normalizedOptions[node.type]; + + if ( + (node.type === "ImportDeclaration" && + !node.specifiers.some( + specifier => specifier.type === "ImportSpecifier", + )) || + (node.type === "ExportNamedDeclaration" && + !node.specifiers.some( + specifier => specifier.type === "ExportSpecifier", + )) + ) { + return; + } + + const openBrace = sourceCode.getFirstToken( + node, + token => token.value === "{", + ); + + let closeBrace; + + if (node.typeAnnotation) { + closeBrace = sourceCode.getTokenBefore(node.typeAnnotation); + } else { + closeBrace = sourceCode.getLastToken( + node, + token => token.value === "}", + ); + } + + let first = sourceCode.getTokenAfter(openBrace, { + includeComments: true, + }); + let last = sourceCode.getTokenBefore(closeBrace, { + includeComments: true, + }); + + const needsLineBreaks = areLineBreaksRequired( + node, + options, + first, + last, + ); + + const hasCommentsFirstToken = astUtils.isCommentToken(first); + const hasCommentsLastToken = astUtils.isCommentToken(last); + + /* + * Use tokens or comments to check multiline or not. + * But use only tokens to check whether line breaks are needed. + * This allows: + * var obj = { // eslint-disable-line foo + * a: 1 + * } + */ + first = sourceCode.getTokenAfter(openBrace); + last = sourceCode.getTokenBefore(closeBrace); + + if (needsLineBreaks) { + if (astUtils.isTokenOnSameLine(openBrace, first)) { + context.report({ + messageId: "expectedLinebreakAfterOpeningBrace", + node, + loc: openBrace.loc, + fix(fixer) { + if (hasCommentsFirstToken) { + return null; + } + + return fixer.insertTextAfter(openBrace, "\n"); + }, + }); + } + if (astUtils.isTokenOnSameLine(last, closeBrace)) { + context.report({ + messageId: "expectedLinebreakBeforeClosingBrace", + node, + loc: closeBrace.loc, + fix(fixer) { + if (hasCommentsLastToken) { + return null; + } + + return fixer.insertTextBefore(closeBrace, "\n"); + }, + }); + } + } else { + const consistent = options.consistent; + const hasLineBreakBetweenOpenBraceAndFirst = + !astUtils.isTokenOnSameLine(openBrace, first); + const hasLineBreakBetweenCloseBraceAndLast = + !astUtils.isTokenOnSameLine(last, closeBrace); + + if ( + (!consistent && hasLineBreakBetweenOpenBraceAndFirst) || + (consistent && + hasLineBreakBetweenOpenBraceAndFirst && + !hasLineBreakBetweenCloseBraceAndLast) + ) { + context.report({ + messageId: "unexpectedLinebreakAfterOpeningBrace", + node, + loc: openBrace.loc, + fix(fixer) { + if (hasCommentsFirstToken) { + return null; + } + + return fixer.removeRange([ + openBrace.range[1], + first.range[0], + ]); + }, + }); + } + if ( + (!consistent && hasLineBreakBetweenCloseBraceAndLast) || + (consistent && + !hasLineBreakBetweenOpenBraceAndFirst && + hasLineBreakBetweenCloseBraceAndLast) + ) { + context.report({ + messageId: "unexpectedLinebreakBeforeClosingBrace", + node, + loc: closeBrace.loc, + fix(fixer) { + if (hasCommentsLastToken) { + return null; + } + + return fixer.removeRange([ + last.range[1], + closeBrace.range[0], + ]); + }, + }); + } + } + } + + return { + ObjectExpression: check, + ObjectPattern: check, + ImportDeclaration: check, + ExportNamedDeclaration: check, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/object-curly-spacing.js b/node_modules/eslint/lib/rules/object-curly-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..acbc8ddedff9d1f2a6864393c6fdf3285a11c507 --- /dev/null +++ b/node_modules/eslint/lib/rules/object-curly-spacing.js @@ -0,0 +1,369 @@ +/** + * @fileoverview Disallows or enforces spaces inside of object literals. + * @author Jamund Ferguson + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "object-curly-spacing", + url: "https://eslint.style/rules/object-curly-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing inside braces", + recommended: false, + url: "https://eslint.org/docs/latest/rules/object-curly-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + arraysInObjects: { + type: "boolean", + }, + objectsInObjects: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + requireSpaceBefore: "A space is required before '{{token}}'.", + requireSpaceAfter: "A space is required after '{{token}}'.", + unexpectedSpaceBefore: + "There should be no space before '{{token}}'.", + unexpectedSpaceAfter: "There should be no space after '{{token}}'.", + }, + }, + + create(context) { + const spaced = context.options[0] === "always", + sourceCode = context.sourceCode; + + /** + * Determines whether an option is set, relative to the spacing option. + * If spaced is "always", then check whether option is set to false. + * If spaced is "never", then check whether option is set to true. + * @param {Object} option The option to exclude. + * @returns {boolean} Whether or not the property is excluded. + */ + function isOptionSet(option) { + return context.options[1] + ? context.options[1][option] === !spaced + : false; + } + + const options = { + spaced, + arraysInObjectsException: isOptionSet("arraysInObjects"), + objectsInObjectsException: isOptionSet("objectsInObjects"), + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoBeginningSpace(node, token) { + const nextToken = context.sourceCode.getTokenAfter(token, { + includeComments: true, + }); + + context.report({ + node, + loc: { start: token.loc.end, end: nextToken.loc.start }, + messageId: "unexpectedSpaceAfter", + data: { + token: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + token.range[1], + nextToken.range[0], + ]); + }, + }); + } + + /** + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoEndingSpace(node, token) { + const previousToken = context.sourceCode.getTokenBefore(token, { + includeComments: true, + }); + + context.report({ + node, + loc: { start: previousToken.loc.end, end: token.loc.start }, + messageId: "unexpectedSpaceBefore", + data: { + token: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + previousToken.range[1], + token.range[0], + ]); + }, + }); + } + + /** + * Reports that there should be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "requireSpaceAfter", + data: { + token: token.value, + }, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + + /** + * Reports that there should be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "requireSpaceBefore", + data: { + token: token.value, + }, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + + /** + * Determines if spacing in curly braces is valid. + * @param {ASTNode} node The AST node to check. + * @param {Token} first The first token to check (should be the opening brace) + * @param {Token} second The second token to check (should be first after the opening brace) + * @param {Token} penultimate The penultimate token to check (should be last before closing brace) + * @param {Token} last The last token to check (should be closing brace) + * @returns {void} + */ + function validateBraceSpacing(node, first, second, penultimate, last) { + if (astUtils.isTokenOnSameLine(first, second)) { + const firstSpaced = sourceCode.isSpaceBetween(first, second); + + if (options.spaced && !firstSpaced) { + reportRequiredBeginningSpace(node, first); + } + if (!options.spaced && firstSpaced && second.type !== "Line") { + reportNoBeginningSpace(node, first); + } + } + + if (astUtils.isTokenOnSameLine(penultimate, last)) { + const shouldCheckPenultimate = + (options.arraysInObjectsException && + astUtils.isClosingBracketToken(penultimate)) || + (options.objectsInObjectsException && + astUtils.isClosingBraceToken(penultimate)); + const penultimateType = + shouldCheckPenultimate && + sourceCode.getNodeByRangeIndex(penultimate.range[0]).type; + + const closingCurlyBraceMustBeSpaced = + (options.arraysInObjectsException && + penultimateType === "ArrayExpression") || + (options.objectsInObjectsException && + (penultimateType === "ObjectExpression" || + penultimateType === "ObjectPattern")) + ? !options.spaced + : options.spaced; + + const lastSpaced = sourceCode.isSpaceBetween(penultimate, last); + + if (closingCurlyBraceMustBeSpaced && !lastSpaced) { + reportRequiredEndingSpace(node, last); + } + if (!closingCurlyBraceMustBeSpaced && lastSpaced) { + reportNoEndingSpace(node, last); + } + } + } + + /** + * Gets '}' token of an object node. + * + * Because the last token of object patterns might be a type annotation, + * this traverses tokens preceded by the last property, then returns the + * first '}' token. + * @param {ASTNode} node The node to get. This node is an + * ObjectExpression or an ObjectPattern. And this node has one or + * more properties. + * @returns {Token} '}' token. + */ + function getClosingBraceOfObject(node) { + const lastProperty = node.properties.at(-1); + + return sourceCode.getTokenAfter( + lastProperty, + astUtils.isClosingBraceToken, + ); + } + + /** + * Reports a given object node if spacing in curly braces is invalid. + * @param {ASTNode} node An ObjectExpression or ObjectPattern node to check. + * @returns {void} + */ + function checkForObject(node) { + if (node.properties.length === 0) { + return; + } + + const first = sourceCode.getFirstToken(node), + last = getClosingBraceOfObject(node), + second = sourceCode.getTokenAfter(first, { + includeComments: true, + }), + penultimate = sourceCode.getTokenBefore(last, { + includeComments: true, + }); + + validateBraceSpacing(node, first, second, penultimate, last); + } + + /** + * Reports a given import node if spacing in curly braces is invalid. + * @param {ASTNode} node An ImportDeclaration node to check. + * @returns {void} + */ + function checkForImport(node) { + if (node.specifiers.length === 0) { + return; + } + + let firstSpecifier = node.specifiers[0]; + const lastSpecifier = node.specifiers.at(-1); + + if (lastSpecifier.type !== "ImportSpecifier") { + return; + } + if (firstSpecifier.type !== "ImportSpecifier") { + firstSpecifier = node.specifiers[1]; + } + + const first = sourceCode.getTokenBefore(firstSpecifier), + last = sourceCode.getTokenAfter( + lastSpecifier, + astUtils.isNotCommaToken, + ), + second = sourceCode.getTokenAfter(first, { + includeComments: true, + }), + penultimate = sourceCode.getTokenBefore(last, { + includeComments: true, + }); + + validateBraceSpacing(node, first, second, penultimate, last); + } + + /** + * Reports a given export node if spacing in curly braces is invalid. + * @param {ASTNode} node An ExportNamedDeclaration node to check. + * @returns {void} + */ + function checkForExport(node) { + if (node.specifiers.length === 0) { + return; + } + + const firstSpecifier = node.specifiers[0], + lastSpecifier = node.specifiers.at(-1), + first = sourceCode.getTokenBefore(firstSpecifier), + last = sourceCode.getTokenAfter( + lastSpecifier, + astUtils.isNotCommaToken, + ), + second = sourceCode.getTokenAfter(first, { + includeComments: true, + }), + penultimate = sourceCode.getTokenBefore(last, { + includeComments: true, + }); + + validateBraceSpacing(node, first, second, penultimate, last); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + // var {x} = y; + ObjectPattern: checkForObject, + + // var y = {x: 'y'} + ObjectExpression: checkForObject, + + // import {y} from 'x'; + ImportDeclaration: checkForImport, + + // export {name} from 'yo'; + ExportNamedDeclaration: checkForExport, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/object-property-newline.js b/node_modules/eslint/lib/rules/object-property-newline.js new file mode 100644 index 0000000000000000000000000000000000000000..6921e048a6ee316947dee4b6f755d99766c90f09 --- /dev/null +++ b/node_modules/eslint/lib/rules/object-property-newline.js @@ -0,0 +1,151 @@ +/** + * @fileoverview Rule to enforce placing object properties on separate lines. + * @author Vitor Balocco + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "object-property-newline", + url: "https://eslint.style/rules/object-property-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce placing object properties on separate lines", + recommended: false, + url: "https://eslint.org/docs/latest/rules/object-property-newline", + }, + + schema: [ + { + type: "object", + properties: { + allowAllPropertiesOnSameLine: { + type: "boolean", + default: false, + }, + allowMultiplePropertiesPerLine: { + // Deprecated + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + fixable: "whitespace", + + messages: { + propertiesOnNewlineAll: + "Object properties must go on a new line if they aren't all on the same line.", + propertiesOnNewline: "Object properties must go on a new line.", + }, + }, + + create(context) { + const allowSameLine = + context.options[0] && + (context.options[0].allowAllPropertiesOnSameLine || + context.options[0] + .allowMultiplePropertiesPerLine); /* Deprecated */ + const messageId = allowSameLine + ? "propertiesOnNewlineAll" + : "propertiesOnNewline"; + + const sourceCode = context.sourceCode; + + return { + ObjectExpression(node) { + if (allowSameLine) { + if (node.properties.length > 1) { + const firstTokenOfFirstProperty = + sourceCode.getFirstToken(node.properties[0]); + const lastTokenOfLastProperty = sourceCode.getLastToken( + node.properties.at(-1), + ); + + if ( + firstTokenOfFirstProperty.loc.end.line === + lastTokenOfLastProperty.loc.start.line + ) { + // All keys and values are on the same line + return; + } + } + } + + for (let i = 1; i < node.properties.length; i++) { + const lastTokenOfPreviousProperty = sourceCode.getLastToken( + node.properties[i - 1], + ); + const firstTokenOfCurrentProperty = + sourceCode.getFirstToken(node.properties[i]); + + if ( + lastTokenOfPreviousProperty.loc.end.line === + firstTokenOfCurrentProperty.loc.start.line + ) { + context.report({ + node, + loc: firstTokenOfCurrentProperty.loc, + messageId, + fix(fixer) { + const comma = sourceCode.getTokenBefore( + firstTokenOfCurrentProperty, + ); + const rangeAfterComma = [ + comma.range[1], + firstTokenOfCurrentProperty.range[0], + ]; + + // Don't perform a fix if there are any comments between the comma and the next property. + if ( + sourceCode.text + .slice( + rangeAfterComma[0], + rangeAfterComma[1], + ) + .trim() + ) { + return null; + } + + return fixer.replaceTextRange( + rangeAfterComma, + "\n", + ); + }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/object-shorthand.js b/node_modules/eslint/lib/rules/object-shorthand.js new file mode 100644 index 0000000000000000000000000000000000000000..bb49833b01b2c73ad15249c40326d7f6eed76aa1 --- /dev/null +++ b/node_modules/eslint/lib/rules/object-shorthand.js @@ -0,0 +1,654 @@ +/** + * @fileoverview Rule to enforce concise object methods and properties. + * @author Jamund Ferguson + */ + +"use strict"; + +const OPTIONS = { + always: "always", + never: "never", + methods: "methods", + properties: "properties", + consistent: "consistent", + consistentAsNeeded: "consistent-as-needed", +}; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ +const astUtils = require("./utils/ast-utils"); + +//-------------------------------------------------------------------------- +// Helpers +//-------------------------------------------------------------------------- +const CTOR_PREFIX_REGEX = /[^_$0-9]/u; +const JSDOC_COMMENT_REGEX = /^\s*\*/u; + +/** + * Determines if the first character of the name is a capital letter. + * @param {string} name The name of the node to evaluate. + * @returns {boolean} True if the first character of the property name is a capital letter, false if not. + * @private + */ +function isConstructor(name) { + const match = CTOR_PREFIX_REGEX.exec(name); + + // Not a constructor if name has no characters apart from '_', '$' and digits e.g. '_', '$$', '_8' + if (!match) { + return false; + } + + const firstChar = name.charAt(match.index); + + return firstChar === firstChar.toUpperCase(); +} + +/** + * Determines if the property can have a shorthand form. + * @param {ASTNode} property Property AST node + * @returns {boolean} True if the property can have a shorthand form + * @private + */ +function canHaveShorthand(property) { + return ( + property.kind !== "set" && + property.kind !== "get" && + property.type !== "SpreadElement" && + property.type !== "SpreadProperty" && + property.type !== "ExperimentalSpreadProperty" + ); +} + +/** + * Checks whether a node is a string literal. + * @param {ASTNode} node Any AST node. + * @returns {boolean} `true` if it is a string literal. + */ +function isStringLiteral(node) { + return node.type === "Literal" && typeof node.value === "string"; +} + +/** + * Determines if the property is a shorthand or not. + * @param {ASTNode} property Property AST node + * @returns {boolean} True if the property is considered shorthand, false if not. + * @private + */ +function isShorthand(property) { + // property.method is true when `{a(){}}`. + return property.shorthand || property.method; +} + +/** + * Determines if the property's key and method or value are named equally. + * @param {ASTNode} property Property AST node + * @returns {boolean} True if the key and value are named equally, false if not. + * @private + */ +function isRedundant(property) { + const value = property.value; + + if (value.type === "FunctionExpression") { + return !value.id; // Only anonymous should be shorthand method. + } + if (value.type === "Identifier") { + return astUtils.getStaticPropertyName(property) === value.name; + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require or disallow method and property shorthand syntax for object literals", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/object-shorthand", + }, + + fixable: "code", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: [ + "always", + "methods", + "properties", + "never", + "consistent", + "consistent-as-needed", + ], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["always", "methods", "properties"], + }, + { + type: "object", + properties: { + avoidQuotes: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + { + type: "array", + items: [ + { + enum: ["always", "methods"], + }, + { + type: "object", + properties: { + ignoreConstructors: { + type: "boolean", + }, + methodsIgnorePattern: { + type: "string", + }, + avoidQuotes: { + type: "boolean", + }, + avoidExplicitReturnArrows: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + defaultOptions: ["always"], + + messages: { + expectedAllPropertiesShorthanded: + "Expected shorthand for all properties.", + expectedLiteralMethodLongform: + "Expected longform method syntax for string literal keys.", + expectedPropertyShorthand: "Expected property shorthand.", + expectedPropertyLongform: "Expected longform property syntax.", + expectedMethodShorthand: "Expected method shorthand.", + expectedMethodLongform: "Expected longform method syntax.", + unexpectedMix: + "Unexpected mix of shorthand and non-shorthand properties.", + }, + }, + + create(context) { + const APPLY = context.options[0]; + const APPLY_TO_METHODS = + APPLY === OPTIONS.methods || APPLY === OPTIONS.always; + const APPLY_TO_PROPS = + APPLY === OPTIONS.properties || APPLY === OPTIONS.always; + const APPLY_NEVER = APPLY === OPTIONS.never; + const APPLY_CONSISTENT = APPLY === OPTIONS.consistent; + const APPLY_CONSISTENT_AS_NEEDED = APPLY === OPTIONS.consistentAsNeeded; + + const PARAMS = context.options[1] || {}; + const IGNORE_CONSTRUCTORS = PARAMS.ignoreConstructors; + const METHODS_IGNORE_PATTERN = PARAMS.methodsIgnorePattern + ? new RegExp(PARAMS.methodsIgnorePattern, "u") + : null; + const AVOID_QUOTES = PARAMS.avoidQuotes; + const AVOID_EXPLICIT_RETURN_ARROWS = !!PARAMS.avoidExplicitReturnArrows; + const sourceCode = context.sourceCode; + + /** + * Ensures that an object's properties are consistently shorthand, or not shorthand at all. + * @param {ASTNode} node Property AST node + * @param {boolean} checkRedundancy Whether to check longform redundancy + * @returns {void} + */ + function checkConsistency(node, checkRedundancy) { + // We are excluding getters/setters and spread properties as they are considered neither longform nor shorthand. + const properties = node.properties.filter(canHaveShorthand); + + // Do we still have properties left after filtering the getters and setters? + if (properties.length > 0) { + const shorthandProperties = properties.filter(isShorthand); + + /* + * If we do not have an equal number of longform properties as + * shorthand properties, we are using the annotations inconsistently + */ + if (shorthandProperties.length !== properties.length) { + // We have at least 1 shorthand property + if (shorthandProperties.length > 0) { + context.report({ node, messageId: "unexpectedMix" }); + } else if (checkRedundancy) { + /* + * If all properties of the object contain a method or value with a name matching it's key, + * all the keys are redundant. + */ + const canAlwaysUseShorthand = + properties.every(isRedundant); + + if (canAlwaysUseShorthand) { + context.report({ + node, + messageId: "expectedAllPropertiesShorthanded", + }); + } + } + } + } + } + + /** + * Fixes a FunctionExpression node by making it into a shorthand property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value + * @returns {Object} A fix for this node + */ + function makeFunctionShorthand(fixer, node) { + const firstKeyToken = node.computed + ? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken) + : sourceCode.getFirstToken(node.key); + const lastKeyToken = node.computed + ? sourceCode.getFirstTokenBetween( + node.key, + node.value, + astUtils.isClosingBracketToken, + ) + : sourceCode.getLastToken(node.key); + const keyText = sourceCode.text.slice( + firstKeyToken.range[0], + lastKeyToken.range[1], + ); + let keyPrefix = ""; + + // key: /* */ () => {} + if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) { + return null; + } + + if (node.value.async) { + keyPrefix += "async "; + } + if (node.value.generator) { + keyPrefix += "*"; + } + + const fixRange = [firstKeyToken.range[0], node.range[1]]; + const methodPrefix = keyPrefix + keyText; + + if (node.value.type === "FunctionExpression") { + const functionToken = sourceCode + .getTokens(node.value) + .find( + token => + token.type === "Keyword" && + token.value === "function", + ); + const tokenBeforeParams = node.value.generator + ? sourceCode.getTokenAfter(functionToken) + : functionToken; + + return fixer.replaceTextRange( + fixRange, + methodPrefix + + sourceCode.text.slice( + tokenBeforeParams.range[1], + node.value.range[1], + ), + ); + } + + const arrowToken = sourceCode.getTokenBefore( + node.value.body, + astUtils.isArrowToken, + ); + const fnBody = sourceCode.text.slice( + arrowToken.range[1], + node.value.range[1], + ); + + // First token should not be `async` + const firstValueToken = sourceCode.getFirstToken(node.value, { + skip: node.value.async ? 1 : 0, + }); + + const sliceStart = firstValueToken.range[0]; + const sliceEnd = sourceCode.getTokenBefore(arrowToken).range[1]; + const shouldAddParens = + node.value.params.length === 1 && + node.value.params[0].range[0] === sliceStart; + + const oldParamText = sourceCode.text.slice(sliceStart, sliceEnd); + const newParamText = shouldAddParens + ? `(${oldParamText})` + : oldParamText; + + return fixer.replaceTextRange( + fixRange, + methodPrefix + newParamText + fnBody, + ); + } + + /** + * Fixes a FunctionExpression node by making it into a longform property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value + * @returns {Object} A fix for this node + */ + function makeFunctionLongform(fixer, node) { + const firstKeyToken = node.computed + ? sourceCode.getTokens(node).find(token => token.value === "[") + : sourceCode.getFirstToken(node.key); + const lastKeyToken = node.computed + ? sourceCode + .getTokensBetween(node.key, node.value) + .find(token => token.value === "]") + : sourceCode.getLastToken(node.key); + const keyText = sourceCode.text.slice( + firstKeyToken.range[0], + lastKeyToken.range[1], + ); + let functionHeader = "function"; + + if (node.value.async) { + functionHeader = `async ${functionHeader}`; + } + if (node.value.generator) { + functionHeader = `${functionHeader}*`; + } + + return fixer.replaceTextRange( + [node.range[0], lastKeyToken.range[1]], + `${keyText}: ${functionHeader}`, + ); + } + + /* + * To determine whether a given arrow function has a lexical identifier (`this`, `arguments`, `super`, or `new.target`), + * create a stack of functions that define these identifiers (i.e. all functions except arrow functions) as the AST is + * traversed. Whenever a new function is encountered, create a new entry on the stack (corresponding to a different lexical + * scope of `this`), and whenever a function is exited, pop that entry off the stack. When an arrow function is entered, + * keep a reference to it on the current stack entry, and remove that reference when the arrow function is exited. + * When a lexical identifier is encountered, mark all the arrow functions on the current stack entry by adding them + * to an `arrowsWithLexicalIdentifiers` set. Any arrow function in that set will not be reported by this rule, + * because converting it into a method would change the value of one of the lexical identifiers. + */ + const lexicalScopeStack = []; + const arrowsWithLexicalIdentifiers = new WeakSet(); + const argumentsIdentifiers = new WeakSet(); + + /** + * Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack. + * Also, this marks all `arguments` identifiers so that they can be detected later. + * @param {ASTNode} node The node representing the function. + * @returns {void} + */ + function enterFunction(node) { + lexicalScopeStack.unshift(new Set()); + sourceCode + .getScope(node) + .variables.filter(variable => variable.name === "arguments") + .forEach(variable => { + variable.references + .map(ref => ref.identifier) + .forEach(identifier => + argumentsIdentifiers.add(identifier), + ); + }); + } + + /** + * Exits a function. This pops the current set of arrow functions off the lexical scope stack. + * @returns {void} + */ + function exitFunction() { + lexicalScopeStack.shift(); + } + + /** + * Marks the current function as having a lexical keyword. This implies that all arrow functions + * in the current lexical scope contain a reference to this lexical keyword. + * @returns {void} + */ + function reportLexicalIdentifier() { + lexicalScopeStack[0].forEach(arrowFunction => + arrowsWithLexicalIdentifiers.add(arrowFunction), + ); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: enterFunction, + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + "Program:exit": exitFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + + ArrowFunctionExpression(node) { + lexicalScopeStack[0].add(node); + }, + "ArrowFunctionExpression:exit"(node) { + lexicalScopeStack[0].delete(node); + }, + + ThisExpression: reportLexicalIdentifier, + Super: reportLexicalIdentifier, + MetaProperty(node) { + if ( + node.meta.name === "new" && + node.property.name === "target" + ) { + reportLexicalIdentifier(); + } + }, + Identifier(node) { + if (argumentsIdentifiers.has(node)) { + reportLexicalIdentifier(); + } + }, + + ObjectExpression(node) { + if (APPLY_CONSISTENT) { + checkConsistency(node, false); + } else if (APPLY_CONSISTENT_AS_NEEDED) { + checkConsistency(node, true); + } + }, + + "Property:exit"(node) { + const isConciseProperty = node.method || node.shorthand; + + // Ignore destructuring assignment + if (node.parent.type === "ObjectPattern") { + return; + } + + // getters and setters are ignored + if (node.kind === "get" || node.kind === "set") { + return; + } + + // only computed methods can fail the following checks + if ( + node.computed && + node.value.type !== "FunctionExpression" && + node.value.type !== "ArrowFunctionExpression" + ) { + return; + } + + //-------------------------------------------------------------- + // Checks for property/method shorthand. + if (isConciseProperty) { + if ( + node.method && + (APPLY_NEVER || + (AVOID_QUOTES && isStringLiteral(node.key))) + ) { + const messageId = APPLY_NEVER + ? "expectedMethodLongform" + : "expectedLiteralMethodLongform"; + + // { x() {} } should be written as { x: function() {} } + context.report({ + node, + messageId, + fix: fixer => makeFunctionLongform(fixer, node), + }); + } else if (APPLY_NEVER) { + // { x } should be written as { x: x } + context.report({ + node, + messageId: "expectedPropertyLongform", + fix: fixer => + fixer.insertTextAfter( + node.key, + `: ${node.key.name}`, + ), + }); + } + } else if ( + APPLY_TO_METHODS && + !node.value.id && + (node.value.type === "FunctionExpression" || + node.value.type === "ArrowFunctionExpression") + ) { + if ( + IGNORE_CONSTRUCTORS && + node.key.type === "Identifier" && + isConstructor(node.key.name) + ) { + return; + } + + if (METHODS_IGNORE_PATTERN) { + const propertyName = + astUtils.getStaticPropertyName(node); + + if ( + propertyName !== null && + METHODS_IGNORE_PATTERN.test(propertyName) + ) { + return; + } + } + + if (AVOID_QUOTES && isStringLiteral(node.key)) { + return; + } + + // {[x]: function(){}} should be written as {[x]() {}} + if ( + node.value.type === "FunctionExpression" || + (node.value.type === "ArrowFunctionExpression" && + node.value.body.type === "BlockStatement" && + AVOID_EXPLICIT_RETURN_ARROWS && + !arrowsWithLexicalIdentifiers.has(node.value)) + ) { + context.report({ + node, + messageId: "expectedMethodShorthand", + fix: fixer => makeFunctionShorthand(fixer, node), + }); + } + } else if ( + node.value.type === "Identifier" && + node.key.name === node.value.name && + APPLY_TO_PROPS + ) { + // Skip if there are JSDoc comments inside the property (e.g., JSDoc type annotations) + const comments = sourceCode.getCommentsInside(node); + if ( + comments.some( + comment => + comment.type === "Block" && + JSDOC_COMMENT_REGEX.test(comment.value) && + comment.value.includes("@type"), + ) + ) { + return; + } + + // {x: x} should be written as {x} + context.report({ + node, + messageId: "expectedPropertyShorthand", + fix(fixer) { + // x: /* */ x + // x: (/* */ x) + if (sourceCode.getCommentsInside(node).length > 0) { + return null; + } + + return fixer.replaceText(node, node.value.name); + }, + }); + } else if ( + node.value.type === "Identifier" && + node.key.type === "Literal" && + node.key.value === node.value.name && + APPLY_TO_PROPS + ) { + if (AVOID_QUOTES) { + return; + } + + const comments = sourceCode.getCommentsInside(node); + if ( + comments.some( + comment => + comment.type === "Block" && + comment.value.startsWith("*") && + comment.value.includes("@type"), + ) + ) { + return; + } + + // {"x": x} should be written as {x} + context.report({ + node, + messageId: "expectedPropertyShorthand", + fix(fixer) { + // "x": /* */ x + // "x": (/* */ x) + if (sourceCode.getCommentsInside(node).length > 0) { + return null; + } + + return fixer.replaceText(node, node.value.name); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/one-var-declaration-per-line.js b/node_modules/eslint/lib/rules/one-var-declaration-per-line.js new file mode 100644 index 0000000000000000000000000000000000000000..3671e27213e491f89518a4a42baab307b22f0137 --- /dev/null +++ b/node_modules/eslint/lib/rules/one-var-declaration-per-line.js @@ -0,0 +1,117 @@ +/** + * @fileoverview Rule to check multiple var declarations per line + * @author Alberto Rodríguez + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "one-var-declaration-per-line", + url: "https://eslint.style/rules/one-var-declaration-per-line", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: + "Require or disallow newlines around variable declarations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/one-var-declaration-per-line", + }, + + schema: [ + { + enum: ["always", "initializations"], + }, + ], + + fixable: "whitespace", + + messages: { + expectVarOnNewline: + "Expected variable declaration to be on a new line.", + }, + }, + + create(context) { + const always = context.options[0] === "always"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determine if provided keyword is a variant of for specifiers + * @private + * @param {string} keyword keyword to test + * @returns {boolean} True if `keyword` is a variant of for specifier + */ + function isForTypeSpecifier(keyword) { + return ( + keyword === "ForStatement" || + keyword === "ForInStatement" || + keyword === "ForOfStatement" + ); + } + + /** + * Checks newlines around variable declarations. + * @private + * @param {ASTNode} node `VariableDeclaration` node to test + * @returns {void} + */ + function checkForNewLine(node) { + if (isForTypeSpecifier(node.parent.type)) { + return; + } + + const declarations = node.declarations; + let prev; + + declarations.forEach(current => { + if (prev && prev.loc.end.line === current.loc.start.line) { + if (always || prev.init || current.init) { + context.report({ + node, + messageId: "expectVarOnNewline", + loc: current.loc, + fix: fixer => fixer.insertTextBefore(current, "\n"), + }); + } + } + prev = current; + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclaration: checkForNewLine, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/one-var.js b/node_modules/eslint/lib/rules/one-var.js new file mode 100644 index 0000000000000000000000000000000000000000..4241afa71135f33592eeac9bef30e9d83d3037f7 --- /dev/null +++ b/node_modules/eslint/lib/rules/one-var.js @@ -0,0 +1,719 @@ +/** + * @fileoverview A rule to control the use of single variable declarations. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given node is in a statement list. + * @param {ASTNode} node node to check + * @returns {boolean} `true` if the given node is in a statement list + */ +function isInStatementList(node) { + return astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce variables to be declared either together or separately in functions", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/one-var", + }, + + fixable: "code", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never", "consecutive"], + }, + { + type: "object", + properties: { + separateRequires: { + type: "boolean", + }, + var: { + enum: ["always", "never", "consecutive"], + }, + let: { + enum: ["always", "never", "consecutive"], + }, + const: { + enum: ["always", "never", "consecutive"], + }, + using: { + enum: ["always", "never", "consecutive"], + }, + awaitUsing: { + enum: ["always", "never", "consecutive"], + }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + initialized: { + enum: ["always", "never", "consecutive"], + }, + uninitialized: { + enum: ["always", "never", "consecutive"], + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + defaultOptions: ["always"], + + messages: { + combineUninitialized: + "Combine this with the previous '{{type}}' statement with uninitialized variables.", + combineInitialized: + "Combine this with the previous '{{type}}' statement with initialized variables.", + splitUninitialized: + "Split uninitialized '{{type}}' declarations into multiple statements.", + splitInitialized: + "Split initialized '{{type}}' declarations into multiple statements.", + splitRequires: + "Split requires to be separated into a single block.", + combine: "Combine this with the previous '{{type}}' statement.", + split: "Split '{{type}}' declarations into multiple statements.", + }, + }, + + create(context) { + const MODE_ALWAYS = "always"; + const MODE_NEVER = "never"; + const MODE_CONSECUTIVE = "consecutive"; + const mode = context.options[0]; + + const options = {}; + + if (typeof mode === "string") { + // simple options configuration with just a string + options.var = { uninitialized: mode, initialized: mode }; + options.let = { uninitialized: mode, initialized: mode }; + options.const = { uninitialized: mode, initialized: mode }; + options.using = { uninitialized: mode, initialized: mode }; + options.awaitUsing = { uninitialized: mode, initialized: mode }; + } else if (typeof mode === "object") { + // options configuration is an object + options.separateRequires = !!mode.separateRequires; + options.var = { uninitialized: mode.var, initialized: mode.var }; + options.let = { uninitialized: mode.let, initialized: mode.let }; + options.const = { + uninitialized: mode.const, + initialized: mode.const, + }; + options.using = { + uninitialized: mode.using, + initialized: mode.using, + }; + options.awaitUsing = { + uninitialized: mode.awaitUsing, + initialized: mode.awaitUsing, + }; + if (Object.hasOwn(mode, "uninitialized")) { + options.var.uninitialized = mode.uninitialized; + options.let.uninitialized = mode.uninitialized; + options.const.uninitialized = mode.uninitialized; + options.using.uninitialized = mode.uninitialized; + options.awaitUsing.uninitialized = mode.uninitialized; + } + if (Object.hasOwn(mode, "initialized")) { + options.var.initialized = mode.initialized; + options.let.initialized = mode.initialized; + options.const.initialized = mode.initialized; + options.using.initialized = mode.initialized; + options.awaitUsing.initialized = mode.initialized; + } + } + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + const functionStack = []; + const blockStack = []; + + /** + * Increments the blockStack counter. + * @returns {void} + * @private + */ + function startBlock() { + blockStack.push({ + let: { initialized: false, uninitialized: false }, + const: { initialized: false, uninitialized: false }, + using: { initialized: false, uninitialized: false }, + awaitUsing: { initialized: false, uninitialized: false }, + }); + } + + /** + * Increments the functionStack counter. + * @returns {void} + * @private + */ + function startFunction() { + functionStack.push({ initialized: false, uninitialized: false }); + startBlock(); + } + + /** + * Decrements the blockStack counter. + * @returns {void} + * @private + */ + function endBlock() { + blockStack.pop(); + } + + /** + * Decrements the functionStack counter. + * @returns {void} + * @private + */ + function endFunction() { + functionStack.pop(); + endBlock(); + } + + /** + * Check if a variable declaration is a require. + * @param {ASTNode} decl variable declaration Node + * @returns {bool} if decl is a require, return true; else return false. + * @private + */ + function isRequire(decl) { + return ( + decl.init && + decl.init.type === "CallExpression" && + decl.init.callee.name === "require" + ); + } + + /** + * Records whether initialized/uninitialized/required variables are defined in current scope. + * @param {string} statementType one of: "var", "let", "const", "using", or "awaitUsing" + * @param {ASTNode[]} declarations List of declarations + * @param {Object} currentScope The scope being investigated + * @returns {void} + * @private + */ + function recordTypes(statementType, declarations, currentScope) { + for (let i = 0; i < declarations.length; i++) { + if (declarations[i].init === null) { + if ( + options[statementType] && + options[statementType].uninitialized === MODE_ALWAYS + ) { + currentScope.uninitialized = true; + } + } else { + if ( + options[statementType] && + options[statementType].initialized === MODE_ALWAYS + ) { + if ( + options.separateRequires && + isRequire(declarations[i]) + ) { + currentScope.required = true; + } else { + currentScope.initialized = true; + } + } + } + } + } + + /** + * Determines the current scope (function or block) + * @param {string} statementType one of: "var", "let", "const", "using", or "awaitUsing" + * @returns {Object} The scope associated with statementType + */ + function getCurrentScope(statementType) { + let currentScope; + + if (statementType === "var") { + currentScope = functionStack.at(-1); + } else if (statementType === "let") { + currentScope = blockStack.at(-1).let; + } else if (statementType === "const") { + currentScope = blockStack.at(-1).const; + } else if (statementType === "using") { + currentScope = blockStack.at(-1).using; + } else if (statementType === "awaitUsing") { + currentScope = blockStack.at(-1).awaitUsing; + } + return currentScope; + } + + /** + * Counts the number of initialized and uninitialized declarations in a list of declarations + * @param {ASTNode[]} declarations List of declarations + * @returns {Object} Counts of 'uninitialized' and 'initialized' declarations + * @private + */ + function countDeclarations(declarations) { + const counts = { uninitialized: 0, initialized: 0 }; + + for (let i = 0; i < declarations.length; i++) { + if (declarations[i].init === null) { + counts.uninitialized++; + } else { + counts.initialized++; + } + } + return counts; + } + + /** + * Determines if there is more than one var statement in the current scope. + * @param {string} statementType one of: "var", "let", "const", "using", or "awaitUsing" + * @param {ASTNode[]} declarations List of declarations + * @returns {boolean} Returns true if it is the first var declaration, false if not. + * @private + */ + function hasOnlyOneStatement(statementType, declarations) { + const declarationCounts = countDeclarations(declarations); + const currentOptions = options[statementType] || {}; + const currentScope = getCurrentScope(statementType); + const hasRequires = declarations.some(isRequire); + + if ( + currentOptions.uninitialized === MODE_ALWAYS && + currentOptions.initialized === MODE_ALWAYS + ) { + if (currentScope.uninitialized || currentScope.initialized) { + if (!hasRequires) { + return false; + } + } + } + + if (declarationCounts.uninitialized > 0) { + if ( + currentOptions.uninitialized === MODE_ALWAYS && + currentScope.uninitialized + ) { + return false; + } + } + if (declarationCounts.initialized > 0) { + if ( + currentOptions.initialized === MODE_ALWAYS && + currentScope.initialized + ) { + if (!hasRequires) { + return false; + } + } + } + if (currentScope.required && hasRequires) { + return false; + } + recordTypes(statementType, declarations, currentScope); + return true; + } + + /** + * Fixer to join VariableDeclaration's into a single declaration + * @param {VariableDeclarator[]} declarations The `VariableDeclaration` to join + * @returns {Function} The fixer function + */ + function joinDeclarations(declarations) { + const declaration = declarations[0]; + const body = Array.isArray(declaration.parent.parent.body) + ? declaration.parent.parent.body + : []; + const currentIndex = body.findIndex( + node => node.range[0] === declaration.parent.range[0], + ); + const previousNode = body[currentIndex - 1]; + + return function* joinDeclarationsFixer(fixer) { + const type = sourceCode.getFirstToken(declaration.parent); + const beforeType = sourceCode.getTokenBefore(type); + + if ( + previousNode && + previousNode.kind === declaration.parent.kind + ) { + if (beforeType.value === ";") { + yield fixer.replaceText(beforeType, ","); + } else { + yield fixer.insertTextAfter(beforeType, ","); + } + + if (declaration.parent.kind === "await using") { + const usingToken = sourceCode.getTokenAfter(type); + yield fixer.remove(usingToken); + } + + yield fixer.replaceText(type, ""); + } + }; + } + + /** + * Fixer to split a VariableDeclaration into individual declarations + * @param {VariableDeclaration} declaration The `VariableDeclaration` to split + * @returns {Function|null} The fixer function + */ + function splitDeclarations(declaration) { + const { parent } = declaration; + + // don't autofix code such as: if (foo) var x, y; + if ( + !isInStatementList( + parent.type === "ExportNamedDeclaration" + ? parent + : declaration, + ) + ) { + return null; + } + + return fixer => + declaration.declarations + .map(declarator => { + const tokenAfterDeclarator = + sourceCode.getTokenAfter(declarator); + + if (tokenAfterDeclarator === null) { + return null; + } + + const afterComma = sourceCode.getTokenAfter( + tokenAfterDeclarator, + { includeComments: true }, + ); + + if (tokenAfterDeclarator.value !== ",") { + return null; + } + + const exportPlacement = + declaration.parent.type === "ExportNamedDeclaration" + ? "export " + : ""; + + /* + * `var x,y` + * tokenAfterDeclarator ^^ afterComma + */ + if ( + afterComma.range[0] === + tokenAfterDeclarator.range[1] + ) { + return fixer.replaceText( + tokenAfterDeclarator, + `; ${exportPlacement}${declaration.kind} `, + ); + } + + /* + * `var x, + * tokenAfterDeclarator ^ + * y` + * ^ afterComma + */ + if ( + afterComma.loc.start.line > + tokenAfterDeclarator.loc.end.line || + afterComma.type === "Line" || + afterComma.type === "Block" + ) { + let lastComment = afterComma; + + while ( + lastComment.type === "Line" || + lastComment.type === "Block" + ) { + lastComment = sourceCode.getTokenAfter( + lastComment, + { includeComments: true }, + ); + } + + return fixer.replaceTextRange( + [ + tokenAfterDeclarator.range[0], + lastComment.range[0], + ], + `;${sourceCode.text.slice( + tokenAfterDeclarator.range[1], + lastComment.range[0], + )}${exportPlacement}${declaration.kind} `, + ); + } + + return fixer.replaceText( + tokenAfterDeclarator, + `; ${exportPlacement}${declaration.kind}`, + ); + }) + .filter(x => x); + } + + /** + * Checks a given VariableDeclaration node for errors. + * @param {ASTNode} node The VariableDeclaration node to check + * @returns {void} + * @private + */ + function checkVariableDeclaration(node) { + const parent = node.parent; + const type = node.kind; + const key = type === "await using" ? "awaitUsing" : type; + + if (!options[key]) { + return; + } + + const declarations = node.declarations; + const declarationCounts = countDeclarations(declarations); + const mixedRequires = + declarations.some(isRequire) && !declarations.every(isRequire); + + if (options[key].initialized === MODE_ALWAYS) { + if (options.separateRequires && mixedRequires) { + context.report({ + node, + messageId: "splitRequires", + }); + } + } + + // consecutive + const nodeIndex = + (parent.body && + parent.body.length > 0 && + parent.body.indexOf(node)) || + 0; + + if (nodeIndex > 0) { + const previousNode = parent.body[nodeIndex - 1]; + const isPreviousNodeDeclaration = + previousNode.type === "VariableDeclaration"; + const declarationsWithPrevious = declarations.concat( + previousNode.declarations || [], + ); + + if ( + isPreviousNodeDeclaration && + previousNode.kind === type && + !( + declarationsWithPrevious.some(isRequire) && + !declarationsWithPrevious.every(isRequire) + ) + ) { + const previousDeclCounts = countDeclarations( + previousNode.declarations, + ); + + if ( + options[key].initialized === MODE_CONSECUTIVE && + options[key].uninitialized === MODE_CONSECUTIVE + ) { + context.report({ + node, + messageId: "combine", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } else if ( + options[key].initialized === MODE_CONSECUTIVE && + declarationCounts.initialized > 0 && + previousDeclCounts.initialized > 0 + ) { + context.report({ + node, + messageId: "combineInitialized", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } else if ( + options[key].uninitialized === MODE_CONSECUTIVE && + declarationCounts.uninitialized > 0 && + previousDeclCounts.uninitialized > 0 + ) { + context.report({ + node, + messageId: "combineUninitialized", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } + } + } + + // always + if (!hasOnlyOneStatement(key, declarations)) { + if ( + options[key].initialized === MODE_ALWAYS && + options[key].uninitialized === MODE_ALWAYS + ) { + context.report({ + node, + messageId: "combine", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } else { + if ( + options[key].initialized === MODE_ALWAYS && + declarationCounts.initialized > 0 + ) { + context.report({ + node, + messageId: "combineInitialized", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } + if ( + options[key].uninitialized === MODE_ALWAYS && + declarationCounts.uninitialized > 0 + ) { + if ( + node.parent.left === node && + (node.parent.type === "ForInStatement" || + node.parent.type === "ForOfStatement") + ) { + return; + } + context.report({ + node, + messageId: "combineUninitialized", + data: { + type, + }, + fix: joinDeclarations(declarations), + }); + } + } + } + + // never + if (parent.type !== "ForStatement" || parent.init !== node) { + const totalDeclarations = + declarationCounts.uninitialized + + declarationCounts.initialized; + + if (totalDeclarations > 1) { + if ( + options[key].initialized === MODE_NEVER && + options[key].uninitialized === MODE_NEVER + ) { + // both initialized and uninitialized + context.report({ + node, + messageId: "split", + data: { + type, + }, + fix: splitDeclarations(node), + }); + } else if ( + options[key].initialized === MODE_NEVER && + declarationCounts.initialized > 0 + ) { + // initialized + context.report({ + node, + messageId: "splitInitialized", + data: { + type, + }, + fix: splitDeclarations(node), + }); + } else if ( + options[key].uninitialized === MODE_NEVER && + declarationCounts.uninitialized > 0 + ) { + // uninitialized + context.report({ + node, + messageId: "splitUninitialized", + data: { + type, + }, + fix: splitDeclarations(node), + }); + } + } + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + Program: startFunction, + FunctionDeclaration: startFunction, + FunctionExpression: startFunction, + ArrowFunctionExpression: startFunction, + StaticBlock: startFunction, // StaticBlock creates a new scope for `var` variables + + BlockStatement: startBlock, + ForStatement: startBlock, + ForInStatement: startBlock, + ForOfStatement: startBlock, + SwitchStatement: startBlock, + VariableDeclaration: checkVariableDeclaration, + "ForStatement:exit": endBlock, + "ForOfStatement:exit": endBlock, + "ForInStatement:exit": endBlock, + "SwitchStatement:exit": endBlock, + "BlockStatement:exit": endBlock, + + "Program:exit": endFunction, + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction, + "StaticBlock:exit": endFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/operator-assignment.js b/node_modules/eslint/lib/rules/operator-assignment.js new file mode 100644 index 0000000000000000000000000000000000000000..50ae9996da1e32ab7fc9fabdcb7ad30276b3c9eb --- /dev/null +++ b/node_modules/eslint/lib/rules/operator-assignment.js @@ -0,0 +1,270 @@ +/** + * @fileoverview Rule to replace assignment expressions with operator assignment + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether an operator is commutative and has an operator assignment + * shorthand form. + * @param {string} operator Operator to check. + * @returns {boolean} True if the operator is commutative and has a + * shorthand form. + */ +function isCommutativeOperatorWithShorthand(operator) { + return ["*", "&", "^", "|"].includes(operator); +} + +/** + * Checks whether an operator is not commutative and has an operator assignment + * shorthand form. + * @param {string} operator Operator to check. + * @returns {boolean} True if the operator is not commutative and has + * a shorthand form. + */ +function isNonCommutativeOperatorWithShorthand(operator) { + return ["+", "-", "/", "%", "<<", ">>", ">>>", "**"].includes(operator); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and) + * toString calls regardless of whether assignment shorthand is used) + * @param {ASTNode} node The node on the left side of the expression + * @returns {boolean} `true` if the node can be fixed + */ +function canBeFixed(node) { + return ( + node.type === "Identifier" || + (node.type === "MemberExpression" && + (node.object.type === "Identifier" || + node.object.type === "ThisExpression") && + (!node.computed || node.property.type === "Literal")) + ); +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: ["always"], + + docs: { + description: + "Require or disallow assignment operator shorthand where possible", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/operator-assignment", + }, + + schema: [ + { + enum: ["always", "never"], + }, + ], + + fixable: "code", + messages: { + replaced: + "Assignment (=) can be replaced with operator assignment ({{operator}}).", + unexpected: + "Unexpected operator assignment ({{operator}}) shorthand.", + }, + }, + + create(context) { + const never = context.options[0] === "never"; + const sourceCode = context.sourceCode; + + /** + * Returns the operator token of an AssignmentExpression or BinaryExpression + * @param {ASTNode} node An AssignmentExpression or BinaryExpression node + * @returns {Token} The operator token in the node + */ + function getOperatorToken(node) { + return sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + } + + /** + * Ensures that an assignment uses the shorthand form where possible. + * @param {ASTNode} node An AssignmentExpression node. + * @returns {void} + */ + function verify(node) { + if ( + node.operator !== "=" || + node.right.type !== "BinaryExpression" + ) { + return; + } + + const left = node.left; + const expr = node.right; + const operator = expr.operator; + + if ( + isCommutativeOperatorWithShorthand(operator) || + isNonCommutativeOperatorWithShorthand(operator) + ) { + const replacementOperator = `${operator}=`; + + if (astUtils.isSameReference(left, expr.left, true)) { + context.report({ + node, + messageId: "replaced", + data: { operator: replacementOperator }, + fix(fixer) { + if (canBeFixed(left) && canBeFixed(expr.left)) { + const equalsToken = getOperatorToken(node); + const operatorToken = getOperatorToken(expr); + const leftText = sourceCode + .getText() + .slice(node.range[0], equalsToken.range[0]); + const rightText = sourceCode + .getText() + .slice( + operatorToken.range[1], + node.right.range[1], + ); + + // Check for comments that would be removed. + if ( + sourceCode.commentsExistBetween( + equalsToken, + operatorToken, + ) + ) { + return null; + } + + return fixer.replaceText( + node, + `${leftText}${replacementOperator}${rightText}`, + ); + } + return null; + }, + }); + } else if ( + astUtils.isSameReference(left, expr.right, true) && + isCommutativeOperatorWithShorthand(operator) + ) { + /* + * This case can't be fixed safely. + * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would + * change the execution order of the valueOf() functions. + */ + context.report({ + node, + messageId: "replaced", + data: { operator: replacementOperator }, + }); + } + } + } + + /** + * Warns if an assignment expression uses operator assignment shorthand. + * @param {ASTNode} node An AssignmentExpression node. + * @returns {void} + */ + function prohibit(node) { + if ( + node.operator !== "=" && + !astUtils.isLogicalAssignmentOperator(node.operator) + ) { + context.report({ + node, + messageId: "unexpected", + data: { operator: node.operator }, + fix(fixer) { + if (canBeFixed(node.left)) { + const firstToken = sourceCode.getFirstToken(node); + const operatorToken = getOperatorToken(node); + const leftText = sourceCode + .getText() + .slice(node.range[0], operatorToken.range[0]); + const newOperator = node.operator.slice(0, -1); + let rightText; + + // Check for comments that would be duplicated. + if ( + sourceCode.commentsExistBetween( + firstToken, + operatorToken, + ) + ) { + return null; + } + + // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side. + if ( + astUtils.getPrecedence(node.right) <= + astUtils.getPrecedence({ + type: "BinaryExpression", + operator: newOperator, + }) && + !astUtils.isParenthesised( + sourceCode, + node.right, + ) + ) { + rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`; + } else { + const tokenAfterOperator = + sourceCode.getTokenAfter(operatorToken, { + includeComments: true, + }); + let rightTextPrefix = ""; + + if ( + operatorToken.range[1] === + tokenAfterOperator.range[0] && + !astUtils.canTokensBeAdjacent( + { + type: "Punctuator", + value: newOperator, + }, + tokenAfterOperator, + ) + ) { + rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar + } + + rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`; + } + + return fixer.replaceText( + node, + `${leftText}= ${leftText}${newOperator}${rightText}`, + ); + } + return null; + }, + }); + } + } + + return { + AssignmentExpression: !never ? verify : prohibit, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/operator-linebreak.js b/node_modules/eslint/lib/rules/operator-linebreak.js new file mode 100644 index 0000000000000000000000000000000000000000..f0b7d46fa2f1ddf96c5c047b9b1a6d0f2531cbb7 --- /dev/null +++ b/node_modules/eslint/lib/rules/operator-linebreak.js @@ -0,0 +1,315 @@ +/** + * @fileoverview Operator linebreak - enforces operator linebreak style of two types: after and before + * @author Benoît Zugmeyer + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "operator-linebreak", + url: "https://eslint.style/rules/operator-linebreak", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent linebreak style for operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/operator-linebreak", + }, + + schema: [ + { + enum: ["after", "before", "none", null], + }, + { + type: "object", + properties: { + overrides: { + type: "object", + additionalProperties: { + enum: ["after", "before", "none", "ignore"], + }, + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + operatorAtBeginning: + "'{{operator}}' should be placed at the beginning of the line.", + operatorAtEnd: + "'{{operator}}' should be placed at the end of the line.", + badLinebreak: "Bad line breaking before and after '{{operator}}'.", + noLinebreak: + "There should be no line break before or after '{{operator}}'.", + }, + }, + + create(context) { + const usedDefaultGlobal = !context.options[0]; + const globalStyle = context.options[0] || "after"; + const options = context.options[1] || {}; + const styleOverrides = options.overrides + ? Object.assign({}, options.overrides) + : {}; + + if (usedDefaultGlobal && !styleOverrides["?"]) { + styleOverrides["?"] = "before"; + } + + if (usedDefaultGlobal && !styleOverrides[":"]) { + styleOverrides[":"] = "before"; + } + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Gets a fixer function to fix rule issues + * @param {Token} operatorToken The operator token of an expression + * @param {string} desiredStyle The style for the rule. One of 'before', 'after', 'none' + * @returns {Function} A fixer function + */ + function getFixer(operatorToken, desiredStyle) { + return fixer => { + const tokenBefore = sourceCode.getTokenBefore(operatorToken); + const tokenAfter = sourceCode.getTokenAfter(operatorToken); + const textBefore = sourceCode.text.slice( + tokenBefore.range[1], + operatorToken.range[0], + ); + const textAfter = sourceCode.text.slice( + operatorToken.range[1], + tokenAfter.range[0], + ); + const hasLinebreakBefore = !astUtils.isTokenOnSameLine( + tokenBefore, + operatorToken, + ); + const hasLinebreakAfter = !astUtils.isTokenOnSameLine( + operatorToken, + tokenAfter, + ); + let newTextBefore, newTextAfter; + + if ( + hasLinebreakBefore !== hasLinebreakAfter && + desiredStyle !== "none" + ) { + // If there is a comment before and after the operator, don't do a fix. + if ( + sourceCode.getTokenBefore(operatorToken, { + includeComments: true, + }) !== tokenBefore && + sourceCode.getTokenAfter(operatorToken, { + includeComments: true, + }) !== tokenAfter + ) { + return null; + } + + /* + * If there is only one linebreak and it's on the wrong side of the operator, swap the text before and after the operator. + * foo && + * bar + * would get fixed to + * foo + * && bar + */ + newTextBefore = textAfter; + newTextAfter = textBefore; + } else { + const LINEBREAK_REGEX = + astUtils.createGlobalLinebreakMatcher(); + + // Otherwise, if no linebreak is desired and no comments interfere, replace the linebreaks with empty strings. + newTextBefore = + desiredStyle === "before" || textBefore.trim() + ? textBefore + : textBefore.replace(LINEBREAK_REGEX, ""); + newTextAfter = + desiredStyle === "after" || textAfter.trim() + ? textAfter + : textAfter.replace(LINEBREAK_REGEX, ""); + + // If there was no change (due to interfering comments), don't output a fix. + if ( + newTextBefore === textBefore && + newTextAfter === textAfter + ) { + return null; + } + } + + if ( + newTextAfter === "" && + tokenAfter.type === "Punctuator" && + "+-".includes(operatorToken.value) && + tokenAfter.value === operatorToken.value + ) { + // To avoid accidentally creating a ++ or -- operator, insert a space if the operator is a +/- and the following token is a unary +/-. + newTextAfter += " "; + } + + return fixer.replaceTextRange( + [tokenBefore.range[1], tokenAfter.range[0]], + newTextBefore + operatorToken.value + newTextAfter, + ); + }; + } + + /** + * Checks the operator placement + * @param {ASTNode} node The node to check + * @param {ASTNode} rightSide The node that comes after the operator in `node` + * @param {string} operator The operator + * @private + * @returns {void} + */ + function validateNode(node, rightSide, operator) { + /* + * Find the operator token by searching from the right side, because between the left side and the operator + * there could be additional tokens from type annotations. Search specifically for the token which + * value equals the operator, in order to skip possible opening parentheses before the right side node. + */ + const operatorToken = sourceCode.getTokenBefore( + rightSide, + token => token.value === operator, + ); + const leftToken = sourceCode.getTokenBefore(operatorToken); + const rightToken = sourceCode.getTokenAfter(operatorToken); + const operatorStyleOverride = styleOverrides[operator]; + const style = operatorStyleOverride || globalStyle; + const fix = getFixer(operatorToken, style); + + // if single line + if ( + astUtils.isTokenOnSameLine(leftToken, operatorToken) && + astUtils.isTokenOnSameLine(operatorToken, rightToken) + ) { + // do nothing. + } else if ( + operatorStyleOverride !== "ignore" && + !astUtils.isTokenOnSameLine(leftToken, operatorToken) && + !astUtils.isTokenOnSameLine(operatorToken, rightToken) + ) { + // lone operator + context.report({ + node, + loc: operatorToken.loc, + messageId: "badLinebreak", + data: { + operator, + }, + fix, + }); + } else if ( + style === "before" && + astUtils.isTokenOnSameLine(leftToken, operatorToken) + ) { + context.report({ + node, + loc: operatorToken.loc, + messageId: "operatorAtBeginning", + data: { + operator, + }, + fix, + }); + } else if ( + style === "after" && + astUtils.isTokenOnSameLine(operatorToken, rightToken) + ) { + context.report({ + node, + loc: operatorToken.loc, + messageId: "operatorAtEnd", + data: { + operator, + }, + fix, + }); + } else if (style === "none") { + context.report({ + node, + loc: operatorToken.loc, + messageId: "noLinebreak", + data: { + operator, + }, + fix, + }); + } + } + + /** + * Validates a binary expression using `validateNode` + * @param {BinaryExpression|LogicalExpression|AssignmentExpression} node node to be validated + * @returns {void} + */ + function validateBinaryExpression(node) { + validateNode(node, node.right, node.operator); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + BinaryExpression: validateBinaryExpression, + LogicalExpression: validateBinaryExpression, + AssignmentExpression: validateBinaryExpression, + VariableDeclarator(node) { + if (node.init) { + validateNode(node, node.init, "="); + } + }, + PropertyDefinition(node) { + if (node.value) { + validateNode(node, node.value, "="); + } + }, + ConditionalExpression(node) { + validateNode(node, node.consequent, "?"); + validateNode(node, node.alternate, ":"); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/padded-blocks.js b/node_modules/eslint/lib/rules/padded-blocks.js new file mode 100644 index 0000000000000000000000000000000000000000..2df44f890f17db73085ed5b21f3a5718b4f8a1e5 --- /dev/null +++ b/node_modules/eslint/lib/rules/padded-blocks.js @@ -0,0 +1,366 @@ +/** + * @fileoverview A rule to ensure blank lines within blocks. + * @author Mathias Schreck + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "padded-blocks", + url: "https://eslint.style/rules/padded-blocks", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require or disallow padding within blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/padded-blocks", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + blocks: { + enum: ["always", "never"], + }, + switches: { + enum: ["always", "never"], + }, + classes: { + enum: ["always", "never"], + }, + }, + additionalProperties: false, + minProperties: 1, + }, + ], + }, + { + type: "object", + properties: { + allowSingleLineBlocks: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + alwaysPadBlock: "Block must be padded by blank lines.", + neverPadBlock: "Block must not be padded by blank lines.", + }, + }, + + create(context) { + const options = {}; + const typeOptions = context.options[0] || "always"; + const exceptOptions = context.options[1] || {}; + + if (typeof typeOptions === "string") { + const shouldHavePadding = typeOptions === "always"; + + options.blocks = shouldHavePadding; + options.switches = shouldHavePadding; + options.classes = shouldHavePadding; + } else { + if (Object.hasOwn(typeOptions, "blocks")) { + options.blocks = typeOptions.blocks === "always"; + } + if (Object.hasOwn(typeOptions, "switches")) { + options.switches = typeOptions.switches === "always"; + } + if (Object.hasOwn(typeOptions, "classes")) { + options.classes = typeOptions.classes === "always"; + } + } + + if (Object.hasOwn(exceptOptions, "allowSingleLineBlocks")) { + options.allowSingleLineBlocks = + exceptOptions.allowSingleLineBlocks === true; + } + + const sourceCode = context.sourceCode; + + /** + * Gets the open brace token from a given node. + * @param {ASTNode} node A BlockStatement or SwitchStatement node from which to get the open brace. + * @returns {Token} The token of the open brace. + */ + function getOpenBrace(node) { + if (node.type === "SwitchStatement") { + return sourceCode.getTokenBefore(node.cases[0]); + } + + if (node.type === "StaticBlock") { + return sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token + } + + // `BlockStatement` or `ClassBody` + return sourceCode.getFirstToken(node); + } + + /** + * Checks if the given parameter is a comment node + * @param {ASTNode|Token} node An AST node or token + * @returns {boolean} True if node is a comment + */ + function isComment(node) { + return node.type === "Line" || node.type === "Block"; + } + + /** + * Checks if there is padding between two tokens + * @param {Token} first The first token + * @param {Token} second The second token + * @returns {boolean} True if there is at least a line between the tokens + */ + function isPaddingBetweenTokens(first, second) { + return second.loc.start.line - first.loc.end.line >= 2; + } + + /** + * Checks if the given token has a blank line after it. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the token is followed by a blank line. + */ + function getFirstBlockToken(token) { + let prev, + first = token; + + do { + prev = first; + first = sourceCode.getTokenAfter(first, { + includeComments: true, + }); + } while ( + isComment(first) && + first.loc.start.line === prev.loc.end.line + ); + + return first; + } + + /** + * Checks if the given token is preceded by a blank line. + * @param {Token} token The token to check + * @returns {boolean} Whether or not the token is preceded by a blank line + */ + function getLastBlockToken(token) { + let last = token, + next; + + do { + next = last; + last = sourceCode.getTokenBefore(last, { + includeComments: true, + }); + } while ( + isComment(last) && + last.loc.end.line === next.loc.start.line + ); + + return last; + } + + /** + * Checks if a node should be padded, according to the rule config. + * @param {ASTNode} node The AST node to check. + * @throws {Error} (Unreachable) + * @returns {boolean} True if the node should be padded, false otherwise. + */ + function requirePaddingFor(node) { + switch (node.type) { + case "BlockStatement": + case "StaticBlock": + return options.blocks; + case "SwitchStatement": + return options.switches; + case "ClassBody": + return options.classes; + + /* c8 ignore next */ + default: + throw new Error("unreachable"); + } + } + + /** + * Checks the given BlockStatement node to be padded if the block is not empty. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {void} undefined. + */ + function checkPadding(node) { + const openBrace = getOpenBrace(node), + firstBlockToken = getFirstBlockToken(openBrace), + tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, { + includeComments: true, + }), + closeBrace = sourceCode.getLastToken(node), + lastBlockToken = getLastBlockToken(closeBrace), + tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, { + includeComments: true, + }), + blockHasTopPadding = isPaddingBetweenTokens( + tokenBeforeFirst, + firstBlockToken, + ), + blockHasBottomPadding = isPaddingBetweenTokens( + lastBlockToken, + tokenAfterLast, + ); + + if ( + options.allowSingleLineBlocks && + astUtils.isTokenOnSameLine(tokenBeforeFirst, tokenAfterLast) + ) { + return; + } + + if (requirePaddingFor(node)) { + if (!blockHasTopPadding) { + context.report({ + node, + loc: { + start: tokenBeforeFirst.loc.start, + end: firstBlockToken.loc.start, + }, + fix(fixer) { + return fixer.insertTextAfter( + tokenBeforeFirst, + "\n", + ); + }, + messageId: "alwaysPadBlock", + }); + } + if (!blockHasBottomPadding) { + context.report({ + node, + loc: { + end: tokenAfterLast.loc.start, + start: lastBlockToken.loc.end, + }, + fix(fixer) { + return fixer.insertTextBefore(tokenAfterLast, "\n"); + }, + messageId: "alwaysPadBlock", + }); + } + } else { + if (blockHasTopPadding) { + context.report({ + node, + loc: { + start: tokenBeforeFirst.loc.start, + end: firstBlockToken.loc.start, + }, + fix(fixer) { + return fixer.replaceTextRange( + [ + tokenBeforeFirst.range[1], + firstBlockToken.range[0] - + firstBlockToken.loc.start.column, + ], + "\n", + ); + }, + messageId: "neverPadBlock", + }); + } + + if (blockHasBottomPadding) { + context.report({ + node, + loc: { + end: tokenAfterLast.loc.start, + start: lastBlockToken.loc.end, + }, + messageId: "neverPadBlock", + fix(fixer) { + return fixer.replaceTextRange( + [ + lastBlockToken.range[1], + tokenAfterLast.range[0] - + tokenAfterLast.loc.start.column, + ], + "\n", + ); + }, + }); + } + } + } + + const rule = {}; + + if (Object.hasOwn(options, "switches")) { + rule.SwitchStatement = function (node) { + if (node.cases.length === 0) { + return; + } + checkPadding(node); + }; + } + + if (Object.hasOwn(options, "blocks")) { + rule.BlockStatement = function (node) { + if (node.body.length === 0) { + return; + } + checkPadding(node); + }; + rule.StaticBlock = rule.BlockStatement; + } + + if (Object.hasOwn(options, "classes")) { + rule.ClassBody = function (node) { + if (node.body.length === 0) { + return; + } + checkPadding(node); + }; + } + + return rule; + }, +}; diff --git a/node_modules/eslint/lib/rules/padding-line-between-statements.js b/node_modules/eslint/lib/rules/padding-line-between-statements.js new file mode 100644 index 0000000000000000000000000000000000000000..4287170f5772db9b3f869d0b7f2c18b5d1f01514 --- /dev/null +++ b/node_modules/eslint/lib/rules/padding-line-between-statements.js @@ -0,0 +1,612 @@ +/** + * @fileoverview Rule to require or disallow newlines between statements + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const LT = `[${Array.from(astUtils.LINEBREAKS).join("")}]`; +const PADDING_LINE_SEQUENCE = new RegExp( + String.raw`^(\s*?${LT})\s*${LT}(\s*;?)$`, + "u", +); +const CJS_EXPORT = /^(?:module\s*\.\s*)?exports(?:\s*\.|\s*\[|$)/u; +const CJS_IMPORT = /^require\(/u; + +/** + * Creates tester which check if a node starts with specific keyword. + * @param {string} keyword The keyword to test. + * @returns {Object} the created tester. + * @private + */ +function newKeywordTester(keyword) { + return { + test: (node, sourceCode) => + sourceCode.getFirstToken(node).value === keyword, + }; +} + +/** + * Creates tester which check if a node starts with specific keyword and spans a single line. + * @param {string} keyword The keyword to test. + * @returns {Object} the created tester. + * @private + */ +function newSinglelineKeywordTester(keyword) { + return { + test: (node, sourceCode) => + node.loc.start.line === node.loc.end.line && + sourceCode.getFirstToken(node).value === keyword, + }; +} + +/** + * Creates tester which check if a node starts with specific keyword and spans multiple lines. + * @param {string} keyword The keyword to test. + * @returns {Object} the created tester. + * @private + */ +function newMultilineKeywordTester(keyword) { + return { + test: (node, sourceCode) => + node.loc.start.line !== node.loc.end.line && + sourceCode.getFirstToken(node).value === keyword, + }; +} + +/** + * Creates tester which check if a node is specific type. + * @param {string} type The node type to test. + * @returns {Object} the created tester. + * @private + */ +function newNodeTypeTester(type) { + return { + test: node => node.type === type, + }; +} + +/** + * Checks the given node is an expression statement of IIFE. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is an expression statement of IIFE. + * @private + */ +function isIIFEStatement(node) { + if (node.type === "ExpressionStatement") { + let call = astUtils.skipChainExpression(node.expression); + + if (call.type === "UnaryExpression") { + call = astUtils.skipChainExpression(call.argument); + } + return ( + call.type === "CallExpression" && astUtils.isFunction(call.callee) + ); + } + return false; +} + +/** + * Checks whether the given node is a block-like statement. + * This checks the last token of the node is the closing brace of a block. + * @param {SourceCode} sourceCode The source code to get tokens. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a block-like statement. + * @private + */ +function isBlockLikeStatement(sourceCode, node) { + // do-while with a block is a block-like statement. + if ( + node.type === "DoWhileStatement" && + node.body.type === "BlockStatement" + ) { + return true; + } + + /* + * IIFE is a block-like statement specially from + * JSCS#disallowPaddingNewLinesAfterBlocks. + */ + if (isIIFEStatement(node)) { + return true; + } + + // Checks the last token is a closing brace of blocks. + const lastToken = sourceCode.getLastToken( + node, + astUtils.isNotSemicolonToken, + ); + const belongingNode = + lastToken && astUtils.isClosingBraceToken(lastToken) + ? sourceCode.getNodeByRangeIndex(lastToken.range[0]) + : null; + + return ( + Boolean(belongingNode) && + (belongingNode.type === "BlockStatement" || + belongingNode.type === "SwitchStatement") + ); +} + +/** + * Gets the actual last token. + * + * If a semicolon is semicolon-less style's semicolon, this ignores it. + * For example: + * + * foo() + * ;[1, 2, 3].forEach(bar) + * @param {SourceCode} sourceCode The source code to get tokens. + * @param {ASTNode} node The node to get. + * @returns {Token} The actual last token. + * @private + */ +function getActualLastToken(sourceCode, node) { + const semiToken = sourceCode.getLastToken(node); + const prevToken = sourceCode.getTokenBefore(semiToken); + const nextToken = sourceCode.getTokenAfter(semiToken); + const isSemicolonLessStyle = Boolean( + prevToken && + nextToken && + prevToken.range[0] >= node.range[0] && + astUtils.isSemicolonToken(semiToken) && + semiToken.loc.start.line !== prevToken.loc.end.line && + semiToken.loc.end.line === nextToken.loc.start.line, + ); + + return isSemicolonLessStyle ? prevToken : semiToken; +} + +/** + * This returns the concatenation of the first 2 captured strings. + * @param {string} _ Unused. Whole matched string. + * @param {string} trailingSpaces The trailing spaces of the first line. + * @param {string} indentSpaces The indentation spaces of the last line. + * @returns {string} The concatenation of trailingSpaces and indentSpaces. + * @private + */ +function replacerToRemovePaddingLines(_, trailingSpaces, indentSpaces) { + return trailingSpaces + indentSpaces; +} + +/** + * Check and report statements for `any` configuration. + * It does nothing. + * @returns {void} + * @private + */ +function verifyForAny() {} + +/** + * Check and report statements for `never` configuration. + * This autofix removes blank lines between the given 2 statements. + * However, if comments exist between 2 blank lines, it does not remove those + * blank lines automatically. + * @param {RuleContext} context The rule context to report. + * @param {ASTNode} _ Unused. The previous node to check. + * @param {ASTNode} nextNode The next node to check. + * @param {Array} paddingLines The array of token pairs that blank + * lines exist between the pair. + * @returns {void} + * @private + */ +function verifyForNever(context, _, nextNode, paddingLines) { + if (paddingLines.length === 0) { + return; + } + + context.report({ + node: nextNode, + messageId: "unexpectedBlankLine", + fix(fixer) { + if (paddingLines.length >= 2) { + return null; + } + + const prevToken = paddingLines[0][0]; + const nextToken = paddingLines[0][1]; + const start = prevToken.range[1]; + const end = nextToken.range[0]; + const text = context.sourceCode.text + .slice(start, end) + .replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines); + + return fixer.replaceTextRange([start, end], text); + }, + }); +} + +/** + * Check and report statements for `always` configuration. + * This autofix inserts a blank line between the given 2 statements. + * If the `prevNode` has trailing comments, it inserts a blank line after the + * trailing comments. + * @param {RuleContext} context The rule context to report. + * @param {ASTNode} prevNode The previous node to check. + * @param {ASTNode} nextNode The next node to check. + * @param {Array} paddingLines The array of token pairs that blank + * lines exist between the pair. + * @returns {void} + * @private + */ +function verifyForAlways(context, prevNode, nextNode, paddingLines) { + if (paddingLines.length > 0) { + return; + } + + context.report({ + node: nextNode, + messageId: "expectedBlankLine", + fix(fixer) { + const sourceCode = context.sourceCode; + let prevToken = getActualLastToken(sourceCode, prevNode); + const nextToken = + sourceCode.getFirstTokenBetween(prevToken, nextNode, { + includeComments: true, + + /** + * Skip the trailing comments of the previous node. + * This inserts a blank line after the last trailing comment. + * + * For example: + * + * foo(); // trailing comment. + * // comment. + * bar(); + * + * Get fixed to: + * + * foo(); // trailing comment. + * + * // comment. + * bar(); + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is not a trailing comment. + * @private + */ + filter(token) { + if (astUtils.isTokenOnSameLine(prevToken, token)) { + prevToken = token; + return false; + } + return true; + }, + }) || nextNode; + const insertText = astUtils.isTokenOnSameLine(prevToken, nextToken) + ? "\n\n" + : "\n"; + + return fixer.insertTextAfter(prevToken, insertText); + }, + }); +} + +/** + * Types of blank lines. + * `any`, `never`, and `always` are defined. + * Those have `verify` method to check and report statements. + * @private + */ +const PaddingTypes = { + any: { verify: verifyForAny }, + never: { verify: verifyForNever }, + always: { verify: verifyForAlways }, +}; + +/** + * Types of statements. + * Those have `test` method to check it matches to the given statement. + * @private + */ +const StatementTypes = { + "*": { test: () => true }, + "block-like": { + test: (node, sourceCode) => isBlockLikeStatement(sourceCode, node), + }, + "cjs-export": { + test: (node, sourceCode) => + node.type === "ExpressionStatement" && + node.expression.type === "AssignmentExpression" && + CJS_EXPORT.test(sourceCode.getText(node.expression.left)), + }, + "cjs-import": { + test: (node, sourceCode) => + node.type === "VariableDeclaration" && + node.declarations.length > 0 && + Boolean(node.declarations[0].init) && + CJS_IMPORT.test(sourceCode.getText(node.declarations[0].init)), + }, + directive: { + test: astUtils.isDirective, + }, + expression: { + test: node => + node.type === "ExpressionStatement" && !astUtils.isDirective(node), + }, + iife: { + test: isIIFEStatement, + }, + "multiline-block-like": { + test: (node, sourceCode) => + node.loc.start.line !== node.loc.end.line && + isBlockLikeStatement(sourceCode, node), + }, + "multiline-expression": { + test: node => + node.loc.start.line !== node.loc.end.line && + node.type === "ExpressionStatement" && + !astUtils.isDirective(node), + }, + + "multiline-const": newMultilineKeywordTester("const"), + "multiline-let": newMultilineKeywordTester("let"), + "multiline-var": newMultilineKeywordTester("var"), + "singleline-const": newSinglelineKeywordTester("const"), + "singleline-let": newSinglelineKeywordTester("let"), + "singleline-var": newSinglelineKeywordTester("var"), + + block: newNodeTypeTester("BlockStatement"), + empty: newNodeTypeTester("EmptyStatement"), + function: newNodeTypeTester("FunctionDeclaration"), + + break: newKeywordTester("break"), + case: newKeywordTester("case"), + class: newKeywordTester("class"), + const: newKeywordTester("const"), + continue: newKeywordTester("continue"), + debugger: newKeywordTester("debugger"), + default: newKeywordTester("default"), + do: newKeywordTester("do"), + export: newKeywordTester("export"), + for: newKeywordTester("for"), + if: newKeywordTester("if"), + import: newKeywordTester("import"), + let: newKeywordTester("let"), + return: newKeywordTester("return"), + switch: newKeywordTester("switch"), + throw: newKeywordTester("throw"), + try: newKeywordTester("try"), + var: newKeywordTester("var"), + while: newKeywordTester("while"), + with: newKeywordTester("with"), +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "padding-line-between-statements", + url: "https://eslint.style/rules/padding-line-between-statements", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require or disallow padding lines between statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/padding-line-between-statements", + }, + + fixable: "whitespace", + + schema: { + definitions: { + paddingType: { + enum: Object.keys(PaddingTypes), + }, + statementType: { + anyOf: [ + { enum: Object.keys(StatementTypes) }, + { + type: "array", + items: { enum: Object.keys(StatementTypes) }, + minItems: 1, + uniqueItems: true, + }, + ], + }, + }, + type: "array", + items: { + type: "object", + properties: { + blankLine: { $ref: "#/definitions/paddingType" }, + prev: { $ref: "#/definitions/statementType" }, + next: { $ref: "#/definitions/statementType" }, + }, + additionalProperties: false, + required: ["blankLine", "prev", "next"], + }, + }, + + messages: { + unexpectedBlankLine: "Unexpected blank line before this statement.", + expectedBlankLine: "Expected blank line before this statement.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const configureList = context.options || []; + let scopeInfo = null; + + /** + * Processes to enter to new scope. + * This manages the current previous statement. + * @returns {void} + * @private + */ + function enterScope() { + scopeInfo = { + upper: scopeInfo, + prevNode: null, + }; + } + + /** + * Processes to exit from the current scope. + * @returns {void} + * @private + */ + function exitScope() { + scopeInfo = scopeInfo.upper; + } + + /** + * Checks whether the given node matches the given type. + * @param {ASTNode} node The statement node to check. + * @param {string|string[]} type The statement type to check. + * @returns {boolean} `true` if the statement node matched the type. + * @private + */ + function match(node, type) { + let innerStatementNode = node; + + while (innerStatementNode.type === "LabeledStatement") { + innerStatementNode = innerStatementNode.body; + } + if (Array.isArray(type)) { + return type.some(match.bind(null, innerStatementNode)); + } + return StatementTypes[type].test(innerStatementNode, sourceCode); + } + + /** + * Finds the last matched configure from configureList. + * @param {ASTNode} prevNode The previous statement to match. + * @param {ASTNode} nextNode The current statement to match. + * @returns {Object} The tester of the last matched configure. + * @private + */ + function getPaddingType(prevNode, nextNode) { + for (let i = configureList.length - 1; i >= 0; --i) { + const configure = configureList[i]; + const matched = + match(prevNode, configure.prev) && + match(nextNode, configure.next); + + if (matched) { + return PaddingTypes[configure.blankLine]; + } + } + return PaddingTypes.any; + } + + /** + * Gets padding line sequences between the given 2 statements. + * Comments are separators of the padding line sequences. + * @param {ASTNode} prevNode The previous statement to count. + * @param {ASTNode} nextNode The current statement to count. + * @returns {Array} The array of token pairs. + * @private + */ + function getPaddingLineSequences(prevNode, nextNode) { + const pairs = []; + let prevToken = getActualLastToken(sourceCode, prevNode); + + if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) { + do { + const token = sourceCode.getTokenAfter(prevToken, { + includeComments: true, + }); + + if (token.loc.start.line - prevToken.loc.end.line >= 2) { + pairs.push([prevToken, token]); + } + prevToken = token; + } while (prevToken.range[0] < nextNode.range[0]); + } + + return pairs; + } + + /** + * Verify padding lines between the given node and the previous node. + * @param {ASTNode} node The node to verify. + * @returns {void} + * @private + */ + function verify(node) { + const parentType = node.parent.type; + const validParent = + astUtils.STATEMENT_LIST_PARENTS.has(parentType) || + parentType === "SwitchStatement"; + + if (!validParent) { + return; + } + + // Save this node as the current previous statement. + const prevNode = scopeInfo.prevNode; + + // Verify. + if (prevNode) { + const type = getPaddingType(prevNode, node); + const paddingLines = getPaddingLineSequences(prevNode, node); + + type.verify(context, prevNode, node, paddingLines); + } + + scopeInfo.prevNode = node; + } + + /** + * Verify padding lines between the given node and the previous node. + * Then process to enter to new scope. + * @param {ASTNode} node The node to verify. + * @returns {void} + * @private + */ + function verifyThenEnterScope(node) { + verify(node); + enterScope(); + } + + return { + Program: enterScope, + BlockStatement: enterScope, + SwitchStatement: enterScope, + StaticBlock: enterScope, + "Program:exit": exitScope, + "BlockStatement:exit": exitScope, + "SwitchStatement:exit": exitScope, + "StaticBlock:exit": exitScope, + + ":statement": verify, + + SwitchCase: verifyThenEnterScope, + "SwitchCase:exit": exitScope, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-arrow-callback.js b/node_modules/eslint/lib/rules/prefer-arrow-callback.js new file mode 100644 index 0000000000000000000000000000000000000000..df2ea3bb706ca8983fee5407896d4091b193bb47 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-arrow-callback.js @@ -0,0 +1,453 @@ +/** + * @fileoverview A rule to suggest using arrow functions as callbacks. + * @author Toru Nagashima + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("eslint-scope").Variable} Variable */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given variable is a function name. + * @param {Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is a function name. + */ +function isFunctionName(variable) { + return variable && variable.defs[0].type === "FunctionName"; +} + +/** + * Checks whether or not a given MetaProperty node equals to a given value. + * @param {ASTNode} node A MetaProperty node to check. + * @param {string} metaName The name of `MetaProperty.meta`. + * @param {string} propertyName The name of `MetaProperty.property`. + * @returns {boolean} `true` if the node is the specific value. + */ +function checkMetaProperty(node, metaName, propertyName) { + return node.meta.name === metaName && node.property.name === propertyName; +} + +/** + * Gets the variable object of `arguments` which is defined implicitly. + * @param {Scope} scope A scope to get. + * @returns {Variable} The found variable object. + */ +function getVariableOfArguments(scope) { + const variables = scope.variables; + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + + if (variable.name === "arguments") { + /* + * If there was a parameter which is named "arguments", the + * implicit "arguments" is not defined. + * So does fast return with null. + */ + return variable.identifiers.length === 0 ? variable : null; + } + } + + /* c8 ignore next */ + return null; +} + +/** + * Checks whether or not a given node is a callback. + * @param {ASTNode} node A node to check. + * @throws {Error} (Unreachable.) + * @returns {Object} + * {boolean} retv.isCallback - `true` if the node is a callback. + * {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`. + */ +function getCallbackInfo(node) { + const retv = { isCallback: false, isLexicalThis: false }; + let currentNode = node; + let parent = node.parent; + let bound = false; + + while (currentNode) { + switch (parent.type) { + // Checks parents recursively. + + case "LogicalExpression": + case "ChainExpression": + case "ConditionalExpression": + break; + + // Checks whether the parent node is `.bind(this)` call. + case "MemberExpression": + if ( + parent.object === currentNode && + !parent.property.computed && + parent.property.type === "Identifier" && + parent.property.name === "bind" + ) { + const maybeCallee = + parent.parent.type === "ChainExpression" + ? parent.parent + : parent; + + if (astUtils.isCallee(maybeCallee)) { + if (!bound) { + bound = true; // Use only the first `.bind()` to make `isLexicalThis` value. + retv.isLexicalThis = + maybeCallee.parent.arguments.length === 1 && + maybeCallee.parent.arguments[0].type === + "ThisExpression"; + } + parent = maybeCallee.parent; + } else { + return retv; + } + } else { + return retv; + } + break; + + // Checks whether the node is a callback. + case "CallExpression": + case "NewExpression": + if (parent.callee !== currentNode) { + retv.isCallback = true; + } + return retv; + + default: + return retv; + } + + currentNode = parent; + parent = parent.parent; + } + + /* c8 ignore next */ + throw new Error("unreachable"); +} + +/** + * Checks whether a simple list of parameters contains any duplicates. This does not handle complex + * parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate + * parameter names anyway. Instead, it always returns `false` for complex parameter lists. + * @param {ASTNode[]} paramsList The list of parameters for a function + * @returns {boolean} `true` if the list of parameters contains any duplicates + */ +function hasDuplicateParams(paramsList) { + return ( + paramsList.every(param => param.type === "Identifier") && + paramsList.length !== new Set(paramsList.map(param => param.name)).size + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { allowNamedFunctions: false, allowUnboundThis: true }, + ], + + docs: { + description: "Require using arrow functions for callbacks", + dialects: ["JavaScript", "TypeScript"], + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/prefer-arrow-callback", + }, + + schema: [ + { + type: "object", + properties: { + allowNamedFunctions: { + type: "boolean", + }, + allowUnboundThis: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + preferArrowCallback: "Unexpected function expression.", + }, + }, + + create(context) { + const [{ allowNamedFunctions, allowUnboundThis }] = context.options; + const sourceCode = context.sourceCode; + + /* + * {Array<{this: boolean, super: boolean, meta: boolean}>} + * - this - A flag which shows there are one or more ThisExpression. + * - super - A flag which shows there are one or more Super. + * - meta - A flag which shows there are one or more MethProperty. + */ + let stack = []; + + /** + * Pushes new function scope with all `false` flags. + * @returns {void} + */ + function enterScope() { + stack.push({ this: false, super: false, meta: false }); + } + + /** + * Pops a function scope from the stack. + * @returns {{this: boolean, super: boolean, meta: boolean}} The information of the last scope. + */ + function exitScope() { + return stack.pop(); + } + + return { + // Reset internal state. + Program() { + stack = []; + }, + + // If there are below, it cannot replace with arrow functions merely. + ThisExpression() { + const info = stack.at(-1); + + if (info) { + info.this = true; + } + }, + + Super() { + const info = stack.at(-1); + + if (info) { + info.super = true; + } + }, + + MetaProperty(node) { + const info = stack.at(-1); + + if (info && checkMetaProperty(node, "new", "target")) { + info.meta = true; + } + }, + + // To skip nested scopes. + FunctionDeclaration: enterScope, + "FunctionDeclaration:exit": exitScope, + + // Main. + FunctionExpression: enterScope, + "FunctionExpression:exit"(node) { + const scopeInfo = exitScope(); + + // Skip named function expressions + if (allowNamedFunctions && node.id && node.id.name) { + return; + } + + // Skip generators. + if (node.generator) { + return; + } + + // Skip recursive functions. + const nameVar = sourceCode.getDeclaredVariables(node)[0]; + + if (isFunctionName(nameVar) && nameVar.references.length > 0) { + return; + } + + // Skip if it's using arguments. + const variable = getVariableOfArguments( + sourceCode.getScope(node), + ); + + if (variable && variable.references.length > 0) { + return; + } + + // Reports if it's a callback which can replace with arrows. + const callbackInfo = getCallbackInfo(node); + + if ( + callbackInfo.isCallback && + (!allowUnboundThis || + !scopeInfo.this || + callbackInfo.isLexicalThis) && + !scopeInfo.super && + !scopeInfo.meta + ) { + context.report({ + node, + messageId: "preferArrowCallback", + *fix(fixer) { + if ( + (!callbackInfo.isLexicalThis && + scopeInfo.this) || + hasDuplicateParams(node.params) + ) { + /* + * If the callback function does not have .bind(this) and contains a reference to `this`, there + * is no way to determine what `this` should be, so don't perform any fixes. + * If the callback function has duplicates in its list of parameters (possible in sloppy mode), + * don't replace it with an arrow function, because this is a SyntaxError with arrow functions. + */ + return; + } + + if ( + node.params.length && + node.params[0].name === "this" + ) { + return; + } + + const functionToken = sourceCode.getFirstToken( + node, + node.async ? 1 : 0, + ); + const leftParenToken = sourceCode.getTokenAfter( + functionToken, + astUtils.isOpeningParenToken, + ); + + if (node.async) { + if ( + functionToken.loc.end.line < + leftParenToken.loc.start.line + ) { + return; + } + } + + // Remove `.bind(this)` if exists. + if (callbackInfo.isLexicalThis) { + const memberNode = node.parent; + + /* + * If `.bind(this)` exists but the parent is not `.bind(this)`, don't remove it automatically. + * E.g. `(foo || function(){}).bind(this)` + */ + if (memberNode.type !== "MemberExpression") { + return; + } + + const callNode = memberNode.parent; + const firstTokenToRemove = + sourceCode.getTokenAfter( + memberNode.object, + astUtils.isNotClosingParenToken, + ); + const lastTokenToRemove = + sourceCode.getLastToken(callNode); + + /* + * If the member expression is parenthesized, don't remove the right paren. + * E.g. `(function(){}.bind)(this)` + * ^^^^^^^^^^^^ + */ + if ( + astUtils.isParenthesised( + sourceCode, + memberNode, + ) + ) { + return; + } + + // If comments exist in the `.bind(this)`, don't remove those. + if ( + sourceCode.commentsExistBetween( + firstTokenToRemove, + lastTokenToRemove, + ) + ) { + return; + } + + yield fixer.removeRange([ + firstTokenToRemove.range[0], + lastTokenToRemove.range[1], + ]); + } + + // Convert the function expression to an arrow function. + const tokenBeforeBody = sourceCode.getTokenBefore( + node.body, + ); + + if ( + sourceCode.commentsExistBetween( + functionToken, + leftParenToken, + ) + ) { + // Remove only extra tokens to keep comments. + yield fixer.remove(functionToken); + if (node.id) { + yield fixer.remove(node.id); + } + } else { + // Remove extra tokens and spaces. + yield fixer.removeRange([ + functionToken.range[0], + leftParenToken.range[0], + ]); + } + yield fixer.insertTextAfter(tokenBeforeBody, " =>"); + + // Get the node that will become the new arrow function. + let replacedNode = callbackInfo.isLexicalThis + ? node.parent.parent + : node; + + if (replacedNode.type === "ChainExpression") { + replacedNode = replacedNode.parent; + } + + /* + * If the replaced node is part of a BinaryExpression, LogicalExpression, or MemberExpression, then + * the arrow function needs to be parenthesized, because `foo || () => {}` is invalid syntax even + * though `foo || function() {}` is valid. + */ + if ( + replacedNode.parent.type !== "CallExpression" && + replacedNode.parent.type !== + "ConditionalExpression" && + !astUtils.isParenthesised( + sourceCode, + replacedNode, + ) && + !astUtils.isParenthesised(sourceCode, node) + ) { + yield fixer.insertTextBefore(replacedNode, "("); + yield fixer.insertTextAfter(replacedNode, ")"); + } + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-const.js b/node_modules/eslint/lib/rules/prefer-const.js new file mode 100644 index 0000000000000000000000000000000000000000..57cfb7ee496d3f2faa2337bdae85c2f39720680a --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-const.js @@ -0,0 +1,554 @@ +/** + * @fileoverview A rule to suggest using of const declaration for variables that are never reassigned after declared. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const FixTracker = require("./utils/fix-tracker"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("eslint-scope").Variable} Variable */ +/** @typedef {import("eslint-scope").Reference} Reference */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const PATTERN_TYPE = + /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/u; +const DECLARATION_HOST_TYPE = + /^(?:Program|BlockStatement|StaticBlock|SwitchCase)$/u; +const DESTRUCTURING_HOST_TYPE = + /^(?:VariableDeclarator|AssignmentExpression)$/u; + +/** + * Checks whether a given node is located at `ForStatement.init` or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is located at `ForStatement.init`. + */ +function isInitOfForStatement(node) { + return node.parent.type === "ForStatement" && node.parent.init === node; +} + +/** + * Checks whether a given Identifier node becomes a VariableDeclaration or not. + * @param {ASTNode} identifier An Identifier node to check. + * @returns {boolean} `true` if the node can become a VariableDeclaration. + */ +function canBecomeVariableDeclaration(identifier) { + let node = identifier.parent; + + while (PATTERN_TYPE.test(node.type)) { + node = node.parent; + } + + return ( + node.type === "VariableDeclarator" || + (node.type === "AssignmentExpression" && + node.parent.type === "ExpressionStatement" && + DECLARATION_HOST_TYPE.test(node.parent.parent.type)) + ); +} + +/** + * Checks if an property or element is from outer scope or function parameters + * in destructing pattern. + * @param {string} name A variable name to be checked. + * @param {Scope} initScope A scope to start find. + * @returns {boolean} Indicates if the variable is from outer scope or function parameters. + */ +function isOuterVariableInDestructing(name, initScope) { + if ( + initScope.through.some( + ref => ref.resolved && ref.resolved.name === name, + ) + ) { + return true; + } + + const variable = astUtils.getVariableByName(initScope, name); + + if (variable !== null) { + return variable.defs.some(def => def.type === "Parameter"); + } + + return false; +} + +/** + * Gets the VariableDeclarator/AssignmentExpression node that a given reference + * belongs to. + * This is used to detect a mix of reassigned and never reassigned in a + * destructuring. + * @param {Reference} reference A reference to get. + * @returns {ASTNode|null} A VariableDeclarator/AssignmentExpression node or + * null. + */ +function getDestructuringHost(reference) { + if (!reference.isWrite()) { + return null; + } + let node = reference.identifier.parent; + + while (PATTERN_TYPE.test(node.type)) { + node = node.parent; + } + + if (!DESTRUCTURING_HOST_TYPE.test(node.type)) { + return null; + } + return node; +} + +/** + * Determines if a destructuring assignment node contains + * any MemberExpression nodes. This is used to determine if a + * variable that is only written once using destructuring can be + * safely converted into a const declaration. + * @param {ASTNode} node The ObjectPattern or ArrayPattern node to check. + * @returns {boolean} True if the destructuring pattern contains + * a MemberExpression, false if not. + */ +function hasMemberExpressionAssignment(node) { + switch (node.type) { + case "ObjectPattern": + return node.properties.some(prop => { + if (prop) { + /* + * Spread elements have an argument property while + * others have a value property. Because different + * parsers use different node types for spread elements, + * we just check if there is an argument property. + */ + return hasMemberExpressionAssignment( + prop.argument || prop.value, + ); + } + + return false; + }); + + case "ArrayPattern": + return node.elements.some(element => { + if (element) { + return hasMemberExpressionAssignment(element); + } + + return false; + }); + + case "AssignmentPattern": + return hasMemberExpressionAssignment(node.left); + + case "MemberExpression": + return true; + + // no default + } + + return false; +} + +/** + * Gets an identifier node of a given variable. + * + * If the initialization exists or one or more reading references exist before + * the first assignment, the identifier node is the node of the declaration. + * Otherwise, the identifier node is the node of the first assignment. + * + * If the variable should not change to const, this function returns null. + * - If the variable is reassigned. + * - If the variable is never initialized nor assigned. + * - If the variable is initialized in a different scope from the declaration. + * - If the unique assignment of the variable cannot change to a declaration. + * e.g. `if (a) b = 1` / `return (b = 1)` + * - If the variable is declared in the global scope and `eslintUsed` is `true`. + * `/*exported foo` directive comment makes such variables. This rule does not + * warn such variables because this rule cannot distinguish whether the + * exported variables are reassigned or not. + * @param {Variable} variable A variable to get. + * @param {boolean} ignoreReadBeforeAssign + * The value of `ignoreReadBeforeAssign` option. + * @returns {ASTNode|null} + * An Identifier node if the variable should change to const. + * Otherwise, null. + */ +function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) { + if (variable.eslintUsed && variable.scope.type === "global") { + return null; + } + + // Finds the unique WriteReference. + let writer = null; + let isReadBeforeInit = false; + const references = variable.references; + + for (let i = 0; i < references.length; ++i) { + const reference = references[i]; + + if (reference.isWrite()) { + const isReassigned = + writer !== null && writer.identifier !== reference.identifier; + + if (isReassigned) { + return null; + } + + const destructuringHost = getDestructuringHost(reference); + + if ( + destructuringHost !== null && + destructuringHost.left !== void 0 + ) { + const leftNode = destructuringHost.left; + let hasOuterVariables = false, + hasNonIdentifiers = false; + + if (leftNode.type === "ObjectPattern") { + const properties = leftNode.properties; + + hasOuterVariables = properties + .filter(prop => prop.value) + .map(prop => prop.value.name) + .some(name => + isOuterVariableInDestructing(name, variable.scope), + ); + + hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); + } else if (leftNode.type === "ArrayPattern") { + const elements = leftNode.elements; + + hasOuterVariables = elements + .map(element => element && element.name) + .some(name => + isOuterVariableInDestructing(name, variable.scope), + ); + + hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); + } + + if (hasOuterVariables || hasNonIdentifiers) { + return null; + } + } + + writer = reference; + } else if (reference.isRead() && writer === null) { + if (ignoreReadBeforeAssign) { + return null; + } + isReadBeforeInit = true; + } + } + + /* + * If the assignment is from a different scope, ignore it. + * If the assignment cannot change to a declaration, ignore it. + */ + const shouldBeConst = + writer !== null && + writer.from === variable.scope && + canBecomeVariableDeclaration(writer.identifier); + + if (!shouldBeConst) { + return null; + } + + if (isReadBeforeInit) { + return variable.defs[0].name; + } + + return writer.identifier; +} + +/** + * Groups by the VariableDeclarator/AssignmentExpression node that each + * reference of given variables belongs to. + * This is used to detect a mix of reassigned and never reassigned in a + * destructuring. + * @param {Variable[]} variables Variables to group by destructuring. + * @param {boolean} ignoreReadBeforeAssign + * The value of `ignoreReadBeforeAssign` option. + * @returns {Map} Grouped identifier nodes. + */ +function groupByDestructuring(variables, ignoreReadBeforeAssign) { + const identifierMap = new Map(); + + for (let i = 0; i < variables.length; ++i) { + const variable = variables[i]; + const references = variable.references; + const identifier = getIdentifierIfShouldBeConst( + variable, + ignoreReadBeforeAssign, + ); + let prevId = null; + + for (let j = 0; j < references.length; ++j) { + const reference = references[j]; + const id = reference.identifier; + + /* + * Avoid counting a reference twice or more for default values of + * destructuring. + */ + if (id === prevId) { + continue; + } + prevId = id; + + // Add the identifier node into the destructuring group. + const group = getDestructuringHost(reference); + + if (group) { + if (identifierMap.has(group)) { + identifierMap.get(group).push(identifier); + } else { + identifierMap.set(group, [identifier]); + } + } + } + } + + return identifierMap; +} + +/** + * Finds the nearest parent of node with a given type. + * @param {ASTNode} node The node to search from. + * @param {string} type The type field of the parent node. + * @param {Function} shouldStop A predicate that returns true if the traversal should stop, and false otherwise. + * @returns {ASTNode} The closest ancestor with the specified type; null if no such ancestor exists. + */ +function findUp(node, type, shouldStop) { + if (!node || shouldStop(node)) { + return null; + } + if (node.type === type) { + return node; + } + return findUp(node.parent, type, shouldStop); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + destructuring: "any", + ignoreReadBeforeAssign: false, + }, + ], + + docs: { + description: + "Require `const` declarations for variables that are never reassigned after declared", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-const", + }, + + fixable: "code", + + schema: [ + { + type: "object", + properties: { + destructuring: { enum: ["any", "all"] }, + ignoreReadBeforeAssign: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + messages: { + useConst: "'{{name}}' is never reassigned. Use 'const' instead.", + }, + }, + + create(context) { + const [{ destructuring, ignoreReadBeforeAssign }] = context.options; + const shouldMatchAnyDestructuredVariable = destructuring !== "all"; + const sourceCode = context.sourceCode; + const variables = []; + let reportCount = 0; + let checkedId = null; + let checkedName = ""; + + /** + * Reports given identifier nodes if all of the nodes should be declared + * as const. + * + * The argument 'nodes' is an array of Identifier nodes. + * This node is the result of 'getIdentifierIfShouldBeConst()', so it's + * nullable. In simple declaration or assignment cases, the length of + * the array is 1. In destructuring cases, the length of the array can + * be 2 or more. + * @param {(Reference|null)[]} nodes + * References which are grouped by destructuring to report. + * @returns {void} + */ + function checkGroup(nodes) { + const nodesToReport = nodes.filter(Boolean); + + if ( + nodes.length && + (shouldMatchAnyDestructuredVariable || + nodesToReport.length === nodes.length) + ) { + const varDeclParent = findUp( + nodes[0], + "VariableDeclaration", + parentNode => parentNode.type.endsWith("Statement"), + ); + const isVarDecParentNull = varDeclParent === null; + + if ( + !isVarDecParentNull && + varDeclParent.declarations.length > 0 + ) { + const firstDeclaration = varDeclParent.declarations[0]; + + if (firstDeclaration.init) { + const firstDecParent = firstDeclaration.init.parent; + + /* + * First we check the declaration type and then depending on + * if the type is a "VariableDeclarator" or its an "ObjectPattern" + * we compare the name and id from the first identifier, if the names are different + * we assign the new name, id and reset the count of reportCount and nodeCount in + * order to check each block for the number of reported errors and base our fix + * based on comparing nodes.length and nodesToReport.length. + */ + + if (firstDecParent.type === "VariableDeclarator") { + if (firstDecParent.id.name !== checkedName) { + checkedName = firstDecParent.id.name; + reportCount = 0; + } + + if (firstDecParent.id.type === "ObjectPattern") { + if (firstDecParent.init.name !== checkedName) { + checkedName = firstDecParent.init.name; + reportCount = 0; + } + } + + if (firstDecParent.id !== checkedId) { + checkedId = firstDecParent.id; + reportCount = 0; + } + } + } + } + + let shouldFix = + varDeclParent && + // Don't do a fix unless all variables in the declarations are initialized (or it's in a for-in or for-of loop) + (varDeclParent.parent.type === "ForInStatement" || + varDeclParent.parent.type === "ForOfStatement" || + varDeclParent.declarations.every( + declaration => declaration.init, + )) && + /* + * If options.destructuring is "all", then this warning will not occur unless + * every assignment in the destructuring should be const. In that case, it's safe + * to apply the fix. + */ + nodesToReport.length === nodes.length; + + if ( + !isVarDecParentNull && + varDeclParent.declarations && + varDeclParent.declarations.length !== 1 + ) { + if ( + varDeclParent && + varDeclParent.declarations && + varDeclParent.declarations.length >= 1 + ) { + /* + * Add nodesToReport.length to a count, then comparing the count to the length + * of the declarations in the current block. + */ + + reportCount += nodesToReport.length; + + let totalDeclarationsCount = 0; + + varDeclParent.declarations.forEach(declaration => { + if (declaration.id.type === "ObjectPattern") { + totalDeclarationsCount += + declaration.id.properties.length; + } else if (declaration.id.type === "ArrayPattern") { + totalDeclarationsCount += + declaration.id.elements.length; + } else { + totalDeclarationsCount += 1; + } + }); + + shouldFix = + shouldFix && reportCount === totalDeclarationsCount; + } + } + + nodesToReport.forEach(node => { + context.report({ + node, + messageId: "useConst", + data: node, + fix: shouldFix + ? fixer => { + const letKeywordToken = + sourceCode.getFirstToken( + varDeclParent, + t => t.value === varDeclParent.kind, + ); + + /** + * Extend the replacement range to the whole declaration, + * in order to prevent other fixes in the same pass + * https://github.com/eslint/eslint/issues/13899 + */ + return new FixTracker(fixer, sourceCode) + .retainRange(varDeclParent.range) + .replaceTextRange( + letKeywordToken.range, + "const", + ); + } + : null, + }); + }); + } + } + + return { + "Program:exit"() { + groupByDestructuring(variables, ignoreReadBeforeAssign).forEach( + checkGroup, + ); + }, + + VariableDeclaration(node) { + if (node.kind === "let" && !isInitOfForStatement(node)) { + variables.push(...sourceCode.getDeclaredVariables(node)); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-destructuring.js b/node_modules/eslint/lib/rules/prefer-destructuring.js new file mode 100644 index 0000000000000000000000000000000000000000..09d0e5be3ad59de6f9c17ff3b537aa964ce0d9bb --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-destructuring.js @@ -0,0 +1,332 @@ +/** + * @fileoverview Prefer destructuring from arrays and objects + * @author Alex LaFroscia + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const PRECEDENCE_OF_ASSIGNMENT_EXPR = astUtils.getPrecedence({ + type: "AssignmentExpression", +}); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require destructuring from arrays and/or objects", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/prefer-destructuring", + }, + + fixable: "code", + + schema: [ + { + /* + * old support {array: Boolean, object: Boolean} + * new support {VariableDeclarator: {}, AssignmentExpression: {}} + */ + oneOf: [ + { + type: "object", + properties: { + VariableDeclarator: { + type: "object", + properties: { + array: { + type: "boolean", + }, + object: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + AssignmentExpression: { + type: "object", + properties: { + array: { + type: "boolean", + }, + object: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + array: { + type: "boolean", + }, + object: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + { + type: "object", + properties: { + enforceForRenamedProperties: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + preferDestructuring: "Use {{type}} destructuring.", + }, + }, + create(context) { + const enabledTypes = context.options[0]; + const enforceForRenamedProperties = + context.options[1] && + context.options[1].enforceForRenamedProperties; + let normalizedOptions = { + VariableDeclarator: { array: true, object: true }, + AssignmentExpression: { array: true, object: true }, + }; + + if (enabledTypes) { + normalizedOptions = + typeof enabledTypes.array !== "undefined" || + typeof enabledTypes.object !== "undefined" + ? { + VariableDeclarator: enabledTypes, + AssignmentExpression: enabledTypes, + } + : enabledTypes; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks if destructuring type should be checked. + * @param {string} nodeType "AssignmentExpression" or "VariableDeclarator" + * @param {string} destructuringType "array" or "object" + * @returns {boolean} `true` if the destructuring type should be checked for the given node + */ + function shouldCheck(nodeType, destructuringType) { + return ( + normalizedOptions && + normalizedOptions[nodeType] && + normalizedOptions[nodeType][destructuringType] + ); + } + + /** + * Determines if the given node is accessing an array index + * + * This is used to differentiate array index access from object property + * access. + * @param {ASTNode} node the node to evaluate + * @returns {boolean} whether or not the node is an integer + */ + function isArrayIndexAccess(node) { + return Number.isInteger(node.property.value); + } + + /** + * Report that the given node should use destructuring + * @param {ASTNode} reportNode the node to report + * @param {string} type the type of destructuring that should have been done + * @param {Function|null} fix the fix function or null to pass to context.report + * @returns {void} + */ + function report(reportNode, type, fix) { + context.report({ + node: reportNode, + messageId: "preferDestructuring", + data: { type }, + fix, + }); + } + + /** + * Determines if a node should be fixed into object destructuring + * + * The fixer only fixes the simplest case of object destructuring, + * like: `let x = a.x`; + * + * Assignment expression is not fixed. + * Array destructuring is not fixed. + * Renamed property is not fixed. + * @param {ASTNode} node the node to evaluate + * @returns {boolean} whether or not the node should be fixed + */ + function shouldFix(node) { + return ( + node.type === "VariableDeclarator" && + node.id.type === "Identifier" && + node.init.type === "MemberExpression" && + !node.init.computed && + node.init.property.type === "Identifier" && + node.id.name === node.init.property.name + ); + } + + /** + * Fix a node into object destructuring. + * This function only handles the simplest case of object destructuring, + * see {@link shouldFix}. + * @param {SourceCodeFixer} fixer the fixer object + * @param {ASTNode} node the node to be fixed. + * @returns {Object} a fix for the node + */ + function fixIntoObjectDestructuring(fixer, node) { + const rightNode = node.init; + const sourceCode = context.sourceCode; + + // Don't fix if that would remove any comments. Only comments inside `rightNode.object` can be preserved. + if ( + sourceCode.getCommentsInside(node).length > + sourceCode.getCommentsInside(rightNode.object).length + ) { + return null; + } + + let objectText = sourceCode.getText(rightNode.object); + + if ( + astUtils.getPrecedence(rightNode.object) < + PRECEDENCE_OF_ASSIGNMENT_EXPR + ) { + objectText = `(${objectText})`; + } + + return fixer.replaceText( + node, + `{${rightNode.property.name}} = ${objectText}`, + ); + } + + /** + * Check that the `prefer-destructuring` rules are followed based on the + * given left- and right-hand side of the assignment. + * + * Pulled out into a separate method so that VariableDeclarators and + * AssignmentExpressions can share the same verification logic. + * @param {ASTNode} leftNode the left-hand side of the assignment + * @param {ASTNode} rightNode the right-hand side of the assignment + * @param {ASTNode} reportNode the node to report the error on + * @returns {void} + */ + function performCheck(leftNode, rightNode, reportNode) { + if ( + rightNode.type !== "MemberExpression" || + rightNode.object.type === "Super" || + rightNode.property.type === "PrivateIdentifier" + ) { + return; + } + + if (isArrayIndexAccess(rightNode)) { + if (shouldCheck(reportNode.type, "array")) { + report(reportNode, "array", null); + } + return; + } + + const fix = shouldFix(reportNode) + ? fixer => fixIntoObjectDestructuring(fixer, reportNode) + : null; + + if ( + shouldCheck(reportNode.type, "object") && + enforceForRenamedProperties + ) { + report(reportNode, "object", fix); + return; + } + + if (shouldCheck(reportNode.type, "object")) { + const property = rightNode.property; + + if ( + (property.type === "Literal" && + leftNode.name === property.value) || + (property.type === "Identifier" && + leftNode.name === property.name && + !rightNode.computed) + ) { + report(reportNode, "object", fix); + } + } + } + + /** + * Check if a given variable declarator is coming from an property access + * that should be using destructuring instead + * @param {ASTNode} node the variable declarator to check + * @returns {void} + */ + function checkVariableDeclarator(node) { + // Skip if variable is declared without assignment + if (!node.init) { + return; + } + + // Variable declarations using explicit resource management cannot use destructuring (parse error) + if ( + node.parent.kind === "using" || + node.parent.kind === "await using" + ) { + return; + } + + // We only care about member expressions past this point + if (node.init.type !== "MemberExpression") { + return; + } + + performCheck(node.id, node.init, node); + } + + /** + * Run the `prefer-destructuring` check on an AssignmentExpression + * @param {ASTNode} node the AssignmentExpression node + * @returns {void} + */ + function checkAssignmentExpression(node) { + if (node.operator === "=") { + performCheck(node.left, node.right, node); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclarator: checkVariableDeclarator, + AssignmentExpression: checkAssignmentExpression, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js b/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js new file mode 100644 index 0000000000000000000000000000000000000000..beb78438b59888ff954d825998f83c341ea52f42 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js @@ -0,0 +1,235 @@ +/** + * @fileoverview Rule to disallow Math.pow in favor of the ** operator + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { CALL, ReferenceTracker } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const PRECEDENCE_OF_EXPONENTIATION_EXPR = astUtils.getPrecedence({ + type: "BinaryExpression", + operator: "**", +}); + +/** + * Determines whether the given node needs parens if used as the base in an exponentiation binary expression. + * @param {ASTNode} base The node to check. + * @returns {boolean} `true` if the node needs to be parenthesised. + */ +function doesBaseNeedParens(base) { + return ( + // '**' is right-associative, parens are needed when Math.pow(a ** b, c) is converted to (a ** b) ** c + astUtils.getPrecedence(base) <= PRECEDENCE_OF_EXPONENTIATION_EXPR || + // An unary operator cannot be used immediately before an exponentiation expression + base.type === "AwaitExpression" || + base.type === "UnaryExpression" + ); +} + +/** + * Determines whether the given node needs parens if used as the exponent in an exponentiation binary expression. + * @param {ASTNode} exponent The node to check. + * @returns {boolean} `true` if the node needs to be parenthesised. + */ +function doesExponentNeedParens(exponent) { + // '**' is right-associative, there is no need for parens when Math.pow(a, b ** c) is converted to a ** b ** c + return astUtils.getPrecedence(exponent) < PRECEDENCE_OF_EXPONENTIATION_EXPR; +} + +/** + * Determines whether an exponentiation binary expression at the place of the given node would need parens. + * @param {ASTNode} node A node that would be replaced by an exponentiation binary expression. + * @param {SourceCode} sourceCode A SourceCode object. + * @returns {boolean} `true` if the expression needs to be parenthesised. + */ +function doesExponentiationExpressionNeedParens(node, sourceCode) { + const parent = + node.parent.type === "ChainExpression" + ? node.parent.parent + : node.parent; + + const parentPrecedence = astUtils.getPrecedence(parent); + const needsParens = + parent.type === "ClassDeclaration" || + (parent.type.endsWith("Expression") && + (parentPrecedence === -1 || + parentPrecedence >= PRECEDENCE_OF_EXPONENTIATION_EXPR) && + !( + parent.type === "BinaryExpression" && + parent.operator === "**" && + parent.right === node + ) && + !( + (parent.type === "CallExpression" || + parent.type === "NewExpression") && + parent.arguments.includes(node) + ) && + !( + parent.type === "MemberExpression" && + parent.computed && + parent.property === node + ) && + !(parent.type === "ArrayExpression")); + + return needsParens && !astUtils.isParenthesised(sourceCode, node); +} + +/** + * Optionally parenthesizes given text. + * @param {string} text The text to parenthesize. + * @param {boolean} shouldParenthesize If `true`, the text will be parenthesised. + * @returns {string} parenthesised or unchanged text. + */ +function parenthesizeIfShould(text, shouldParenthesize) { + return shouldParenthesize ? `(${text})` : text; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow the use of `Math.pow` in favor of the `**` operator", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/prefer-exponentiation-operator", + }, + + schema: [], + fixable: "code", + + messages: { + useExponentiation: "Use the '**' operator instead of 'Math.pow'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Reports the given node. + * @param {ASTNode} node 'Math.pow()' node to report. + * @returns {void} + */ + function report(node) { + context.report({ + node, + messageId: "useExponentiation", + fix(fixer) { + if ( + node.arguments.length !== 2 || + node.arguments.some( + arg => arg.type === "SpreadElement", + ) || + sourceCode.getCommentsInside(node).length > 0 + ) { + return null; + } + + const base = node.arguments[0], + exponent = node.arguments[1], + baseText = sourceCode.getText(base), + exponentText = sourceCode.getText(exponent), + shouldParenthesizeBase = doesBaseNeedParens(base), + shouldParenthesizeExponent = + doesExponentNeedParens(exponent), + shouldParenthesizeAll = + doesExponentiationExpressionNeedParens( + node, + sourceCode, + ); + + let prefix = "", + suffix = ""; + + if (!shouldParenthesizeAll) { + if (!shouldParenthesizeBase) { + const firstReplacementToken = + sourceCode.getFirstToken(base), + tokenBefore = sourceCode.getTokenBefore(node); + + if ( + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBefore, + firstReplacementToken, + ) + ) { + prefix = " "; // a+Math.pow(++b, c) -> a+ ++b**c + } + } + if (!shouldParenthesizeExponent) { + const lastReplacementToken = + sourceCode.getLastToken(exponent), + tokenAfter = sourceCode.getTokenAfter(node); + + if ( + tokenAfter && + node.range[1] === tokenAfter.range[0] && + !astUtils.canTokensBeAdjacent( + lastReplacementToken, + tokenAfter, + ) + ) { + suffix = " "; // Math.pow(a, b)in c -> a**b in c + } + } + } + + const baseReplacement = parenthesizeIfShould( + baseText, + shouldParenthesizeBase, + ), + exponentReplacement = parenthesizeIfShould( + exponentText, + shouldParenthesizeExponent, + ), + replacement = parenthesizeIfShould( + `${baseReplacement}**${exponentReplacement}`, + shouldParenthesizeAll, + ); + + return fixer.replaceText( + node, + `${prefix}${replacement}${suffix}`, + ); + }, + }); + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const trackMap = { + Math: { + pow: { [CALL]: true }, + }, + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences( + trackMap, + )) { + report(refNode); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-named-capture-group.js b/node_modules/eslint/lib/rules/prefer-named-capture-group.js new file mode 100644 index 0000000000000000000000000000000000000000..d5c1f46028e277310e67eddb929a340651b0f8da --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-named-capture-group.js @@ -0,0 +1,197 @@ +/** + * @fileoverview Rule to enforce requiring named capture groups in regular expression. + * @author Pig Fang + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + CALL, + CONSTRUCT, + ReferenceTracker, + getStringIfConstant, +} = require("@eslint-community/eslint-utils"); +const regexpp = require("@eslint-community/regexpp"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @import { SuggestedEdit } from "@eslint/core"; */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const parser = new regexpp.RegExpParser(); + +/** + * Creates fixer suggestions for the regex, if statically determinable. + * @param {number} groupStart Starting index of the regex group. + * @param {string} pattern The regular expression pattern to be checked. + * @param {string} rawText Source text of the regexNode. + * @param {ASTNode} regexNode AST node which contains the regular expression. + * @returns {Array} Fixer suggestions for the regex, if statically determinable. + */ +function suggestIfPossible(groupStart, pattern, rawText, regexNode) { + switch (regexNode.type) { + case "Literal": + if (typeof regexNode.value === "string" && rawText.includes("\\")) { + return null; + } + break; + case "TemplateLiteral": + if ( + regexNode.expressions.length || + rawText.slice(1, -1) !== pattern + ) { + return null; + } + break; + default: + return null; + } + + const start = regexNode.range[0] + groupStart + 2; + + return [ + { + fix(fixer) { + const existingTemps = pattern.match(/temp\d+/gu) || []; + const highestTempCount = existingTemps.reduce( + (previous, next) => + Math.max(previous, Number(next.slice("temp".length))), + 0, + ); + + return fixer.insertTextBeforeRange( + [start, start], + `?`, + ); + }, + messageId: "addGroupName", + }, + { + fix(fixer) { + return fixer.insertTextBeforeRange([start, start], "?:"); + }, + messageId: "addNonCapture", + }, + ]; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce using named capture group in regular expression", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-named-capture-group", + }, + + hasSuggestions: true, + + schema: [], + + messages: { + addGroupName: "Add name to capture group.", + addNonCapture: "Convert group to non-capturing.", + required: + "Capture group '{{group}}' should be converted to a named or non-capturing group.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Function to check regular expression. + * @param {string} pattern The regular expression pattern to be checked. + * @param {ASTNode} node AST node which contains the regular expression or a call/new expression. + * @param {ASTNode} regexNode AST node which contains the regular expression. + * @param {string|null} flags The regular expression flags to be checked. + * @returns {void} + */ + function checkRegex(pattern, node, regexNode, flags) { + let ast; + + try { + ast = parser.parsePattern(pattern, 0, pattern.length, { + unicode: Boolean(flags && flags.includes("u")), + unicodeSets: Boolean(flags && flags.includes("v")), + }); + } catch { + // ignore regex syntax errors + return; + } + + regexpp.visitRegExpAST(ast, { + onCapturingGroupEnter(group) { + if (!group.name) { + const rawText = sourceCode.getText(regexNode); + const suggest = suggestIfPossible( + group.start, + pattern, + rawText, + regexNode, + ); + + context.report({ + node, + messageId: "required", + data: { + group: group.raw, + }, + suggest, + }); + } + }, + }); + } + + return { + Literal(node) { + if (node.regex) { + checkRegex( + node.regex.pattern, + node, + node, + node.regex.flags, + ); + } + }, + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const traceMap = { + RegExp: { + [CALL]: true, + [CONSTRUCT]: true, + }, + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences( + traceMap, + )) { + const regex = getStringIfConstant(refNode.arguments[0]); + const flags = getStringIfConstant(refNode.arguments[1]); + + if (regex) { + checkRegex(regex, refNode, refNode.arguments[0], flags); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-numeric-literals.js b/node_modules/eslint/lib/rules/prefer-numeric-literals.js new file mode 100644 index 0000000000000000000000000000000000000000..86dec88797807b95f580ca079b28934c0a3f85db --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-numeric-literals.js @@ -0,0 +1,157 @@ +/** + * @fileoverview Rule to disallow `parseInt()` in favor of binary, octal, and hexadecimal literals + * @author Annie Zhang, Henry Zhu + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const radixMap = new Map([ + [2, { system: "binary", literalPrefix: "0b" }], + [8, { system: "octal", literalPrefix: "0o" }], + [16, { system: "hexadecimal", literalPrefix: "0x" }], +]); + +/** + * Checks to see if a CallExpression's callee node is `parseInt` or + * `Number.parseInt`. + * @param {ASTNode} calleeNode The callee node to evaluate. + * @returns {boolean} True if the callee is `parseInt` or `Number.parseInt`, + * false otherwise. + */ +function isParseInt(calleeNode) { + return ( + astUtils.isSpecificId(calleeNode, "parseInt") || + astUtils.isSpecificMemberAccess(calleeNode, "Number", "parseInt") + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/prefer-numeric-literals", + }, + + schema: [], + + messages: { + useLiteral: + "Use {{system}} literals instead of {{functionName}}().", + }, + + fixable: "code", + }, + + create(context) { + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + "CallExpression[arguments.length=2]"(node) { + const [strNode, radixNode] = node.arguments, + str = astUtils.getStaticStringValue(strNode), + radix = radixNode.value; + + if ( + str !== null && + astUtils.isStringLiteral(strNode) && + radixNode.type === "Literal" && + typeof radix === "number" && + radixMap.has(radix) && + isParseInt(node.callee) + ) { + const { system, literalPrefix } = radixMap.get(radix); + + context.report({ + node, + messageId: "useLiteral", + data: { + system, + functionName: sourceCode.getText(node.callee), + }, + fix(fixer) { + if (sourceCode.getCommentsInside(node).length) { + return null; + } + + const replacement = `${literalPrefix}${str}`; + + if (+replacement !== parseInt(str, radix)) { + /* + * If the newly-produced literal would be invalid, (e.g. 0b1234), + * or it would yield an incorrect parseInt result for some other reason, don't make a fix. + * + * If `str` had numeric separators, `+replacement` will evaluate to `NaN` because unary `+` + * per the specification doesn't support numeric separators. Thus, the above condition will be `true` + * (`NaN !== anything` is always `true`) regardless of the `parseInt(str, radix)` value. + * Consequently, no autofixes will be made. This is correct behavior because `parseInt` also + * doesn't support numeric separators, but it does parse part of the string before the first `_`, + * so the autofix would be invalid: + * + * parseInt("1_1", 2) // === 1 + * 0b1_1 // === 3 + */ + return null; + } + + const tokenBefore = sourceCode.getTokenBefore(node), + tokenAfter = sourceCode.getTokenAfter(node); + let prefix = "", + suffix = ""; + + if ( + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBefore, + replacement, + ) + ) { + prefix = " "; + } + + if ( + tokenAfter && + node.range[1] === tokenAfter.range[0] && + !astUtils.canTokensBeAdjacent( + replacement, + tokenAfter, + ) + ) { + suffix = " "; + } + + return fixer.replaceText( + node, + `${prefix}${replacement}${suffix}`, + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-object-has-own.js b/node_modules/eslint/lib/rules/prefer-object-has-own.js new file mode 100644 index 0000000000000000000000000000000000000000..3e0bb5209c588c53566df6c0fe3ca9e012c448f6 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-object-has-own.js @@ -0,0 +1,148 @@ +/** + * @fileoverview Prefers Object.hasOwn() instead of Object.prototype.hasOwnProperty.call() + * @author Nitin Kumar + * @author Gautam Arora + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks if the given node is considered to be an access to a property of `Object.prototype`. + * @param {ASTNode} node `MemberExpression` node to evaluate. + * @returns {boolean} `true` if `node.object` is `Object`, `Object.prototype`, or `{}` (empty 'ObjectExpression' node). + */ +function hasLeftHandObject(node) { + /* + * ({}).hasOwnProperty.call(obj, prop) - `true` + * ({ foo }.hasOwnProperty.call(obj, prop)) - `false`, object literal should be empty + */ + if ( + node.object.type === "ObjectExpression" && + node.object.properties.length === 0 + ) { + return true; + } + + const objectNodeToCheck = + node.object.type === "MemberExpression" && + astUtils.getStaticPropertyName(node.object) === "prototype" + ? node.object.object + : node.object; + + if ( + objectNodeToCheck.type === "Identifier" && + objectNodeToCheck.name === "Object" + ) { + return true; + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + docs: { + description: + "Disallow use of `Object.prototype.hasOwnProperty.call()` and prefer use of `Object.hasOwn()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-object-has-own", + }, + schema: [], + messages: { + useHasOwn: + "Use 'Object.hasOwn()' instead of 'Object.prototype.hasOwnProperty.call()'.", + }, + fixable: "code", + }, + create(context) { + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + if ( + !( + node.callee.type === "MemberExpression" && + node.callee.object.type === "MemberExpression" + ) + ) { + return; + } + + const calleePropertyName = astUtils.getStaticPropertyName( + node.callee, + ); + const objectPropertyName = astUtils.getStaticPropertyName( + node.callee.object, + ); + const isObject = hasLeftHandObject(node.callee.object); + + // check `Object` scope + const scope = sourceCode.getScope(node); + const variable = astUtils.getVariableByName(scope, "Object"); + + if ( + calleePropertyName === "call" && + objectPropertyName === "hasOwnProperty" && + isObject && + variable && + variable.scope.type === "global" + ) { + context.report({ + node, + messageId: "useHasOwn", + fix(fixer) { + if ( + sourceCode.getCommentsInside(node.callee) + .length > 0 + ) { + return null; + } + + const tokenJustBeforeNode = + sourceCode.getTokenBefore(node.callee, { + includeComments: true, + }); + + // for https://github.com/eslint/eslint/pull/15346#issuecomment-991417335 + if ( + tokenJustBeforeNode && + tokenJustBeforeNode.range[1] === + node.callee.range[0] && + !astUtils.canTokensBeAdjacent( + tokenJustBeforeNode, + "Object.hasOwn", + ) + ) { + return fixer.replaceText( + node.callee, + " Object.hasOwn", + ); + } + + return fixer.replaceText( + node.callee, + "Object.hasOwn", + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-object-spread.js b/node_modules/eslint/lib/rules/prefer-object-spread.js new file mode 100644 index 0000000000000000000000000000000000000000..6827e2c25dc02b261d75188563d3cff68e9e3128 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-object-spread.js @@ -0,0 +1,319 @@ +/** + * @fileoverview Rule to disallow using `Object.assign` with an object literal as the first argument and prefer the use of object spread instead + * @author Sharmila Jesupaul + */ + +"use strict"; + +const { CALL, ReferenceTracker } = require("@eslint-community/eslint-utils"); +const { + isCommaToken, + isOpeningParenToken, + isClosingParenToken, + isParenthesised, +} = require("./utils/ast-utils"); + +const ANY_SPACE = /\s/u; + +/** + * Helper that checks if the Object.assign call has array spread + * @param {ASTNode} node The node that the rule warns on + * @returns {boolean} - Returns true if the Object.assign call has array spread + */ +function hasArraySpread(node) { + return node.arguments.some(arg => arg.type === "SpreadElement"); +} + +/** + * Determines whether the given node is an accessor property (getter/setter). + * @param {ASTNode} node Node to check. + * @returns {boolean} `true` if the node is a getter or a setter. + */ +function isAccessorProperty(node) { + return ( + node.type === "Property" && (node.kind === "get" || node.kind === "set") + ); +} + +/** + * Determines whether the given object expression node has accessor properties (getters/setters). + * @param {ASTNode} node `ObjectExpression` node to check. + * @returns {boolean} `true` if the node has at least one getter/setter. + */ +function hasAccessors(node) { + return node.properties.some(isAccessorProperty); +} + +/** + * Determines whether the given call expression node has object expression arguments with accessor properties (getters/setters). + * @param {ASTNode} node `CallExpression` node to check. + * @returns {boolean} `true` if the node has at least one argument that is an object expression with at least one getter/setter. + */ +function hasArgumentsWithAccessors(node) { + return node.arguments + .filter(arg => arg.type === "ObjectExpression") + .some(hasAccessors); +} + +/** + * Helper that checks if the node needs parentheses to be valid JS. + * The default is to wrap the node in parentheses to avoid parsing errors. + * @param {ASTNode} node The node that the rule warns on + * @param {Object} sourceCode in context sourcecode object + * @returns {boolean} - Returns true if the node needs parentheses + */ +function needsParens(node, sourceCode) { + const parent = node.parent; + + switch (parent.type) { + case "VariableDeclarator": + case "ArrayExpression": + case "ReturnStatement": + case "CallExpression": + case "Property": + return false; + case "AssignmentExpression": + return parent.left === node && !isParenthesised(sourceCode, node); + default: + return !isParenthesised(sourceCode, node); + } +} + +/** + * Determines if an argument needs parentheses. The default is to not add parens. + * @param {ASTNode} node The node to be checked. + * @param {Object} sourceCode in context sourcecode object + * @returns {boolean} True if the node needs parentheses + */ +function argNeedsParens(node, sourceCode) { + switch (node.type) { + case "AssignmentExpression": + case "ArrowFunctionExpression": + case "ConditionalExpression": + return !isParenthesised(sourceCode, node); + default: + return false; + } +} + +/** + * Get the parenthesis tokens of a given ObjectExpression node. + * This includes the braces of the object literal and enclosing parentheses. + * @param {ASTNode} node The node to get. + * @param {Token} leftArgumentListParen The opening paren token of the argument list. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {Token[]} The parenthesis tokens of the node. This is sorted by the location. + */ +function getParenTokens(node, leftArgumentListParen, sourceCode) { + const parens = [ + sourceCode.getFirstToken(node), + sourceCode.getLastToken(node), + ]; + let leftNext = sourceCode.getTokenBefore(node); + let rightNext = sourceCode.getTokenAfter(node); + + // Note: don't include the parens of the argument list. + while ( + leftNext && + rightNext && + leftNext.range[0] > leftArgumentListParen.range[0] && + isOpeningParenToken(leftNext) && + isClosingParenToken(rightNext) + ) { + parens.push(leftNext, rightNext); + leftNext = sourceCode.getTokenBefore(leftNext); + rightNext = sourceCode.getTokenAfter(rightNext); + } + + return parens.sort((a, b) => a.range[0] - b.range[0]); +} + +/** + * Get the range of a given token and around whitespaces. + * @param {Token} token The token to get range. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {number} The end of the range of the token and around whitespaces. + */ +function getStartWithSpaces(token, sourceCode) { + const text = sourceCode.text; + let start = token.range[0]; + + // If the previous token is a line comment then skip this step to avoid commenting this token out. + { + const prevToken = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + + if (prevToken && prevToken.type === "Line") { + return start; + } + } + + // Detect spaces before the token. + while (ANY_SPACE.test(text[start - 1] || "")) { + start -= 1; + } + + return start; +} + +/** + * Get the range of a given token and around whitespaces. + * @param {Token} token The token to get range. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {number} The start of the range of the token and around whitespaces. + */ +function getEndWithSpaces(token, sourceCode) { + const text = sourceCode.text; + let end = token.range[1]; + + // Detect spaces after the token. + while (ANY_SPACE.test(text[end] || "")) { + end += 1; + } + + return end; +} + +/** + * Autofixes the Object.assign call to use an object spread instead. + * @param {ASTNode|null} node The node that the rule warns on, i.e. the Object.assign call + * @param {string} sourceCode sourceCode of the Object.assign call + * @returns {Function} autofixer - replaces the Object.assign with a spread object. + */ +function defineFixer(node, sourceCode) { + return function* (fixer) { + const leftParen = sourceCode.getTokenAfter( + node.callee, + isOpeningParenToken, + ); + const rightParen = sourceCode.getLastToken(node); + + // Remove everything before the opening paren: callee `Object.assign`, type arguments, and whitespace between the callee and the paren. + yield fixer.removeRange([node.range[0], leftParen.range[0]]); + + // Replace the parens of argument list to braces. + if (needsParens(node, sourceCode)) { + yield fixer.replaceText(leftParen, "({"); + yield fixer.replaceText(rightParen, "})"); + } else { + yield fixer.replaceText(leftParen, "{"); + yield fixer.replaceText(rightParen, "}"); + } + + // Process arguments. + for (const argNode of node.arguments) { + const innerParens = getParenTokens(argNode, leftParen, sourceCode); + const left = innerParens.shift(); + const right = innerParens.pop(); + + if (argNode.type === "ObjectExpression") { + const maybeTrailingComma = sourceCode.getLastToken(argNode, 1); + const maybeArgumentComma = sourceCode.getTokenAfter(right); + + /* + * Make bare this object literal. + * And remove spaces inside of the braces for better formatting. + */ + for (const innerParen of innerParens) { + yield fixer.remove(innerParen); + } + const leftRange = [ + left.range[0], + getEndWithSpaces(left, sourceCode), + ]; + const rightRange = [ + Math.max( + getStartWithSpaces(right, sourceCode), + leftRange[1], + ), // Ensure ranges don't overlap + right.range[1], + ]; + + yield fixer.removeRange(leftRange); + yield fixer.removeRange(rightRange); + + // Remove the comma of this argument if it's duplication. + if ( + (argNode.properties.length === 0 || + isCommaToken(maybeTrailingComma)) && + isCommaToken(maybeArgumentComma) + ) { + yield fixer.remove(maybeArgumentComma); + } + } else { + // Make spread. + if (argNeedsParens(argNode, sourceCode)) { + yield fixer.insertTextBefore(left, "...("); + yield fixer.insertTextAfter(right, ")"); + } else { + yield fixer.insertTextBefore(left, "..."); + } + } + } + }; +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow using `Object.assign` with an object literal as the first argument and prefer the use of object spread instead", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/prefer-object-spread", + }, + + schema: [], + fixable: "code", + + messages: { + useSpreadMessage: + "Use an object spread instead of `Object.assign` eg: `{ ...foo }`.", + useLiteralMessage: + "Use an object literal instead of `Object.assign`. eg: `{ foo: bar }`.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const trackMap = { + Object: { + assign: { [CALL]: true }, + }, + }; + + // Iterate all calls of `Object.assign` (only of the global variable `Object`). + for (const { node: refNode } of tracker.iterateGlobalReferences( + trackMap, + )) { + if ( + refNode.arguments.length >= 1 && + refNode.arguments[0].type === "ObjectExpression" && + !hasArraySpread(refNode) && + !( + refNode.arguments.length > 1 && + hasArgumentsWithAccessors(refNode) + ) + ) { + const messageId = + refNode.arguments.length === 1 + ? "useLiteralMessage" + : "useSpreadMessage"; + const fix = defineFixer(refNode, sourceCode); + + context.report({ node: refNode, messageId, fix }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js b/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js new file mode 100644 index 0000000000000000000000000000000000000000..7043f296d386ed410d5018d83c3188c9dd11640f --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js @@ -0,0 +1,154 @@ +/** + * @fileoverview restrict values that can be used as Promise rejection reasons + * @author Teddy Katz + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowEmptyReject: false, + }, + ], + + docs: { + description: + "Require using Error objects as Promise rejection reasons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-promise-reject-errors", + }, + + fixable: null, + + schema: [ + { + type: "object", + properties: { + allowEmptyReject: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + + messages: { + rejectAnError: + "Expected the Promise rejection reason to be an Error.", + }, + }, + + create(context) { + const [{ allowEmptyReject }] = context.options; + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks the argument of a reject() or Promise.reject() CallExpression, and reports it if it can't be an Error + * @param {ASTNode} callExpression A CallExpression node which is used to reject a Promise + * @returns {void} + */ + function checkRejectCall(callExpression) { + if (!callExpression.arguments.length && allowEmptyReject) { + return; + } + if ( + !callExpression.arguments.length || + !astUtils.couldBeError(callExpression.arguments[0]) || + (callExpression.arguments[0].type === "Identifier" && + callExpression.arguments[0].name === "undefined") + ) { + context.report({ + node: callExpression, + messageId: "rejectAnError", + }); + } + } + + /** + * Determines whether a function call is a Promise.reject() call + * @param {ASTNode} node A CallExpression node + * @returns {boolean} `true` if the call is a Promise.reject() call + */ + function isPromiseRejectCall(node) { + return astUtils.isSpecificMemberAccess( + node.callee, + "Promise", + "reject", + ); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + // Check `Promise.reject(value)` calls. + CallExpression(node) { + if (isPromiseRejectCall(node)) { + checkRejectCall(node); + } + }, + + /* + * Check for `new Promise((resolve, reject) => {})`, and check for reject() calls. + * This function is run on "NewExpression:exit" instead of "NewExpression" to ensure that + * the nodes in the expression already have the `parent` property. + */ + "NewExpression:exit"(node) { + if ( + node.callee.type === "Identifier" && + node.callee.name === "Promise" && + node.arguments.length && + astUtils.isFunction(node.arguments[0]) && + node.arguments[0].params.length > 1 && + node.arguments[0].params[1].type === "Identifier" + ) { + sourceCode + .getDeclaredVariables(node.arguments[0]) + + /* + * Find the first variable that matches the second parameter's name. + * If the first parameter has the same name as the second parameter, then the variable will actually + * be "declared" when the first parameter is evaluated, but then it will be immediately overwritten + * by the second parameter. It's not possible for an expression with the variable to be evaluated before + * the variable is overwritten, because functions with duplicate parameters cannot have destructuring or + * default assignments in their parameter lists. Therefore, it's not necessary to explicitly account for + * this case. + */ + .find( + variable => + variable.name === + node.arguments[0].params[1].name, + ) + + // Get the references to that variable. + .references // Only check the references that read the parameter's value. + .filter(ref => ref.isRead()) + + // Only check the references that are used as the callee in a function call, e.g. `reject(foo)`. + .filter( + ref => + ref.identifier.parent.type === + "CallExpression" && + ref.identifier === ref.identifier.parent.callee, + ) + + // Check the argument of the function call to determine whether it's an Error. + .forEach(ref => checkRejectCall(ref.identifier.parent)); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-reflect.js b/node_modules/eslint/lib/rules/prefer-reflect.js new file mode 100644 index 0000000000000000000000000000000000000000..4eae98afb5e422d20f2fddec3a180a7c26dbff6c --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-reflect.js @@ -0,0 +1,150 @@ +/** + * @fileoverview Rule to suggest using "Reflect" api over Function/Object methods + * @author Keith Cirkel + * @deprecated in ESLint v3.9.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `Reflect` methods where applicable", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-reflect", + }, + + deprecated: { + message: "The original intention of this rule was misguided.", + deprecatedSince: "3.9.0", + availableUntil: null, + replacedBy: [], + }, + + schema: [ + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + enum: [ + "apply", + "call", + "delete", + "defineProperty", + "getOwnPropertyDescriptor", + "getPrototypeOf", + "setPrototypeOf", + "isExtensible", + "getOwnPropertyNames", + "preventExtensions", + ], + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + preferReflect: + "Avoid using {{existing}}, instead use {{substitute}}.", + }, + }, + + create(context) { + const existingNames = { + apply: "Function.prototype.apply", + call: "Function.prototype.call", + defineProperty: "Object.defineProperty", + getOwnPropertyDescriptor: "Object.getOwnPropertyDescriptor", + getPrototypeOf: "Object.getPrototypeOf", + setPrototypeOf: "Object.setPrototypeOf", + isExtensible: "Object.isExtensible", + getOwnPropertyNames: "Object.getOwnPropertyNames", + preventExtensions: "Object.preventExtensions", + }; + + const reflectSubstitutes = { + apply: "Reflect.apply", + call: "Reflect.apply", + defineProperty: "Reflect.defineProperty", + getOwnPropertyDescriptor: "Reflect.getOwnPropertyDescriptor", + getPrototypeOf: "Reflect.getPrototypeOf", + setPrototypeOf: "Reflect.setPrototypeOf", + isExtensible: "Reflect.isExtensible", + getOwnPropertyNames: "Reflect.getOwnPropertyNames", + preventExtensions: "Reflect.preventExtensions", + }; + + const exceptions = (context.options[0] || {}).exceptions || []; + + /** + * Reports the Reflect violation based on the `existing` and `substitute` + * @param {Object} node The node that violates the rule. + * @param {string} existing The existing method name that has been used. + * @param {string} substitute The Reflect substitute that should be used. + * @returns {void} + */ + function report(node, existing, substitute) { + context.report({ + node, + messageId: "preferReflect", + data: { + existing, + substitute, + }, + }); + } + + return { + CallExpression(node) { + const methodName = (node.callee.property || {}).name; + const isReflectCall = + (node.callee.object || {}).name === "Reflect"; + const hasReflectSubstitute = Object.hasOwn( + reflectSubstitutes, + methodName, + ); + const userConfiguredException = exceptions.includes(methodName); + + if ( + hasReflectSubstitute && + !isReflectCall && + !userConfiguredException + ) { + report( + node, + existingNames[methodName], + reflectSubstitutes[methodName], + ); + } + }, + UnaryExpression(node) { + const isDeleteOperator = node.operator === "delete"; + const targetsIdentifier = node.argument.type === "Identifier"; + const userConfiguredException = exceptions.includes("delete"); + + if ( + isDeleteOperator && + !targetsIdentifier && + !userConfiguredException + ) { + report( + node, + "the delete keyword", + "Reflect.deleteProperty", + ); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/prefer-regex-literals.js b/node_modules/eslint/lib/rules/prefer-regex-literals.js new file mode 100644 index 0000000000000000000000000000000000000000..f1414dfa91a35ef658574606c5850bb18bea8708 --- /dev/null +++ b/node_modules/eslint/lib/rules/prefer-regex-literals.js @@ -0,0 +1,605 @@ +/** + * @fileoverview Rule to disallow use of the `RegExp` constructor in favor of regular expression literals + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { + CALL, + CONSTRUCT, + ReferenceTracker, +} = require("@eslint-community/eslint-utils"); +const { + RegExpValidator, + visitRegExpAST, + RegExpParser, +} = require("@eslint-community/regexpp"); +const { canTokensBeAdjacent } = require("./utils/ast-utils"); +const { REGEXPP_LATEST_ECMA_VERSION } = require("./utils/regular-expressions"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether the given node is a string literal. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a string literal. + */ +function isStringLiteral(node) { + return node.type === "Literal" && typeof node.value === "string"; +} + +/** + * Determines whether the given node is a regex literal. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a regex literal. + */ +function isRegexLiteral(node) { + return node.type === "Literal" && Object.hasOwn(node, "regex"); +} + +const validPrecedingTokens = new Set([ + "(", + ";", + "[", + ",", + "=", + "+", + "*", + "-", + "?", + "~", + "%", + "**", + "!", + "typeof", + "instanceof", + "&&", + "||", + "??", + "return", + "...", + "delete", + "void", + "in", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "<<", + ">>", + ">>>", + "&", + "|", + "^", + ":", + "{", + "=>", + "*=", + "<<=", + ">>=", + ">>>=", + "^=", + "|=", + "&=", + "??=", + "||=", + "&&=", + "**=", + "+=", + "-=", + "/=", + "%=", + "/", + "do", + "break", + "continue", + "debugger", + "case", + "throw", +]); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + disallowRedundantWrapping: false, + }, + ], + + docs: { + description: + "Disallow use of the `RegExp` constructor in favor of regular expression literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/prefer-regex-literals", + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + disallowRedundantWrapping: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedRegExp: + "Use a regular expression literal instead of the 'RegExp' constructor.", + replaceWithLiteral: + "Replace with an equivalent regular expression literal.", + replaceWithLiteralAndFlags: + "Replace with an equivalent regular expression literal with flags '{{ flags }}'.", + replaceWithIntendedLiteralAndFlags: + "Replace with a regular expression literal with flags '{{ flags }}'.", + unexpectedRedundantRegExp: + "Regular expression literal is unnecessarily wrapped within a 'RegExp' constructor.", + unexpectedRedundantRegExpWithFlags: + "Use regular expression literal with flags instead of the 'RegExp' constructor.", + }, + }, + + create(context) { + const [{ disallowRedundantWrapping }] = context.options; + const sourceCode = context.sourceCode; + + /** + * Determines whether the given node is a String.raw`` tagged template expression + * with a static template literal. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is String.raw`` with a static template. + */ + function isStringRawTaggedStaticTemplateLiteral(node) { + return ( + node.type === "TaggedTemplateExpression" && + astUtils.isSpecificMemberAccess(node.tag, "String", "raw") && + sourceCode.isGlobalReference( + astUtils.skipChainExpression(node.tag).object, + ) && + astUtils.isStaticTemplateLiteral(node.quasi) + ); + } + + /** + * Gets the value of a string + * @param {ASTNode} node The node to get the string of. + * @returns {string|null} The value of the node. + */ + function getStringValue(node) { + if (isStringLiteral(node)) { + return node.value; + } + + if (astUtils.isStaticTemplateLiteral(node)) { + return node.quasis[0].value.cooked; + } + + if (isStringRawTaggedStaticTemplateLiteral(node)) { + return node.quasi.quasis[0].value.raw; + } + + return null; + } + + /** + * Determines whether the given node is considered to be a static string by the logic of this rule. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a static string. + */ + function isStaticString(node) { + return ( + isStringLiteral(node) || + astUtils.isStaticTemplateLiteral(node) || + isStringRawTaggedStaticTemplateLiteral(node) + ); + } + + /** + * Determines whether the relevant arguments of the given are all static string literals. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if all arguments are static strings. + */ + function hasOnlyStaticStringArguments(node) { + const args = node.arguments; + + if ( + (args.length === 1 || args.length === 2) && + args.every(isStaticString) + ) { + return true; + } + + return false; + } + + /** + * Determines whether the arguments of the given node indicate that a regex literal is unnecessarily wrapped. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node already contains a regex literal argument. + */ + function isUnnecessarilyWrappedRegexLiteral(node) { + const args = node.arguments; + + if (args.length === 1 && isRegexLiteral(args[0])) { + return true; + } + + if ( + args.length === 2 && + isRegexLiteral(args[0]) && + isStaticString(args[1]) + ) { + return true; + } + + return false; + } + + /** + * Returns a ecmaVersion compatible for regexpp. + * @param {number} ecmaVersion The ecmaVersion to convert. + * @returns {import("@eslint-community/regexpp/ecma-versions").EcmaVersion} The resulting ecmaVersion compatible for regexpp. + */ + function getRegexppEcmaVersion(ecmaVersion) { + if (ecmaVersion <= 5) { + return 5; + } + return Math.min(ecmaVersion, REGEXPP_LATEST_ECMA_VERSION); + } + + const regexppEcmaVersion = getRegexppEcmaVersion( + context.languageOptions.ecmaVersion, + ); + + /** + * Makes a character escaped or else returns null. + * @param {string} character The character to escape. + * @returns {string} The resulting escaped character. + */ + function resolveEscapes(character) { + switch (character) { + case "\n": + case "\\\n": + return "\\n"; + + case "\r": + case "\\\r": + return "\\r"; + + case "\t": + case "\\\t": + return "\\t"; + + case "\v": + case "\\\v": + return "\\v"; + + case "\f": + case "\\\f": + return "\\f"; + + case "/": + return "\\/"; + + default: + return null; + } + } + + /** + * Checks whether the given regex and flags are valid for the ecma version or not. + * @param {string} pattern The regex pattern to check. + * @param {string | undefined} flags The regex flags to check. + * @returns {boolean} True if the given regex pattern and flags are valid for the ecma version. + */ + function isValidRegexForEcmaVersion(pattern, flags) { + const validator = new RegExpValidator({ + ecmaVersion: regexppEcmaVersion, + }); + + try { + validator.validatePattern(pattern, 0, pattern.length, { + unicode: flags ? flags.includes("u") : false, + unicodeSets: flags ? flags.includes("v") : false, + }); + if (flags) { + validator.validateFlags(flags); + } + return true; + } catch { + return false; + } + } + + /** + * Checks whether two given regex flags contain the same flags or not. + * @param {string} flagsA The regex flags. + * @param {string} flagsB The regex flags. + * @returns {boolean} True if two regex flags contain same flags. + */ + function areFlagsEqual(flagsA, flagsB) { + return [...flagsA].sort().join("") === [...flagsB].sort().join(""); + } + + /** + * Merges two regex flags. + * @param {string} flagsA The regex flags. + * @param {string} flagsB The regex flags. + * @returns {string} The merged regex flags. + */ + function mergeRegexFlags(flagsA, flagsB) { + const flagsSet = new Set([...flagsA, ...flagsB]); + + return [...flagsSet].join(""); + } + + /** + * Checks whether a give node can be fixed to the given regex pattern and flags. + * @param {ASTNode} node The node to check. + * @param {string} pattern The regex pattern to check. + * @param {string} flags The regex flags + * @returns {boolean} True if a node can be fixed to the given regex pattern and flags. + */ + function canFixTo(node, pattern, flags) { + const tokenBefore = sourceCode.getTokenBefore(node); + + return ( + sourceCode.getCommentsInside(node).length === 0 && + (!tokenBefore || validPrecedingTokens.has(tokenBefore.value)) && + isValidRegexForEcmaVersion(pattern, flags) + ); + } + + /** + * Returns a safe output code considering the before and after tokens. + * @param {ASTNode} node The regex node. + * @param {string} newRegExpValue The new regex expression value. + * @returns {string} The output code. + */ + function getSafeOutput(node, newRegExpValue) { + const tokenBefore = sourceCode.getTokenBefore(node); + const tokenAfter = sourceCode.getTokenAfter(node); + + return ( + (tokenBefore && + !canTokensBeAdjacent(tokenBefore, newRegExpValue) && + tokenBefore.range[1] === node.range[0] + ? " " + : "") + + newRegExpValue + + (tokenAfter && + !canTokensBeAdjacent(newRegExpValue, tokenAfter) && + node.range[1] === tokenAfter.range[0] + ? " " + : "") + ); + } + + return { + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const traceMap = { + RegExp: { + [CALL]: true, + [CONSTRUCT]: true, + }, + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences( + traceMap, + )) { + if ( + disallowRedundantWrapping && + isUnnecessarilyWrappedRegexLiteral(refNode) + ) { + const regexNode = refNode.arguments[0]; + + if (refNode.arguments.length === 2) { + const suggests = []; + + const argFlags = + getStringValue(refNode.arguments[1]) || ""; + + if ( + canFixTo( + refNode, + regexNode.regex.pattern, + argFlags, + ) + ) { + suggests.push({ + messageId: "replaceWithLiteralAndFlags", + pattern: regexNode.regex.pattern, + flags: argFlags, + }); + } + + const literalFlags = regexNode.regex.flags || ""; + const mergedFlags = mergeRegexFlags( + literalFlags, + argFlags, + ); + + if ( + !areFlagsEqual(mergedFlags, argFlags) && + canFixTo( + refNode, + regexNode.regex.pattern, + mergedFlags, + ) + ) { + suggests.push({ + messageId: + "replaceWithIntendedLiteralAndFlags", + pattern: regexNode.regex.pattern, + flags: mergedFlags, + }); + } + + context.report({ + node: refNode, + messageId: "unexpectedRedundantRegExpWithFlags", + suggest: suggests.map( + ({ flags, pattern, messageId }) => ({ + messageId, + data: { + flags, + }, + fix(fixer) { + return fixer.replaceText( + refNode, + getSafeOutput( + refNode, + `/${pattern}/${flags}`, + ), + ); + }, + }), + ), + }); + } else { + const outputs = []; + + if ( + canFixTo( + refNode, + regexNode.regex.pattern, + regexNode.regex.flags, + ) + ) { + outputs.push(sourceCode.getText(regexNode)); + } + + context.report({ + node: refNode, + messageId: "unexpectedRedundantRegExp", + suggest: outputs.map(output => ({ + messageId: "replaceWithLiteral", + fix(fixer) { + return fixer.replaceText( + refNode, + getSafeOutput(refNode, output), + ); + }, + })), + }); + } + } else if (hasOnlyStaticStringArguments(refNode)) { + let regexContent = getStringValue(refNode.arguments[0]); + let noFix = false; + let flags; + + if (refNode.arguments[1]) { + flags = getStringValue(refNode.arguments[1]); + } + + if (!canFixTo(refNode, regexContent, flags)) { + noFix = true; + } + + if ( + !/^[-\w\\[\](){} \t\r\n\v\f!@#$%^&*+=/~`.> + accumulator + + sourceText.slice( + token.range[1], + allTokens[index + 1].range[0], + ), + "", + ); + } + + /** + * Returns a template literal form of the given node. + * @param {ASTNode} currentNode A node that should be converted to a template literal + * @param {string} textBeforeNode Text that should appear before the node + * @param {string} textAfterNode Text that should appear after the node + * @returns {string} A string form of this node, represented as a template literal + */ + function getTemplateLiteral( + currentNode, + textBeforeNode, + textAfterNode, + ) { + if ( + currentNode.type === "Literal" && + typeof currentNode.value === "string" + ) { + /* + * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted + * as a template placeholder. However, if the code already contains a backslash before the ${ or ` + * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause + * an actual backslash character to appear before the dollar sign). + */ + return `\`${currentNode.raw + .slice(1, -1) + .replace(/\\*(\$\{|`)/gu, matched => { + if (matched.lastIndexOf("\\") % 2) { + return `\\${matched}`; + } + return matched; + + // Unescape any quotes that appear in the original Literal that no longer need to be escaped. + }) + .replace( + new RegExp(`\\\\${currentNode.raw[0]}`, "gu"), + currentNode.raw[0], + )}\``; + } + + if (currentNode.type === "TemplateLiteral") { + return sourceCode.getText(currentNode); + } + + if (isConcatenation(currentNode) && hasStringLiteral(currentNode)) { + const plusSign = sourceCode.getFirstTokenBetween( + currentNode.left, + currentNode.right, + token => token.value === "+", + ); + const textBeforePlus = getTextBetween( + currentNode.left, + plusSign, + ); + const textAfterPlus = getTextBetween( + plusSign, + currentNode.right, + ); + const leftEndsWithCurly = endsWithTemplateCurly( + currentNode.left, + ); + const rightStartsWithCurly = startsWithTemplateCurly( + currentNode.right, + ); + + if (leftEndsWithCurly) { + // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket. + // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}` + return ( + getTemplateLiteral( + currentNode.left, + textBeforeNode, + textBeforePlus + textAfterPlus, + ).slice(0, -1) + + getTemplateLiteral( + currentNode.right, + null, + textAfterNode, + ).slice(1) + ); + } + if (rightStartsWithCurly) { + // Otherwise, if the right side of the expression starts with a template curly, add the text there. + // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz` + return ( + getTemplateLiteral( + currentNode.left, + textBeforeNode, + null, + ).slice(0, -1) + + getTemplateLiteral( + currentNode.right, + textBeforePlus + textAfterPlus, + textAfterNode, + ).slice(1) + ); + } + + /* + * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put + * the text between them. + */ + return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`; + } + + return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``; + } + + /** + * Returns a fixer object that converts a non-string binary expression to a template literal + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A node that should be converted to a template literal + * @returns {Object} A fix for this binary expression + */ + function fixNonStringBinaryExpression(fixer, node) { + const topBinaryExpr = getTopConcatBinaryExpression(node.parent); + + if (hasOctalOrNonOctalDecimalEscapeSequence(topBinaryExpr)) { + return null; + } + + return fixer.replaceText( + topBinaryExpr, + getTemplateLiteral(topBinaryExpr, null, null), + ); + } + + /** + * Reports if a given node is string concatenation with non string literals. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function checkForStringConcat(node) { + if ( + !astUtils.isStringLiteral(node) || + !isConcatenation(node.parent) + ) { + return; + } + + const topBinaryExpr = getTopConcatBinaryExpression(node.parent); + + // Checks whether or not this node had been checked already. + if (done[topBinaryExpr.range[0]]) { + return; + } + done[topBinaryExpr.range[0]] = true; + + if (hasNonStringLiteral(topBinaryExpr)) { + context.report({ + node: topBinaryExpr, + messageId: "unexpectedStringConcatenation", + fix: fixer => fixNonStringBinaryExpression(fixer, node), + }); + } + } + + return { + Program() { + done = Object.create(null); + }, + + Literal: checkForStringConcat, + TemplateLiteral: checkForStringConcat, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/preserve-caught-error.js b/node_modules/eslint/lib/rules/preserve-caught-error.js new file mode 100644 index 0000000000000000000000000000000000000000..2a3332b37c109bf56fcb0cf8434a91696d479914 --- /dev/null +++ b/node_modules/eslint/lib/rules/preserve-caught-error.js @@ -0,0 +1,535 @@ +/** + * @fileoverview Rule to preserve caught errors when re-throwing exceptions + * @author Amnish Singh Arora + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("estree").Node} ASTNode */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/* + * This is an indicator of an error cause node, that is too complicated to be detected and fixed. + * Eg, when error options is an `Identifier` or a `SpreadElement`. + */ +const UNKNOWN_CAUSE = Symbol("unknown_cause"); + +const BUILT_IN_ERROR_TYPES = new Set([ + "Error", + "EvalError", + "RangeError", + "ReferenceError", + "SyntaxError", + "TypeError", + "URIError", + "AggregateError", +]); + +/** + * Finds and returns information about the `cause` property of an error being thrown. + * @param {ASTNode} throwStatement `ThrowStatement` to be checked. + * @returns {{ value: ASTNode; multipleDefinitions: boolean; } | UNKNOWN_CAUSE | null} + * Information about the `cause` of the error being thrown, such as the value node and + * whether there are multiple definitions of `cause`. `null` if there is no `cause`. + */ +function getErrorCause(throwStatement) { + const throwExpression = throwStatement.argument; + /* + * Determine which argument index holds the options object + * `AggregateError` is a special case as it accepts the `options` object as third argument. + */ + const optionsIndex = + throwExpression.callee.name === "AggregateError" ? 2 : 1; + + /* + * Make sure there is no `SpreadElement` at or before the `optionsIndex` + * as this messes up the effective order of arguments and makes it complicated + * to track where the actual error options need to be at + */ + const spreadExpressionIndex = throwExpression.arguments.findIndex( + arg => arg.type === "SpreadElement", + ); + if (spreadExpressionIndex >= 0 && spreadExpressionIndex <= optionsIndex) { + return UNKNOWN_CAUSE; + } + + const errorOptions = throwExpression.arguments[optionsIndex]; + + if (errorOptions) { + if (errorOptions.type === "ObjectExpression") { + if ( + errorOptions.properties.some( + prop => prop.type === "SpreadElement", + ) + ) { + /* + * If there is a spread element as part of error options, it is too complicated + * to verify if the cause is used properly and auto-fix. + */ + return UNKNOWN_CAUSE; + } + + const causeProperties = errorOptions.properties.filter( + prop => astUtils.getStaticPropertyName(prop) === "cause", + ); + + const causeProperty = causeProperties.at(-1); + return causeProperty + ? { + value: causeProperty.value, + multipleDefinitions: causeProperties.length > 1, + } + : null; + } + + // Error options exist, but too complicated to be analyzed/fixed + return UNKNOWN_CAUSE; + } + + return null; +} + +/** + * Finds and returns the `CatchClause` node, that the `node` is part of. + * @param {ASTNode} node The AST node to be evaluated. + * @returns {ASTNode | null } The closest parent `CatchClause` node, `null` if the `node` is not in a catch block. + */ +function findParentCatch(node) { + let currentNode = node; + + while (currentNode && currentNode.type !== "CatchClause") { + if ( + [ + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", + "StaticBlock", + ].includes(currentNode.type) + ) { + /* + * Make sure the ThrowStatement is not made inside a function definition or a static block inside a high level catch. + * In such cases, the caught error is not directly related to the Throw. + * + * For example, + * try { + * } catch (error) { + * foo = { + * bar() { + * throw new Error(); + * } + * }; + * } + */ + return null; + } + currentNode = currentNode.parent; + } + + return currentNode; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + requireCatchParameter: false, + }, + ], + + docs: { + description: + "Disallow losing originally caught error when re-throwing custom errors", + recommended: true, + url: "https://eslint.org/docs/latest/rules/preserve-caught-error", // URL to the documentation page for this rule + }, + /* + * TODO: We should allow passing `customErrorTypes` option once something like `typescript-eslint`'s + * `TypeOrValueSpecifier` is implemented in core Eslint. + * See: + * 1. https://typescript-eslint.io/packages/type-utils/type-or-value-specifier/ + * 2. https://github.com/eslint/eslint/pull/19913#discussion_r2192608593 + * 3. https://github.com/eslint/eslint/discussions/16540 + */ + schema: [ + { + type: "object", + properties: { + requireCatchParameter: { + type: "boolean", + description: + "Requires the catch blocks to always have the caught error parameter so it is not discarded.", + }, + }, + additionalProperties: false, + }, + ], + messages: { + missingCause: + "There is no `cause` attached to the symptom error being thrown.", + incorrectCause: + "The symptom error is being thrown with an incorrect `cause`.", + includeCause: + "Include the original caught error as the `cause` of the symptom error.", + missingCatchErrorParam: + "The caught error is not accessible because the catch clause lacks the error parameter. Start referencing the caught error using the catch parameter.", + partiallyLostError: + "Re-throws cannot preserve the caught error as a part of it is being lost due to destructuring.", + caughtErrorShadowed: + "The caught error is being attached as `cause`, but is shadowed by a closer scoped redeclaration.", + }, + hasSuggestions: true, + }, + + create(context) { + const sourceCode = context.sourceCode; + const [{ requireCatchParameter }] = context.options; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks if a `ThrowStatement` is constructing and throwing a new `Error` object. + * + * Covers all the error types on `globalThis` that support `cause` property: + * https://github.com/microsoft/TypeScript/blob/main/src/lib/es2022.error.d.ts + * @param {ASTNode} throwStatement The `ThrowStatement` that needs to be checked. + * @returns {boolean} `true` if a new "Error" is being thrown, else `false`. + */ + function isThrowingNewError(throwStatement) { + return ( + (throwStatement.argument.type === "NewExpression" || + throwStatement.argument.type === "CallExpression") && + throwStatement.argument.callee.type === "Identifier" && + BUILT_IN_ERROR_TYPES.has(throwStatement.argument.callee.name) && + /* + * Make sure the thrown Error is instance is one of the built-in global error types. + * Custom imports could shadow this, which would lead to false positives. + * e.g. import { Error } from "./my-custom-error.js"; + * throw Error("Failed to perform error prone operations"); + */ + sourceCode.isGlobalReference(throwStatement.argument.callee) + ); + } + + /** + * Inserts `cause: ` into an inline options object expression. + * @param {RuleFixer} fixer The fixer object. + * @param {ASTNode} optionsNode The options object node. + * @param {string} caughtErrorName The name of the caught error (e.g., "err"). + * @returns {Fix} The fix object. + */ + function insertCauseIntoOptions(fixer, optionsNode, caughtErrorName) { + const properties = optionsNode.properties; + + if (properties.length === 0) { + // Insert inside empty braces: `{}` → `{ cause: err }` + return fixer.insertTextAfter( + sourceCode.getFirstToken(optionsNode), + `cause: ${caughtErrorName}`, + ); + } + + const lastProp = properties.at(-1); + return fixer.insertTextAfter( + lastProp, + `, cause: ${caughtErrorName}`, + ); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + return { + ThrowStatement(node) { + // Check if the throw is inside a catch block + const parentCatch = findParentCatch(node); + const throwStatement = node; + + // Check if a new error is being thrown in a catch block + if (parentCatch && isThrowingNewError(throwStatement)) { + if ( + parentCatch.param && + parentCatch.param.type !== "Identifier" + ) { + /* + * When a part of the caught error is being lost at the parameter level, commonly due to destructuring. + * e.g. catch({ message, ...rest }) + */ + context.report({ + messageId: "partiallyLostError", + node: parentCatch, + }); + return; + } + + const caughtError = + parentCatch.param?.type === "Identifier" + ? parentCatch.param + : null; + + // Check if there are throw statements and caught error is being ignored + if (!caughtError) { + if (requireCatchParameter) { + context.report({ + node: throwStatement, + messageId: "missingCatchErrorParam", + }); + return; + } + return; + } + + // Check if there is a cause attached to the new error + const errorCauseInfo = getErrorCause(throwStatement); + + if (errorCauseInfo === UNKNOWN_CAUSE) { + // Error options exist, but too complicated to be analyzed/fixed + return; + } + + if (errorCauseInfo === null) { + // If there is no `cause` attached to the error being thrown. + context.report({ + messageId: "missingCause", + node: throwStatement, + suggest: [ + { + messageId: "includeCause", + fix(fixer) { + const throwExpression = + throwStatement.argument; + const args = throwExpression.arguments; + const errorType = + throwExpression.callee.name; + + // AggregateError: errors, message, options + if (errorType === "AggregateError") { + const errorsArg = args[0]; + const messageArg = args[1]; + const optionsArg = args[2]; + + if (!errorsArg) { + // Case: `throw new AggregateError()` → insert all arguments + const lastToken = + sourceCode.getLastToken( + throwExpression, + ); + const lastCalleeToken = + sourceCode.getLastToken( + throwExpression.callee, + ); + const parenToken = + sourceCode.getFirstTokenBetween( + lastCalleeToken, + lastToken, + astUtils.isOpeningParenToken, + ); + + if (parenToken) { + return fixer.insertTextAfter( + parenToken, + `[], "", { cause: ${caughtError.name} }`, + ); + } + return fixer.insertTextAfter( + throwExpression.callee, + `([], "", { cause: ${caughtError.name} })`, + ); + } + + if (!messageArg) { + // Case: `throw new AggregateError([])` → insert message and options + return fixer.insertTextAfter( + errorsArg, + `, "", { cause: ${caughtError.name} }`, + ); + } + + if (!optionsArg) { + // Case: `throw new AggregateError([], "")` → insert error options only + return fixer.insertTextAfter( + messageArg, + `, { cause: ${caughtError.name} }`, + ); + } + + if ( + optionsArg.type === + "ObjectExpression" + ) { + return insertCauseIntoOptions( + fixer, + optionsArg, + caughtError.name, + ); + } + + // Complex dynamic options — skip + return null; + } + + // Normal Error types + const messageArg = args[0]; + const optionsArg = args[1]; + + if (!messageArg) { + // Case: `throw new Error()` → insert both message and options + const lastToken = + sourceCode.getLastToken( + throwExpression, + ); + const lastCalleeToken = + sourceCode.getLastToken( + throwExpression.callee, + ); + const parenToken = + sourceCode.getFirstTokenBetween( + lastCalleeToken, + lastToken, + astUtils.isOpeningParenToken, + ); + + if (parenToken) { + return fixer.insertTextAfter( + parenToken, + `"", { cause: ${caughtError.name} }`, + ); + } + return fixer.insertTextAfter( + throwExpression.callee, + `("", { cause: ${caughtError.name} })`, + ); + } + if (!optionsArg) { + // Case: `throw new Error("Some message")` → insert only options + return fixer.insertTextAfter( + messageArg, + `, { cause: ${caughtError.name} }`, + ); + } + + if ( + optionsArg.type === + "ObjectExpression" + ) { + return insertCauseIntoOptions( + fixer, + optionsArg, + caughtError.name, + ); + } + + return null; // Identifier or spread — do not fix + }, + }, + ], + }); + + // We don't need to check further + return; + } + + const { value: thrownErrorCause } = errorCauseInfo; + + // If there is an attached cause, verify that it matches the caught error + if ( + !( + thrownErrorCause.type === "Identifier" && + thrownErrorCause.name === caughtError.name + ) + ) { + const suggest = errorCauseInfo.multipleDefinitions + ? null // If there are multiple `cause` definitions, a suggestion could be confusing. + : [ + { + messageId: "includeCause", + fix(fixer) { + /* + * In case `cause` is attached using object property shorthand or as a method or accessor. + * e.g. throw Error("fail", { cause }); + * throw Error("fail", { cause() { doSomething(); } }); + * throw Error("fail", { get cause() { return error; } }); + */ + if ( + thrownErrorCause.parent + .method || + thrownErrorCause.parent + .shorthand || + thrownErrorCause.parent.kind !== + "init" + ) { + return fixer.replaceText( + thrownErrorCause.parent, + `cause: ${caughtError.name}`, + ); + } + + return fixer.replaceText( + thrownErrorCause, + caughtError.name, + ); + }, + }, + ]; + context.report({ + messageId: "incorrectCause", + node: thrownErrorCause, + suggest, + }); + return; + } + + /* + * If the attached cause matches the identifier name of the caught error, + * make sure it is not being shadowed by a closer scoped redeclaration. + * + * e.g. try { + * doSomething(); + * } catch (error) { + * if (whatever) { + * const error = anotherError; + * throw new Error("Something went wrong"); + * } + * } + */ + let scope = sourceCode.getScope(throwStatement); + do { + const variable = scope.set.get(caughtError.name); + if (variable) { + break; + } + scope = scope.upper; + } while (scope); + + if (scope?.block !== parentCatch) { + // Caught error is being shadowed + context.report({ + messageId: "caughtErrorShadowed", + node: throwStatement, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/quote-props.js b/node_modules/eslint/lib/rules/quote-props.js new file mode 100644 index 0000000000000000000000000000000000000000..5cbf77d56f1f56350a66a2ff6134e5748087c9f7 --- /dev/null +++ b/node_modules/eslint/lib/rules/quote-props.js @@ -0,0 +1,394 @@ +/** + * @fileoverview Rule to flag non-quoted property names in object literals. + * @author Mathias Bynens + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const espree = require("espree"); +const astUtils = require("./utils/ast-utils"); +const keywords = require("./utils/keywords"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "quote-props", + url: "https://eslint.style/rules/quote-props", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: "Require quotes around object literal property names", + recommended: false, + url: "https://eslint.org/docs/latest/rules/quote-props", + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: [ + "always", + "as-needed", + "consistent", + "consistent-as-needed", + ], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: [ + "always", + "as-needed", + "consistent", + "consistent-as-needed", + ], + }, + { + type: "object", + properties: { + keywords: { + type: "boolean", + }, + unnecessary: { + type: "boolean", + }, + numbers: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + fixable: "code", + messages: { + requireQuotesDueToReservedWord: + "Properties should be quoted as '{{property}}' is a reserved word.", + inconsistentlyQuotedProperty: + "Inconsistently quoted property '{{key}}' found.", + unnecessarilyQuotedProperty: + "Unnecessarily quoted property '{{property}}' found.", + unquotedReservedProperty: + "Unquoted reserved word '{{property}}' used as key.", + unquotedNumericProperty: + "Unquoted number literal '{{property}}' used as key.", + unquotedPropertyFound: "Unquoted property '{{property}}' found.", + redundantQuoting: + "Properties shouldn't be quoted as all quotes are redundant.", + }, + }, + + create(context) { + const MODE = context.options[0], + KEYWORDS = context.options[1] && context.options[1].keywords, + CHECK_UNNECESSARY = + !context.options[1] || context.options[1].unnecessary !== false, + NUMBERS = context.options[1] && context.options[1].numbers, + sourceCode = context.sourceCode; + + /** + * Checks whether a certain string constitutes an ES3 token + * @param {string} tokenStr The string to be checked. + * @returns {boolean} `true` if it is an ES3 token. + */ + function isKeyword(tokenStr) { + return keywords.includes(tokenStr); + } + + /** + * Checks if an espree-tokenized key has redundant quotes (i.e. whether quotes are unnecessary) + * @param {string} rawKey The raw key value from the source + * @param {espreeTokens} tokens The espree-tokenized node key + * @param {boolean} [skipNumberLiterals=false] Indicates whether number literals should be checked + * @returns {boolean} Whether or not a key has redundant quotes. + * @private + */ + function areQuotesRedundant(rawKey, tokens, skipNumberLiterals) { + return ( + tokens.length === 1 && + tokens[0].start === 0 && + tokens[0].end === rawKey.length && + (["Identifier", "Keyword", "Null", "Boolean"].includes( + tokens[0].type, + ) || + (tokens[0].type === "Numeric" && + !skipNumberLiterals && + String(+tokens[0].value) === tokens[0].value)) + ); + } + + /** + * Returns a string representation of a property node with quotes removed + * @param {ASTNode} key Key AST Node, which may or may not be quoted + * @returns {string} A replacement string for this property + */ + function getUnquotedKey(key) { + return key.type === "Identifier" ? key.name : key.value; + } + + /** + * Returns a string representation of a property node with quotes added + * @param {ASTNode} key Key AST Node, which may or may not be quoted + * @returns {string} A replacement string for this property + */ + function getQuotedKey(key) { + if (key.type === "Literal" && typeof key.value === "string") { + // If the key is already a string literal, don't replace the quotes with double quotes. + return sourceCode.getText(key); + } + + // Otherwise, the key is either an identifier or a number literal. + return `"${key.type === "Identifier" ? key.name : key.value}"`; + } + + /** + * Ensures that a property's key is quoted only when necessary + * @param {ASTNode} node Property AST node + * @returns {void} + */ + function checkUnnecessaryQuotes(node) { + const key = node.key; + + if (node.method || node.computed || node.shorthand) { + return; + } + + if (key.type === "Literal" && typeof key.value === "string") { + let tokens; + + try { + tokens = espree.tokenize(key.value); + } catch { + return; + } + + if (tokens.length !== 1) { + return; + } + + const isKeywordToken = isKeyword(tokens[0].value); + + if (isKeywordToken && KEYWORDS) { + return; + } + + if ( + CHECK_UNNECESSARY && + areQuotesRedundant(key.value, tokens, NUMBERS) + ) { + context.report({ + node, + messageId: "unnecessarilyQuotedProperty", + data: { property: key.value }, + fix: fixer => + fixer.replaceText(key, getUnquotedKey(key)), + }); + } + } else if ( + KEYWORDS && + key.type === "Identifier" && + isKeyword(key.name) + ) { + context.report({ + node, + messageId: "unquotedReservedProperty", + data: { property: key.name }, + fix: fixer => fixer.replaceText(key, getQuotedKey(key)), + }); + } else if ( + NUMBERS && + key.type === "Literal" && + astUtils.isNumericLiteral(key) + ) { + context.report({ + node, + messageId: "unquotedNumericProperty", + data: { property: key.value }, + fix: fixer => fixer.replaceText(key, getQuotedKey(key)), + }); + } + } + + /** + * Ensures that a property's key is quoted + * @param {ASTNode} node Property AST node + * @returns {void} + */ + function checkOmittedQuotes(node) { + const key = node.key; + + if ( + !node.method && + !node.computed && + !node.shorthand && + !(key.type === "Literal" && typeof key.value === "string") + ) { + context.report({ + node, + messageId: "unquotedPropertyFound", + data: { property: key.name || key.value }, + fix: fixer => fixer.replaceText(key, getQuotedKey(key)), + }); + } + } + + /** + * Ensures that an object's keys are consistently quoted, optionally checks for redundancy of quotes + * @param {ASTNode} node Property AST node + * @param {boolean} checkQuotesRedundancy Whether to check quotes' redundancy + * @returns {void} + */ + function checkConsistency(node, checkQuotesRedundancy) { + const quotedProps = [], + unquotedProps = []; + let keywordKeyName = null, + necessaryQuotes = false; + + node.properties.forEach(property => { + const key = property.key; + + if ( + !key || + property.method || + property.computed || + property.shorthand + ) { + return; + } + + if (key.type === "Literal" && typeof key.value === "string") { + quotedProps.push(property); + + if (checkQuotesRedundancy) { + let tokens; + + try { + tokens = espree.tokenize(key.value); + } catch { + necessaryQuotes = true; + return; + } + + necessaryQuotes = + necessaryQuotes || + !areQuotesRedundant(key.value, tokens) || + (KEYWORDS && isKeyword(tokens[0].value)); + } + } else if ( + KEYWORDS && + checkQuotesRedundancy && + key.type === "Identifier" && + isKeyword(key.name) + ) { + unquotedProps.push(property); + necessaryQuotes = true; + keywordKeyName = key.name; + } else { + unquotedProps.push(property); + } + }); + + if ( + checkQuotesRedundancy && + quotedProps.length && + !necessaryQuotes + ) { + quotedProps.forEach(property => { + context.report({ + node: property, + messageId: "redundantQuoting", + fix: fixer => + fixer.replaceText( + property.key, + getUnquotedKey(property.key), + ), + }); + }); + } else if (unquotedProps.length && keywordKeyName) { + unquotedProps.forEach(property => { + context.report({ + node: property, + messageId: "requireQuotesDueToReservedWord", + data: { property: keywordKeyName }, + fix: fixer => + fixer.replaceText( + property.key, + getQuotedKey(property.key), + ), + }); + }); + } else if (quotedProps.length && unquotedProps.length) { + unquotedProps.forEach(property => { + context.report({ + node: property, + messageId: "inconsistentlyQuotedProperty", + data: { key: property.key.name || property.key.value }, + fix: fixer => + fixer.replaceText( + property.key, + getQuotedKey(property.key), + ), + }); + }); + } + } + + return { + Property(node) { + if (MODE === "always" || !MODE) { + checkOmittedQuotes(node); + } + if (MODE === "as-needed") { + checkUnnecessaryQuotes(node); + } + }, + ObjectExpression(node) { + if (MODE === "consistent") { + checkConsistency(node, false); + } + if (MODE === "consistent-as-needed") { + checkConsistency(node, true); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/quotes.js b/node_modules/eslint/lib/rules/quotes.js new file mode 100644 index 0000000000000000000000000000000000000000..4de678cd35bc5255af3b1add815ed6d5a15f9b0f --- /dev/null +++ b/node_modules/eslint/lib/rules/quotes.js @@ -0,0 +1,416 @@ +/** + * @fileoverview A rule to choose between single and double quote marks + * @author Matt DuVall , Brandon Payton + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const QUOTE_SETTINGS = { + double: { + quote: '"', + alternateQuote: "'", + description: "doublequote", + }, + single: { + quote: "'", + alternateQuote: '"', + description: "singlequote", + }, + backtick: { + quote: "`", + alternateQuote: '"', + description: "backtick", + }, +}; + +// An unescaped newline is a newline preceded by an even number of backslashes. +const UNESCAPED_LINEBREAK_PATTERN = new RegExp( + String.raw`(^|[^\\])(\\\\)*[${Array.from(astUtils.LINEBREAKS).join("")}]`, + "u", +); + +/** + * Switches quoting of javascript string between ' " and ` + * escaping and unescaping as necessary. + * Only escaping of the minimal set of characters is changed. + * Note: escaping of newlines when switching from backtick to other quotes is not handled. + * @param {string} str A string to convert. + * @returns {string} The string with changed quotes. + * @private + */ +QUOTE_SETTINGS.double.convert = + QUOTE_SETTINGS.single.convert = + QUOTE_SETTINGS.backtick.convert = + function (str) { + const newQuote = this.quote; + const oldQuote = str[0]; + + if (newQuote === oldQuote) { + return str; + } + return ( + newQuote + + str + .slice(1, -1) + .replace( + /\\(\$\{|\r\n?|\n|.)|["'`]|\$\{|(\r\n?|\n)/gu, + (match, escaped, newline) => { + if ( + escaped === oldQuote || + (oldQuote === "`" && escaped === "${") + ) { + return escaped; // unescape + } + if ( + match === newQuote || + (newQuote === "`" && match === "${") + ) { + return `\\${match}`; // escape + } + if (newline && oldQuote === "`") { + return "\\n"; // escape newlines + } + return match; + }, + ) + + newQuote + ); + }; + +const AVOID_ESCAPE = "avoid-escape"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "quotes", + url: "https://eslint.style/rules/quotes", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce the consistent use of either backticks, double, or single quotes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/quotes", + }, + + fixable: "code", + + schema: [ + { + enum: ["single", "double", "backtick"], + }, + { + anyOf: [ + { + enum: ["avoid-escape"], + }, + { + type: "object", + properties: { + avoidEscape: { + type: "boolean", + }, + allowTemplateLiterals: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + wrongQuotes: "Strings must use {{description}}.", + }, + }, + + create(context) { + const quoteOption = context.options[0], + settings = QUOTE_SETTINGS[quoteOption || "double"], + options = context.options[1], + allowTemplateLiterals = + options && options.allowTemplateLiterals === true, + sourceCode = context.sourceCode; + let avoidEscape = options && options.avoidEscape === true; + + // deprecated + if (options === AVOID_ESCAPE) { + avoidEscape = true; + } + + /** + * Determines if a given node is part of JSX syntax. + * + * This function returns `true` in the following cases: + * + * - `
` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`. + * - `
foo
` ... If the literal is a text content, the parent of the literal is `JSXElement`. + * - `<>foo` ... If the literal is a text content, the parent of the literal is `JSXFragment`. + * + * In particular, this function returns `false` in the following cases: + * + * - `
` + * - `
{"foo"}
` + * + * In both cases, inside of the braces is handled as normal JavaScript. + * The braces are `JSXExpressionContainer` nodes. + * @param {ASTNode} node The Literal node to check. + * @returns {boolean} True if the node is a part of JSX, false if not. + * @private + */ + function isJSXLiteral(node) { + return ( + node.parent.type === "JSXAttribute" || + node.parent.type === "JSXElement" || + node.parent.type === "JSXFragment" + ); + } + + /** + * Checks whether or not a given node is a directive. + * The directive is a `ExpressionStatement` which has only a string literal not surrounded by + * parentheses. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a directive. + * @private + */ + function isDirective(node) { + return ( + node.type === "ExpressionStatement" && + node.expression.type === "Literal" && + typeof node.expression.value === "string" && + !astUtils.isParenthesised(sourceCode, node.expression) + ); + } + + /** + * Checks whether a specified node is either part of, or immediately follows a (possibly empty) directive prologue. + * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive} + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether a specified node is either part of, or immediately follows a (possibly empty) directive prologue. + * @private + */ + function isExpressionInOrJustAfterDirectivePrologue(node) { + if (!astUtils.isTopLevelExpressionStatement(node.parent)) { + return false; + } + const block = node.parent.parent; + + // Check the node is at a prologue. + for (let i = 0; i < block.body.length; ++i) { + const statement = block.body[i]; + + if (statement === node.parent) { + return true; + } + if (!isDirective(statement)) { + break; + } + } + + return false; + } + + /** + * Checks whether or not a given node is allowed as non backtick. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is allowed as non backtick. + * @private + */ + function isAllowedAsNonBacktick(node) { + const parent = node.parent; + + switch (parent.type) { + // Directive Prologues. + case "ExpressionStatement": + return ( + !astUtils.isParenthesised(sourceCode, node) && + isExpressionInOrJustAfterDirectivePrologue(node) + ); + + // LiteralPropertyName. + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + return parent.key === node && !parent.computed; + + // ModuleSpecifier. + case "ImportDeclaration": + case "ExportNamedDeclaration": + return parent.source === node; + + // ModuleExportName or ModuleSpecifier. + case "ExportAllDeclaration": + return parent.exported === node || parent.source === node; + + // ModuleExportName. + case "ImportSpecifier": + return parent.imported === node; + + // ModuleExportName. + case "ExportSpecifier": + return parent.local === node || parent.exported === node; + + // Others don't allow. + default: + return false; + } + } + + /** + * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings. + * @param {ASTNode} node A TemplateLiteral node to check. + * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings. + * @private + */ + function isUsingFeatureOfTemplateLiteral(node) { + const hasTag = + node.parent.type === "TaggedTemplateExpression" && + node === node.parent.quasi; + + if (hasTag) { + return true; + } + + const hasStringInterpolation = node.expressions.length > 0; + + if (hasStringInterpolation) { + return true; + } + + const isMultilineString = + node.quasis.length >= 1 && + UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw); + + if (isMultilineString) { + return true; + } + + return false; + } + + return { + Literal(node) { + const val = node.value, + rawVal = node.raw; + + if (settings && typeof val === "string") { + let isValid = + (quoteOption === "backtick" && + isAllowedAsNonBacktick(node)) || + isJSXLiteral(node) || + astUtils.isSurroundedBy(rawVal, settings.quote); + + if (!isValid && avoidEscape) { + isValid = + astUtils.isSurroundedBy( + rawVal, + settings.alternateQuote, + ) && rawVal.includes(settings.quote); + } + + if (!isValid) { + context.report({ + node, + messageId: "wrongQuotes", + data: { + description: settings.description, + }, + fix(fixer) { + if ( + quoteOption === "backtick" && + astUtils.hasOctalOrNonOctalDecimalEscapeSequence( + rawVal, + ) + ) { + /* + * An octal or non-octal decimal escape sequence in a template literal would + * produce syntax error, even in non-strict mode. + */ + return null; + } + + return fixer.replaceText( + node, + settings.convert(node.raw), + ); + }, + }); + } + } + }, + + TemplateLiteral(node) { + // Don't throw an error if backticks are expected or a template literal feature is in use. + if ( + allowTemplateLiterals || + quoteOption === "backtick" || + isUsingFeatureOfTemplateLiteral(node) + ) { + return; + } + + context.report({ + node, + messageId: "wrongQuotes", + data: { + description: settings.description, + }, + fix(fixer) { + if ( + astUtils.isTopLevelExpressionStatement( + node.parent, + ) && + !astUtils.isParenthesised(sourceCode, node) + ) { + /* + * TemplateLiterals aren't actually directives, but fixing them might turn + * them into directives and change the behavior of the code. + */ + return null; + } + return fixer.replaceText( + node, + settings.convert(sourceCode.getText(node)), + ); + }, + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/radix.js b/node_modules/eslint/lib/rules/radix.js new file mode 100644 index 0000000000000000000000000000000000000000..48d8bab5df526a5290b219c70ea5d451b0f05769 --- /dev/null +++ b/node_modules/eslint/lib/rules/radix.js @@ -0,0 +1,199 @@ +/** + * @fileoverview Rule to flag use of parseInt without a radix argument + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Variable} Variable */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const validRadixValues = new Set( + Array.from({ length: 37 - 2 }, (_, index) => index + 2), +); + +/** + * Checks whether a given variable is shadowed or not. + * @param {Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is shadowed. + */ +function isShadowed(variable) { + return variable.defs.length >= 1; +} + +/** + * Checks whether a given node is a MemberExpression of `parseInt` method or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a MemberExpression of `parseInt` + * method. + */ +function isParseIntMethod(node) { + return ( + node.type === "MemberExpression" && + !node.computed && + node.property.type === "Identifier" && + node.property.name === "parseInt" + ); +} + +/** + * Checks whether a given node is a valid value of radix or not. + * + * The following values are invalid. + * + * - A literal except integers between 2 and 36. + * - undefined. + * @param {ASTNode} radix A node of radix to check. + * @returns {boolean} `true` if the node is valid. + */ +function isValidRadix(radix) { + return !( + (radix.type === "Literal" && !validRadixValues.has(radix.value)) || + (radix.type === "Identifier" && radix.name === "undefined") + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce the use of the radix argument when using `parseInt()`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/radix", + }, + + hasSuggestions: true, + + schema: [ + // deprecated + { + enum: ["always", "as-needed"], + }, + ], + + messages: { + missingParameters: "Missing parameters.", + missingRadix: "Missing radix parameter.", + invalidRadix: + "Invalid radix parameter, must be an integer between 2 and 36.", + addRadixParameter10: + "Add radix parameter `10` for parsing decimal numbers.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Checks the arguments of a given CallExpression node and reports it if it + * offends this rule. + * @param {ASTNode} node A CallExpression node to check. + * @returns {void} + */ + function checkArguments(node) { + const args = node.arguments; + + switch (args.length) { + case 0: + context.report({ + node, + messageId: "missingParameters", + }); + break; + + case 1: + context.report({ + node, + messageId: "missingRadix", + suggest: [ + { + messageId: "addRadixParameter10", + fix(fixer) { + const tokens = sourceCode.getTokens(node); + const lastToken = tokens.at(-1); // Parenthesis. + const secondToLastToken = tokens.at(-2); // May or may not be a comma. + const hasTrailingComma = + secondToLastToken.type === + "Punctuator" && + secondToLastToken.value === ","; + + return fixer.insertTextBefore( + lastToken, + hasTrailingComma ? " 10," : ", 10", + ); + }, + }, + ], + }); + break; + + default: + if (!isValidRadix(args[1])) { + context.report({ + node, + messageId: "invalidRadix", + }); + } + break; + } + } + + return { + "Program:exit"(node) { + const scope = sourceCode.getScope(node); + let variable; + + // Check `parseInt()` + variable = astUtils.getVariableByName(scope, "parseInt"); + if (variable && !isShadowed(variable)) { + variable.references.forEach(reference => { + const idNode = reference.identifier; + + if (astUtils.isCallee(idNode)) { + checkArguments(idNode.parent); + } + }); + } + + // Check `Number.parseInt()` + variable = astUtils.getVariableByName(scope, "Number"); + if (variable && !isShadowed(variable)) { + variable.references.forEach(reference => { + const parentNode = reference.identifier.parent; + const maybeCallee = + parentNode.parent.type === "ChainExpression" + ? parentNode.parent + : parentNode; + + if ( + isParseIntMethod(parentNode) && + astUtils.isCallee(maybeCallee) + ) { + checkArguments(maybeCallee.parent); + } + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/require-atomic-updates.js b/node_modules/eslint/lib/rules/require-atomic-updates.js new file mode 100644 index 0000000000000000000000000000000000000000..c3935cca87205325c4d37773fa25afa3479cbbfe --- /dev/null +++ b/node_modules/eslint/lib/rules/require-atomic-updates.js @@ -0,0 +1,365 @@ +/** + * @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield` + * @author Teddy Katz + * @author Toru Nagashima + */ +"use strict"; + +/** + * Make the map from identifiers to each reference. + * @param {escope.Scope} scope The scope to get references. + * @param {Map} [outReferenceMap] The map from identifier nodes to each reference object. + * @returns {Map} `referenceMap`. + */ +function createReferenceMap(scope, outReferenceMap = new Map()) { + for (const reference of scope.references) { + if (reference.resolved === null) { + continue; + } + + outReferenceMap.set(reference.identifier, reference); + } + for (const childScope of scope.childScopes) { + if (childScope.type !== "function") { + createReferenceMap(childScope, outReferenceMap); + } + } + + return outReferenceMap; +} + +/** + * Get `reference.writeExpr` of a given reference. + * If it's the read reference of MemberExpression in LHS, returns RHS in order to address `a.b = await a` + * @param {escope.Reference} reference The reference to get. + * @returns {Expression|null} The `reference.writeExpr`. + */ +function getWriteExpr(reference) { + if (reference.writeExpr) { + return reference.writeExpr; + } + let node = reference.identifier; + + while (node) { + const t = node.parent.type; + + if (t === "AssignmentExpression" && node.parent.left === node) { + return node.parent.right; + } + if (t === "MemberExpression" && node.parent.object === node) { + node = node.parent; + continue; + } + + break; + } + + return null; +} + +/** + * Checks if an expression is a variable that can only be observed within the given function. + * @param {Variable|null} variable The variable to check + * @param {boolean} isMemberAccess If `true` then this is a member access. + * @returns {boolean} `true` if the variable is local to the given function, and is never referenced in a closure. + */ +function isLocalVariableWithoutEscape(variable, isMemberAccess) { + if (!variable) { + return false; // A global variable which was not defined. + } + + // If the reference is a property access and the variable is a parameter, it handles the variable is not local. + if (isMemberAccess && variable.defs.some(d => d.type === "Parameter")) { + return false; + } + + const functionScope = variable.scope.variableScope; + + return variable.references.every( + reference => reference.from.variableScope === functionScope, + ); +} + +/** + * Represents segment information. + */ +class SegmentInfo { + constructor() { + this.info = new WeakMap(); + } + + /** + * Initialize the segment information. + * @param {PathSegment} segment The segment to initialize. + * @returns {void} + */ + initialize(segment) { + const outdatedReadVariables = new Set(); + const freshReadVariables = new Set(); + + for (const prevSegment of segment.prevSegments) { + const info = this.info.get(prevSegment); + + if (info) { + info.outdatedReadVariables.forEach( + Set.prototype.add, + outdatedReadVariables, + ); + info.freshReadVariables.forEach( + Set.prototype.add, + freshReadVariables, + ); + } + } + + this.info.set(segment, { outdatedReadVariables, freshReadVariables }); + } + + /** + * Mark a given variable as read on given segments. + * @param {PathSegment[]} segments The segments that it read the variable on. + * @param {Variable} variable The variable to be read. + * @returns {void} + */ + markAsRead(segments, variable) { + for (const segment of segments) { + const info = this.info.get(segment); + + if (info) { + info.freshReadVariables.add(variable); + + // If a variable is freshly read again, then it's no more out-dated. + info.outdatedReadVariables.delete(variable); + } + } + } + + /** + * Move `freshReadVariables` to `outdatedReadVariables`. + * @param {PathSegment[]} segments The segments to process. + * @returns {void} + */ + makeOutdated(segments) { + for (const segment of segments) { + const info = this.info.get(segment); + + if (info) { + info.freshReadVariables.forEach( + Set.prototype.add, + info.outdatedReadVariables, + ); + info.freshReadVariables.clear(); + } + } + } + + /** + * Check if a given variable is outdated on the current segments. + * @param {PathSegment[]} segments The current segments. + * @param {Variable} variable The variable to check. + * @returns {boolean} `true` if the variable is outdated on the segments. + */ + isOutdated(segments, variable) { + for (const segment of segments) { + const info = this.info.get(segment); + + if (info && info.outdatedReadVariables.has(variable)) { + return true; + } + } + return false; + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowProperties: false, + }, + ], + + docs: { + description: + "Disallow assignments that can lead to race conditions due to usage of `await` or `yield`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/require-atomic-updates", + }, + + fixable: null, + + schema: [ + { + type: "object", + properties: { + allowProperties: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + nonAtomicUpdate: + "Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`.", + nonAtomicObjectUpdate: + "Possible race condition: `{{value}}` might be assigned based on an outdated state of `{{object}}`.", + }, + }, + + create(context) { + const [{ allowProperties }] = context.options; + + const sourceCode = context.sourceCode; + const assignmentReferences = new Map(); + const segmentInfo = new SegmentInfo(); + let stack = null; + + return { + onCodePathStart(codePath, node) { + const scope = sourceCode.getScope(node); + const shouldVerify = + scope.type === "function" && + (scope.block.async || scope.block.generator); + + stack = { + upper: stack, + codePath, + referenceMap: shouldVerify + ? createReferenceMap(scope) + : null, + currentSegments: new Set(), + }; + }, + onCodePathEnd() { + stack = stack.upper; + }, + + // Initialize the segment information. + onCodePathSegmentStart(segment) { + segmentInfo.initialize(segment); + stack.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentStart(segment) { + stack.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + stack.currentSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + stack.currentSegments.delete(segment); + }, + + // Handle references to prepare verification. + Identifier(node) { + const { referenceMap } = stack; + const reference = referenceMap && referenceMap.get(node); + + // Ignore if this is not a valid variable reference. + if (!reference) { + return; + } + const variable = reference.resolved; + const writeExpr = getWriteExpr(reference); + const isMemberAccess = + reference.identifier.parent.type === "MemberExpression"; + + // Add a fresh read variable. + if ( + reference.isRead() && + !(writeExpr && writeExpr.parent.operator === "=") + ) { + segmentInfo.markAsRead(stack.currentSegments, variable); + } + + /* + * Register the variable to verify after ESLint traversed the `writeExpr` node + * if this reference is an assignment to a variable which is referred from other closure. + */ + if ( + writeExpr && + writeExpr.parent.right === writeExpr && // ← exclude variable declarations. + !isLocalVariableWithoutEscape(variable, isMemberAccess) + ) { + let refs = assignmentReferences.get(writeExpr); + + if (!refs) { + refs = []; + assignmentReferences.set(writeExpr, refs); + } + + refs.push(reference); + } + }, + + /* + * Verify assignments. + * If the reference exists in `outdatedReadVariables` list, report it. + */ + ":expression:exit"(node) { + // referenceMap exists if this is in a resumable function scope. + if (!stack.referenceMap) { + return; + } + + // Mark the read variables on this code path as outdated. + if ( + node.type === "AwaitExpression" || + node.type === "YieldExpression" + ) { + segmentInfo.makeOutdated(stack.currentSegments); + } + + // Verify. + const references = assignmentReferences.get(node); + + if (references) { + assignmentReferences.delete(node); + + for (const reference of references) { + const variable = reference.resolved; + + if ( + segmentInfo.isOutdated( + stack.currentSegments, + variable, + ) + ) { + if (node.parent.left === reference.identifier) { + context.report({ + node: node.parent, + messageId: "nonAtomicUpdate", + data: { + value: variable.name, + }, + }); + } else if (!allowProperties) { + context.report({ + node: node.parent, + messageId: "nonAtomicObjectUpdate", + data: { + value: sourceCode.getText( + node.parent.left, + ), + object: variable.name, + }, + }); + } + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/require-await.js b/node_modules/eslint/lib/rules/require-await.js new file mode 100644 index 0000000000000000000000000000000000000000..f297ef10953656ce986f19a9689979848821e26d --- /dev/null +++ b/node_modules/eslint/lib/rules/require-await.js @@ -0,0 +1,186 @@ +/** + * @fileoverview Rule to disallow async functions which have no `await` expression. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Capitalize the 1st letter of the given text. + * @param {string} text The text to capitalize. + * @returns {string} The text that the 1st letter was capitalized. + */ +function capitalizeFirstLetter(text) { + return text[0].toUpperCase() + text.slice(1); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Disallow async functions which have no `await` expression", + recommended: false, + url: "https://eslint.org/docs/latest/rules/require-await", + }, + + schema: [], + + messages: { + missingAwait: "{{name}} has no 'await' expression.", + removeAsync: "Remove 'async'.", + }, + + hasSuggestions: true, + }, + + create(context) { + const sourceCode = context.sourceCode; + let scopeInfo = null; + + /** + * Push the scope info object to the stack. + * @returns {void} + */ + function enterFunction() { + scopeInfo = { + upper: scopeInfo, + hasAwait: false, + }; + } + + /** + * Pop the top scope info object from the stack. + * Also, it reports the function if needed. + * @param {ASTNode} node The node to report. + * @returns {void} + */ + function exitFunction(node) { + if ( + !node.generator && + node.async && + !scopeInfo.hasAwait && + !astUtils.isEmptyFunction(node) + ) { + /* + * If the function belongs to a method definition or + * property, then the function's range may not include the + * `async` keyword and we should look at the parent instead. + */ + const nodeWithAsyncKeyword = + (node.parent.type === "MethodDefinition" && + node.parent.value === node) || + (node.parent.type === "Property" && + node.parent.method && + node.parent.value === node) + ? node.parent + : node; + + const asyncToken = sourceCode.getFirstToken( + nodeWithAsyncKeyword, + token => token.value === "async", + ); + const asyncRange = [ + asyncToken.range[0], + sourceCode.getTokenAfter(asyncToken, { + includeComments: true, + }).range[0], + ]; + + /* + * Removing the `async` keyword can cause parsing errors if the current + * statement is relying on automatic semicolon insertion. If ASI is currently + * being used, then we should replace the `async` keyword with a semicolon. + */ + const nextToken = sourceCode.getTokenAfter(asyncToken); + const addSemiColon = + ((astUtils.isOpeningParenToken(nextToken) && + astUtils.isStartOfExpressionStatement( + nodeWithAsyncKeyword, + )) || + (nodeWithAsyncKeyword.type === "MethodDefinition" && + astUtils.canContinueExpressionInClassBody( + nextToken, + ))) && + astUtils.needsPrecedingSemicolon( + sourceCode, + nodeWithAsyncKeyword, + ); + + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + messageId: "missingAwait", + data: { + name: capitalizeFirstLetter( + astUtils.getFunctionNameWithKind(node), + ), + }, + suggest: [ + { + messageId: "removeAsync", + fix: fixer => + fixer.replaceTextRange( + asyncRange, + addSemiColon ? ";" : "", + ), + }, + ], + }); + } + + scopeInfo = scopeInfo.upper; + } + + return { + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + ArrowFunctionExpression: enterFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + "ArrowFunctionExpression:exit": exitFunction, + + AwaitExpression() { + if (!scopeInfo) { + return; + } + + scopeInfo.hasAwait = true; + }, + ForOfStatement(node) { + if (!scopeInfo) { + return; + } + + if (node.await) { + scopeInfo.hasAwait = true; + } + }, + VariableDeclaration(node) { + if (!scopeInfo) { + return; + } + + if (node.kind === "await using") { + scopeInfo.hasAwait = true; + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/require-unicode-regexp.js b/node_modules/eslint/lib/rules/require-unicode-regexp.js new file mode 100644 index 0000000000000000000000000000000000000000..fd039afe14773d0788bfe4694be30d98aeb9ef0f --- /dev/null +++ b/node_modules/eslint/lib/rules/require-unicode-regexp.js @@ -0,0 +1,317 @@ +/** + * @fileoverview Rule to enforce the use of `u` or `v` flag on regular expressions. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { + CALL, + CONSTRUCT, + ReferenceTracker, + getStringIfConstant, +} = require("@eslint-community/eslint-utils"); +const astUtils = require("./utils/ast-utils.js"); +const { isValidWithUnicodeFlag } = require("./utils/regular-expressions"); + +/** + * Checks whether the flag configuration should be treated as a missing flag. + * @param {"u"|"v"|undefined} requireFlag A particular flag to require + * @param {string} flags The regex flags + * @returns {boolean} Whether the flag configuration results in a missing flag. + */ +function checkFlags(requireFlag, flags) { + let missingFlag; + + if (requireFlag === "v") { + missingFlag = !flags.includes("v"); + } else if (requireFlag === "u") { + missingFlag = !flags.includes("u"); + } else { + missingFlag = !flags.includes("u") && !flags.includes("v"); + } + + return missingFlag; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{}], + + docs: { + description: + "Enforce the use of `u` or `v` flag on regular expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/require-unicode-regexp", + }, + + hasSuggestions: true, + + messages: { + addUFlag: "Add the 'u' flag.", + addVFlag: "Add the 'v' flag.", + requireUFlag: "Use the 'u' flag.", + requireVFlag: "Use the 'v' flag.", + }, + + schema: [ + { + type: "object", + properties: { + requireFlag: { + enum: ["u", "v"], + }, + }, + additionalProperties: false, + }, + ], + }, + + create(context) { + const sourceCode = context.sourceCode; + + const [{ requireFlag }] = context.options; + + return { + "Literal[regex]"(node) { + const flags = node.regex.flags || ""; + + const missingFlag = checkFlags(requireFlag, flags); + + if (missingFlag) { + context.report({ + messageId: + requireFlag === "v" + ? "requireVFlag" + : "requireUFlag", + node, + suggest: isValidWithUnicodeFlag( + context.languageOptions.ecmaVersion, + node.regex.pattern, + requireFlag, + ) + ? [ + { + fix(fixer) { + const replaceFlag = + requireFlag ?? "u"; + const regex = + sourceCode.getText(node); + const slashPos = + regex.lastIndexOf("/"); + + if (requireFlag) { + const flag = + requireFlag === "u" + ? "v" + : "u"; + + if ( + regex.includes( + flag, + slashPos, + ) + ) { + return fixer.replaceText( + node, + regex.slice( + 0, + slashPos, + ) + + regex + .slice(slashPos) + .replace( + flag, + requireFlag, + ), + ); + } + } + + return fixer.insertTextAfter( + node, + replaceFlag, + ); + }, + messageId: + requireFlag === "v" + ? "addVFlag" + : "addUFlag", + }, + ] + : null, + }); + } + }, + + Program(node) { + const scope = sourceCode.getScope(node); + const tracker = new ReferenceTracker(scope); + const trackMap = { + RegExp: { [CALL]: true, [CONSTRUCT]: true }, + }; + + for (const { node: refNode } of tracker.iterateGlobalReferences( + trackMap, + )) { + const [patternNode, flagsNode] = refNode.arguments; + + if (patternNode && patternNode.type === "SpreadElement") { + continue; + } + const pattern = getStringIfConstant(patternNode, scope); + const flags = getStringIfConstant(flagsNode, scope); + + let missingFlag = !flagsNode; + + if (typeof flags === "string") { + missingFlag = checkFlags(requireFlag, flags); + } + + if (missingFlag) { + context.report({ + messageId: + requireFlag === "v" + ? "requireVFlag" + : "requireUFlag", + node: refNode, + suggest: + typeof pattern === "string" && + isValidWithUnicodeFlag( + context.languageOptions.ecmaVersion, + pattern, + requireFlag, + ) + ? [ + { + fix(fixer) { + const replaceFlag = + requireFlag ?? "u"; + + if (flagsNode) { + if ( + (flagsNode.type === + "Literal" && + typeof flagsNode.value === + "string") || + flagsNode.type === + "TemplateLiteral" + ) { + const flagsNodeText = + sourceCode.getText( + flagsNode, + ); + const flag = + requireFlag === + "u" + ? "v" + : "u"; + + if ( + flags.includes( + flag, + ) + ) { + // Avoid replacing "u" in escapes like `\uXXXX` + if ( + flagsNode.type === + "Literal" && + flagsNode.raw.includes( + "\\", + ) + ) { + return null; + } + + // Avoid replacing "u" in expressions like "`${regularFlags}g`" + if ( + flagsNode.type === + "TemplateLiteral" && + (flagsNode + .expressions + .length || + flagsNode.quasis.some( + ({ + value: { + raw, + }, + }) => + raw.includes( + "\\", + ), + )) + ) { + return null; + } + + return fixer.replaceText( + flagsNode, + flagsNodeText.replace( + flag, + replaceFlag, + ), + ); + } + + return fixer.replaceText( + flagsNode, + [ + flagsNodeText.slice( + 0, + flagsNodeText.length - + 1, + ), + flagsNodeText.slice( + flagsNodeText.length - + 1, + ), + ].join( + replaceFlag, + ), + ); + } + + // We intentionally don't suggest concatenating + "u" to non-literals + return null; + } + + const penultimateToken = + sourceCode.getLastToken( + refNode, + { skip: 1 }, + ); // skip closing parenthesis + + return fixer.insertTextAfter( + penultimateToken, + astUtils.isCommaToken( + penultimateToken, + ) + ? ` "${replaceFlag}",` + : `, "${replaceFlag}"`, + ); + }, + messageId: + requireFlag === "v" + ? "addVFlag" + : "addUFlag", + }, + ] + : null, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/require-yield.js b/node_modules/eslint/lib/rules/require-yield.js new file mode 100644 index 0000000000000000000000000000000000000000..b29000266a306f7480253f52a7d84153dd990c35 --- /dev/null +++ b/node_modules/eslint/lib/rules/require-yield.js @@ -0,0 +1,86 @@ +/** + * @fileoverview Rule to flag the generator functions that does not have yield. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require generator functions to contain `yield`", + recommended: true, + url: "https://eslint.org/docs/latest/rules/require-yield", + }, + + schema: [], + + messages: { + missingYield: "This generator function does not have 'yield'.", + }, + }, + + create(context) { + const stack = []; + const sourceCode = context.sourceCode; + + /** + * If the node is a generator function, start counting `yield` keywords. + * @param {Node} node A function node to check. + * @returns {void} + */ + function beginChecking(node) { + if (node.generator) { + stack.push(0); + } + } + + /** + * If the node is a generator function, end counting `yield` keywords, then + * reports result. + * @param {Node} node A function node to check. + * @returns {void} + */ + function endChecking(node) { + if (!node.generator) { + return; + } + + const countYield = stack.pop(); + + if (countYield === 0 && node.body.body.length > 0) { + context.report({ + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + messageId: "missingYield", + }); + } + } + + return { + FunctionDeclaration: beginChecking, + "FunctionDeclaration:exit": endChecking, + FunctionExpression: beginChecking, + "FunctionExpression:exit": endChecking, + + // Increases the count of `yield` keyword. + YieldExpression() { + if (stack.length > 0) { + stack[stack.length - 1] += 1; + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/rest-spread-spacing.js b/node_modules/eslint/lib/rules/rest-spread-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..bcd1c960e962204be5404cd9706bfd0560ac4686 --- /dev/null +++ b/node_modules/eslint/lib/rules/rest-spread-spacing.js @@ -0,0 +1,150 @@ +/** + * @fileoverview Enforce spacing between rest and spread operators and their expressions. + * @author Kai Cataldo + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "rest-spread-spacing", + url: "https://eslint.style/rules/rest-spread-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce spacing between rest and spread operators and their expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/rest-spread-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + ], + + messages: { + unexpectedWhitespace: + "Unexpected whitespace after {{type}} operator.", + expectedWhitespace: "Expected whitespace after {{type}} operator.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode, + alwaysSpace = context.options[0] === "always"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks whitespace between rest/spread operators and their expressions + * @param {ASTNode} node The node to check + * @returns {void} + */ + function checkWhiteSpace(node) { + const operator = sourceCode.getFirstToken(node), + nextToken = sourceCode.getTokenAfter(operator), + hasWhitespace = sourceCode.isSpaceBetween(operator, nextToken); + let type; + + switch (node.type) { + case "SpreadElement": + type = "spread"; + if (node.parent.type === "ObjectExpression") { + type += " property"; + } + break; + case "RestElement": + type = "rest"; + if (node.parent.type === "ObjectPattern") { + type += " property"; + } + break; + case "ExperimentalSpreadProperty": + type = "spread property"; + break; + case "ExperimentalRestProperty": + type = "rest property"; + break; + default: + return; + } + + if (alwaysSpace && !hasWhitespace) { + context.report({ + node, + loc: operator.loc, + messageId: "expectedWhitespace", + data: { + type, + }, + fix(fixer) { + return fixer.replaceTextRange( + [operator.range[1], nextToken.range[0]], + " ", + ); + }, + }); + } else if (!alwaysSpace && hasWhitespace) { + context.report({ + node, + loc: { + start: operator.loc.end, + end: nextToken.loc.start, + }, + messageId: "unexpectedWhitespace", + data: { + type, + }, + fix(fixer) { + return fixer.removeRange([ + operator.range[1], + nextToken.range[0], + ]); + }, + }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + SpreadElement: checkWhiteSpace, + RestElement: checkWhiteSpace, + ExperimentalSpreadProperty: checkWhiteSpace, + ExperimentalRestProperty: checkWhiteSpace, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/semi-spacing.js b/node_modules/eslint/lib/rules/semi-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..4d00d978a46b0345ec588b8357d01999ced5b262 --- /dev/null +++ b/node_modules/eslint/lib/rules/semi-spacing.js @@ -0,0 +1,297 @@ +/** + * @fileoverview Validates spacing before and after semicolon + * @author Mathias Schreck + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "semi-spacing", + url: "https://eslint.style/rules/semi-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing before and after semicolons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/semi-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { + type: "boolean", + default: false, + }, + after: { + type: "boolean", + default: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedWhitespaceBefore: + "Unexpected whitespace before semicolon.", + unexpectedWhitespaceAfter: "Unexpected whitespace after semicolon.", + missingWhitespaceBefore: "Missing whitespace before semicolon.", + missingWhitespaceAfter: "Missing whitespace after semicolon.", + }, + }, + + create(context) { + const config = context.options[0], + sourceCode = context.sourceCode; + let requireSpaceBefore = false, + requireSpaceAfter = true; + + if (typeof config === "object") { + requireSpaceBefore = config.before; + requireSpaceAfter = config.after; + } + + /** + * Checks if a given token has leading whitespace. + * @param {Object} token The token to check. + * @returns {boolean} True if the given token has leading space, false if not. + */ + function hasLeadingSpace(token) { + const tokenBefore = sourceCode.getTokenBefore(token); + + return ( + tokenBefore && + astUtils.isTokenOnSameLine(tokenBefore, token) && + sourceCode.isSpaceBetween(tokenBefore, token) + ); + } + + /** + * Checks if a given token has trailing whitespace. + * @param {Object} token The token to check. + * @returns {boolean} True if the given token has trailing space, false if not. + */ + function hasTrailingSpace(token) { + const tokenAfter = sourceCode.getTokenAfter(token); + + return ( + tokenAfter && + astUtils.isTokenOnSameLine(token, tokenAfter) && + sourceCode.isSpaceBetween(token, tokenAfter) + ); + } + + /** + * Checks if the given token is the last token in its line. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the token is the last in its line. + */ + function isLastTokenInCurrentLine(token) { + const tokenAfter = sourceCode.getTokenAfter(token); + + return !( + tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter) + ); + } + + /** + * Checks if the given token is the first token in its line + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the token is the first in its line. + */ + function isFirstTokenInCurrentLine(token) { + const tokenBefore = sourceCode.getTokenBefore(token); + + return !( + tokenBefore && astUtils.isTokenOnSameLine(token, tokenBefore) + ); + } + + /** + * Checks if the next token of a given token is a closing parenthesis. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the next token of a given token is a closing parenthesis. + */ + function isBeforeClosingParen(token) { + const nextToken = sourceCode.getTokenAfter(token); + + return ( + (nextToken && astUtils.isClosingBraceToken(nextToken)) || + astUtils.isClosingParenToken(nextToken) + ); + } + + /** + * Report location example : + * + * for unexpected space `before` + * + * var a = 'b' ; + * ^^^ + * + * for unexpected space `after` + * + * var a = 'b'; c = 10; + * ^^ + * + * Reports if the given token has invalid spacing. + * @param {Token} token The semicolon token to check. + * @param {ASTNode} node The corresponding node of the token. + * @returns {void} + */ + function checkSemicolonSpacing(token, node) { + if (astUtils.isSemicolonToken(token)) { + if (hasLeadingSpace(token)) { + if (!requireSpaceBefore) { + const tokenBefore = sourceCode.getTokenBefore(token); + const loc = { + start: tokenBefore.loc.end, + end: token.loc.start, + }; + + context.report({ + node, + loc, + messageId: "unexpectedWhitespaceBefore", + fix(fixer) { + return fixer.removeRange([ + tokenBefore.range[1], + token.range[0], + ]); + }, + }); + } + } else { + if (requireSpaceBefore) { + const loc = token.loc; + + context.report({ + node, + loc, + messageId: "missingWhitespaceBefore", + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + } + + if ( + !isFirstTokenInCurrentLine(token) && + !isLastTokenInCurrentLine(token) && + !isBeforeClosingParen(token) + ) { + if (hasTrailingSpace(token)) { + if (!requireSpaceAfter) { + const tokenAfter = sourceCode.getTokenAfter(token); + const loc = { + start: token.loc.end, + end: tokenAfter.loc.start, + }; + + context.report({ + node, + loc, + messageId: "unexpectedWhitespaceAfter", + fix(fixer) { + return fixer.removeRange([ + token.range[1], + tokenAfter.range[0], + ]); + }, + }); + } + } else { + if (requireSpaceAfter) { + const loc = token.loc; + + context.report({ + node, + loc, + messageId: "missingWhitespaceAfter", + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + } + } + } + } + + /** + * Checks the spacing of the semicolon with the assumption that the last token is the semicolon. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNode(node) { + const token = sourceCode.getLastToken(node); + + checkSemicolonSpacing(token, node); + } + + return { + VariableDeclaration: checkNode, + ExpressionStatement: checkNode, + BreakStatement: checkNode, + ContinueStatement: checkNode, + DebuggerStatement: checkNode, + DoWhileStatement: checkNode, + ReturnStatement: checkNode, + ThrowStatement: checkNode, + ImportDeclaration: checkNode, + ExportNamedDeclaration: checkNode, + ExportAllDeclaration: checkNode, + ExportDefaultDeclaration: checkNode, + ForStatement(node) { + if (node.init) { + checkSemicolonSpacing( + sourceCode.getTokenAfter(node.init), + node, + ); + } + + if (node.test) { + checkSemicolonSpacing( + sourceCode.getTokenAfter(node.test), + node, + ); + } + }, + PropertyDefinition: checkNode, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/semi-style.js b/node_modules/eslint/lib/rules/semi-style.js new file mode 100644 index 0000000000000000000000000000000000000000..43b32e1486f7286f36778c8d8a84ceedfad9b125 --- /dev/null +++ b/node_modules/eslint/lib/rules/semi-style.js @@ -0,0 +1,218 @@ +/** + * @fileoverview Rule to enforce location of semicolons. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const SELECTOR = [ + "BreakStatement", + "ContinueStatement", + "DebuggerStatement", + "DoWhileStatement", + "ExportAllDeclaration", + "ExportDefaultDeclaration", + "ExportNamedDeclaration", + "ExpressionStatement", + "ImportDeclaration", + "ReturnStatement", + "ThrowStatement", + "VariableDeclaration", + "PropertyDefinition", +].join(","); + +/** + * Get the child node list of a given node. + * This returns `BlockStatement#body`, `StaticBlock#body`, `Program#body`, + * `ClassBody#body`, or `SwitchCase#consequent`. + * This is used to check whether a node is the first/last child. + * @param {Node} node A node to get child node list. + * @returns {Node[]|null} The child node list. + */ +function getChildren(node) { + const t = node.type; + + if ( + t === "BlockStatement" || + t === "StaticBlock" || + t === "Program" || + t === "ClassBody" + ) { + return node.body; + } + if (t === "SwitchCase") { + return node.consequent; + } + return null; +} + +/** + * Check whether a given node is the last statement in the parent block. + * @param {Node} node A node to check. + * @returns {boolean} `true` if the node is the last statement in the parent block. + */ +function isLastChild(node) { + const t = node.parent.type; + + if ( + t === "IfStatement" && + node.parent.consequent === node && + node.parent.alternate + ) { + // before `else` keyword. + return true; + } + if (t === "DoWhileStatement") { + // before `while` keyword. + return true; + } + const nodeList = getChildren(node.parent); + + return nodeList !== null && nodeList.at(-1) === node; // before `}` or etc. +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "semi-style", + url: "https://eslint.style/rules/semi-style", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce location of semicolons", + recommended: false, + url: "https://eslint.org/docs/latest/rules/semi-style", + }, + + schema: [{ enum: ["last", "first"] }], + fixable: "whitespace", + + messages: { + expectedSemiColon: "Expected this semicolon to be at {{pos}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0] || "last"; + + /** + * Check the given semicolon token. + * @param {Token} semiToken The semicolon token to check. + * @param {"first"|"last"} expected The expected location to check. + * @returns {void} + */ + function check(semiToken, expected) { + const prevToken = sourceCode.getTokenBefore(semiToken); + const nextToken = sourceCode.getTokenAfter(semiToken); + const prevIsSameLine = + !prevToken || astUtils.isTokenOnSameLine(prevToken, semiToken); + const nextIsSameLine = + !nextToken || astUtils.isTokenOnSameLine(semiToken, nextToken); + + if ( + (expected === "last" && !prevIsSameLine) || + (expected === "first" && !nextIsSameLine) + ) { + context.report({ + loc: semiToken.loc, + messageId: "expectedSemiColon", + data: { + pos: + expected === "last" + ? "the end of the previous line" + : "the beginning of the next line", + }, + fix(fixer) { + if ( + prevToken && + nextToken && + sourceCode.commentsExistBetween( + prevToken, + nextToken, + ) + ) { + return null; + } + + const start = prevToken + ? prevToken.range[1] + : semiToken.range[0]; + const end = nextToken + ? nextToken.range[0] + : semiToken.range[1]; + const text = expected === "last" ? ";\n" : "\n;"; + + return fixer.replaceTextRange([start, end], text); + }, + }); + } + } + + return { + [SELECTOR](node) { + if (option === "first" && isLastChild(node)) { + return; + } + + const lastToken = sourceCode.getLastToken(node); + + if (astUtils.isSemicolonToken(lastToken)) { + check(lastToken, option); + } + }, + + ForStatement(node) { + const firstSemi = + node.init && + sourceCode.getTokenAfter( + node.init, + astUtils.isSemicolonToken, + ); + const secondSemi = + node.test && + sourceCode.getTokenAfter( + node.test, + astUtils.isSemicolonToken, + ); + + if (firstSemi) { + check(firstSemi, "last"); + } + if (secondSemi) { + check(secondSemi, "last"); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/semi.js b/node_modules/eslint/lib/rules/semi.js new file mode 100644 index 0000000000000000000000000000000000000000..b6d28d88e19d70066dfe0a8d8176064852d5f794 --- /dev/null +++ b/node_modules/eslint/lib/rules/semi.js @@ -0,0 +1,476 @@ +/** + * @fileoverview Rule to flag missing semicolons. + * @author Nicholas C. Zakas + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const FixTracker = require("./utils/fix-tracker"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "semi", + url: "https://eslint.style/rules/semi", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require or disallow semicolons instead of ASI", + recommended: false, + url: "https://eslint.org/docs/latest/rules/semi", + }, + + fixable: "code", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["never"], + }, + { + type: "object", + properties: { + beforeStatementContinuationChars: { + enum: ["always", "any", "never"], + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + { + type: "array", + items: [ + { + enum: ["always"], + }, + { + type: "object", + properties: { + omitLastInOneLineBlock: { type: "boolean" }, + omitLastInOneLineClassBody: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + messages: { + missingSemi: "Missing semicolon.", + extraSemi: "Extra semicolon.", + }, + }, + + create(context) { + const OPT_OUT_PATTERN = /^[-[(/+`]/u; // One of [(/+-` + const unsafeClassFieldNames = new Set(["get", "set", "static"]); + const unsafeClassFieldFollowers = new Set(["*", "in", "instanceof"]); + const options = context.options[1]; + const never = context.options[0] === "never"; + const exceptOneLine = Boolean( + options && options.omitLastInOneLineBlock, + ); + const exceptOneLineClassBody = Boolean( + options && options.omitLastInOneLineClassBody, + ); + const beforeStatementContinuationChars = + (options && options.beforeStatementContinuationChars) || "any"; + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports a semicolon error with appropriate location and message. + * @param {ASTNode} node The node with an extra or missing semicolon. + * @param {boolean} missing True if the semicolon is missing. + * @returns {void} + */ + function report(node, missing) { + const lastToken = sourceCode.getLastToken(node); + let messageId, fix, loc; + + if (!missing) { + messageId = "missingSemi"; + loc = { + start: lastToken.loc.end, + end: astUtils.getNextLocation( + sourceCode, + lastToken.loc.end, + ), + }; + fix = function (fixer) { + return fixer.insertTextAfter(lastToken, ";"); + }; + } else { + messageId = "extraSemi"; + loc = lastToken.loc; + fix = function (fixer) { + /* + * Expand the replacement range to include the surrounding + * tokens to avoid conflicting with no-extra-semi. + * https://github.com/eslint/eslint/issues/7928 + */ + return new FixTracker(fixer, sourceCode) + .retainSurroundingTokens(lastToken) + .remove(lastToken); + }; + } + + context.report({ + node, + loc, + messageId, + fix, + }); + } + + /** + * Check whether a given semicolon token is redundant. + * @param {Token} semiToken A semicolon token to check. + * @returns {boolean} `true` if the next token is `;` or `}`. + */ + function isRedundantSemi(semiToken) { + const nextToken = sourceCode.getTokenAfter(semiToken); + + return ( + !nextToken || + astUtils.isClosingBraceToken(nextToken) || + astUtils.isSemicolonToken(nextToken) + ); + } + + /** + * Check whether a given token is the closing brace of an arrow function. + * @param {Token} lastToken A token to check. + * @returns {boolean} `true` if the token is the closing brace of an arrow function. + */ + function isEndOfArrowBlock(lastToken) { + if (!astUtils.isClosingBraceToken(lastToken)) { + return false; + } + const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]); + + return ( + node.type === "BlockStatement" && + node.parent.type === "ArrowFunctionExpression" + ); + } + + /** + * Checks if a given PropertyDefinition node followed by a semicolon + * can safely remove that semicolon. It is not to safe to remove if + * the class field name is "get", "set", or "static", or if + * followed by a generator method. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node cannot have the semicolon + * removed. + */ + function maybeClassFieldAsiHazard(node) { + if (node.type !== "PropertyDefinition") { + return false; + } + + /* + * Computed property names and non-identifiers are always safe + * as they can be distinguished from keywords easily. + */ + const needsNameCheck = + !node.computed && node.key.type === "Identifier"; + + /* + * Certain names are problematic unless they also have a + * a way to distinguish between keywords and property + * names. + */ + if (needsNameCheck && unsafeClassFieldNames.has(node.key.name)) { + /* + * Special case: If the field name is `static`, + * it is only valid if the field is marked as static, + * so "static static" is okay but "static" is not. + */ + const isStaticStatic = + node.static && node.key.name === "static"; + + /* + * For other unsafe names, we only care if there is no + * initializer. No initializer = hazard. + */ + if (!isStaticStatic && !node.value) { + return true; + } + } + + const followingToken = sourceCode.getTokenAfter(node); + + return unsafeClassFieldFollowers.has(followingToken.value); + } + + /** + * Check whether a given node is on the same line with the next token. + * @param {Node} node A statement node to check. + * @returns {boolean} `true` if the node is on the same line with the next token. + */ + function isOnSameLineWithNextToken(node) { + const prevToken = sourceCode.getLastToken(node, 1); + const nextToken = sourceCode.getTokenAfter(node); + + return ( + !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken) + ); + } + + /** + * Check whether a given node can connect the next line if the next line is unreliable. + * @param {Node} node A statement node to check. + * @returns {boolean} `true` if the node can connect the next line. + */ + function maybeAsiHazardAfter(node) { + const t = node.type; + + if ( + t === "DoWhileStatement" || + t === "BreakStatement" || + t === "ContinueStatement" || + t === "DebuggerStatement" || + t === "ImportDeclaration" || + t === "ExportAllDeclaration" + ) { + return false; + } + if (t === "ReturnStatement") { + return Boolean(node.argument); + } + if (t === "ExportNamedDeclaration") { + return Boolean(node.declaration); + } + if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) { + return false; + } + + return true; + } + + /** + * Check whether a given token can connect the previous statement. + * @param {Token} token A token to check. + * @returns {boolean} `true` if the token is one of `[`, `(`, `/`, `+`, `-`, ```, `++`, and `--`. + */ + function maybeAsiHazardBefore(token) { + return ( + Boolean(token) && + OPT_OUT_PATTERN.test(token.value) && + token.value !== "++" && + token.value !== "--" + ); + } + + /** + * Check if the semicolon of a given node is unnecessary, only true if: + * - next token is a valid statement divider (`;` or `}`). + * - next token is on a new line and the node is not connectable to the new line. + * @param {Node} node A statement node to check. + * @returns {boolean} whether the semicolon is unnecessary. + */ + function canRemoveSemicolon(node) { + if (isRedundantSemi(sourceCode.getLastToken(node))) { + return true; // `;;` or `;}` + } + if (maybeClassFieldAsiHazard(node)) { + return false; + } + if (isOnSameLineWithNextToken(node)) { + return false; // One liner. + } + + // continuation characters should not apply to class fields + if ( + node.type !== "PropertyDefinition" && + beforeStatementContinuationChars === "never" && + !maybeAsiHazardAfter(node) + ) { + return true; // ASI works. This statement doesn't connect to the next. + } + if (!maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) { + return true; // ASI works. The next token doesn't connect to this statement. + } + + return false; + } + + /** + * Checks a node to see if it's the last item in a one-liner block. + * Block is any `BlockStatement` or `StaticBlock` node. Block is a one-liner if its + * braces (and consequently everything between them) are on the same line. + * @param {ASTNode} node The node to check. + * @returns {boolean} whether the node is the last item in a one-liner block. + */ + function isLastInOneLinerBlock(node) { + const parent = node.parent; + const nextToken = sourceCode.getTokenAfter(node); + + if (!nextToken || nextToken.value !== "}") { + return false; + } + + if (parent.type === "BlockStatement") { + return parent.loc.start.line === parent.loc.end.line; + } + + if (parent.type === "StaticBlock") { + const openingBrace = sourceCode.getFirstToken(parent, { + skip: 1, + }); // skip the `static` token + + return openingBrace.loc.start.line === parent.loc.end.line; + } + + return false; + } + + /** + * Checks a node to see if it's the last item in a one-liner `ClassBody` node. + * ClassBody is a one-liner if its braces (and consequently everything between them) are on the same line. + * @param {ASTNode} node The node to check. + * @returns {boolean} whether the node is the last item in a one-liner ClassBody. + */ + function isLastInOneLinerClassBody(node) { + const parent = node.parent; + const nextToken = sourceCode.getTokenAfter(node); + + if (!nextToken || nextToken.value !== "}") { + return false; + } + + if (parent.type === "ClassBody") { + return parent.loc.start.line === parent.loc.end.line; + } + + return false; + } + + /** + * Checks a node to see if it's followed by a semicolon. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkForSemicolon(node) { + const isSemi = astUtils.isSemicolonToken( + sourceCode.getLastToken(node), + ); + + if (never) { + if (isSemi && canRemoveSemicolon(node)) { + report(node, true); + } else if ( + !isSemi && + beforeStatementContinuationChars === "always" && + node.type !== "PropertyDefinition" && + maybeAsiHazardBefore(sourceCode.getTokenAfter(node)) + ) { + report(node); + } + } else { + const oneLinerBlock = + exceptOneLine && isLastInOneLinerBlock(node); + const oneLinerClassBody = + exceptOneLineClassBody && isLastInOneLinerClassBody(node); + const oneLinerBlockOrClassBody = + oneLinerBlock || oneLinerClassBody; + + if (isSemi && oneLinerBlockOrClassBody) { + report(node, true); + } else if (!isSemi && !oneLinerBlockOrClassBody) { + report(node); + } + } + } + + /** + * Checks to see if there's a semicolon after a variable declaration. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkForSemicolonForVariableDeclaration(node) { + const parent = node.parent; + + if ( + (parent.type !== "ForStatement" || parent.init !== node) && + (!/^For(?:In|Of)Statement/u.test(parent.type) || + parent.left !== node) + ) { + checkForSemicolon(node); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + VariableDeclaration: checkForSemicolonForVariableDeclaration, + ExpressionStatement: checkForSemicolon, + ReturnStatement: checkForSemicolon, + ThrowStatement: checkForSemicolon, + DoWhileStatement: checkForSemicolon, + DebuggerStatement: checkForSemicolon, + BreakStatement: checkForSemicolon, + ContinueStatement: checkForSemicolon, + ImportDeclaration: checkForSemicolon, + ExportAllDeclaration: checkForSemicolon, + ExportNamedDeclaration(node) { + if (!node.declaration) { + checkForSemicolon(node); + } + }, + ExportDefaultDeclaration(node) { + if ( + !/(?:Class|Function)Declaration/u.test( + node.declaration.type, + ) + ) { + checkForSemicolon(node); + } + }, + PropertyDefinition: checkForSemicolon, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/sort-imports.js b/node_modules/eslint/lib/rules/sort-imports.js new file mode 100644 index 0000000000000000000000000000000000000000..e97f3f05fce1e253c64621aa9bf5f0650634b31f --- /dev/null +++ b/node_modules/eslint/lib/rules/sort-imports.js @@ -0,0 +1,319 @@ +/** + * @fileoverview Rule to enforce sorted `import` declarations within modules + * @author Christian Schuller + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowSeparatedGroups: false, + ignoreCase: false, + ignoreDeclarationSort: false, + ignoreMemberSort: false, + memberSyntaxSortOrder: ["none", "all", "multiple", "single"], + }, + ], + + docs: { + description: "Enforce sorted `import` declarations within modules", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/sort-imports", + }, + + schema: [ + { + type: "object", + properties: { + ignoreCase: { + type: "boolean", + }, + memberSyntaxSortOrder: { + type: "array", + items: { + enum: ["none", "all", "multiple", "single"], + }, + uniqueItems: true, + minItems: 4, + maxItems: 4, + }, + ignoreDeclarationSort: { + type: "boolean", + }, + ignoreMemberSort: { + type: "boolean", + }, + allowSeparatedGroups: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + sortImportsAlphabetically: + "Imports should be sorted alphabetically.", + sortMembersAlphabetically: + "Member '{{memberName}}' of the import declaration should be sorted alphabetically.", + unexpectedSyntaxOrder: + "Expected '{{syntaxA}}' syntax before '{{syntaxB}}' syntax.", + }, + }, + + create(context) { + const [ + { + ignoreCase, + ignoreDeclarationSort, + ignoreMemberSort, + memberSyntaxSortOrder, + allowSeparatedGroups, + }, + ] = context.options; + const sourceCode = context.sourceCode; + let previousDeclaration = null; + + /** + * Gets the used member syntax style. + * + * import "my-module.js" --> none + * import * as myModule from "my-module.js" --> all + * import {myMember} from "my-module.js" --> single + * import {foo, bar} from "my-module.js" --> multiple + * @param {ASTNode} node the ImportDeclaration node. + * @returns {string} used member parameter style, ["all", "multiple", "single"] + */ + function usedMemberSyntax(node) { + if (node.specifiers.length === 0) { + return "none"; + } + if (node.specifiers[0].type === "ImportNamespaceSpecifier") { + return "all"; + } + if (node.specifiers.length === 1) { + return "single"; + } + return "multiple"; + } + + /** + * Gets the group by member parameter index for given declaration. + * @param {ASTNode} node the ImportDeclaration node. + * @returns {number} the declaration group by member index. + */ + function getMemberParameterGroupIndex(node) { + return memberSyntaxSortOrder.indexOf(usedMemberSyntax(node)); + } + + /** + * Gets the local name of the first imported module. + * @param {ASTNode} node the ImportDeclaration node. + * @returns {?string} the local name of the first imported module. + */ + function getFirstLocalMemberName(node) { + if (node.specifiers[0]) { + return node.specifiers[0].local.name; + } + return null; + } + + /** + * Calculates number of lines between two nodes. It is assumed that the given `left` node appears before + * the given `right` node in the source code. Lines are counted from the end of the `left` node till the + * start of the `right` node. If the given nodes are on the same line, it returns `0`, same as if they were + * on two consecutive lines. + * @param {ASTNode} left node that appears before the given `right` node. + * @param {ASTNode} right node that appears after the given `left` node. + * @returns {number} number of lines between nodes. + */ + function getNumberOfLinesBetween(left, right) { + return Math.max(right.loc.start.line - left.loc.end.line - 1, 0); + } + + return { + ImportDeclaration(node) { + if (!ignoreDeclarationSort) { + if ( + previousDeclaration && + allowSeparatedGroups && + getNumberOfLinesBetween(previousDeclaration, node) > 0 + ) { + // reset declaration sort + previousDeclaration = null; + } + + if (previousDeclaration) { + const currentMemberSyntaxGroupIndex = + getMemberParameterGroupIndex(node), + previousMemberSyntaxGroupIndex = + getMemberParameterGroupIndex( + previousDeclaration, + ); + let currentLocalMemberName = + getFirstLocalMemberName(node), + previousLocalMemberName = + getFirstLocalMemberName(previousDeclaration); + + if (ignoreCase) { + previousLocalMemberName = + previousLocalMemberName && + previousLocalMemberName.toLowerCase(); + currentLocalMemberName = + currentLocalMemberName && + currentLocalMemberName.toLowerCase(); + } + + /* + * When the current declaration uses a different member syntax, + * then check if the ordering is correct. + * Otherwise, make a default string compare (like rule sort-vars to be consistent) of the first used local member name. + */ + if ( + currentMemberSyntaxGroupIndex !== + previousMemberSyntaxGroupIndex + ) { + if ( + currentMemberSyntaxGroupIndex < + previousMemberSyntaxGroupIndex + ) { + context.report({ + node, + messageId: "unexpectedSyntaxOrder", + data: { + syntaxA: + memberSyntaxSortOrder[ + currentMemberSyntaxGroupIndex + ], + syntaxB: + memberSyntaxSortOrder[ + previousMemberSyntaxGroupIndex + ], + }, + }); + } + } else { + if ( + previousLocalMemberName && + currentLocalMemberName && + currentLocalMemberName < previousLocalMemberName + ) { + context.report({ + node, + messageId: "sortImportsAlphabetically", + }); + } + } + } + + previousDeclaration = node; + } + + if (!ignoreMemberSort) { + const importSpecifiers = node.specifiers.filter( + specifier => specifier.type === "ImportSpecifier", + ); + const getSortableName = ignoreCase + ? specifier => specifier.local.name.toLowerCase() + : specifier => specifier.local.name; + const firstUnsortedIndex = importSpecifiers + .map(getSortableName) + .findIndex( + (name, index, array) => array[index - 1] > name, + ); + + if (firstUnsortedIndex !== -1) { + context.report({ + node: importSpecifiers[firstUnsortedIndex], + messageId: "sortMembersAlphabetically", + data: { + memberName: + importSpecifiers[firstUnsortedIndex].local + .name, + }, + fix(fixer) { + if ( + importSpecifiers.some( + specifier => + sourceCode.getCommentsBefore( + specifier, + ).length || + sourceCode.getCommentsAfter( + specifier, + ).length, + ) + ) { + // If there are comments in the ImportSpecifier list, don't rearrange the specifiers. + return null; + } + + return fixer.replaceTextRange( + [ + importSpecifiers[0].range[0], + importSpecifiers.at(-1).range[1], + ], + importSpecifiers + + // Clone the importSpecifiers array to avoid mutating it + .slice() + + // Sort the array into the desired order + .sort((specifierA, specifierB) => { + const aName = + getSortableName(specifierA); + const bName = + getSortableName(specifierB); + + return aName > bName ? 1 : -1; + }) + + // Build a string out of the sorted list of import specifiers and the text between the originals + .reduce( + (sourceText, specifier, index) => { + const textAfterSpecifier = + index === + importSpecifiers.length - 1 + ? "" + : sourceCode + .getText() + .slice( + importSpecifiers[ + index + ].range[1], + importSpecifiers[ + index + + 1 + ].range[0], + ); + + return ( + sourceText + + sourceCode.getText( + specifier, + ) + + textAfterSpecifier + ); + }, + "", + ), + ); + }, + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/sort-keys.js b/node_modules/eslint/lib/rules/sort-keys.js new file mode 100644 index 0000000000000000000000000000000000000000..bbb2dc2b6b738c5af72528f884d9daf061511fe5 --- /dev/null +++ b/node_modules/eslint/lib/rules/sort-keys.js @@ -0,0 +1,268 @@ +/** + * @fileoverview Rule to require object keys to be sorted + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"), + naturalCompare = require("natural-compare"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets the property name of the given `Property` node. + * + * - If the property's key is an `Identifier` node, this returns the key's name + * whether it's a computed property or not. + * - If the property has a static name, this returns the static name. + * - Otherwise, this returns null. + * @param {ASTNode} node The `Property` node to get. + * @returns {string|null} The property name or null. + * @private + */ +function getPropertyName(node) { + const staticName = astUtils.getStaticPropertyName(node); + + if (staticName !== null) { + return staticName; + } + + return node.key.name || null; +} + +/** + * Functions which check that the given 2 names are in specific order. + * + * Postfix `I` is meant insensitive. + * Postfix `N` is meant natural. + * @private + */ +const isValidOrders = { + asc(a, b) { + return a <= b; + }, + ascI(a, b) { + return a.toLowerCase() <= b.toLowerCase(); + }, + ascN(a, b) { + return naturalCompare(a, b) <= 0; + }, + ascIN(a, b) { + return naturalCompare(a.toLowerCase(), b.toLowerCase()) <= 0; + }, + desc(a, b) { + return isValidOrders.asc(b, a); + }, + descI(a, b) { + return isValidOrders.ascI(b, a); + }, + descN(a, b) { + return isValidOrders.ascN(b, a); + }, + descIN(a, b) { + return isValidOrders.ascIN(b, a); + }, +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + "asc", + { + allowLineSeparatedGroups: false, + caseSensitive: true, + ignoreComputedKeys: false, + minKeys: 2, + natural: false, + }, + ], + + docs: { + description: "Require object keys to be sorted", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/sort-keys", + }, + + schema: [ + { + enum: ["asc", "desc"], + }, + { + type: "object", + properties: { + caseSensitive: { + type: "boolean", + }, + natural: { + type: "boolean", + }, + minKeys: { + type: "integer", + minimum: 2, + }, + allowLineSeparatedGroups: { + type: "boolean", + }, + ignoreComputedKeys: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + sortKeys: + "Expected object keys to be in {{natural}}{{insensitive}}{{order}}ending order. '{{thisName}}' should be before '{{prevName}}'.", + }, + }, + + create(context) { + const [ + order, + { + caseSensitive, + natural, + minKeys, + allowLineSeparatedGroups, + ignoreComputedKeys, + }, + ] = context.options; + const insensitive = !caseSensitive; + const isValidOrder = + isValidOrders[ + order + (insensitive ? "I" : "") + (natural ? "N" : "") + ]; + + // The stack to save the previous property's name for each object literals. + let stack = null; + const sourceCode = context.sourceCode; + + return { + ObjectExpression(node) { + stack = { + upper: stack, + prevNode: null, + prevBlankLine: false, + prevName: null, + numKeys: node.properties.length, + }; + }, + + "ObjectExpression:exit"() { + stack = stack.upper; + }, + + SpreadElement(node) { + if (node.parent.type === "ObjectExpression") { + stack.prevName = null; + } + }, + + Property(node) { + if (node.parent.type === "ObjectPattern") { + return; + } + + if (ignoreComputedKeys && node.computed) { + stack.prevName = null; // reset sort + return; + } + + const prevName = stack.prevName; + const numKeys = stack.numKeys; + const thisName = getPropertyName(node); + + // Get tokens between current node and previous node + const tokens = + stack.prevNode && + sourceCode.getTokensBetween(stack.prevNode, node, { + includeComments: true, + }); + + let isBlankLineBetweenNodes = stack.prevBlankLine; + + if (tokens) { + // check blank line between tokens + tokens.forEach((token, index) => { + const previousToken = tokens[index - 1]; + + if ( + previousToken && + token.loc.start.line - previousToken.loc.end.line > + 1 + ) { + isBlankLineBetweenNodes = true; + } + }); + + // check blank line between the current node and the last token + if ( + !isBlankLineBetweenNodes && + node.loc.start.line - tokens.at(-1).loc.end.line > 1 + ) { + isBlankLineBetweenNodes = true; + } + + // check blank line between the first token and the previous node + if ( + !isBlankLineBetweenNodes && + tokens[0].loc.start.line - stack.prevNode.loc.end.line > + 1 + ) { + isBlankLineBetweenNodes = true; + } + } + + stack.prevNode = node; + + if (thisName !== null) { + stack.prevName = thisName; + } + + if (allowLineSeparatedGroups && isBlankLineBetweenNodes) { + stack.prevBlankLine = thisName === null; + return; + } + + if ( + prevName === null || + thisName === null || + numKeys < minKeys + ) { + return; + } + + if (!isValidOrder(prevName, thisName)) { + context.report({ + node, + loc: node.key.loc, + messageId: "sortKeys", + data: { + thisName, + prevName, + order, + insensitive: insensitive ? "insensitive " : "", + natural: natural ? "natural " : "", + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/sort-vars.js b/node_modules/eslint/lib/rules/sort-vars.js new file mode 100644 index 0000000000000000000000000000000000000000..34081b955979840da76a14989435259ac52cfec8 --- /dev/null +++ b/node_modules/eslint/lib/rules/sort-vars.js @@ -0,0 +1,140 @@ +/** + * @fileoverview Rule to require sorting of variables within a single Variable Declaration block + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + ignoreCase: false, + }, + ], + + docs: { + description: + "Require variables within the same declaration block to be sorted", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/sort-vars", + }, + + schema: [ + { + type: "object", + properties: { + ignoreCase: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + sortVars: + "Variables within the same declaration block should be sorted alphabetically.", + }, + }, + + create(context) { + const [{ ignoreCase }] = context.options; + const sourceCode = context.sourceCode; + + return { + VariableDeclaration(node) { + const idDeclarations = node.declarations.filter( + decl => decl.id.type === "Identifier", + ); + const getSortableName = ignoreCase + ? decl => decl.id.name.toLowerCase() + : decl => decl.id.name; + const unfixable = idDeclarations.some( + decl => decl.init !== null && decl.init.type !== "Literal", + ); + let fixed = false; + + idDeclarations.slice(1).reduce((memo, decl) => { + const lastVariableName = getSortableName(memo), + currentVariableName = getSortableName(decl); + + if (currentVariableName < lastVariableName) { + context.report({ + node: decl, + messageId: "sortVars", + fix(fixer) { + if (unfixable || fixed) { + return null; + } + return fixer.replaceTextRange( + [ + idDeclarations[0].range[0], + idDeclarations.at(-1).range[1], + ], + idDeclarations + + // Clone the idDeclarations array to avoid mutating it + .slice() + + // Sort the array into the desired order + .sort((declA, declB) => { + const aName = + getSortableName(declA); + const bName = + getSortableName(declB); + + return aName > bName ? 1 : -1; + }) + + // Build a string out of the sorted list of identifier declarations and the text between the originals + .reduce( + (sourceText, identifier, index) => { + const textAfterIdentifier = + index === + idDeclarations.length - 1 + ? "" + : sourceCode + .getText() + .slice( + idDeclarations[ + index + ].range[1], + idDeclarations[ + index + + 1 + ].range[0], + ); + + return ( + sourceText + + sourceCode.getText( + identifier, + ) + + textAfterIdentifier + ); + }, + "", + ), + ); + }, + }); + fixed = true; + return memo; + } + return decl; + }, idDeclarations[0]); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/space-before-blocks.js b/node_modules/eslint/lib/rules/space-before-blocks.js new file mode 100644 index 0000000000000000000000000000000000000000..524a482a533deb73848bdefb1958e1588a508f1c --- /dev/null +++ b/node_modules/eslint/lib/rules/space-before-blocks.js @@ -0,0 +1,232 @@ +/** + * @fileoverview A rule to ensure whitespace before blocks. + * @author Mathias Schreck + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given node represents the body of a function. + * @param {ASTNode} node the node to check. + * @returns {boolean} `true` if the node is function body. + */ +function isFunctionBody(node) { + const parent = node.parent; + + return ( + node.type === "BlockStatement" && + astUtils.isFunction(parent) && + parent.body === node + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "space-before-blocks", + url: "https://eslint.style/rules/space-before-blocks", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing before blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-before-blocks", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + keywords: { + enum: ["always", "never", "off"], + }, + functions: { + enum: ["always", "never", "off"], + }, + classes: { + enum: ["always", "never", "off"], + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + unexpectedSpace: "Unexpected space before opening brace.", + missingSpace: "Missing space before opening brace.", + }, + }, + + create(context) { + const config = context.options[0], + sourceCode = context.sourceCode; + let alwaysFunctions = true, + alwaysKeywords = true, + alwaysClasses = true, + neverFunctions = false, + neverKeywords = false, + neverClasses = false; + + if (typeof config === "object") { + alwaysFunctions = config.functions === "always"; + alwaysKeywords = config.keywords === "always"; + alwaysClasses = config.classes === "always"; + neverFunctions = config.functions === "never"; + neverKeywords = config.keywords === "never"; + neverClasses = config.classes === "never"; + } else if (config === "never") { + alwaysFunctions = false; + alwaysKeywords = false; + alwaysClasses = false; + neverFunctions = true; + neverKeywords = true; + neverClasses = true; + } + + /** + * Checks whether the spacing before the given block is already controlled by another rule: + * - `arrow-spacing` checks spaces after `=>`. + * - `keyword-spacing` checks spaces after keywords in certain contexts. + * - `switch-colon-spacing` checks spaces after `:` of switch cases. + * @param {Token} precedingToken first token before the block. + * @param {ASTNode|Token} node `BlockStatement` node or `{` token of a `SwitchStatement` node. + * @returns {boolean} `true` if requiring or disallowing spaces before the given block could produce conflicts with other rules. + */ + function isConflicted(precedingToken, node) { + return ( + astUtils.isArrowToken(precedingToken) || + (astUtils.isKeywordToken(precedingToken) && + !isFunctionBody(node)) || + (astUtils.isColonToken(precedingToken) && + node.parent && + node.parent.type === "SwitchCase" && + precedingToken === + astUtils.getSwitchCaseColonToken( + node.parent, + sourceCode, + )) + ); + } + + /** + * Checks the given BlockStatement node has a preceding space if it doesn’t start on a new line. + * @param {ASTNode|Token} node The AST node of a BlockStatement. + * @returns {void} undefined. + */ + function checkPrecedingSpace(node) { + const precedingToken = sourceCode.getTokenBefore(node); + + if ( + precedingToken && + !isConflicted(precedingToken, node) && + astUtils.isTokenOnSameLine(precedingToken, node) + ) { + const hasSpace = sourceCode.isSpaceBetween( + precedingToken, + node, + ); + let requireSpace; + let requireNoSpace; + + if (isFunctionBody(node)) { + requireSpace = alwaysFunctions; + requireNoSpace = neverFunctions; + } else if (node.type === "ClassBody") { + requireSpace = alwaysClasses; + requireNoSpace = neverClasses; + } else { + requireSpace = alwaysKeywords; + requireNoSpace = neverKeywords; + } + + if (requireSpace && !hasSpace) { + context.report({ + node, + messageId: "missingSpace", + fix(fixer) { + return fixer.insertTextBefore(node, " "); + }, + }); + } else if (requireNoSpace && hasSpace) { + context.report({ + node, + messageId: "unexpectedSpace", + fix(fixer) { + return fixer.removeRange([ + precedingToken.range[1], + node.range[0], + ]); + }, + }); + } + } + } + + /** + * Checks if the CaseBlock of an given SwitchStatement node has a preceding space. + * @param {ASTNode} node The node of a SwitchStatement. + * @returns {void} undefined. + */ + function checkSpaceBeforeCaseBlock(node) { + const cases = node.cases; + let openingBrace; + + if (cases.length > 0) { + openingBrace = sourceCode.getTokenBefore(cases[0]); + } else { + openingBrace = sourceCode.getLastToken(node, 1); + } + + checkPrecedingSpace(openingBrace); + } + + return { + BlockStatement: checkPrecedingSpace, + ClassBody: checkPrecedingSpace, + SwitchStatement: checkSpaceBeforeCaseBlock, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/space-before-function-paren.js b/node_modules/eslint/lib/rules/space-before-function-paren.js new file mode 100644 index 0000000000000000000000000000000000000000..2a55550420b017435dc0ff61ed7eb0a00bd02ca9 --- /dev/null +++ b/node_modules/eslint/lib/rules/space-before-function-paren.js @@ -0,0 +1,202 @@ +/** + * @fileoverview Rule to validate spacing before function paren. + * @author Mathias Schreck + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "space-before-function-paren", + url: "https://eslint.style/rules/space-before-function-paren", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing before `function` definition opening parenthesis", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-before-function-paren", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + anonymous: { + enum: ["always", "never", "ignore"], + }, + named: { + enum: ["always", "never", "ignore"], + }, + asyncArrow: { + enum: ["always", "never", "ignore"], + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + unexpectedSpace: "Unexpected space before function parentheses.", + missingSpace: "Missing space before function parentheses.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const baseConfig = + typeof context.options[0] === "string" + ? context.options[0] + : "always"; + const overrideConfig = + typeof context.options[0] === "object" ? context.options[0] : {}; + + /** + * Determines whether a function has a name. + * @param {ASTNode} node The function node. + * @returns {boolean} Whether the function has a name. + */ + function isNamedFunction(node) { + if (node.id) { + return true; + } + + const parent = node.parent; + + return ( + parent.type === "MethodDefinition" || + (parent.type === "Property" && + (parent.kind === "get" || + parent.kind === "set" || + parent.method)) + ); + } + + /** + * Gets the config for a given function + * @param {ASTNode} node The function node + * @returns {string} "always", "never", or "ignore" + */ + function getConfigForFunction(node) { + if (node.type === "ArrowFunctionExpression") { + // Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar + if ( + node.async && + astUtils.isOpeningParenToken( + sourceCode.getFirstToken(node, { skip: 1 }), + ) + ) { + return overrideConfig.asyncArrow || baseConfig; + } + } else if (isNamedFunction(node)) { + return overrideConfig.named || baseConfig; + + // `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}` + } else if (!node.generator) { + return overrideConfig.anonymous || baseConfig; + } + + return "ignore"; + } + + /** + * Checks the parens of a function node + * @param {ASTNode} node A function node + * @returns {void} + */ + function checkFunction(node) { + const functionConfig = getConfigForFunction(node); + + if (functionConfig === "ignore") { + return; + } + + const rightToken = sourceCode.getFirstToken( + node, + astUtils.isOpeningParenToken, + ); + const leftToken = sourceCode.getTokenBefore(rightToken); + const hasSpacing = sourceCode.isSpaceBetween(leftToken, rightToken); + + if (hasSpacing && functionConfig === "never") { + context.report({ + node, + loc: { + start: leftToken.loc.end, + end: rightToken.loc.start, + }, + messageId: "unexpectedSpace", + fix(fixer) { + const comments = + sourceCode.getCommentsBefore(rightToken); + + // Don't fix anything if there's a single line comment between the left and the right token + if (comments.some(comment => comment.type === "Line")) { + return null; + } + return fixer.replaceTextRange( + [leftToken.range[1], rightToken.range[0]], + comments.reduce( + (text, comment) => + text + sourceCode.getText(comment), + "", + ), + ); + }, + }); + } else if (!hasSpacing && functionConfig === "always") { + context.report({ + node, + loc: rightToken.loc, + messageId: "missingSpace", + fix: fixer => fixer.insertTextAfter(leftToken, " "), + }); + } + } + + return { + ArrowFunctionExpression: checkFunction, + FunctionDeclaration: checkFunction, + FunctionExpression: checkFunction, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/space-in-parens.js b/node_modules/eslint/lib/rules/space-in-parens.js new file mode 100644 index 0000000000000000000000000000000000000000..d4deaee22966603edc67593999fe9422b0f757e3 --- /dev/null +++ b/node_modules/eslint/lib/rules/space-in-parens.js @@ -0,0 +1,374 @@ +/** + * @fileoverview Disallows or enforces spaces inside of parentheses. + * @author Jonathan Rajavuori + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "space-in-parens", + url: "https://eslint.style/rules/space-in-parens", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing inside parentheses", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-in-parens", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + enum: ["{}", "[]", "()", "empty"], + }, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missingOpeningSpace: "There must be a space after this paren.", + missingClosingSpace: "There must be a space before this paren.", + rejectedOpeningSpace: "There should be no space after this paren.", + rejectedClosingSpace: "There should be no space before this paren.", + }, + }, + + create(context) { + const ALWAYS = context.options[0] === "always", + exceptionsArrayOptions = + (context.options[1] && context.options[1].exceptions) || [], + options = {}; + + let exceptions; + + if (exceptionsArrayOptions.length) { + options.braceException = exceptionsArrayOptions.includes("{}"); + options.bracketException = exceptionsArrayOptions.includes("[]"); + options.parenException = exceptionsArrayOptions.includes("()"); + options.empty = exceptionsArrayOptions.includes("empty"); + } + + /** + * Produces an object with the opener and closer exception values + * @returns {Object} `openers` and `closers` exception values + * @private + */ + function getExceptions() { + const openers = [], + closers = []; + + if (options.braceException) { + openers.push("{"); + closers.push("}"); + } + + if (options.bracketException) { + openers.push("["); + closers.push("]"); + } + + if (options.parenException) { + openers.push("("); + closers.push(")"); + } + + if (options.empty) { + openers.push(")"); + closers.push("("); + } + + return { + openers, + closers, + }; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + const sourceCode = context.sourceCode; + + /** + * Determines if a token is one of the exceptions for the opener paren + * @param {Object} token The token to check + * @returns {boolean} True if the token is one of the exceptions for the opener paren + */ + function isOpenerException(token) { + return exceptions.openers.includes(token.value); + } + + /** + * Determines if a token is one of the exceptions for the closer paren + * @param {Object} token The token to check + * @returns {boolean} True if the token is one of the exceptions for the closer paren + */ + function isCloserException(token) { + return exceptions.closers.includes(token.value); + } + + /** + * Determines if an opening paren is immediately followed by a required space + * @param {Object} openingParenToken The paren token + * @param {Object} tokenAfterOpeningParen The token after it + * @returns {boolean} True if the opening paren is missing a required space + */ + function openerMissingSpace(openingParenToken, tokenAfterOpeningParen) { + if ( + sourceCode.isSpaceBetween( + openingParenToken, + tokenAfterOpeningParen, + ) + ) { + return false; + } + + if ( + !options.empty && + astUtils.isClosingParenToken(tokenAfterOpeningParen) + ) { + return false; + } + + if (ALWAYS) { + return !isOpenerException(tokenAfterOpeningParen); + } + return isOpenerException(tokenAfterOpeningParen); + } + + /** + * Determines if an opening paren is immediately followed by a disallowed space + * @param {Object} openingParenToken The paren token + * @param {Object} tokenAfterOpeningParen The token after it + * @returns {boolean} True if the opening paren has a disallowed space + */ + function openerRejectsSpace(openingParenToken, tokenAfterOpeningParen) { + if ( + !astUtils.isTokenOnSameLine( + openingParenToken, + tokenAfterOpeningParen, + ) + ) { + return false; + } + + if (tokenAfterOpeningParen.type === "Line") { + return false; + } + + if ( + !sourceCode.isSpaceBetween( + openingParenToken, + tokenAfterOpeningParen, + ) + ) { + return false; + } + + if (ALWAYS) { + return isOpenerException(tokenAfterOpeningParen); + } + return !isOpenerException(tokenAfterOpeningParen); + } + + /** + * Determines if a closing paren is immediately preceded by a required space + * @param {Object} tokenBeforeClosingParen The token before the paren + * @param {Object} closingParenToken The paren token + * @returns {boolean} True if the closing paren is missing a required space + */ + function closerMissingSpace( + tokenBeforeClosingParen, + closingParenToken, + ) { + if ( + sourceCode.isSpaceBetween( + tokenBeforeClosingParen, + closingParenToken, + ) + ) { + return false; + } + + if ( + !options.empty && + astUtils.isOpeningParenToken(tokenBeforeClosingParen) + ) { + return false; + } + + if (ALWAYS) { + return !isCloserException(tokenBeforeClosingParen); + } + return isCloserException(tokenBeforeClosingParen); + } + + /** + * Determines if a closer paren is immediately preceded by a disallowed space + * @param {Object} tokenBeforeClosingParen The token before the paren + * @param {Object} closingParenToken The paren token + * @returns {boolean} True if the closing paren has a disallowed space + */ + function closerRejectsSpace( + tokenBeforeClosingParen, + closingParenToken, + ) { + if ( + !astUtils.isTokenOnSameLine( + tokenBeforeClosingParen, + closingParenToken, + ) + ) { + return false; + } + + if ( + !sourceCode.isSpaceBetween( + tokenBeforeClosingParen, + closingParenToken, + ) + ) { + return false; + } + + if (ALWAYS) { + return isCloserException(tokenBeforeClosingParen); + } + return !isCloserException(tokenBeforeClosingParen); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkParenSpaces(node) { + exceptions = getExceptions(); + const tokens = sourceCode.tokensAndComments; + + tokens.forEach((token, i) => { + const prevToken = tokens[i - 1]; + const nextToken = tokens[i + 1]; + + // if token is not an opening or closing paren token, do nothing + if ( + !astUtils.isOpeningParenToken(token) && + !astUtils.isClosingParenToken(token) + ) { + return; + } + + // if token is an opening paren and is not followed by a required space + if ( + token.value === "(" && + openerMissingSpace(token, nextToken) + ) { + context.report({ + node, + loc: token.loc, + messageId: "missingOpeningSpace", + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + + // if token is an opening paren and is followed by a disallowed space + if ( + token.value === "(" && + openerRejectsSpace(token, nextToken) + ) { + context.report({ + node, + loc: { + start: token.loc.end, + end: nextToken.loc.start, + }, + messageId: "rejectedOpeningSpace", + fix(fixer) { + return fixer.removeRange([ + token.range[1], + nextToken.range[0], + ]); + }, + }); + } + + // if token is a closing paren and is not preceded by a required space + if ( + token.value === ")" && + closerMissingSpace(prevToken, token) + ) { + context.report({ + node, + loc: token.loc, + messageId: "missingClosingSpace", + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + + // if token is a closing paren and is preceded by a disallowed space + if ( + token.value === ")" && + closerRejectsSpace(prevToken, token) + ) { + context.report({ + node, + loc: { + start: prevToken.loc.end, + end: token.loc.start, + }, + messageId: "rejectedClosingSpace", + fix(fixer) { + return fixer.removeRange([ + prevToken.range[1], + token.range[0], + ]); + }, + }); + } + }); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/space-infix-ops.js b/node_modules/eslint/lib/rules/space-infix-ops.js new file mode 100644 index 0000000000000000000000000000000000000000..4b2f619d2509923d74c3e7a5991ebc133ef4f1be --- /dev/null +++ b/node_modules/eslint/lib/rules/space-infix-ops.js @@ -0,0 +1,249 @@ +/** + * @fileoverview Require spaces around infix operators + * @author Michael Ficarra + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const { isEqToken } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "space-infix-ops", + url: "https://eslint.style/rules/space-infix-ops", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require spacing around infix operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-infix-ops", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + int32Hint: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missingSpace: "Operator '{{operator}}' must be spaced.", + }, + }, + + create(context) { + const int32Hint = context.options[0] + ? context.options[0].int32Hint === true + : false; + const sourceCode = context.sourceCode; + + /** + * Returns the first token which violates the rule + * @param {ASTNode} left The left node of the main node + * @param {ASTNode} right The right node of the main node + * @param {string} op The operator of the main node + * @returns {Object} The violator token or null + * @private + */ + function getFirstNonSpacedToken(left, right, op) { + const operator = sourceCode.getFirstTokenBetween( + left, + right, + token => token.value === op, + ); + const prev = sourceCode.getTokenBefore(operator); + const next = sourceCode.getTokenAfter(operator); + + if ( + !sourceCode.isSpaceBetween(prev, operator) || + !sourceCode.isSpaceBetween(operator, next) + ) { + return operator; + } + + return null; + } + + /** + * Reports an AST node as a rule violation + * @param {ASTNode} mainNode The node to report + * @param {Object} culpritToken The token which has a problem + * @returns {void} + * @private + */ + function report(mainNode, culpritToken) { + context.report({ + node: mainNode, + loc: culpritToken.loc, + messageId: "missingSpace", + data: { + operator: culpritToken.value, + }, + fix(fixer) { + const previousToken = + sourceCode.getTokenBefore(culpritToken); + const afterToken = sourceCode.getTokenAfter(culpritToken); + let fixString = ""; + + if (culpritToken.range[0] - previousToken.range[1] === 0) { + fixString = " "; + } + + fixString += culpritToken.value; + + if (afterToken.range[0] - culpritToken.range[1] === 0) { + fixString += " "; + } + + return fixer.replaceText(culpritToken, fixString); + }, + }); + } + + /** + * Check if the node is binary then report + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkBinary(node) { + const leftNode = node.left.typeAnnotation + ? node.left.typeAnnotation + : node.left; + const rightNode = node.right; + + // search for = in AssignmentPattern nodes + const operator = node.operator || "="; + + const nonSpacedNode = getFirstNonSpacedToken( + leftNode, + rightNode, + operator, + ); + + if (nonSpacedNode) { + if (!(int32Hint && sourceCode.getText(node).endsWith("|0"))) { + report(node, nonSpacedNode); + } + } + } + + /** + * Check if the node is conditional + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkConditional(node) { + const nonSpacedConsequentNode = getFirstNonSpacedToken( + node.test, + node.consequent, + "?", + ); + const nonSpacedAlternateNode = getFirstNonSpacedToken( + node.consequent, + node.alternate, + ":", + ); + + if (nonSpacedConsequentNode) { + report(node, nonSpacedConsequentNode); + } + + if (nonSpacedAlternateNode) { + report(node, nonSpacedAlternateNode); + } + } + + /** + * Check if the node is a variable + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkVar(node) { + const leftNode = node.id.typeAnnotation + ? node.id.typeAnnotation + : node.id; + const rightNode = node.init; + + if (rightNode) { + const nonSpacedNode = getFirstNonSpacedToken( + leftNode, + rightNode, + "=", + ); + + if (nonSpacedNode) { + report(node, nonSpacedNode); + } + } + } + + return { + AssignmentExpression: checkBinary, + AssignmentPattern: checkBinary, + BinaryExpression: checkBinary, + LogicalExpression: checkBinary, + ConditionalExpression: checkConditional, + VariableDeclarator: checkVar, + + PropertyDefinition(node) { + if (!node.value) { + return; + } + + /* + * Because of computed properties and type annotations, some + * tokens may exist between `node.key` and `=`. + * Therefore, find the `=` from the right. + */ + const operatorToken = sourceCode.getTokenBefore( + node.value, + isEqToken, + ); + const leftToken = sourceCode.getTokenBefore(operatorToken); + const rightToken = sourceCode.getTokenAfter(operatorToken); + + if ( + !sourceCode.isSpaceBetween(leftToken, operatorToken) || + !sourceCode.isSpaceBetween(operatorToken, rightToken) + ) { + report(node, operatorToken); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/space-unary-ops.js b/node_modules/eslint/lib/rules/space-unary-ops.js new file mode 100644 index 0000000000000000000000000000000000000000..ee58714741b1b6a2052aaef924f341f3836f9261 --- /dev/null +++ b/node_modules/eslint/lib/rules/space-unary-ops.js @@ -0,0 +1,400 @@ +/** + * @fileoverview This rule should require or disallow spaces before or after unary operations. + * @author Marcin Kumorek + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "space-unary-ops", + url: "https://eslint.style/rules/space-unary-ops", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing before or after unary operators", + recommended: false, + url: "https://eslint.org/docs/latest/rules/space-unary-ops", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + words: { + type: "boolean", + default: true, + }, + nonwords: { + type: "boolean", + default: false, + }, + overrides: { + type: "object", + additionalProperties: { + type: "boolean", + }, + }, + }, + additionalProperties: false, + }, + ], + messages: { + unexpectedBefore: + "Unexpected space before unary operator '{{operator}}'.", + unexpectedAfter: + "Unexpected space after unary operator '{{operator}}'.", + unexpectedAfterWord: + "Unexpected space after unary word operator '{{word}}'.", + wordOperator: + "Unary word operator '{{word}}' must be followed by whitespace.", + operator: + "Unary operator '{{operator}}' must be followed by whitespace.", + beforeUnaryExpressions: + "Space is required before unary expressions '{{token}}'.", + }, + }, + + create(context) { + const options = context.options[0] || { words: true, nonwords: false }; + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if the node is the first "!" in a "!!" convert to Boolean expression + * @param {ASTnode} node AST node + * @returns {boolean} Whether or not the node is first "!" in "!!" + */ + function isFirstBangInBangBangExpression(node) { + return ( + node && + node.type === "UnaryExpression" && + node.argument.operator === "!" && + node.argument && + node.argument.type === "UnaryExpression" && + node.argument.operator === "!" + ); + } + + /** + * Checks if an override exists for a given operator. + * @param {string} operator Operator + * @returns {boolean} Whether or not an override has been provided for the operator + */ + function overrideExistsForOperator(operator) { + return ( + options.overrides && Object.hasOwn(options.overrides, operator) + ); + } + + /** + * Gets the value that the override was set to for this operator + * @param {string} operator Operator + * @returns {boolean} Whether or not an override enforces a space with this operator + */ + function overrideEnforcesSpaces(operator) { + return options.overrides[operator]; + } + + /** + * Verify Unary Word Operator has spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ + function verifyWordHasSpaces(node, firstToken, secondToken, word) { + if (secondToken.range[0] === firstToken.range[1]) { + context.report({ + node, + messageId: "wordOperator", + data: { + word, + }, + fix(fixer) { + return fixer.insertTextAfter(firstToken, " "); + }, + }); + } + } + + /** + * Verify Unary Word Operator doesn't have spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ + function verifyWordDoesntHaveSpaces( + node, + firstToken, + secondToken, + word, + ) { + if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) { + if (secondToken.range[0] > firstToken.range[1]) { + context.report({ + node, + messageId: "unexpectedAfterWord", + data: { + word, + }, + fix(fixer) { + return fixer.removeRange([ + firstToken.range[1], + secondToken.range[0], + ]); + }, + }); + } + } + } + + /** + * Check Unary Word Operators for spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ + function checkUnaryWordOperatorForSpaces( + node, + firstToken, + secondToken, + word, + ) { + if (overrideExistsForOperator(word)) { + if (overrideEnforcesSpaces(word)) { + verifyWordHasSpaces(node, firstToken, secondToken, word); + } else { + verifyWordDoesntHaveSpaces( + node, + firstToken, + secondToken, + word, + ); + } + } else if (options.words) { + verifyWordHasSpaces(node, firstToken, secondToken, word); + } else { + verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word); + } + } + + /** + * Verifies YieldExpressions satisfy spacing requirements + * @param {ASTnode} node AST node + * @returns {void} + */ + function checkForSpacesAfterYield(node) { + const tokens = sourceCode.getFirstTokens(node, 3), + word = "yield"; + + if (!node.argument || node.delegate) { + return; + } + + checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], word); + } + + /** + * Verifies AwaitExpressions satisfy spacing requirements + * @param {ASTNode} node AwaitExpression AST node + * @returns {void} + */ + function checkForSpacesAfterAwait(node) { + const tokens = sourceCode.getFirstTokens(node, 3); + + checkUnaryWordOperatorForSpaces( + node, + tokens[0], + tokens[1], + "await", + ); + } + + /** + * Verifies UnaryExpression, UpdateExpression and NewExpression have spaces before or after the operator + * @param {ASTnode} node AST node + * @param {Object} firstToken First token in the expression + * @param {Object} secondToken Second token in the expression + * @returns {void} + */ + function verifyNonWordsHaveSpaces(node, firstToken, secondToken) { + if (node.prefix) { + if (isFirstBangInBangBangExpression(node)) { + return; + } + if (firstToken.range[1] === secondToken.range[0]) { + context.report({ + node, + messageId: "operator", + data: { + operator: firstToken.value, + }, + fix(fixer) { + return fixer.insertTextAfter(firstToken, " "); + }, + }); + } + } else { + if (firstToken.range[1] === secondToken.range[0]) { + context.report({ + node, + messageId: "beforeUnaryExpressions", + data: { + token: secondToken.value, + }, + fix(fixer) { + return fixer.insertTextBefore(secondToken, " "); + }, + }); + } + } + } + + /** + * Verifies UnaryExpression, UpdateExpression and NewExpression don't have spaces before or after the operator + * @param {ASTnode} node AST node + * @param {Object} firstToken First token in the expression + * @param {Object} secondToken Second token in the expression + * @returns {void} + */ + function verifyNonWordsDontHaveSpaces(node, firstToken, secondToken) { + if (node.prefix) { + if (secondToken.range[0] > firstToken.range[1]) { + context.report({ + node, + messageId: "unexpectedAfter", + data: { + operator: firstToken.value, + }, + fix(fixer) { + if ( + astUtils.canTokensBeAdjacent( + firstToken, + secondToken, + ) + ) { + return fixer.removeRange([ + firstToken.range[1], + secondToken.range[0], + ]); + } + return null; + }, + }); + } + } else { + if (secondToken.range[0] > firstToken.range[1]) { + context.report({ + node, + messageId: "unexpectedBefore", + data: { + operator: secondToken.value, + }, + fix(fixer) { + return fixer.removeRange([ + firstToken.range[1], + secondToken.range[0], + ]); + }, + }); + } + } + } + + /** + * Verifies UnaryExpression, UpdateExpression and NewExpression satisfy spacing requirements + * @param {ASTnode} node AST node + * @returns {void} + */ + function checkForSpaces(node) { + const tokens = + node.type === "UpdateExpression" && !node.prefix + ? sourceCode.getLastTokens(node, 2) + : sourceCode.getFirstTokens(node, 2); + const firstToken = tokens[0]; + const secondToken = tokens[1]; + + if ( + (node.type === "NewExpression" || node.prefix) && + firstToken.type === "Keyword" + ) { + checkUnaryWordOperatorForSpaces( + node, + firstToken, + secondToken, + firstToken.value, + ); + return; + } + + const operator = node.prefix ? tokens[0].value : tokens[1].value; + + if (overrideExistsForOperator(operator)) { + if (overrideEnforcesSpaces(operator)) { + verifyNonWordsHaveSpaces(node, firstToken, secondToken); + } else { + verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); + } + } else if (options.nonwords) { + verifyNonWordsHaveSpaces(node, firstToken, secondToken); + } else { + verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + UnaryExpression: checkForSpaces, + UpdateExpression: checkForSpaces, + NewExpression: checkForSpaces, + YieldExpression: checkForSpacesAfterYield, + AwaitExpression: checkForSpacesAfterAwait, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/spaced-comment.js b/node_modules/eslint/lib/rules/spaced-comment.js new file mode 100644 index 0000000000000000000000000000000000000000..cb2a97822ed5a6e14d5cfcb5a25b019404a7a592 --- /dev/null +++ b/node_modules/eslint/lib/rules/spaced-comment.js @@ -0,0 +1,447 @@ +/** + * @fileoverview Source code for spaced-comments rule + * @author Gyandeep Singh + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const escapeRegExp = require("escape-string-regexp"); +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Escapes the control characters of a given string. + * @param {string} s A string to escape. + * @returns {string} An escaped string. + */ +function escape(s) { + return `(?:${escapeRegExp(s)})`; +} + +/** + * Escapes the control characters of a given string. + * And adds a repeat flag. + * @param {string} s A string to escape. + * @returns {string} An escaped string. + */ +function escapeAndRepeat(s) { + return `${escape(s)}+`; +} + +/** + * Parses `markers` option. + * If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments. + * @param {string[]} [markers] A marker list. + * @returns {string[]} A marker list. + */ +function parseMarkersOption(markers) { + // `*` is a marker for JSDoc comments. + if (!markers.includes("*")) { + return markers.concat("*"); + } + + return markers; +} + +/** + * Creates string pattern for exceptions. + * Generated pattern: + * + * 1. A space or an exception pattern sequence. + * @param {string[]} exceptions An exception pattern list. + * @returns {string} A regular expression string for exceptions. + */ +function createExceptionsPattern(exceptions) { + let pattern = ""; + + /* + * A space or an exception pattern sequence. + * [] ==> "\s" + * ["-"] ==> "(?:\s|\-+$)" + * ["-", "="] ==> "(?:\s|(?:\-+|=+)$)" + * ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24) + */ + if (exceptions.length === 0) { + // a space. + pattern += "\\s"; + } else { + // a space or... + pattern += "(?:\\s|"; + + if (exceptions.length === 1) { + // a sequence of the exception pattern. + pattern += escapeAndRepeat(exceptions[0]); + } else { + // a sequence of one of the exception patterns. + pattern += "(?:"; + pattern += exceptions.map(escapeAndRepeat).join("|"); + pattern += ")"; + } + pattern += `(?:$|[${Array.from(astUtils.LINEBREAKS).join("")}]))`; + } + + return pattern; +} + +/** + * Creates RegExp object for `always` mode. + * Generated pattern for beginning of comment: + * + * 1. First, a marker or nothing. + * 2. Next, a space or an exception pattern sequence. + * @param {string[]} markers A marker list. + * @param {string[]} exceptions An exception pattern list. + * @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode. + */ +function createAlwaysStylePattern(markers, exceptions) { + let pattern = "^"; + + /* + * A marker or nothing. + * ["*"] ==> "\*?" + * ["*", "!"] ==> "(?:\*|!)?" + * ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F + */ + if (markers.length === 1) { + // the marker. + pattern += escape(markers[0]); + } else { + // one of markers. + pattern += "(?:"; + pattern += markers.map(escape).join("|"); + pattern += ")"; + } + + pattern += "?"; // or nothing. + pattern += createExceptionsPattern(exceptions); + + return new RegExp(pattern, "u"); +} + +/** + * Creates RegExp object for `never` mode. + * Generated pattern for beginning of comment: + * + * 1. First, a marker or nothing (captured). + * 2. Next, a space or a tab. + * @param {string[]} markers A marker list. + * @returns {RegExp} A RegExp object for `never` mode. + */ +function createNeverStylePattern(markers) { + const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`; + + return new RegExp(pattern, "u"); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "spaced-comment", + url: "https://eslint.style/rules/spaced-comment", + }, + }, + ], + }, + type: "suggestion", + + docs: { + description: + "Enforce consistent spacing after the `//` or `/*` in a comment", + recommended: false, + url: "https://eslint.org/docs/latest/rules/spaced-comment", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string", + }, + }, + markers: { + type: "array", + items: { + type: "string", + }, + }, + line: { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string", + }, + }, + markers: { + type: "array", + items: { + type: "string", + }, + }, + }, + additionalProperties: false, + }, + block: { + type: "object", + properties: { + exceptions: { + type: "array", + items: { + type: "string", + }, + }, + markers: { + type: "array", + items: { + type: "string", + }, + }, + balanced: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedSpaceAfterMarker: + "Unexpected space or tab after marker ({{refChar}}) in comment.", + expectedExceptionAfter: + "Expected exception block, space or tab after '{{refChar}}' in comment.", + unexpectedSpaceBefore: + "Unexpected space or tab before '*/' in comment.", + unexpectedSpaceAfter: + "Unexpected space or tab after '{{refChar}}' in comment.", + expectedSpaceBefore: + "Expected space or tab before '*/' in comment.", + expectedSpaceAfter: + "Expected space or tab after '{{refChar}}' in comment.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + // Unless the first option is never, require a space + const requireSpace = context.options[0] !== "never"; + + /* + * Parse the second options. + * If markers don't include `"*"`, it's added automatically for JSDoc + * comments. + */ + const config = context.options[1] || {}; + const balanced = config.block && config.block.balanced; + + const styleRules = ["block", "line"].reduce((rule, type) => { + const markers = parseMarkersOption( + (config[type] && config[type].markers) || config.markers || [], + ); + const exceptions = + (config[type] && config[type].exceptions) || + config.exceptions || + []; + const endNeverPattern = "[ \t]+$"; + + // Create RegExp object for valid patterns. + rule[type] = { + beginRegex: requireSpace + ? createAlwaysStylePattern(markers, exceptions) + : createNeverStylePattern(markers), + endRegex: + balanced && requireSpace + ? new RegExp( + `${createExceptionsPattern(exceptions)}$`, + "u", + ) + : new RegExp(endNeverPattern, "u"), + hasExceptions: exceptions.length > 0, + captureMarker: new RegExp( + `^(${markers.map(escape).join("|")})`, + "u", + ), + markers: new Set(markers), + }; + + return rule; + }, {}); + + /** + * Reports a beginning spacing error with an appropriate message. + * @param {ASTNode} node A comment node to check. + * @param {string} messageId An error message to report. + * @param {Array} match An array of match results for markers. + * @param {string} refChar Character used for reference in the error message. + * @returns {void} + */ + function reportBegin(node, messageId, match, refChar) { + const type = node.type.toLowerCase(), + commentIdentifier = type === "block" ? "/*" : "//"; + + context.report({ + node, + fix(fixer) { + const start = node.range[0]; + let end = start + 2; + + if (requireSpace) { + if (match) { + end += match[0].length; + } + return fixer.insertTextAfterRange([start, end], " "); + } + end += match[0].length; + return fixer.replaceTextRange( + [start, end], + commentIdentifier + (match[1] ? match[1] : ""), + ); + }, + messageId, + data: { refChar }, + }); + } + + /** + * Reports an ending spacing error with an appropriate message. + * @param {ASTNode} node A comment node to check. + * @param {string} messageId An error message to report. + * @param {string} match An array of the matched whitespace characters. + * @returns {void} + */ + function reportEnd(node, messageId, match) { + context.report({ + node, + fix(fixer) { + if (requireSpace) { + return fixer.insertTextAfterRange( + [node.range[0], node.range[1] - 2], + " ", + ); + } + const end = node.range[1] - 2, + start = end - match[0].length; + + return fixer.replaceTextRange([start, end], ""); + }, + messageId, + }); + } + + /** + * Reports a given comment if it's invalid. + * @param {ASTNode} node a comment node to check. + * @returns {void} + */ + function checkCommentForSpace(node) { + const type = node.type.toLowerCase(), + rule = styleRules[type], + commentIdentifier = type === "block" ? "/*" : "//"; + + // Ignores empty comments and comments that consist only of a marker. + if (node.value.length === 0 || rule.markers.has(node.value)) { + return; + } + + const beginMatch = rule.beginRegex.exec(node.value); + const endMatch = rule.endRegex.exec(node.value); + + // Checks. + if (requireSpace) { + if (!beginMatch) { + const hasMarker = rule.captureMarker.exec(node.value); + const marker = hasMarker + ? commentIdentifier + hasMarker[0] + : commentIdentifier; + + if (rule.hasExceptions) { + reportBegin( + node, + "expectedExceptionAfter", + hasMarker, + marker, + ); + } else { + reportBegin( + node, + "expectedSpaceAfter", + hasMarker, + marker, + ); + } + } + + if (balanced && type === "block" && !endMatch) { + reportEnd(node, "expectedSpaceBefore"); + } + } else { + if (beginMatch) { + if (!beginMatch[1]) { + reportBegin( + node, + "unexpectedSpaceAfter", + beginMatch, + commentIdentifier, + ); + } else { + reportBegin( + node, + "unexpectedSpaceAfterMarker", + beginMatch, + beginMatch[1], + ); + } + } + + if (balanced && type === "block" && endMatch) { + reportEnd(node, "unexpectedSpaceBefore", endMatch); + } + } + } + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments + .filter(token => token.type !== "Shebang") + .forEach(checkCommentForSpace); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/strict.js b/node_modules/eslint/lib/rules/strict.js new file mode 100644 index 0000000000000000000000000000000000000000..fb837adec0216099ec2064f342fbf8c6d989b7c4 --- /dev/null +++ b/node_modules/eslint/lib/rules/strict.js @@ -0,0 +1,324 @@ +/** + * @fileoverview Rule to control usage of strict mode directives. + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets all of the Use Strict Directives in the Directive Prologue of a group of + * statements. + * @param {ASTNode[]} statements Statements in the program or function body. + * @returns {ASTNode[]} All of the Use Strict Directives. + */ +function getUseStrictDirectives(statements) { + const directives = []; + + for (let i = 0; i < statements.length; i++) { + const statement = statements[i]; + + if ( + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + statement.expression.value === "use strict" + ) { + directives[i] = statement; + } else { + break; + } + } + + return directives; +} + +/** + * Checks whether a given parameter is a simple parameter. + * @param {ASTNode} node A pattern node to check. + * @returns {boolean} `true` if the node is an Identifier node. + */ +function isSimpleParameter(node) { + return node.type === "Identifier"; +} + +/** + * Checks whether a given parameter list is a simple parameter list. + * @param {ASTNode[]} params A parameter list to check. + * @returns {boolean} `true` if the every parameter is an Identifier node. + */ +function isSimpleParameterList(params) { + return params.every(isSimpleParameter); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: ["safe"], + + docs: { + description: "Require or disallow strict mode directives", + recommended: false, + url: "https://eslint.org/docs/latest/rules/strict", + }, + + schema: [ + { + enum: ["never", "global", "function", "safe"], + }, + ], + + fixable: "code", + messages: { + function: "Use the function form of 'use strict'.", + global: "Use the global form of 'use strict'.", + multiple: "Multiple 'use strict' directives.", + never: "Strict mode is not permitted.", + unnecessary: "Unnecessary 'use strict' directive.", + module: "'use strict' is unnecessary inside of modules.", + implied: + "'use strict' is unnecessary when implied strict mode is enabled.", + unnecessaryInClasses: + "'use strict' is unnecessary inside of classes.", + nonSimpleParameterList: + "'use strict' directive inside a function with non-simple parameter list throws a syntax error since ES2016.", + wrap: "Wrap {{name}} in a function with 'use strict' directive.", + }, + }, + + create(context) { + const ecmaFeatures = + context.languageOptions.parserOptions.ecmaFeatures || {}, + scopes = [], + classScopes = []; + let [mode] = context.options; + + if (ecmaFeatures.impliedStrict) { + mode = "implied"; + } else if (mode === "safe") { + mode = + ecmaFeatures.globalReturn || + context.languageOptions.sourceType === "commonjs" + ? "global" + : "function"; + } + + /** + * Determines whether a reported error should be fixed, depending on the error type. + * @param {string} errorType The type of error + * @returns {boolean} `true` if the reported error should be fixed + */ + function shouldFix(errorType) { + return ( + errorType === "multiple" || + errorType === "unnecessary" || + errorType === "module" || + errorType === "implied" || + errorType === "unnecessaryInClasses" + ); + } + + /** + * Gets a fixer function to remove a given 'use strict' directive. + * @param {ASTNode} node The directive that should be removed + * @returns {Function} A fixer function + */ + function getFixFunction(node) { + return fixer => fixer.remove(node); + } + + /** + * Report a slice of an array of nodes with a given message. + * @param {ASTNode[]} nodes Nodes. + * @param {string} start Index to start from. + * @param {string} end Index to end before. + * @param {string} messageId Message to display. + * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) + * @returns {void} + */ + function reportSlice(nodes, start, end, messageId, fix) { + nodes.slice(start, end).forEach(node => { + context.report({ + node, + messageId, + fix: fix ? getFixFunction(node) : null, + }); + }); + } + + /** + * Report all nodes in an array with a given message. + * @param {ASTNode[]} nodes Nodes. + * @param {string} messageId Message id to display. + * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) + * @returns {void} + */ + function reportAll(nodes, messageId, fix) { + reportSlice(nodes, 0, nodes.length, messageId, fix); + } + + /** + * Report all nodes in an array, except the first, with a given message. + * @param {ASTNode[]} nodes Nodes. + * @param {string} messageId Message id to display. + * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) + * @returns {void} + */ + function reportAllExceptFirst(nodes, messageId, fix) { + reportSlice(nodes, 1, nodes.length, messageId, fix); + } + + /** + * Entering a function in 'function' mode pushes a new nested scope onto the + * stack. The new scope is true if the nested function is strict mode code. + * @param {ASTNode} node The function declaration or expression. + * @param {ASTNode[]} useStrictDirectives The Use Strict Directives of the node. + * @returns {void} + */ + function enterFunctionInFunctionMode(node, useStrictDirectives) { + const isInClass = classScopes.length > 0, + isParentGlobal = + scopes.length === 0 && classScopes.length === 0, + isParentStrict = scopes.length > 0 && scopes.at(-1), + isStrict = useStrictDirectives.length > 0; + + if (isStrict) { + if (!isSimpleParameterList(node.params)) { + context.report({ + node: useStrictDirectives[0], + messageId: "nonSimpleParameterList", + }); + } else if (isParentStrict) { + context.report({ + node: useStrictDirectives[0], + messageId: "unnecessary", + fix: getFixFunction(useStrictDirectives[0]), + }); + } else if (isInClass) { + context.report({ + node: useStrictDirectives[0], + messageId: "unnecessaryInClasses", + fix: getFixFunction(useStrictDirectives[0]), + }); + } + + reportAllExceptFirst(useStrictDirectives, "multiple", true); + } else if (isParentGlobal) { + if (isSimpleParameterList(node.params)) { + context.report({ node, messageId: "function" }); + } else { + context.report({ + node, + messageId: "wrap", + data: { name: astUtils.getFunctionNameWithKind(node) }, + }); + } + } + + scopes.push(isParentStrict || isStrict); + } + + /** + * Exiting a function in 'function' mode pops its scope off the stack. + * @returns {void} + */ + function exitFunctionInFunctionMode() { + scopes.pop(); + } + + /** + * Enter a function and either: + * - Push a new nested scope onto the stack (in 'function' mode). + * - Report all the Use Strict Directives (in the other modes). + * @param {ASTNode} node The function declaration or expression. + * @returns {void} + */ + function enterFunction(node) { + const isBlock = node.body.type === "BlockStatement", + useStrictDirectives = isBlock + ? getUseStrictDirectives(node.body.body) + : []; + + if (mode === "function") { + enterFunctionInFunctionMode(node, useStrictDirectives); + } else if (useStrictDirectives.length > 0) { + if (isSimpleParameterList(node.params)) { + reportAll(useStrictDirectives, mode, shouldFix(mode)); + } else { + context.report({ + node: useStrictDirectives[0], + messageId: "nonSimpleParameterList", + }); + reportAllExceptFirst(useStrictDirectives, "multiple", true); + } + } + } + + /** @type {import('../types').Rule.RuleListener} */ + const rule = { + Program(node) { + const useStrictDirectives = getUseStrictDirectives(node.body); + + if (node.sourceType === "module") { + mode = "module"; + } + + if (mode === "global") { + if ( + node.body.length > 0 && + useStrictDirectives.length === 0 + ) { + /* + * Report the range as v9 does + */ + context.report({ + loc: { + start: node.body[0].loc.start, + end: node.body.at(-1).loc.end, + }, + messageId: "global", + }); + } + reportAllExceptFirst(useStrictDirectives, "multiple", true); + } else { + reportAll(useStrictDirectives, mode, shouldFix(mode)); + } + }, + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + ArrowFunctionExpression: enterFunction, + }; + + if (mode === "function") { + Object.assign(rule, { + // Inside of class bodies are always strict mode. + ClassBody() { + classScopes.push(true); + }, + "ClassBody:exit"() { + classScopes.pop(); + }, + + "FunctionDeclaration:exit": exitFunctionInFunctionMode, + "FunctionExpression:exit": exitFunctionInFunctionMode, + "ArrowFunctionExpression:exit": exitFunctionInFunctionMode, + }); + } + + return rule; + }, +}; diff --git a/node_modules/eslint/lib/rules/switch-colon-spacing.js b/node_modules/eslint/lib/rules/switch-colon-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..4690aa83203280c1ffe3a262500541ddd308b364 --- /dev/null +++ b/node_modules/eslint/lib/rules/switch-colon-spacing.js @@ -0,0 +1,158 @@ +/** + * @fileoverview Rule to enforce spacing around colons of switch statements. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "switch-colon-spacing", + url: "https://eslint.style/rules/switch-colon-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce spacing around colons of switch statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/switch-colon-spacing", + }, + + schema: [ + { + type: "object", + properties: { + before: { type: "boolean", default: false }, + after: { type: "boolean", default: true }, + }, + additionalProperties: false, + }, + ], + fixable: "whitespace", + messages: { + expectedBefore: "Expected space(s) before this colon.", + expectedAfter: "Expected space(s) after this colon.", + unexpectedBefore: "Unexpected space(s) before this colon.", + unexpectedAfter: "Unexpected space(s) after this colon.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const options = context.options[0] || {}; + const beforeSpacing = options.before === true; // false by default + const afterSpacing = options.after !== false; // true by default + + /** + * Check whether the spacing between the given 2 tokens is valid or not. + * @param {Token} left The left token to check. + * @param {Token} right The right token to check. + * @param {boolean} expected The expected spacing to check. `true` if there should be a space. + * @returns {boolean} `true` if the spacing between the tokens is valid. + */ + function isValidSpacing(left, right, expected) { + return ( + astUtils.isClosingBraceToken(right) || + !astUtils.isTokenOnSameLine(left, right) || + sourceCode.isSpaceBetween(left, right) === expected + ); + } + + /** + * Check whether comments exist between the given 2 tokens. + * @param {Token} left The left token to check. + * @param {Token} right The right token to check. + * @returns {boolean} `true` if comments exist between the given 2 tokens. + */ + function commentsExistBetween(left, right) { + return ( + sourceCode.getFirstTokenBetween(left, right, { + includeComments: true, + filter: astUtils.isCommentToken, + }) !== null + ); + } + + /** + * Fix the spacing between the given 2 tokens. + * @param {RuleFixer} fixer The fixer to fix. + * @param {Token} left The left token of fix range. + * @param {Token} right The right token of fix range. + * @param {boolean} spacing The spacing style. `true` if there should be a space. + * @returns {Fix|null} The fix object. + */ + function fix(fixer, left, right, spacing) { + if (commentsExistBetween(left, right)) { + return null; + } + if (spacing) { + return fixer.insertTextAfter(left, " "); + } + return fixer.removeRange([left.range[1], right.range[0]]); + } + + return { + SwitchCase(node) { + const colonToken = astUtils.getSwitchCaseColonToken( + node, + sourceCode, + ); + const beforeToken = sourceCode.getTokenBefore(colonToken); + const afterToken = sourceCode.getTokenAfter(colonToken); + + if (!isValidSpacing(beforeToken, colonToken, beforeSpacing)) { + context.report({ + node, + loc: colonToken.loc, + messageId: beforeSpacing + ? "expectedBefore" + : "unexpectedBefore", + fix: fixer => + fix(fixer, beforeToken, colonToken, beforeSpacing), + }); + } + if (!isValidSpacing(colonToken, afterToken, afterSpacing)) { + context.report({ + node, + loc: colonToken.loc, + messageId: afterSpacing + ? "expectedAfter" + : "unexpectedAfter", + fix: fixer => + fix(fixer, colonToken, afterToken, afterSpacing), + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/symbol-description.js b/node_modules/eslint/lib/rules/symbol-description.js new file mode 100644 index 0000000000000000000000000000000000000000..054c16bec7cff676be1f1bbce336e64d9c48601e --- /dev/null +++ b/node_modules/eslint/lib/rules/symbol-description.js @@ -0,0 +1,70 @@ +/** + * @fileoverview Rule to enforce description with the `Symbol` object + * @author Jarek Rencz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require symbol descriptions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/symbol-description", + }, + fixable: null, + schema: [], + messages: { + expected: "Expected Symbol to have a description.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Reports if node does not conform the rule in case rule is set to + * report missing description + * @param {ASTNode} node A CallExpression node to check. + * @returns {void} + */ + function checkArgument(node) { + if (node.arguments.length === 0) { + context.report({ + node, + messageId: "expected", + }); + } + } + + return { + "Program:exit"(node) { + const scope = sourceCode.getScope(node); + const variable = astUtils.getVariableByName(scope, "Symbol"); + + if (variable && variable.defs.length === 0) { + variable.references.forEach(reference => { + const idNode = reference.identifier; + + if (astUtils.isCallee(idNode)) { + checkArgument(idNode.parent); + } + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/template-curly-spacing.js b/node_modules/eslint/lib/rules/template-curly-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..25e3aad027b54c90664ab3bb0ddee85b0cf054f1 --- /dev/null +++ b/node_modules/eslint/lib/rules/template-curly-spacing.js @@ -0,0 +1,168 @@ +/** + * @fileoverview Rule to enforce spacing around embedded expressions of template strings + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "template-curly-spacing", + url: "https://eslint.style/rules/template-curly-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require or disallow spacing around embedded expressions of template strings", + recommended: false, + url: "https://eslint.org/docs/latest/rules/template-curly-spacing", + }, + + fixable: "whitespace", + + schema: [{ enum: ["always", "never"] }], + messages: { + expectedBefore: "Expected space(s) before '}'.", + expectedAfter: "Expected space(s) after '${'.", + unexpectedBefore: "Unexpected space(s) before '}'.", + unexpectedAfter: "Unexpected space(s) after '${'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const always = context.options[0] === "always"; + + /** + * Checks spacing before `}` of a given token. + * @param {Token} token A token to check. This is a Template token. + * @returns {void} + */ + function checkSpacingBefore(token) { + if (!token.value.startsWith("}")) { + return; // starts with a backtick, this is the first template element in the template literal + } + + const prevToken = sourceCode.getTokenBefore(token, { + includeComments: true, + }), + hasSpace = sourceCode.isSpaceBetween(prevToken, token); + + if (!astUtils.isTokenOnSameLine(prevToken, token)) { + return; + } + + if (always && !hasSpace) { + context.report({ + loc: { + start: token.loc.start, + end: { + line: token.loc.start.line, + column: token.loc.start.column + 1, + }, + }, + messageId: "expectedBefore", + fix: fixer => fixer.insertTextBefore(token, " "), + }); + } + + if (!always && hasSpace) { + context.report({ + loc: { + start: prevToken.loc.end, + end: token.loc.start, + }, + messageId: "unexpectedBefore", + fix: fixer => + fixer.removeRange([prevToken.range[1], token.range[0]]), + }); + } + } + + /** + * Checks spacing after `${` of a given token. + * @param {Token} token A token to check. This is a Template token. + * @returns {void} + */ + function checkSpacingAfter(token) { + if (!token.value.endsWith("${")) { + return; // ends with a backtick, this is the last template element in the template literal + } + + const nextToken = sourceCode.getTokenAfter(token, { + includeComments: true, + }), + hasSpace = sourceCode.isSpaceBetween(token, nextToken); + + if (!astUtils.isTokenOnSameLine(token, nextToken)) { + return; + } + + if (always && !hasSpace) { + context.report({ + loc: { + start: { + line: token.loc.end.line, + column: token.loc.end.column - 2, + }, + end: token.loc.end, + }, + messageId: "expectedAfter", + fix: fixer => fixer.insertTextAfter(token, " "), + }); + } + + if (!always && hasSpace) { + context.report({ + loc: { + start: token.loc.end, + end: nextToken.loc.start, + }, + messageId: "unexpectedAfter", + fix: fixer => + fixer.removeRange([token.range[1], nextToken.range[0]]), + }); + } + } + + return { + TemplateElement(node) { + const token = sourceCode.getFirstToken(node); + + checkSpacingBefore(token); + checkSpacingAfter(token); + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/template-tag-spacing.js b/node_modules/eslint/lib/rules/template-tag-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..92563d0db6ae319dc03e00cf5dcaa44f050b1be1 --- /dev/null +++ b/node_modules/eslint/lib/rules/template-tag-spacing.js @@ -0,0 +1,121 @@ +/** + * @fileoverview Rule to check spacing between template tags and their literals + * @author Jonathan Wilsson + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "template-tag-spacing", + url: "https://eslint.style/rules/template-tag-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require or disallow spacing between template tags and their literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/template-tag-spacing", + }, + + fixable: "whitespace", + + schema: [{ enum: ["always", "never"] }], + messages: { + unexpected: + "Unexpected space between template tag and template literal.", + missing: "Missing space between template tag and template literal.", + }, + }, + + create(context) { + const never = context.options[0] !== "always"; + const sourceCode = context.sourceCode; + + /** + * Check if a space is present between a template tag and its literal + * @param {ASTNode} node node to evaluate + * @returns {void} + * @private + */ + function checkSpacing(node) { + const tagToken = sourceCode.getTokenBefore(node.quasi); + const literalToken = sourceCode.getFirstToken(node.quasi); + const hasWhitespace = sourceCode.isSpaceBetween( + tagToken, + literalToken, + ); + + if (never && hasWhitespace) { + context.report({ + node, + loc: { + start: tagToken.loc.end, + end: literalToken.loc.start, + }, + messageId: "unexpected", + fix(fixer) { + const comments = sourceCode.getCommentsBefore( + node.quasi, + ); + + // Don't fix anything if there's a single line comment after the template tag + if (comments.some(comment => comment.type === "Line")) { + return null; + } + + return fixer.replaceTextRange( + [tagToken.range[1], literalToken.range[0]], + comments.reduce( + (text, comment) => + text + sourceCode.getText(comment), + "", + ), + ); + }, + }); + } else if (!never && !hasWhitespace) { + context.report({ + node, + loc: { + start: node.loc.start, + end: literalToken.loc.start, + }, + messageId: "missing", + fix(fixer) { + return fixer.insertTextAfter(tagToken, " "); + }, + }); + } + } + + return { + TaggedTemplateExpression: checkSpacing, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/unicode-bom.js b/node_modules/eslint/lib/rules/unicode-bom.js new file mode 100644 index 0000000000000000000000000000000000000000..7b054489182cbc55e41febfa814fde7f6658de26 --- /dev/null +++ b/node_modules/eslint/lib/rules/unicode-bom.js @@ -0,0 +1,73 @@ +/** + * @fileoverview Require or disallow Unicode BOM + * @author Andrew Johnston + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + defaultOptions: ["never"], + + docs: { + description: "Require or disallow Unicode byte order mark (BOM)", + recommended: false, + url: "https://eslint.org/docs/latest/rules/unicode-bom", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + ], + messages: { + expected: "Expected Unicode BOM (Byte Order Mark).", + unexpected: "Unexpected Unicode BOM (Byte Order Mark).", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkUnicodeBOM(node) { + const sourceCode = context.sourceCode, + location = { column: 0, line: 1 }; + const [requireBOM] = context.options; + + if (!sourceCode.hasBOM && requireBOM === "always") { + context.report({ + node, + loc: location, + messageId: "expected", + fix(fixer) { + return fixer.insertTextBeforeRange( + [0, 1], + "\uFEFF", + ); + }, + }); + } else if (sourceCode.hasBOM && requireBOM === "never") { + context.report({ + node, + loc: location, + messageId: "unexpected", + fix(fixer) { + return fixer.removeRange([-1, 0]); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/use-isnan.js b/node_modules/eslint/lib/rules/use-isnan.js new file mode 100644 index 0000000000000000000000000000000000000000..2c73acf7e219bdbf61b9ff7aa1404c99b3abd152 --- /dev/null +++ b/node_modules/eslint/lib/rules/use-isnan.js @@ -0,0 +1,268 @@ +/** + * @fileoverview Rule to flag comparisons to the value NaN + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if the given node is a NaN `Identifier` node. + * @param {ASTNode|null} node The node to check. + * @returns {boolean} `true` if the node is 'NaN' identifier. + */ +function isNaNIdentifier(node) { + if (!node) { + return false; + } + + const nodeToCheck = + node.type === "SequenceExpression" ? node.expressions.at(-1) : node; + + return ( + astUtils.isSpecificId(nodeToCheck, "NaN") || + astUtils.isSpecificMemberAccess(nodeToCheck, "Number", "NaN") + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + hasSuggestions: true, + type: "problem", + + docs: { + description: "Require calls to `isNaN()` when checking for `NaN`", + recommended: true, + url: "https://eslint.org/docs/latest/rules/use-isnan", + }, + + schema: [ + { + type: "object", + properties: { + enforceForSwitchCase: { + type: "boolean", + }, + enforceForIndexOf: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [ + { + enforceForIndexOf: false, + enforceForSwitchCase: true, + }, + ], + + messages: { + comparisonWithNaN: "Use the isNaN function to compare with NaN.", + switchNaN: + "'switch(NaN)' can never match a case clause. Use Number.isNaN instead of the switch.", + caseNaN: + "'case NaN' can never match. Use Number.isNaN before the switch.", + indexOfNaN: + "Array prototype method '{{ methodName }}' cannot find NaN.", + replaceWithIsNaN: "Replace with Number.isNaN.", + replaceWithCastingAndIsNaN: + "Replace with Number.isNaN and cast to a Number.", + replaceWithFindIndex: + "Replace with Array.prototype.{{ methodName }}.", + }, + }, + + create(context) { + const [{ enforceForIndexOf, enforceForSwitchCase }] = context.options; + const sourceCode = context.sourceCode; + + const fixableOperators = new Set(["==", "===", "!=", "!=="]); + const castableOperators = new Set(["==", "!="]); + + /** + * Get a fixer for a binary expression that compares to NaN. + * @param {ASTNode} node The node to fix. + * @param {function(string): string} wrapValue A function that wraps the compared value with a fix. + * @returns {function(Fixer): Fix} The fixer function. + */ + function getBinaryExpressionFixer(node, wrapValue) { + return fixer => { + const comparedValue = isNaNIdentifier(node.left) + ? node.right + : node.left; + const shouldWrap = comparedValue.type === "SequenceExpression"; + const shouldNegate = node.operator[0] === "!"; + + const negation = shouldNegate ? "!" : ""; + let comparedValueText = sourceCode.getText(comparedValue); + + if (shouldWrap) { + comparedValueText = `(${comparedValueText})`; + } + + const fixedValue = wrapValue(comparedValueText); + + return fixer.replaceText(node, `${negation}${fixedValue}`); + }; + } + + /** + * Checks the given `BinaryExpression` node for `foo === NaN` and other comparisons. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkBinaryExpression(node) { + if ( + /^(?:[<>]|[!=]=)=?$/u.test(node.operator) && + (isNaNIdentifier(node.left) || isNaNIdentifier(node.right)) + ) { + const suggestedFixes = []; + const NaNNode = isNaNIdentifier(node.left) + ? node.left + : node.right; + + const isSequenceExpression = + NaNNode.type === "SequenceExpression"; + const isSuggestable = + fixableOperators.has(node.operator) && + !isSequenceExpression; + const isCastable = castableOperators.has(node.operator); + + if (isSuggestable) { + suggestedFixes.push({ + messageId: "replaceWithIsNaN", + fix: getBinaryExpressionFixer( + node, + value => `Number.isNaN(${value})`, + ), + }); + + if (isCastable) { + suggestedFixes.push({ + messageId: "replaceWithCastingAndIsNaN", + fix: getBinaryExpressionFixer( + node, + value => `Number.isNaN(Number(${value}))`, + ), + }); + } + } + + context.report({ + node, + messageId: "comparisonWithNaN", + suggest: suggestedFixes, + }); + } + } + + /** + * Checks the discriminant and all case clauses of the given `SwitchStatement` node for `switch(NaN)` and `case NaN:` + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkSwitchStatement(node) { + if (isNaNIdentifier(node.discriminant)) { + context.report({ node, messageId: "switchNaN" }); + } + + for (const switchCase of node.cases) { + if (isNaNIdentifier(switchCase.test)) { + context.report({ node: switchCase, messageId: "caseNaN" }); + } + } + } + + /** + * Checks the given `CallExpression` node for `.indexOf(NaN)` and `.lastIndexOf(NaN)`. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkCallExpression(node) { + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type === "MemberExpression") { + const methodName = astUtils.getStaticPropertyName(callee); + + if ( + (methodName === "indexOf" || + methodName === "lastIndexOf") && + node.arguments.length <= 2 && + isNaNIdentifier(node.arguments[0]) + ) { + /* + * To retain side effects, it's essential to address `NaN` beforehand, which + * is not possible with fixes like `arr.findIndex(Number.isNaN)`. + */ + const isSuggestable = + node.arguments[0].type !== "SequenceExpression" && + !node.arguments[1]; + const suggestedFixes = []; + + if (isSuggestable) { + const shouldWrap = callee.computed; + const findIndexMethod = + methodName === "indexOf" + ? "findIndex" + : "findLastIndex"; + const propertyName = shouldWrap + ? `"${findIndexMethod}"` + : findIndexMethod; + + suggestedFixes.push({ + messageId: "replaceWithFindIndex", + data: { methodName: findIndexMethod }, + fix: fixer => [ + fixer.replaceText( + callee.property, + propertyName, + ), + fixer.replaceText( + node.arguments[0], + "Number.isNaN", + ), + ], + }); + } + + context.report({ + node, + messageId: "indexOfNaN", + data: { methodName }, + suggest: suggestedFixes, + }); + } + } + } + + const listeners = { + BinaryExpression: checkBinaryExpression, + }; + + if (enforceForSwitchCase) { + listeners.SwitchStatement = checkSwitchStatement; + } + + if (enforceForIndexOf) { + listeners.CallExpression = checkCallExpression; + } + + return listeners; + }, +}; diff --git a/node_modules/eslint/lib/rules/utils/ast-utils.js b/node_modules/eslint/lib/rules/utils/ast-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..06f28f914d630b872dcbd41569910656b8dcd939 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/ast-utils.js @@ -0,0 +1,2880 @@ +/** + * @fileoverview Common utils for AST. + * @author Gyandeep Singh + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { KEYS: eslintVisitorKeys } = require("eslint-visitor-keys"); +const esutils = require("esutils"); +const espree = require("espree"); +const escapeRegExp = require("escape-string-regexp"); +const { + breakableTypePattern, + createGlobalLinebreakMatcher, + lineBreakPattern, + shebangPattern, +} = require("../../shared/ast-utils"); +const globals = require("../../../conf/globals"); +const { LATEST_ECMA_VERSION } = require("../../../conf/ecma-version"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("eslint-scope").Variable} Variable */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const anyFunctionPattern = + /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/u; +const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u; +const arrayMethodWithThisArgPattern = + /^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|some)$/u; +const arrayOrTypedArrayPattern = /Array$/u; +const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u; +const thisTagPattern = /^[\s*]*@this/mu; + +const COMMENTS_IGNORE_PATTERN = + /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u; +const ESLINT_DIRECTIVE_PATTERN = /^(?:eslint[- ]|(?:globals?|exported) )/u; +const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]); + +// A set of node types that can contain a list of statements +const STATEMENT_LIST_PARENTS = new Set([ + "Program", + "BlockStatement", + "StaticBlock", + "SwitchCase", +]); +const LEXICAL_DECLARATION_KINDS = new Set([ + "let", + "const", + "using", + "await using", +]); + +const DECIMAL_INTEGER_PATTERN = /^(?:0|0[0-7]*[89]\d*|[1-9](?:_?\d)*)$/u; + +// Tests the presence of at least one LegacyOctalEscapeSequence or NonOctalDecimalEscapeSequence in a raw string +const OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN = + /^(?:[^\\]|\\.)*\\(?:[1-9]|0\d)/su; + +const LOGICAL_ASSIGNMENT_OPERATORS = new Set(["&&=", "||=", "??="]); + +/** + * All builtin global variables defined in the latest ECMAScript specification. + * @type {Record} Key is the name of the variable. Value is `true` if the variable is considered writable, `false` otherwise. + */ +const ECMASCRIPT_GLOBALS = globals[`es${LATEST_ECMA_VERSION}`]; + +/** + * Checks reference if is non initializer and writable. + * @param {Reference} reference A reference to check. + * @param {number} index The index of the reference in the references. + * @param {Reference[]} references The array that the reference belongs to. + * @returns {boolean} Success/Failure + * @private + */ +function isModifyingReference(reference, index, references) { + const identifier = reference.identifier; + + /* + * Destructuring assignments can have multiple default value, so + * possibly there are multiple writeable references for the same + * identifier. + */ + const modifyingDifferentIdentifier = + index === 0 || references[index - 1].identifier !== identifier; + + return ( + identifier && + reference.init === false && + reference.isWrite() && + modifyingDifferentIdentifier + ); +} + +/** + * Checks whether the given string starts with uppercase or not. + * @param {string} s The string to check. + * @returns {boolean} `true` if the string starts with uppercase. + */ +function startsWithUpperCase(s) { + return s[0] !== s[0].toLocaleLowerCase(); +} + +/** + * Checks whether or not a node is a constructor. + * @param {ASTNode} node A function node to check. + * @returns {boolean} Whether or not a node is a constructor. + */ +function isES5Constructor(node) { + return node.id && startsWithUpperCase(node.id.name); +} + +/** + * Finds a function node from ancestors of a node. + * @param {ASTNode} node A start node to find. + * @returns {Node|null} A found function node. + */ +function getUpperFunction(node) { + for ( + let currentNode = node; + currentNode; + currentNode = currentNode.parent + ) { + if (anyFunctionPattern.test(currentNode.type)) { + return currentNode; + } + } + return null; +} + +/** + * Checks whether a given node is a function node or not. + * The following types are function nodes: + * + * - ArrowFunctionExpression + * - FunctionDeclaration + * - FunctionExpression + * @param {ASTNode|null} node A node to check. + * @returns {boolean} `true` if the node is a function node. + */ +function isFunction(node) { + return Boolean(node && anyFunctionPattern.test(node.type)); +} + +/** + * Checks whether a given node is a loop node or not. + * The following types are loop nodes: + * + * - DoWhileStatement + * - ForInStatement + * - ForOfStatement + * - ForStatement + * - WhileStatement + * @param {ASTNode|null} node A node to check. + * @returns {boolean} `true` if the node is a loop node. + */ +function isLoop(node) { + return Boolean(node && anyLoopPattern.test(node.type)); +} + +/** + * Checks whether the given node is in a loop or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is in a loop. + */ +function isInLoop(node) { + for ( + let currentNode = node; + currentNode && !isFunction(currentNode); + currentNode = currentNode.parent + ) { + if (isLoop(currentNode)) { + return true; + } + } + + return false; +} + +/** + * Determines whether the given node is a `null` literal. + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if the node is a `null` literal + */ +function isNullLiteral(node) { + /* + * Checking `node.value === null` does not guarantee that a literal is a null literal. + * When parsing values that cannot be represented in the current environment (e.g. unicode + * regexes in Node 4), `node.value` is set to `null` because it wouldn't be possible to + * set `node.value` to a unicode regex. To make sure a literal is actually `null`, check + * `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020 + */ + return ( + node.type === "Literal" && + node.value === null && + !node.regex && + !node.bigint + ); +} + +/** + * Checks whether or not a node is `null` or `undefined`. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `null` or `undefined`. + * @public + */ +function isNullOrUndefined(node) { + return ( + isNullLiteral(node) || + (node.type === "Identifier" && node.name === "undefined") || + (node.type === "UnaryExpression" && node.operator === "void") + ); +} + +/** + * Checks whether or not a node is callee. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is callee. + */ +function isCallee(node) { + return node.parent.type === "CallExpression" && node.parent.callee === node; +} + +/** + * Returns the result of the string conversion applied to the evaluated value of the given expression node, + * if it can be determined statically. + * + * This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only. + * In all other cases, this function returns `null`. + * @param {ASTNode} node Expression node. + * @returns {string|null} String value if it can be determined. Otherwise, `null`. + */ +function getStaticStringValue(node) { + switch (node.type) { + case "Literal": + if (node.value === null) { + if (isNullLiteral(node)) { + return String(node.value); // "null" + } + if (node.regex) { + return `/${node.regex.pattern}/${node.regex.flags}`; + } + if (node.bigint) { + return node.bigint; + } + + // Otherwise, this is an unknown literal. The function will return null. + } else { + return String(node.value); + } + break; + case "TemplateLiteral": + if (node.expressions.length === 0 && node.quasis.length === 1) { + return node.quasis[0].value.cooked; + } + break; + + // no default + } + + return null; +} + +/** + * Gets the property name of a given node. + * The node can be a MemberExpression, a Property, or a MethodDefinition. + * + * If the name is dynamic, this returns `null`. + * + * For examples: + * + * a.b // => "b" + * a["b"] // => "b" + * a['b'] // => "b" + * a[`b`] // => "b" + * a[100] // => "100" + * a[b] // => null + * a["a" + "b"] // => null + * a[tag`b`] // => null + * a[`${b}`] // => null + * + * let a = {b: 1} // => "b" + * let a = {["b"]: 1} // => "b" + * let a = {['b']: 1} // => "b" + * let a = {[`b`]: 1} // => "b" + * let a = {[100]: 1} // => "100" + * let a = {[b]: 1} // => null + * let a = {["a" + "b"]: 1} // => null + * let a = {[tag`b`]: 1} // => null + * let a = {[`${b}`]: 1} // => null + * @param {ASTNode} node The node to get. + * @returns {string|null} The property name if static. Otherwise, null. + */ +function getStaticPropertyName(node) { + let prop; + + switch (node && node.type) { + case "ChainExpression": + return getStaticPropertyName(node.expression); + + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + case "TSPropertySignature": + case "TSMethodSignature": + prop = node.key; + break; + + case "MemberExpression": + prop = node.property; + break; + + // no default + } + + if (prop) { + if (prop.type === "Identifier" && !node.computed) { + return prop.name; + } + + return getStaticStringValue(prop); + } + + return null; +} + +/** + * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it. + * @param {ASTNode} node The node to address. + * @returns {ASTNode} The `ChainExpression#expression` value if the node is a `ChainExpression` node. Otherwise, the node. + */ +function skipChainExpression(node) { + return node && node.type === "ChainExpression" ? node.expression : node; +} + +/** + * Check if the `actual` is an expected value. + * @param {string} actual The string value to check. + * @param {string | RegExp} expected The expected string value or pattern. + * @returns {boolean} `true` if the `actual` is an expected value. + */ +function checkText(actual, expected) { + return typeof expected === "string" + ? actual === expected + : expected.test(actual); +} + +/** + * Check if a given node is an Identifier node with a given name. + * @param {ASTNode} node The node to check. + * @param {string | RegExp} name The expected name or the expected pattern of the object name. + * @returns {boolean} `true` if the node is an Identifier node with the name. + */ +function isSpecificId(node, name) { + return node.type === "Identifier" && checkText(node.name, name); +} + +/** + * Check if a given node is member access with a given object name and property name pair. + * This is regardless of optional or not. + * @param {ASTNode} node The node to check. + * @param {string | RegExp | null} objectName The expected name or the expected pattern of the object name. If this is nullish, this method doesn't check object. + * @param {string | RegExp | null} propertyName The expected name or the expected pattern of the property name. If this is nullish, this method doesn't check property. + * @returns {boolean} `true` if the node is member access with the object name and property name pair. + * The node is a `MemberExpression` or `ChainExpression`. + */ +function isSpecificMemberAccess(node, objectName, propertyName) { + const checkNode = skipChainExpression(node); + + if (checkNode.type !== "MemberExpression") { + return false; + } + + if (objectName && !isSpecificId(checkNode.object, objectName)) { + return false; + } + + if (propertyName) { + const actualPropertyName = getStaticPropertyName(checkNode); + + if ( + typeof actualPropertyName !== "string" || + !checkText(actualPropertyName, propertyName) + ) { + return false; + } + } + + return true; +} + +/** + * Check if two literal nodes are the same value. + * @param {ASTNode} left The Literal node to compare. + * @param {ASTNode} right The other Literal node to compare. + * @returns {boolean} `true` if the two literal nodes are the same value. + */ +function equalLiteralValue(left, right) { + // RegExp literal. + if (left.regex || right.regex) { + return Boolean( + left.regex && + right.regex && + left.regex.pattern === right.regex.pattern && + left.regex.flags === right.regex.flags, + ); + } + + // BigInt literal. + if (left.bigint || right.bigint) { + return left.bigint === right.bigint; + } + + return left.value === right.value; +} + +/** + * Check if two expressions reference the same value. For example: + * a = a + * a.b = a.b + * a[0] = a[0] + * a['b'] = a['b'] + * @param {ASTNode} left The left side of the comparison. + * @param {ASTNode} right The right side of the comparison. + * @param {boolean} [disableStaticComputedKey] Don't address `a.b` and `a["b"]` are the same if `true`. For backward compatibility. + * @returns {boolean} `true` if both sides match and reference the same value. + */ +function isSameReference(left, right, disableStaticComputedKey = false) { + if (left.type !== right.type) { + // Handle `a.b` and `a?.b` are samely. + if (left.type === "ChainExpression") { + return isSameReference( + left.expression, + right, + disableStaticComputedKey, + ); + } + if (right.type === "ChainExpression") { + return isSameReference( + left, + right.expression, + disableStaticComputedKey, + ); + } + + return false; + } + + switch (left.type) { + case "Super": + case "ThisExpression": + return true; + + case "Identifier": + case "PrivateIdentifier": + return left.name === right.name; + case "Literal": + return equalLiteralValue(left, right); + + case "ChainExpression": + return isSameReference( + left.expression, + right.expression, + disableStaticComputedKey, + ); + + case "MemberExpression": { + if (!disableStaticComputedKey) { + const nameA = getStaticPropertyName(left); + + // x.y = x["y"] + if (nameA !== null) { + return ( + isSameReference( + left.object, + right.object, + disableStaticComputedKey, + ) && nameA === getStaticPropertyName(right) + ); + } + } + + /* + * x[0] = x[0] + * x[y] = x[y] + * x.y = x.y + */ + return ( + left.computed === right.computed && + isSameReference( + left.object, + right.object, + disableStaticComputedKey, + ) && + isSameReference( + left.property, + right.property, + disableStaticComputedKey, + ) + ); + } + + default: + return false; + } +} + +/** + * Checks whether or not a node is `Reflect.apply`. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `Reflect.apply`. + */ +function isReflectApply(node) { + return isSpecificMemberAccess(node, "Reflect", "apply"); +} + +/** + * Checks whether or not a node is `Array.from`. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `Array.from`. + */ +function isArrayFromMethod(node) { + return isSpecificMemberAccess(node, arrayOrTypedArrayPattern, "from"); +} + +/** + * Checks whether or not a node is `Array.fromAsync`. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a `Array.fromAsync`. + */ +function isArrayFromAsyncMethod(node) { + return isSpecificMemberAccess(node, "Array", "fromAsync"); +} + +/** + * Checks whether or not a node is a method which expects a function as a first argument, and `thisArg` as a second argument. + * @param {ASTNode} node A node to check. + * @returns {boolean} Whether or not the node is a method which expects a function as a first argument, and `thisArg` as a second argument. + */ +function isMethodWhichHasThisArg(node) { + return isSpecificMemberAccess(node, null, arrayMethodWithThisArgPattern); +} + +/** + * Creates the negate function of the given function. + * @param {Function} f The function to negate. + * @returns {Function} Negated function. + */ +function negate(f) { + return token => !f(token); +} + +/** + * Determines if a node is surrounded by parentheses. + * @param {SourceCode} sourceCode The ESLint source code object + * @param {ASTNode} node The node to be checked. + * @returns {boolean} True if the node is parenthesised. + * @private + */ +function isParenthesised(sourceCode, node) { + const previousToken = sourceCode.getTokenBefore(node), + nextToken = sourceCode.getTokenAfter(node); + + return ( + Boolean(previousToken && nextToken) && + previousToken.value === "(" && + previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && + nextToken.range[0] >= node.range[1] + ); +} + +/** + * Checks if the given token is a `=` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a `=` token. + */ +function isEqToken(token) { + return token.value === "=" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an arrow token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an arrow token. + */ +function isArrowToken(token) { + return token.value === "=>" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a comma token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a comma token. + */ +function isCommaToken(token) { + return token.value === "," && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a dot token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a dot token. + */ +function isDotToken(token) { + return token.value === "." && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a `?.` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a `?.` token. + */ +function isQuestionDotToken(token) { + return token.value === "?." && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a semicolon token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a semicolon token. + */ +function isSemicolonToken(token) { + return token.value === ";" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a colon token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a colon token. + */ +function isColonToken(token) { + return token.value === ":" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an opening parenthesis token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an opening parenthesis token. + */ +function isOpeningParenToken(token) { + return token.value === "(" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a closing parenthesis token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a closing parenthesis token. + */ +function isClosingParenToken(token) { + return token.value === ")" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an opening square bracket token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an opening square bracket token. + */ +function isOpeningBracketToken(token) { + return token.value === "[" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a closing square bracket token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a closing square bracket token. + */ +function isClosingBracketToken(token) { + return token.value === "]" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is an opening brace token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an opening brace token. + */ +function isOpeningBraceToken(token) { + return token.value === "{" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a closing brace token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a closing brace token. + */ +function isClosingBraceToken(token) { + return token.value === "}" && token.type === "Punctuator"; +} + +/** + * Checks if the given token is a comment token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a comment token. + */ +function isCommentToken(token) { + return ( + token.type === "Line" || + token.type === "Block" || + token.type === "Shebang" + ); +} + +/** + * Checks if the given token is a keyword token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a keyword token. + */ +function isKeywordToken(token) { + return token.type === "Keyword"; +} + +/** + * Checks whether the given node represents an ES6 export declaration. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is an export declaration. + * @private + */ +function isExportDeclaration(node) { + return ( + node.type === "ExportDefaultDeclaration" || + node.type === "ExportNamedDeclaration" || + node.type === "ExportAllDeclaration" + ); +} + +/** + * Checks for the presence of a JSDoc comment for the given node and returns it. + * @param {ASTNode} node The node to get the comment for. + * @param {SourceCode} sourceCode A SourceCode instance to get comments. + * @returns {Token|null} The Block comment token containing the JSDoc comment for the given node or null if not found. + * @private + */ +function findJSDocComment(node, sourceCode) { + const tokenBefore = sourceCode.getTokenBefore(node, { + includeComments: true, + }); + + if ( + tokenBefore && + tokenBefore.type === "Block" && + tokenBefore.value.charAt(0) === "*" && + node.loc.start.line - tokenBefore.loc.end.line <= 1 + ) { + return tokenBefore; + } + + return null; +} + +/** + * Retrieves the JSDoc comment for a given node. + * @param {ASTNode} node The node to get the comment for. + * @param {SourceCode} sourceCode A SourceCode instance to get comments. + * @returns {Token|null} The Block comment token containing the JSDoc comment for the given node or null if not found. + * @private + */ +function getJSDocComment(node, sourceCode) { + let parent = node.parent; + + switch (node.type) { + case "ClassDeclaration": + case "FunctionDeclaration": + return findJSDocComment( + isExportDeclaration(parent) ? parent : node, + sourceCode, + ); + + case "ClassExpression": + return findJSDocComment(parent.parent, sourceCode); + + case "ArrowFunctionExpression": + case "FunctionExpression": + if ( + parent.type !== "CallExpression" && + parent.type !== "NewExpression" + ) { + while ( + !sourceCode.getCommentsBefore(parent).length && + !/Function/u.test(parent.type) && + parent.type !== "MethodDefinition" && + parent.type !== "Property" + ) { + parent = parent.parent; + + if (!parent) { + break; + } + } + + if ( + parent && + parent.type !== "FunctionDeclaration" && + parent.type !== "Program" + ) { + return findJSDocComment(parent, sourceCode); + } + } + + return findJSDocComment(node, sourceCode); + + // falls through + default: + return null; + } +} + +/** + * Checks whether or not a node has a `@this` tag in its comments. + * @param {ASTNode} node A node to check. + * @param {SourceCode} sourceCode A SourceCode instance to get comments. + * @returns {boolean} Whether or not the node has a `@this` tag in its comments. + */ +function hasJSDocThisTag(node, sourceCode) { + const jsdocComment = getJSDocComment(node, sourceCode); + + if (jsdocComment && thisTagPattern.test(jsdocComment.value)) { + return true; + } + + // Checks `@this` in its leading comments for callbacks, + // because callbacks don't have its JSDoc comment. + // e.g. + // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); }); + return sourceCode + .getCommentsBefore(node) + .some(comment => thisTagPattern.test(comment.value)); +} + +/** + * Gets the `(` token of the given function node. + * @param {ASTNode} node The function node to get. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {Token} `(` token. + */ +function getOpeningParenOfParams(node, sourceCode) { + // If the node is an arrow function and doesn't have parens, this returns the identifier of the first param. + if (node.type === "ArrowFunctionExpression" && node.params.length === 1) { + const argToken = sourceCode.getFirstToken(node.params[0]); + const maybeParenToken = sourceCode.getTokenBefore(argToken); + + return isOpeningParenToken(maybeParenToken) + ? maybeParenToken + : argToken; + } + + // Otherwise, returns paren. + return node.id + ? sourceCode.getTokenAfter(node.id, isOpeningParenToken) + : sourceCode.getFirstToken(node, isOpeningParenToken); +} + +/** + * Checks whether or not the tokens of two given nodes are same. + * @param {ASTNode} left A node 1 to compare. + * @param {ASTNode} right A node 2 to compare. + * @param {SourceCode} sourceCode The ESLint source code object. + * @returns {boolean} the source code for the given node. + */ +function equalTokens(left, right, sourceCode) { + const tokensL = sourceCode.getTokens(left); + const tokensR = sourceCode.getTokens(right); + + if (tokensL.length !== tokensR.length) { + return false; + } + for (let i = 0; i < tokensL.length; ++i) { + if ( + tokensL[i].type !== tokensR[i].type || + tokensL[i].value !== tokensR[i].value + ) { + return false; + } + } + + return true; +} + +/** + * Check if the given node is a true logical expression or not. + * + * The three binary expressions logical-or (`||`), logical-and (`&&`), and + * coalesce (`??`) are known as `ShortCircuitExpression`. + * But ESTree represents those by `LogicalExpression` node. + * + * This function rejects coalesce expressions of `LogicalExpression` node. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is `&&` or `||`. + * @see https://tc39.es/ecma262/#prod-ShortCircuitExpression + */ +function isLogicalExpression(node) { + return ( + node.type === "LogicalExpression" && + (node.operator === "&&" || node.operator === "||") + ); +} + +/** + * Check if the given node is a nullish coalescing expression or not. + * + * The three binary expressions logical-or (`||`), logical-and (`&&`), and + * coalesce (`??`) are known as `ShortCircuitExpression`. + * But ESTree represents those by `LogicalExpression` node. + * + * This function finds only coalesce expressions of `LogicalExpression` node. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is `??`. + */ +function isCoalesceExpression(node) { + return node.type === "LogicalExpression" && node.operator === "??"; +} + +/** + * Check if given two nodes are the pair of a logical expression and a coalesce expression. + * @param {ASTNode} left A node to check. + * @param {ASTNode} right Another node to check. + * @returns {boolean} `true` if the two nodes are the pair of a logical expression and a coalesce expression. + */ +function isMixedLogicalAndCoalesceExpressions(left, right) { + return ( + (isLogicalExpression(left) && isCoalesceExpression(right)) || + (isCoalesceExpression(left) && isLogicalExpression(right)) + ); +} + +/** + * Checks if the given operator is a logical assignment operator. + * @param {string} operator The operator to check. + * @returns {boolean} `true` if the operator is a logical assignment operator. + */ +function isLogicalAssignmentOperator(operator) { + return LOGICAL_ASSIGNMENT_OPERATORS.has(operator); +} + +/** + * Get the colon token of the given SwitchCase node. + * @param {ASTNode} node The SwitchCase node to get. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {Token} The colon token of the node. + */ +function getSwitchCaseColonToken(node, sourceCode) { + if (node.test) { + return sourceCode.getTokenAfter(node.test, isColonToken); + } + return sourceCode.getFirstToken(node, 1); +} + +/** + * Gets ESM module export name represented by the given node. + * @param {ASTNode} node `Identifier` or string `Literal` node in a position + * that represents a module export name: + * - `ImportSpecifier#imported` + * - `ExportSpecifier#local` (if it is a re-export from another module) + * - `ExportSpecifier#exported` + * - `ExportAllDeclaration#exported` + * @returns {string} The module export name. + */ +function getModuleExportName(node) { + if (node.type === "Identifier") { + return node.name; + } + + // string literal + return node.value; +} + +/** + * Returns literal's value converted to the Boolean type + * @param {ASTNode} node any `Literal` node + * @returns {boolean | null} `true` when node is truthy, `false` when node is falsy, + * `null` when it cannot be determined. + */ +function getBooleanValue(node) { + if (node.value === null) { + /* + * it might be a null literal or bigint/regex literal in unsupported environments . + * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es5.md#regexpliteral + * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es2020.md#bigintliteral + */ + + if (node.raw === "null") { + return false; + } + + // regex is always truthy + if (typeof node.regex === "object") { + return true; + } + + return null; + } + + return !!node.value; +} + +/** + * Checks if a branch node of LogicalExpression short circuits the whole condition + * @param {ASTNode} node The branch of main condition which needs to be checked + * @param {string} operator The operator of the main LogicalExpression. + * @returns {boolean} true when condition short circuits whole condition + */ +function isLogicalIdentity(node, operator) { + switch (node.type) { + case "Literal": + return ( + (operator === "||" && getBooleanValue(node) === true) || + (operator === "&&" && getBooleanValue(node) === false) + ); + + case "UnaryExpression": + return operator === "&&" && node.operator === "void"; + + case "LogicalExpression": + /* + * handles `a && false || b` + * `false` is an identity element of `&&` but not `||` + */ + return ( + operator === node.operator && + (isLogicalIdentity(node.left, operator) || + isLogicalIdentity(node.right, operator)) + ); + + case "AssignmentExpression": + return ( + ["||=", "&&="].includes(node.operator) && + operator === node.operator.slice(0, -1) && + isLogicalIdentity(node.right, operator) + ); + + // no default + } + return false; +} + +/** + * Checks if an identifier is a reference to a global variable. + * @param {Scope} scope The scope in which the identifier is referenced. + * @param {ASTNode} node An identifier node to check. + * @returns {boolean} `true` if the identifier is a reference to a global variable. + */ +function isReferenceToGlobalVariable(scope, node) { + const reference = scope.references.find(ref => ref.identifier === node); + + return Boolean( + reference && + reference.resolved && + reference.resolved.scope.type === "global" && + reference.resolved.defs.length === 0, + ); +} + +/** + * Checks if a node has a constant truthiness value. + * @param {Scope} scope Scope in which the node appears. + * @param {ASTNode} node The AST node to check. + * @param {boolean} inBooleanPosition `true` if checking the test of a + * condition. `false` in all other cases. When `false`, checks if -- for + * both string and number -- if coerced to that type, the value will + * be constant. + * @returns {boolean} true when node's truthiness is constant + * @private + */ +function isConstant(scope, node, inBooleanPosition) { + // node.elements can return null values in the case of sparse arrays ex. [,] + if (!node) { + return true; + } + switch (node.type) { + case "Literal": + case "ArrowFunctionExpression": + case "FunctionExpression": + return true; + case "ClassExpression": + case "ObjectExpression": + /** + * In theory objects like: + * + * `{toString: () => a}` + * `{valueOf: () => a}` + * + * Or a classes like: + * + * `class { static toString() { return a } }` + * `class { static valueOf() { return a } }` + * + * Are not constant verifiably when `inBooleanPosition` is + * false, but it's an edge case we've opted not to handle. + */ + return true; + case "TemplateLiteral": + return ( + (inBooleanPosition && + node.quasis.some(quasi => quasi.value.cooked.length)) || + node.expressions.every(exp => isConstant(scope, exp, false)) + ); + + case "ArrayExpression": { + if (!inBooleanPosition) { + return node.elements.every(element => + isConstant(scope, element, false), + ); + } + return true; + } + + case "UnaryExpression": + if ( + node.operator === "void" || + (node.operator === "typeof" && inBooleanPosition) + ) { + return true; + } + + if (node.operator === "!") { + return isConstant(scope, node.argument, true); + } + + return isConstant(scope, node.argument, false); + + case "BinaryExpression": + return ( + isConstant(scope, node.left, false) && + isConstant(scope, node.right, false) && + node.operator !== "in" + ); + + case "LogicalExpression": { + const isLeftConstant = isConstant( + scope, + node.left, + inBooleanPosition, + ); + const isRightConstant = isConstant( + scope, + node.right, + inBooleanPosition, + ); + const isLeftShortCircuit = + isLeftConstant && isLogicalIdentity(node.left, node.operator); + const isRightShortCircuit = + inBooleanPosition && + isRightConstant && + isLogicalIdentity(node.right, node.operator); + + return ( + (isLeftConstant && isRightConstant) || + isLeftShortCircuit || + isRightShortCircuit + ); + } + case "NewExpression": + return inBooleanPosition; + case "AssignmentExpression": + if (node.operator === "=") { + return isConstant(scope, node.right, inBooleanPosition); + } + + if (["||=", "&&="].includes(node.operator) && inBooleanPosition) { + return isLogicalIdentity( + node.right, + node.operator.slice(0, -1), + ); + } + + return false; + + case "SequenceExpression": + return isConstant( + scope, + node.expressions.at(-1), + inBooleanPosition, + ); + case "SpreadElement": + return isConstant(scope, node.argument, inBooleanPosition); + case "CallExpression": + if ( + node.callee.type === "Identifier" && + node.callee.name === "Boolean" + ) { + if ( + node.arguments.length === 0 || + isConstant(scope, node.arguments[0], true) + ) { + return isReferenceToGlobalVariable(scope, node.callee); + } + } + return false; + case "Identifier": + return ( + node.name === "undefined" && + isReferenceToGlobalVariable(scope, node) + ); + + // no default + } + return false; +} + +/** + * Checks whether a node is an ExpressionStatement at the top level of a file, function body, or TypeScript module block. + * A top-level ExpressionStatement node is a directive if it contains a single unparenthesized + * string literal and if it occurs either as the first sibling or immediately after another + * directive. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node is an ExpressionStatement at the top level of a + * file, function body, or TypeScript module block. + */ +function isTopLevelExpressionStatement(node) { + if (node.type !== "ExpressionStatement") { + return false; + } + const parent = node.parent; + + return ( + parent.type === "Program" || + parent.type === "TSModuleBlock" || + (parent.type === "BlockStatement" && isFunction(parent.parent)) + ); +} + +/** + * Check whether the given node is a part of a directive prologue or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a part of directive prologue. + */ +function isDirective(node) { + return ( + node.type === "ExpressionStatement" && + typeof node.directive === "string" + ); +} + +/** + * Tests if a node appears at the beginning of an ancestor ExpressionStatement node. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether the node appears at the beginning of an ancestor ExpressionStatement node. + */ +function isStartOfExpressionStatement(node) { + const start = node.range[0]; + let ancestor = node; + + while ((ancestor = ancestor.parent) && ancestor.range[0] === start) { + if (ancestor.type === "ExpressionStatement") { + return true; + } + } + return false; +} + +/** + * Checks whether a token can cause continuation of a preceding expression + * (for example, of a class field initializer expression) in a class body. + * This function checks specifically for tokens that can appear at the start + * of a class member: `[` (computed key), `*` (generator method), `in` or `instanceof` (valid keys) + * Without a preceding semicolon, these tokens would be parsed as index access or operators. + * @param {Token} token The token to check. + * @returns {boolean} Whether the token can cause continuation of a preceding expression. + */ +function canContinueExpressionInClassBody(token) { + return ( + (token.type === "Punctuator" && + (token.value === "[" || token.value === "*")) || + // Different parsers may return these tokens as either "Identifier" or "Keyword" + ((token.type === "Identifier" || token.type === "Keyword") && + (token.value === "in" || token.value === "instanceof")) + ); +} + +/** + * Determines whether an opening parenthesis `(`, bracket `[`, asterisk `*`, or backtick ``` ` ``` needs to be preceded by a semicolon. + * This opening parenthesis or bracket should be at the start of an `ExpressionStatement`, a `MethodDefinition`, a `PropertyDefinition`, + * or at the start of the body of an `ArrowFunctionExpression`. + * @type {(sourceCode: SourceCode, node: ASTNode) => boolean} + * @param {SourceCode} sourceCode The source code object. + * @param {ASTNode} node A node at the position where an opening parenthesis, bracket, or asterisk will be inserted. + * @returns {boolean} Whether a semicolon is required before the opening parenthesis or bracket. + */ +let needsPrecedingSemicolon; + +{ + const BREAK_OR_CONTINUE = new Set(["BreakStatement", "ContinueStatement"]); + + // Declaration types that cannot be continued by a punctuator when ending with a string Literal that is a direct child. + const DECLARATIONS = new Set([ + "ExportAllDeclaration", + "ExportNamedDeclaration", + "ImportDeclaration", + ]); + + const IDENTIFIER_OR_KEYWORD = new Set(["Identifier", "Keyword"]); + + // Keywords that can immediately precede an ExpressionStatement node, mapped to the their node types. + const NODE_TYPES_BY_KEYWORD = { + __proto__: null, + break: "BreakStatement", + continue: "ContinueStatement", + debugger: "DebuggerStatement", + do: "DoWhileStatement", + else: "IfStatement", + return: "ReturnStatement", + yield: "YieldExpression", + }; + + /* + * Before an opening parenthesis, postfix `++` and `--` always trigger ASI; + * the tokens `:`, `;`, `{` and `=>` don't expect a semicolon, as that would count as an empty statement. + */ + const PUNCTUATORS = new Set([":", ";", "{", "=>", "++", "--"]); + + /* + * Statements that can contain an `ExpressionStatement` after a closing parenthesis. + * DoWhileStatement is an exception in that it always triggers ASI after the closing parenthesis. + */ + const STATEMENTS = new Set([ + "DoWhileStatement", + "ForInStatement", + "ForOfStatement", + "ForStatement", + "IfStatement", + "WhileStatement", + "WithStatement", + ]); + + const TS_TYPE_NODE_TYPES = new Set([ + "TSAsExpression", + "TSSatisfiesExpression", + "TSTypeAliasDeclaration", + "TSTypeAnnotation", + ]); + + /** + * Determines whether a specified node is inside a TypeScript type context. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether the node is inside a TypeScript type context. + */ + function isInType(node) { + for (let currNode = node; ; ) { + const { parent } = currNode; + if (!parent) { + break; + } + if ( + TS_TYPE_NODE_TYPES.has(parent.type) && + currNode === parent.typeAnnotation + ) { + return true; + } + currNode = parent; + } + return false; + } + + needsPrecedingSemicolon = function (sourceCode, node) { + const prevToken = sourceCode.getTokenBefore(node); + + if ( + !prevToken || + (prevToken.type === "Punctuator" && + PUNCTUATORS.has(prevToken.value)) + ) { + return false; + } + + const prevNode = sourceCode.getNodeByRangeIndex(prevToken.range[0]); + + // Uninitialized class fields don't need a semicolon + if ( + // Key + (prevNode.parent.type === "PropertyDefinition" && + prevNode.parent.key === prevNode) || + // Closing bracket of a computed key + (prevNode.type === "PropertyDefinition" && + isClosingBracketToken(prevToken)) + ) { + return false; + } + + if ( + prevNode.type === "TSDeclareFunction" || + prevNode.parent.type === "TSImportEqualsDeclaration" || + prevNode.parent.parent?.type === "TSImportEqualsDeclaration" || + TS_TYPE_NODE_TYPES.has(prevNode.type) || + isInType(prevNode) + ) { + return false; + } + + if (isClosingParenToken(prevToken)) { + return !STATEMENTS.has(prevNode.type); + } + + if (isClosingBraceToken(prevToken)) { + return ( + (prevNode.type === "BlockStatement" && + prevNode.parent.type === "FunctionExpression" && + prevNode.parent.parent.type !== "MethodDefinition") || + (prevNode.type === "ClassBody" && + prevNode.parent.type === "ClassExpression") || + prevNode.type === "ObjectExpression" + ); + } + + if (IDENTIFIER_OR_KEYWORD.has(prevToken.type)) { + if ( + prevNode.parent.type === "VariableDeclarator" && + !prevNode.parent.init + ) { + return false; + } + if (BREAK_OR_CONTINUE.has(prevNode.parent.type)) { + return false; + } + + const keyword = prevToken.value; + const nodeType = NODE_TYPES_BY_KEYWORD[keyword]; + + return prevNode.type !== nodeType; + } + + if (prevToken.type === "String") { + return !DECLARATIONS.has(prevNode.parent.type); + } + + return true; + }; +} + +/** + * Checks if a node is used as an import attribute key, either in a static or dynamic import. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether the node is used as an import attribute key. + */ +function isImportAttributeKey(node) { + const { parent } = node; + + // static import/re-export + if (parent.type === "ImportAttribute" && parent.key === node) { + return true; + } + + // dynamic import + if ( + parent.type === "Property" && + !parent.computed && + (parent.key === node || + (parent.value === node && parent.shorthand && !parent.method)) && + parent.parent.type === "ObjectExpression" + ) { + const objectExpression = parent.parent; + const objectExpressionParent = objectExpression.parent; + + if ( + objectExpressionParent.type === "ImportExpression" && + objectExpressionParent.options === objectExpression + ) { + return true; + } + + // nested key + if ( + objectExpressionParent.type === "Property" && + objectExpressionParent.value === objectExpression + ) { + return isImportAttributeKey(objectExpressionParent.key); + } + } + + return false; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + COMMENTS_IGNORE_PATTERN, + LINEBREAKS, + LINEBREAK_MATCHER: lineBreakPattern, + SHEBANG_MATCHER: shebangPattern, + STATEMENT_LIST_PARENTS, + ECMASCRIPT_GLOBALS, + + /** + * Determines whether two adjacent tokens are on the same line. + * @param {Object} left The left token object. + * @param {Object} right The right token object. + * @returns {boolean} Whether or not the tokens are on the same line. + * @public + */ + isTokenOnSameLine(left, right) { + return left.loc.end.line === right.loc.start.line; + }, + + isNullOrUndefined, + isCallee, + isES5Constructor, + getUpperFunction, + isFunction, + isLoop, + isInLoop, + isArrayFromMethod, + isArrayFromAsyncMethod, + isParenthesised, + createGlobalLinebreakMatcher, + equalTokens, + + isArrowToken, + isClosingBraceToken, + isClosingBracketToken, + isClosingParenToken, + isColonToken, + isCommaToken, + isCommentToken, + isDotToken, + isQuestionDotToken, + isKeywordToken, + isNotClosingBraceToken: negate(isClosingBraceToken), + isNotClosingBracketToken: negate(isClosingBracketToken), + isNotClosingParenToken: negate(isClosingParenToken), + isNotColonToken: negate(isColonToken), + isNotCommaToken: negate(isCommaToken), + isNotDotToken: negate(isDotToken), + isNotQuestionDotToken: negate(isQuestionDotToken), + isNotOpeningBraceToken: negate(isOpeningBraceToken), + isNotOpeningBracketToken: negate(isOpeningBracketToken), + isNotOpeningParenToken: negate(isOpeningParenToken), + isNotSemicolonToken: negate(isSemicolonToken), + isOpeningBraceToken, + isOpeningBracketToken, + isOpeningParenToken, + isSemicolonToken, + isEqToken, + + /** + * Checks whether or not a given node is a string literal. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a string literal. + */ + isStringLiteral(node) { + return ( + (node.type === "Literal" && typeof node.value === "string") || + node.type === "TemplateLiteral" + ); + }, + + /** + * Checks whether a given node is a breakable statement or not. + * The node is breakable if the node is one of the following type: + * + * - DoWhileStatement + * - ForInStatement + * - ForOfStatement + * - ForStatement + * - SwitchStatement + * - WhileStatement + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is breakable. + */ + isBreakableStatement(node) { + return breakableTypePattern.test(node.type); + }, + + /** + * Gets references which are non initializer and writable. + * @param {Reference[]} references An array of references. + * @returns {Reference[]} An array of only references which are non initializer and writable. + * @public + */ + getModifyingReferences(references) { + return references.filter(isModifyingReference); + }, + + /** + * Validate that a string passed in is surrounded by the specified character + * @param {string} val The text to check. + * @param {string} character The character to see if it's surrounded by. + * @returns {boolean} True if the text is surrounded by the character, false if not. + * @private + */ + isSurroundedBy(val, character) { + return val[0] === character && val.at(-1) === character; + }, + + /** + * Returns whether the provided node is an ESLint directive comment or not + * @param {Line|Block} node The comment token to be checked + * @returns {boolean} `true` if the node is an ESLint directive comment + */ + isDirectiveComment(node) { + const comment = node.value.trim(); + + return ( + (node.type === "Line" && comment.startsWith("eslint-")) || + (node.type === "Block" && ESLINT_DIRECTIVE_PATTERN.test(comment)) + ); + }, + + /** + * Gets the trailing statement of a given node. + * + * if (code) + * consequent; + * + * When taking this `IfStatement`, returns `consequent;` statement. + * @param {ASTNode} A node to get. + * @returns {ASTNode|null} The trailing statement's node. + */ + getTrailingStatement: esutils.ast.trailingStatement, + + /** + * Finds the variable by a given name in a given scope and its upper scopes. + * @param {Scope} initScope A scope to start find. + * @param {string} name A variable name to find. + * @returns {Variable|null} A found variable or `null`. + */ + getVariableByName(initScope, name) { + let scope = initScope; + + while (scope) { + const variable = scope.set.get(name); + + if (variable) { + return variable; + } + + scope = scope.upper; + } + + return null; + }, + + /** + * Checks whether or not a given function node is the default `this` binding. + * + * First, this checks the node: + * + * - The given node is not in `PropertyDefinition#value` position. + * - The given node is not `StaticBlock`. + * - The function name does not start with uppercase. It's a convention to capitalize the names + * of constructor functions. This check is not performed if `capIsConstructor` is set to `false`. + * - The function does not have a JSDoc comment that has a `@this` tag. + * + * Next, this checks the location of the node. + * If the location is below, this judges `this` is valid. + * + * - The location is not on an object literal. + * - The location is not assigned to a variable which starts with an uppercase letter. Applies to anonymous + * functions only, as the name of the variable is considered to be the name of the function in this case. + * This check is not performed if `capIsConstructor` is set to `false`. + * - The location is not on an ES2015 class. + * - Its `bind`/`call`/`apply` method is not called directly. + * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given. + * @param {ASTNode} node A function node to check. It also can be an implicit function, like `StaticBlock` + * or any expression that is `PropertyDefinition#value` node. + * @param {SourceCode} sourceCode A SourceCode instance to get comments. + * @param {boolean} [capIsConstructor = true] `false` disables the assumption that functions which name starts + * with an uppercase or are assigned to a variable which name starts with an uppercase are constructors. + * @returns {boolean} The function node is the default `this` binding. + */ + isDefaultThisBinding(node, sourceCode, { capIsConstructor = true } = {}) { + /* + * Class field initializers are implicit functions, but ESTree doesn't have the AST node of field initializers. + * Therefore, A expression node at `PropertyDefinition#value` is a function. + * In this case, `this` is always not default binding. + */ + if ( + node.parent.type === "PropertyDefinition" && + node.parent.value === node + ) { + return false; + } + + // Class static blocks are implicit functions. In this case, `this` is always not default binding. + if (node.type === "StaticBlock") { + return false; + } + + // Check if the function has a parameter named `this`. + if ( + (node.type === "FunctionDeclaration" || + node.type === "FunctionExpression") && + node.params.some( + param => param.type === "Identifier" && param.name === "this", + ) + ) { + return false; + } + + if ( + (capIsConstructor && isES5Constructor(node)) || + hasJSDocThisTag(node, sourceCode) + ) { + return false; + } + const isAnonymous = node.id === null; + let currentNode = node; + + while (currentNode) { + const parent = currentNode.parent; + + switch (parent.type) { + /* + * Looks up the destination. + * e.g., obj.foo = nativeFoo || function foo() { ... }; + */ + case "LogicalExpression": + case "ConditionalExpression": + case "ChainExpression": + currentNode = parent; + break; + + /* + * If the upper function is IIFE, checks the destination of the return value. + * e.g. + * obj.foo = (function() { + * // setup... + * return function foo() { ... }; + * })(); + * obj.foo = (() => + * function foo() { ... } + * )(); + */ + case "ReturnStatement": { + const func = getUpperFunction(parent); + + if (func === null || !isCallee(func)) { + return true; + } + currentNode = func.parent; + break; + } + case "ArrowFunctionExpression": + if (currentNode !== parent.body || !isCallee(parent)) { + return true; + } + currentNode = parent.parent; + break; + + /* + * e.g. + * var obj = { foo() { ... } }; + * var obj = { foo: function() { ... } }; + * class A { constructor() { ... } } + * class A { foo() { ... } } + * class A { get foo() { ... } } + * class A { set foo() { ... } } + * class A { static foo() { ... } } + * class A { foo = function() { ... } } + */ + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + return parent.value !== currentNode; + + /* + * e.g. + * obj.foo = function foo() { ... }; + * Foo = function() { ... }; + * [obj.foo = function foo() { ... }] = a; + * [Foo = function() { ... }] = a; + */ + case "AssignmentExpression": + case "AssignmentPattern": + if (parent.left.type === "MemberExpression") { + return false; + } + if ( + capIsConstructor && + isAnonymous && + parent.left.type === "Identifier" && + startsWithUpperCase(parent.left.name) + ) { + return false; + } + return true; + + /* + * e.g. + * var Foo = function() { ... }; + */ + case "VariableDeclarator": + return !( + capIsConstructor && + isAnonymous && + parent.init === currentNode && + parent.id.type === "Identifier" && + startsWithUpperCase(parent.id.name) + ); + + /* + * e.g. + * var foo = function foo() { ... }.bind(obj); + * (function foo() { ... }).call(obj); + * (function foo() { ... }).apply(obj, []); + */ + case "MemberExpression": + if ( + parent.object === currentNode && + isSpecificMemberAccess( + parent, + null, + bindOrCallOrApplyPattern, + ) + ) { + const maybeCalleeNode = + parent.parent.type === "ChainExpression" + ? parent.parent + : parent; + + return !( + isCallee(maybeCalleeNode) && + maybeCalleeNode.parent.arguments.length >= 1 && + !isNullOrUndefined( + maybeCalleeNode.parent.arguments[0], + ) + ); + } + return true; + + /* + * e.g. + * Reflect.apply(function() {}, obj, []); + * Array.from([], function() {}, obj); + * list.forEach(function() {}, obj); + */ + case "CallExpression": + if (isReflectApply(parent.callee)) { + return ( + parent.arguments.length !== 3 || + parent.arguments[0] !== currentNode || + isNullOrUndefined(parent.arguments[1]) + ); + } + if ( + isArrayFromMethod(parent.callee) || + isArrayFromAsyncMethod(parent.callee) + ) { + return ( + parent.arguments.length !== 3 || + parent.arguments[1] !== currentNode || + isNullOrUndefined(parent.arguments[2]) + ); + } + if (isMethodWhichHasThisArg(parent.callee)) { + return ( + parent.arguments.length !== 2 || + parent.arguments[0] !== currentNode || + isNullOrUndefined(parent.arguments[1]) + ); + } + return true; + + // Otherwise `this` is default. + default: + return true; + } + } + + /* c8 ignore next */ + return true; + }, + + /** + * Get the precedence level based on the node type + * @param {ASTNode} node node to evaluate + * @returns {number} precedence level + * @private + */ + getPrecedence(node) { + switch (node.type) { + case "SequenceExpression": + return 0; + + case "AssignmentExpression": + case "ArrowFunctionExpression": + case "YieldExpression": + return 1; + + case "ConditionalExpression": + return 3; + + case "LogicalExpression": + switch (node.operator) { + case "||": + case "??": + return 4; + case "&&": + return 5; + + // no default + } + + /* falls through */ + + case "BinaryExpression": + switch (node.operator) { + case "|": + return 6; + case "^": + return 7; + case "&": + return 8; + case "==": + case "!=": + case "===": + case "!==": + return 9; + case "<": + case "<=": + case ">": + case ">=": + case "in": + case "instanceof": + return 10; + case "<<": + case ">>": + case ">>>": + return 11; + case "+": + case "-": + return 12; + case "*": + case "/": + case "%": + return 13; + case "**": + return 15; + + // no default + } + + /* falls through */ + + case "UnaryExpression": + case "AwaitExpression": + return 16; + + case "UpdateExpression": + return 17; + + case "CallExpression": + case "ChainExpression": + case "ImportExpression": + return 18; + + case "NewExpression": + return 19; + + default: + if (node.type in eslintVisitorKeys) { + return 20; + } + + /* + * if the node is not a standard node that we know about, then assume it has the lowest precedence + * this will mean that rules will wrap unknown nodes in parentheses where applicable instead of + * unwrapping them and potentially changing the meaning of the code or introducing a syntax error. + */ + return -1; + } + }, + + /** + * Checks whether the given node is an empty block node or not. + * @param {ASTNode|null} node The node to check. + * @returns {boolean} `true` if the node is an empty block. + */ + isEmptyBlock(node) { + return Boolean( + node && node.type === "BlockStatement" && node.body.length === 0, + ); + }, + + /** + * Checks whether the given node is an empty function node or not. + * @param {ASTNode|null} node The node to check. + * @returns {boolean} `true` if the node is an empty function. + */ + isEmptyFunction(node) { + return isFunction(node) && module.exports.isEmptyBlock(node.body); + }, + + /** + * Get directives from directive prologue of a Program or Function node. + * @param {ASTNode} node The node to check. + * @returns {ASTNode[]} The directives found in the directive prologue. + */ + getDirectivePrologue(node) { + const directives = []; + + // Directive prologues only occur at the top of files or functions. + if ( + node.type === "Program" || + node.type === "FunctionDeclaration" || + node.type === "FunctionExpression" || + /* + * Do not check arrow functions with implicit return. + * `() => "use strict";` returns the string `"use strict"`. + */ + (node.type === "ArrowFunctionExpression" && + node.body.type === "BlockStatement") + ) { + const statements = + node.type === "Program" ? node.body : node.body.body; + + for (const statement of statements) { + if ( + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" + ) { + directives.push(statement); + } else { + break; + } + } + } + + return directives; + }, + + /** + * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added + * after the node will be parsed as a decimal point, rather than a property-access dot. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if this node is a decimal integer. + * @example + * + * 0 // true + * 5 // true + * 50 // true + * 5_000 // true + * 1_234_56 // true + * 08 // true + * 0192 // true + * 5. // false + * .5 // false + * 5.0 // false + * 5.00_00 // false + * 05 // false + * 0x5 // false + * 0b101 // false + * 0b11_01 // false + * 0o5 // false + * 5e0 // false + * 5e1_000 // false + * 5n // false + * 1_000n // false + * "5" // false + * + */ + isDecimalInteger(node) { + return ( + node.type === "Literal" && + typeof node.value === "number" && + DECIMAL_INTEGER_PATTERN.test(node.raw) + ); + }, + + /** + * Determines whether this token is a decimal integer numeric token. + * This is similar to isDecimalInteger(), but for tokens. + * @param {Token} token The token to check. + * @returns {boolean} `true` if this token is a decimal integer. + */ + isDecimalIntegerNumericToken(token) { + return ( + token.type === "Numeric" && + DECIMAL_INTEGER_PATTERN.test(token.value) + ); + }, + + /** + * Gets the name and kind of the given function node. + * + * - `function foo() {}` .................... `function 'foo'` + * - `(function foo() {})` .................. `function 'foo'` + * - `(function() {})` ...................... `function` + * - `function* foo() {}` ................... `generator function 'foo'` + * - `(function* foo() {})` ................. `generator function 'foo'` + * - `(function*() {})` ..................... `generator function` + * - `() => {}` ............................. `arrow function` + * - `async () => {}` ....................... `async arrow function` + * - `({ foo: function foo() {} })` ......... `method 'foo'` + * - `({ foo: function() {} })` ............. `method 'foo'` + * - `({ ['foo']: function() {} })` ......... `method 'foo'` + * - `({ [foo]: function() {} })` ........... `method` + * - `({ foo() {} })` ....................... `method 'foo'` + * - `({ foo: function* foo() {} })` ........ `generator method 'foo'` + * - `({ foo: function*() {} })` ............ `generator method 'foo'` + * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'` + * - `({ [foo]: function*() {} })` .......... `generator method` + * - `({ *foo() {} })` ...................... `generator method 'foo'` + * - `({ foo: async function foo() {} })` ... `async method 'foo'` + * - `({ foo: async function() {} })` ....... `async method 'foo'` + * - `({ ['foo']: async function() {} })` ... `async method 'foo'` + * - `({ [foo]: async function() {} })` ..... `async method` + * - `({ async foo() {} })` ................. `async method 'foo'` + * - `({ get foo() {} })` ................... `getter 'foo'` + * - `({ set foo(a) {} })` .................. `setter 'foo'` + * - `class A { constructor() {} }` ......... `constructor` + * - `class A { foo() {} }` ................. `method 'foo'` + * - `class A { *foo() {} }` ................ `generator method 'foo'` + * - `class A { async foo() {} }` ........... `async method 'foo'` + * - `class A { ['foo']() {} }` ............. `method 'foo'` + * - `class A { *['foo']() {} }` ............ `generator method 'foo'` + * - `class A { async ['foo']() {} }` ....... `async method 'foo'` + * - `class A { [foo]() {} }` ............... `method` + * - `class A { *[foo]() {} }` .............. `generator method` + * - `class A { async [foo]() {} }` ......... `async method` + * - `class A { get foo() {} }` ............. `getter 'foo'` + * - `class A { set foo(a) {} }` ............ `setter 'foo'` + * - `class A { static foo() {} }` .......... `static method 'foo'` + * - `class A { static *foo() {} }` ......... `static generator method 'foo'` + * - `class A { static async foo() {} }` .... `static async method 'foo'` + * - `class A { static get foo() {} }` ...... `static getter 'foo'` + * - `class A { static set foo(a) {} }` ..... `static setter 'foo'` + * - `class A { foo = () => {}; }` .......... `method 'foo'` + * - `class A { foo = function() {}; }` ..... `method 'foo'` + * - `class A { foo = function bar() {}; }` . `method 'foo'` + * - `class A { static foo = () => {}; }` ... `static method 'foo'` + * - `class A { '#foo' = () => {}; }` ....... `method '#foo'` + * - `class A { #foo = () => {}; }` ......... `private method #foo` + * - `class A { static #foo = () => {}; }` .. `static private method #foo` + * - `class A { '#foo'() {} }` .............. `method '#foo'` + * - `class A { #foo() {} }` ................ `private method #foo` + * - `class A { static #foo() {} }` ......... `static private method #foo` + * @param {ASTNode} node The function node to get. + * @returns {string} The name and kind of the function node. + */ + getFunctionNameWithKind(node) { + const parent = node.parent; + const tokens = []; + + if ( + parent.type === "MethodDefinition" || + parent.type === "PropertyDefinition" || + node.type === "TSPropertySignature" || + node.type === "TSMethodSignature" + ) { + // The proposal uses `static` word consistently before visibility words: https://github.com/tc39/proposal-static-class-features + if (parent.static) { + tokens.push("static"); + } + if (!parent.computed && parent.key?.type === "PrivateIdentifier") { + tokens.push("private"); + } + } + if (node.async) { + tokens.push("async"); + } + if (node.generator) { + tokens.push("generator"); + } + + if (parent.type === "Property" || parent.type === "MethodDefinition") { + 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 (node.type === "TSMethodSignature") { + if (node.kind === "get") { + tokens.push("getter"); + } else if (node.kind === "set") { + tokens.push("setter"); + } else { + tokens.push("method"); + } + } else if (parent.type === "PropertyDefinition") { + tokens.push("method"); + } else { + if (node.type === "ArrowFunctionExpression") { + tokens.push("arrow"); + } + tokens.push("function"); + } + + if ( + parent.type === "Property" || + parent.type === "MethodDefinition" || + parent.type === "PropertyDefinition" + ) { + if (!parent.computed && parent.key.type === "PrivateIdentifier") { + tokens.push(`#${parent.key.name}`); + } else { + const name = getStaticPropertyName(parent); + + if (name !== null) { + tokens.push(`'${name}'`); + } else if (node.id) { + tokens.push(`'${node.id.name}'`); + } + } + } else if (node.type === "TSMethodSignature") { + tokens.push(`'${getStaticPropertyName(node)}'`); + } else if (node.id) { + tokens.push(`'${node.id.name}'`); + } + + return tokens.join(" "); + }, + + /** + * Gets the location of the given function node for reporting. + * + * - `function foo() {}` + * ^^^^^^^^^^^^ + * - `(function foo() {})` + * ^^^^^^^^^^^^ + * - `(function() {})` + * ^^^^^^^^ + * - `function* foo() {}` + * ^^^^^^^^^^^^^ + * - `(function* foo() {})` + * ^^^^^^^^^^^^^ + * - `(function*() {})` + * ^^^^^^^^^ + * - `() => {}` + * ^^ + * - `async () => {}` + * ^^ + * - `({ foo: function foo() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ foo: function() {} })` + * ^^^^^^^^^^^^^ + * - `({ ['foo']: function() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function() {} })` + * ^^^^^^^^^^^^^^^ + * - `({ foo() {} })` + * ^^^ + * - `({ foo: function* foo() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ foo: function*() {} })` + * ^^^^^^^^^^^^^^ + * - `({ ['foo']: function*() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function*() {} })` + * ^^^^^^^^^^^^^^^^ + * - `({ *foo() {} })` + * ^^^^ + * - `({ foo: async function foo() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ foo: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^ + * - `({ ['foo']: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `({ async foo() {} })` + * ^^^^^^^^^ + * - `({ get foo() {} })` + * ^^^^^^^ + * - `({ set foo(a) {} })` + * ^^^^^^^ + * - `class A { constructor() {} }` + * ^^^^^^^^^^^ + * - `class A { foo() {} }` + * ^^^ + * - `class A { *foo() {} }` + * ^^^^ + * - `class A { async foo() {} }` + * ^^^^^^^^^ + * - `class A { ['foo']() {} }` + * ^^^^^^^ + * - `class A { *['foo']() {} }` + * ^^^^^^^^ + * - `class A { async ['foo']() {} }` + * ^^^^^^^^^^^^^ + * - `class A { [foo]() {} }` + * ^^^^^ + * - `class A { *[foo]() {} }` + * ^^^^^^ + * - `class A { async [foo]() {} }` + * ^^^^^^^^^^^ + * - `class A { get foo() {} }` + * ^^^^^^^ + * - `class A { set foo(a) {} }` + * ^^^^^^^ + * - `class A { static foo() {} }` + * ^^^^^^^^^^ + * - `class A { static *foo() {} }` + * ^^^^^^^^^^^ + * - `class A { static async foo() {} }` + * ^^^^^^^^^^^^^^^^ + * - `class A { static get foo() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static set foo(a) {} }` + * ^^^^^^^^^^^^^^ + * - `class A { foo = function() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static foo = function() {} }` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `class A { foo = (a, b) => {} }` + * ^^^^^^ + * @param {ASTNode} node The function node to get. + * @param {SourceCode} sourceCode The source code object to get tokens. + * @returns {string} The location of the function node for reporting. + */ + getFunctionHeadLoc(node, sourceCode) { + const parent = node.parent; + let start; + let end; + + if ( + parent.type === "Property" || + parent.type === "MethodDefinition" || + parent.type === "PropertyDefinition" || + parent.type === "TSPropertySignature" || + parent.type === "TSMethodSignature" + ) { + start = parent.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } else if (node.type === "ArrowFunctionExpression") { + const arrowToken = sourceCode.getTokenBefore( + node.body, + isArrowToken, + ); + + start = arrowToken.loc.start; + end = arrowToken.loc.end; + } else { + start = node.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } + + return { + start: Object.assign({}, start), + end: Object.assign({}, end), + }; + }, + + /** + * Gets next location when the result is not out of bound, otherwise returns null. + * + * Assumptions: + * + * - The given location represents a valid location in the given source code. + * - Columns are 0-based. + * - Lines are 1-based. + * - Column immediately after the last character in a line (not incl. linebreaks) is considered to be a valid location. + * - If the source code ends with a linebreak, `sourceCode.lines` array will have an extra element (empty string) at the end. + * The start (column 0) of that extra line is considered to be a valid location. + * + * Examples of successive locations (line, column): + * + * code: foo + * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> null + * + * code: foo + * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null + * + * code: foo + * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null + * + * code: ab + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> null + * + * code: ab + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null + * + * code: ab + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null + * + * code: a + * locations: (1, 0) -> (1, 1) -> (2, 0) -> (3, 0) -> null + * + * code: + * locations: (1, 0) -> (2, 0) -> null + * + * code: + * locations: (1, 0) -> null + * @param {SourceCode} sourceCode The sourceCode + * @param {{line: number, column: number}} location The location + * @returns {{line: number, column: number} | null} Next location + */ + getNextLocation(sourceCode, { line, column }) { + if (column < sourceCode.lines[line - 1].length) { + return { + line, + column: column + 1, + }; + } + + if (line < sourceCode.lines.length) { + return { + line: line + 1, + column: 0, + }; + } + + return null; + }, + + /** + * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses + * surrounding the node. + * @param {SourceCode} sourceCode The source code object + * @param {ASTNode} node An expression node + * @returns {string} The text representing the node, with all surrounding parentheses included + */ + getParenthesisedText(sourceCode, node) { + let leftToken = sourceCode.getFirstToken(node); + let rightToken = sourceCode.getLastToken(node); + + while ( + sourceCode.getTokenBefore(leftToken) && + sourceCode.getTokenBefore(leftToken).type === "Punctuator" && + sourceCode.getTokenBefore(leftToken).value === "(" && + sourceCode.getTokenAfter(rightToken) && + sourceCode.getTokenAfter(rightToken).type === "Punctuator" && + sourceCode.getTokenAfter(rightToken).value === ")" + ) { + leftToken = sourceCode.getTokenBefore(leftToken); + rightToken = sourceCode.getTokenAfter(rightToken); + } + + return sourceCode + .getText() + .slice(leftToken.range[0], rightToken.range[1]); + }, + + /** + * Determine if a node has a possibility to be an Error object + * @param {ASTNode} node ASTNode to check + * @returns {boolean} True if there is a chance it contains an Error obj + */ + couldBeError(node) { + switch (node.type) { + case "Identifier": + case "CallExpression": + case "NewExpression": + case "MemberExpression": + case "TaggedTemplateExpression": + case "YieldExpression": + case "AwaitExpression": + case "ChainExpression": + return true; // possibly an error object. + + case "AssignmentExpression": + if (["=", "&&="].includes(node.operator)) { + return module.exports.couldBeError(node.right); + } + + if (["||=", "??="].includes(node.operator)) { + return ( + module.exports.couldBeError(node.left) || + module.exports.couldBeError(node.right) + ); + } + + /** + * All other assignment operators are mathematical assignment operators (arithmetic or bitwise). + * An assignment expression with a mathematical operator can either evaluate to a primitive value, + * or throw, depending on the operands. Thus, it cannot evaluate to an `Error` object. + */ + return false; + + case "SequenceExpression": { + const exprs = node.expressions; + + return ( + exprs.length !== 0 && + module.exports.couldBeError(exprs.at(-1)) + ); + } + + case "LogicalExpression": + /* + * If the && operator short-circuits, the left side was falsy and therefore not an error, and if it + * doesn't short-circuit, it takes the value from the right side, so the right side must always be + * a plausible error. A future improvement could verify that the left side could be truthy by + * excluding falsy literals. + */ + if (node.operator === "&&") { + return module.exports.couldBeError(node.right); + } + + return ( + module.exports.couldBeError(node.left) || + module.exports.couldBeError(node.right) + ); + + case "ConditionalExpression": + return ( + module.exports.couldBeError(node.consequent) || + module.exports.couldBeError(node.alternate) + ); + + default: + return false; + } + }, + + /** + * Check if a given node is a numeric literal or not. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is a number or bigint literal. + */ + isNumericLiteral(node) { + return ( + node.type === "Literal" && + (typeof node.value === "number" || Boolean(node.bigint)) + ); + }, + + /** + * Determines whether two tokens can safely be placed next to each other without merging into a single token + * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used. + * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used. + * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed + * next to each other, behavior is undefined (although it should return `true` in most cases). + */ + canTokensBeAdjacent(leftValue, rightValue) { + const espreeOptions = { + ecmaVersion: espree.latestEcmaVersion, + comment: true, + range: true, + }; + + let leftToken; + + if (typeof leftValue === "string") { + let tokens; + + try { + tokens = espree.tokenize(leftValue, espreeOptions); + } catch { + return false; + } + + const comments = tokens.comments; + + leftToken = tokens.at(-1); + if (comments.length) { + const lastComment = comments.at(-1); + + if (!leftToken || lastComment.range[0] > leftToken.range[0]) { + leftToken = lastComment; + } + } + } else { + leftToken = leftValue; + } + + /* + * If a hashbang comment was passed as a token object from SourceCode, + * its type will be "Shebang" because of the way ESLint itself handles hashbangs. + * If a hashbang comment was passed in a string and then tokenized in this function, + * its type will be "Hashbang" because of the way Espree tokenizes hashbangs. + */ + if (leftToken.type === "Shebang" || leftToken.type === "Hashbang") { + return false; + } + + let rightToken; + + if (typeof rightValue === "string") { + let tokens; + + try { + tokens = espree.tokenize(rightValue, espreeOptions); + } catch { + return false; + } + + const comments = tokens.comments; + + rightToken = tokens[0]; + if (comments.length) { + const firstComment = comments[0]; + + if ( + !rightToken || + firstComment.range[0] < rightToken.range[0] + ) { + rightToken = firstComment; + } + } + } else { + rightToken = rightValue; + } + + if ( + leftToken.type === "Punctuator" || + rightToken.type === "Punctuator" + ) { + if ( + leftToken.type === "Punctuator" && + rightToken.type === "Punctuator" + ) { + const PLUS_TOKENS = new Set(["+", "++"]); + const MINUS_TOKENS = new Set(["-", "--"]); + + return !( + (PLUS_TOKENS.has(leftToken.value) && + PLUS_TOKENS.has(rightToken.value)) || + (MINUS_TOKENS.has(leftToken.value) && + MINUS_TOKENS.has(rightToken.value)) + ); + } + if (leftToken.type === "Punctuator" && leftToken.value === "/") { + return !["Block", "Line", "RegularExpression"].includes( + rightToken.type, + ); + } + return true; + } + + if ( + leftToken.type === "String" || + rightToken.type === "String" || + leftToken.type === "Template" || + rightToken.type === "Template" + ) { + return true; + } + + if ( + leftToken.type !== "Numeric" && + rightToken.type === "Numeric" && + rightToken.value.startsWith(".") + ) { + return true; + } + + if ( + leftToken.type === "Block" || + rightToken.type === "Block" || + rightToken.type === "Line" + ) { + return true; + } + + if (rightToken.type === "PrivateIdentifier") { + return true; + } + + return false; + }, + + /** + * Get the `loc` object of a given name in a `/*globals` directive comment. + * @param {SourceCode} sourceCode The source code to convert index to loc. + * @param {Comment} comment The `/*globals` directive comment which include the name. + * @param {string} name The name to find. + * @returns {SourceLocation} The `loc` object. + */ + getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) { + const namePattern = new RegExp( + `[\\s,]${escapeRegExp(name)}(?:$|[\\s,:])`, + "gu", + ); + + // To ignore the first text "global". + namePattern.lastIndex = comment.value.indexOf("global") + 6; + + // Search a given variable name. + const match = namePattern.exec(comment.value); + + // Convert the index to loc. + const start = sourceCode.getLocFromIndex( + comment.range[0] + "/*".length + (match ? match.index + 1 : 0), + ); + const end = { + line: start.line, + column: start.column + (match ? name.length : 1), + }; + + return { start, end }; + }, + + /** + * Determines whether the given raw string contains an octal escape sequence + * or a non-octal decimal escape sequence ("\8", "\9"). + * + * "\1", "\2" ... "\7", "\8", "\9" + * "\00", "\01" ... "\07", "\08", "\09" + * + * "\0", when not followed by a digit, is not an octal escape sequence. + * @param {string} rawString A string in its raw representation. + * @returns {boolean} `true` if the string contains at least one octal escape sequence + * or at least one non-octal decimal escape sequence. + */ + hasOctalOrNonOctalDecimalEscapeSequence(rawString) { + return OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN.test(rawString); + }, + + /** + * Determines whether the given node is a template literal without expressions. + * @param {ASTNode} node Node to check. + * @returns {boolean} True if the node is a template literal without expressions. + */ + isStaticTemplateLiteral(node) { + return node.type === "TemplateLiteral" && node.expressions.length === 0; + }, + + /** + * Determines whether the existing curly braces around the single statement are necessary to preserve the semantics of the code. + * The braces, which make the given block body, are necessary in either of the following situations: + * + * 1. The statement is a lexical declaration. + * 2. Without the braces, an `if` within the statement would become associated with an `else` after the closing brace: + * + * if (a) { + * if (b) + * foo(); + * } + * else + * bar(); + * + * if (a) + * while (b) + * while (c) { + * while (d) + * if (e) + * while(f) + * foo(); + * } + * else + * bar(); + * @param {ASTNode} node `BlockStatement` body with exactly one statement directly inside. The statement can have its own nested statements. + * @param {SourceCode} sourceCode The source code + * @returns {boolean} `true` if the braces are necessary - removing them (replacing the given `BlockStatement` body with its single statement content) + * would change the semantics of the code or produce a syntax error. + */ + areBracesNecessary(node, sourceCode) { + /** + * Determines if the given node is a lexical declaration (let, const, using, await using, function, or class) + * @param {ASTNode} nodeToCheck The node to check + * @returns {boolean} True if the node is a lexical declaration + * @private + */ + function isLexicalDeclaration(nodeToCheck) { + if (nodeToCheck.type === "VariableDeclaration") { + return LEXICAL_DECLARATION_KINDS.has(nodeToCheck.kind); + } + + return ( + nodeToCheck.type === "FunctionDeclaration" || + nodeToCheck.type === "ClassDeclaration" + ); + } + + /** + * Checks if the given token is an `else` token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is an `else` token. + */ + function isElseKeywordToken(token) { + return token.value === "else" && token.type === "Keyword"; + } + + /** + * Determines whether the given node has an `else` keyword token as the first token after. + * @param {ASTNode} nodeToCheck The node to check. + * @returns {boolean} `true` if the node is followed by an `else` keyword token. + */ + function isFollowedByElseKeyword(nodeToCheck) { + const nextToken = sourceCode.getTokenAfter(nodeToCheck); + + return Boolean(nextToken) && isElseKeywordToken(nextToken); + } + + /** + * Determines whether the code represented by the given node contains an `if` statement + * that would become associated with an `else` keyword directly appended to that code. + * + * Examples where it returns `true`: + * + * if (a) + * foo(); + * + * if (a) { + * foo(); + * } + * + * if (a) + * foo(); + * else if (b) + * bar(); + * + * while (a) + * if (b) + * if(c) + * foo(); + * else + * bar(); + * + * Examples where it returns `false`: + * + * if (a) + * foo(); + * else + * bar(); + * + * while (a) { + * if (b) + * if(c) + * foo(); + * else + * bar(); + * } + * + * while (a) + * if (b) { + * if(c) + * foo(); + * } + * else + * bar(); + * @param {ASTNode} nodeToCheck Node representing the code to check. + * @returns {boolean} `true` if an `if` statement within the code would become associated with an `else` appended to that code. + */ + function hasUnsafeIf(nodeToCheck) { + switch (nodeToCheck.type) { + case "IfStatement": + if (!nodeToCheck.alternate) { + return true; + } + return hasUnsafeIf(nodeToCheck.alternate); + case "ForStatement": + case "ForInStatement": + case "ForOfStatement": + case "LabeledStatement": + case "WithStatement": + case "WhileStatement": + return hasUnsafeIf(nodeToCheck.body); + default: + return false; + } + } + + const statement = node.body[0]; + + return ( + isLexicalDeclaration(statement) || + (hasUnsafeIf(statement) && isFollowedByElseKeyword(node)) + ); + }, + + isReferenceToGlobalVariable, + isLogicalExpression, + isCoalesceExpression, + isMixedLogicalAndCoalesceExpressions, + isNullLiteral, + getStaticStringValue, + getStaticPropertyName, + skipChainExpression, + isSpecificId, + isSpecificMemberAccess, + equalLiteralValue, + isSameReference, + isLogicalAssignmentOperator, + getSwitchCaseColonToken, + getModuleExportName, + isConstant, + isTopLevelExpressionStatement, + isDirective, + isStartOfExpressionStatement, + canContinueExpressionInClassBody, + needsPrecedingSemicolon, + isImportAttributeKey, + getOpeningParenOfParams, +}; diff --git a/node_modules/eslint/lib/rules/utils/char-source.js b/node_modules/eslint/lib/rules/utils/char-source.js new file mode 100644 index 0000000000000000000000000000000000000000..7a25b27b98970c33619e4fe047b6e03a1ecc3d55 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/char-source.js @@ -0,0 +1,247 @@ +/** + * @fileoverview Utility functions to locate the source text of each code unit in the value of a string literal or template token. + * @author Francesco Trotta + */ + +"use strict"; + +/** + * Represents a code unit produced by the evaluation of a JavaScript common token like a string + * literal or template token. + */ +class CodeUnit { + constructor(start, source) { + this.start = start; + this.source = source; + } + + get end() { + return this.start + this.length; + } + + get length() { + return this.source.length; + } +} + +/** + * An object used to keep track of the position in a source text where the next characters will be read. + */ +class TextReader { + constructor(source) { + this.source = source; + this.pos = 0; + } + + /** + * Advances the reading position of the specified number of characters. + * @param {number} length Number of characters to advance. + * @returns {void} + */ + advance(length) { + this.pos += length; + } + + /** + * Reads characters from the source. + * @param {number} [offset=0] The offset where reading starts, relative to the current position. + * @param {number} [length=1] Number of characters to read. + * @returns {string} A substring of source characters. + */ + read(offset = 0, length = 1) { + const start = offset + this.pos; + + return this.source.slice(start, start + length); + } +} + +const SIMPLE_ESCAPE_SEQUENCES = { + __proto__: null, + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t", + v: "\v", +}; + +/** + * Reads a hex escape sequence. + * @param {TextReader} reader The reader should be positioned on the first hexadecimal digit. + * @param {number} length The number of hexadecimal digits. + * @returns {string} A code unit. + */ +function readHexSequence(reader, length) { + const str = reader.read(0, length); + const charCode = parseInt(str, 16); + + reader.advance(length); + return String.fromCharCode(charCode); +} + +/** + * Reads a Unicode escape sequence. + * @param {TextReader} reader The reader should be positioned after the "u". + * @returns {string} A code unit. + */ +function readUnicodeSequence(reader) { + const regExp = /\{(?[\dA-F]+)\}/iuy; + + regExp.lastIndex = reader.pos; + const match = regExp.exec(reader.source); + + if (match) { + const codePoint = parseInt(match.groups.hexDigits, 16); + + reader.pos = regExp.lastIndex; + return String.fromCodePoint(codePoint); + } + return readHexSequence(reader, 4); +} + +/** + * Reads an octal escape sequence. + * @param {TextReader} reader The reader should be positioned after the first octal digit. + * @param {number} maxLength The maximum number of octal digits. + * @returns {string} A code unit. + */ +function readOctalSequence(reader, maxLength) { + const [octalStr] = reader.read(-1, maxLength).match(/^[0-7]+/u); + + reader.advance(octalStr.length - 1); + const octal = parseInt(octalStr, 8); + + return String.fromCharCode(octal); +} + +/** + * Reads an escape sequence or line continuation. + * @param {TextReader} reader The reader should be positioned on the backslash. + * @returns {string} A string of zero, one or two code units. + */ +function readEscapeSequenceOrLineContinuation(reader) { + const char = reader.read(1); + + reader.advance(2); + const unitChar = SIMPLE_ESCAPE_SEQUENCES[char]; + + if (unitChar) { + return unitChar; + } + switch (char) { + case "x": + return readHexSequence(reader, 2); + case "u": + return readUnicodeSequence(reader); + case "\r": + if (reader.read() === "\n") { + reader.advance(1); + } + + // fallthrough + case "\n": + case "\u2028": + case "\u2029": + return ""; + case "0": + case "1": + case "2": + case "3": + return readOctalSequence(reader, 3); + case "4": + case "5": + case "6": + case "7": + return readOctalSequence(reader, 2); + default: + return char; + } +} + +/** + * Reads an escape sequence or line continuation and generates the respective `CodeUnit` elements. + * @param {TextReader} reader The reader should be positioned on the backslash. + * @returns {Generator} Zero, one or two `CodeUnit` elements. + */ +function* mapEscapeSequenceOrLineContinuation(reader) { + const start = reader.pos; + const str = readEscapeSequenceOrLineContinuation(reader); + const end = reader.pos; + const source = reader.source.slice(start, end); + + switch (str.length) { + case 0: + break; + case 1: + yield new CodeUnit(start, source); + break; + default: + yield new CodeUnit(start, source); + yield new CodeUnit(start, source); + break; + } +} + +/** + * Parses a string literal. + * @param {string} source The string literal to parse, including the delimiting quotes. + * @returns {CodeUnit[]} A list of code units produced by the string literal. + */ +function parseStringLiteral(source) { + const reader = new TextReader(source); + const quote = reader.read(); + + reader.advance(1); + const codeUnits = []; + + for (;;) { + const char = reader.read(); + + if (char === quote) { + break; + } + if (char === "\\") { + codeUnits.push(...mapEscapeSequenceOrLineContinuation(reader)); + } else { + codeUnits.push(new CodeUnit(reader.pos, char)); + reader.advance(1); + } + } + return codeUnits; +} + +/** + * Parses a template token. + * @param {string} source The template token to parse, including the delimiting sequences `` ` ``, `${` and `}`. + * @returns {CodeUnit[]} A list of code units produced by the template token. + */ +function parseTemplateToken(source) { + const reader = new TextReader(source); + + reader.advance(1); + const codeUnits = []; + + for (;;) { + const char = reader.read(); + + if (char === "`" || (char === "$" && reader.read(1) === "{")) { + break; + } + if (char === "\\") { + codeUnits.push(...mapEscapeSequenceOrLineContinuation(reader)); + } else { + let unitSource; + + if (char === "\r" && reader.read(1) === "\n") { + unitSource = "\r\n"; + } else { + unitSource = char; + } + codeUnits.push(new CodeUnit(reader.pos, unitSource)); + reader.advance(unitSource.length); + } + } + return codeUnits; +} + +module.exports = { parseStringLiteral, parseTemplateToken }; diff --git a/node_modules/eslint/lib/rules/utils/code-path-utils.js b/node_modules/eslint/lib/rules/utils/code-path-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..5646466f7a3f3d745ec325fda533d509285ddffa --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/code-path-utils.js @@ -0,0 +1,22 @@ +/** + * @fileoverview Code path related utilities. + */ + +"use strict"; + +/** + * Checks all segments in a set and returns true if any are reachable. + * @param {Set} segments The segments to check. + * @returns {boolean} `true` if any segment is reachable; `false` otherwise. + */ +function isAnySegmentReachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return true; + } + } + + return false; +} + +module.exports = { isAnySegmentReachable }; diff --git a/node_modules/eslint/lib/rules/utils/fix-tracker.js b/node_modules/eslint/lib/rules/utils/fix-tracker.js new file mode 100644 index 0000000000000000000000000000000000000000..5721717b87d457dd58147bd1884655d16b218e6d --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/fix-tracker.js @@ -0,0 +1,125 @@ +/** + * @fileoverview Helper class to aid in constructing fix commands. + * @author Alan Pierce + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @import { SourceRange } from "@eslint/core"; + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./ast-utils"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A helper class to combine fix options into a fix command. Currently, it + * exposes some "retain" methods that extend the range of the text being + * replaced so that other fixes won't touch that region in the same pass. + */ +class FixTracker { + /** + * Create a new FixTracker. + * @param {ruleFixer} fixer A ruleFixer instance. + * @param {SourceCode} sourceCode A SourceCode object for the current code. + */ + constructor(fixer, sourceCode) { + this.fixer = fixer; + this.sourceCode = sourceCode; + this.retainedRange = null; + } + + /** + * Mark the given range as "retained", meaning that other fixes may not + * may not modify this region in the same pass. + * @param {SourceRange} range The range to retain. + * @returns {FixTracker} The same RuleFixer, for chained calls. + */ + retainRange(range) { + this.retainedRange = range; + return this; + } + + /** + * Given a node, find the function containing it (or the entire program) and + * mark it as retained, meaning that other fixes may not modify it in this + * pass. This is useful for avoiding conflicts in fixes that modify control + * flow. + * @param {ASTNode} node The node to use as a starting point. + * @returns {FixTracker} The same RuleFixer, for chained calls. + */ + retainEnclosingFunction(node) { + const functionNode = astUtils.getUpperFunction(node); + + return this.retainRange( + functionNode ? functionNode.range : this.sourceCode.ast.range, + ); + } + + /** + * Given a node or token, find the token before and afterward, and mark that + * range as retained, meaning that other fixes may not modify it in this + * pass. This is useful for avoiding conflicts in fixes that make a small + * change to the code where the AST should not be changed. + * @param {ASTNode|Token} nodeOrToken The node or token to use as a starting + * point. The token to the left and right are use in the range. + * @returns {FixTracker} The same RuleFixer, for chained calls. + */ + retainSurroundingTokens(nodeOrToken) { + const tokenBefore = + this.sourceCode.getTokenBefore(nodeOrToken) || nodeOrToken; + const tokenAfter = + this.sourceCode.getTokenAfter(nodeOrToken) || nodeOrToken; + + return this.retainRange([tokenBefore.range[0], tokenAfter.range[1]]); + } + + /** + * Create a fix command that replaces the given range with the given text, + * accounting for any retained ranges. + * @param {SourceRange} range The range to remove in the fix. + * @param {string} text The text to insert in place of the range. + * @returns {Object} The fix command. + */ + replaceTextRange(range, text) { + let actualRange; + + if (this.retainedRange) { + actualRange = [ + Math.min(this.retainedRange[0], range[0]), + Math.max(this.retainedRange[1], range[1]), + ]; + } else { + actualRange = range; + } + + return this.fixer.replaceTextRange( + actualRange, + this.sourceCode.text.slice(actualRange[0], range[0]) + + text + + this.sourceCode.text.slice(range[1], actualRange[1]), + ); + } + + /** + * Create a fix command that removes the given node or token, accounting for + * any retained ranges. + * @param {ASTNode|Token} nodeOrToken The node or token to remove. + * @returns {Object} The fix command. + */ + remove(nodeOrToken) { + return this.replaceTextRange(nodeOrToken.range, ""); + } +} + +module.exports = FixTracker; diff --git a/node_modules/eslint/lib/rules/utils/keywords.js b/node_modules/eslint/lib/rules/utils/keywords.js new file mode 100644 index 0000000000000000000000000000000000000000..eca2076eb4dd8cc4a453cec0ef5fc4e7590bc5df --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/keywords.js @@ -0,0 +1,67 @@ +/** + * @fileoverview A shared list of ES3 keywords. + * @author Josh Perez + */ +"use strict"; + +module.exports = [ + "abstract", + "boolean", + "break", + "byte", + "case", + "catch", + "char", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "double", + "else", + "enum", + "export", + "extends", + "false", + "final", + "finally", + "float", + "for", + "function", + "goto", + "if", + "implements", + "import", + "in", + "instanceof", + "int", + "interface", + "long", + "native", + "new", + "null", + "package", + "private", + "protected", + "public", + "return", + "short", + "static", + "super", + "switch", + "synchronized", + "this", + "throw", + "throws", + "transient", + "true", + "try", + "typeof", + "var", + "void", + "volatile", + "while", + "with", +]; diff --git a/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js b/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js new file mode 100644 index 0000000000000000000000000000000000000000..b93395095b9c6fc2899be87dfab7137bbcbef3cb --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js @@ -0,0 +1,118 @@ +/** + * @fileoverview `Map` to load rules lazily. + * @author Toru Nagashima + */ +"use strict"; + +const debug = require("debug")("eslint:rules"); + +/** @typedef {import("../../types").Rule.RuleModule} Rule */ + +/** + * The `Map` object that loads each rule when it's accessed. + * @example + * const rules = new LazyLoadingRuleMap([ + * ["eqeqeq", () => require("eqeqeq")], + * ["semi", () => require("semi")], + * ["no-unused-vars", () => require("no-unused-vars")] + * ]); + * + * rules.get("semi"); // call `() => require("semi")` here. + * + * @extends {Map} + */ +class LazyLoadingRuleMap extends Map { + /** + * Initialize this map. + * @param {Array<[string, function(): Rule]>} loaders The rule loaders. + */ + constructor(loaders) { + let remaining = loaders.length; + + super( + debug.enabled + ? loaders.map(([ruleId, load]) => { + let cache = null; + + return [ + ruleId, + () => { + if (!cache) { + debug( + "Loading rule %o (remaining=%d)", + ruleId, + --remaining, + ); + cache = load(); + } + return cache; + }, + ]; + }) + : loaders, + ); + + // `super(...iterable)` uses `this.set()`, so disable it here. + Object.defineProperty(LazyLoadingRuleMap.prototype, "set", { + configurable: true, + value: void 0, + }); + } + + /** + * Get a rule. + * Each rule will be loaded on the first access. + * @param {string} ruleId The rule ID to get. + * @returns {Rule|undefined} The rule. + */ + get(ruleId) { + const load = super.get(ruleId); + + return load && load(); + } + + /** + * Iterate rules. + * @returns {IterableIterator} Rules. + */ + *values() { + for (const load of super.values()) { + yield load(); + } + } + + /** + * Iterate rules. + * @returns {IterableIterator<[string, Rule]>} Rules. + */ + *entries() { + for (const [ruleId, load] of super.entries()) { + yield [ruleId, load()]; + } + } + + /** + * Call a function with each rule. + * @param {Function} callbackFn The callback function. + * @param {any} [thisArg] The object to pass to `this` of the callback function. + * @returns {void} + */ + forEach(callbackFn, thisArg) { + for (const [ruleId, load] of super.entries()) { + callbackFn.call(thisArg, load(), ruleId, this); + } + } +} + +// Forbid mutation. +Object.defineProperties(LazyLoadingRuleMap.prototype, { + clear: { configurable: true, value: void 0 }, + delete: { configurable: true, value: void 0 }, + [Symbol.iterator]: { + configurable: true, + writable: true, + value: LazyLoadingRuleMap.prototype.entries, + }, +}); + +module.exports = { LazyLoadingRuleMap }; diff --git a/node_modules/eslint/lib/rules/utils/regular-expressions.js b/node_modules/eslint/lib/rules/utils/regular-expressions.js new file mode 100644 index 0000000000000000000000000000000000000000..6d80654b6ee54f5c7b18092ad7a10ae7fe38221e --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/regular-expressions.js @@ -0,0 +1,58 @@ +/** + * @fileoverview Common utils for regular expressions. + * @author Josh Goldberg + * @author Toru Nagashima + */ + +"use strict"; + +const { RegExpValidator } = require("@eslint-community/regexpp"); + +const REGEXPP_LATEST_ECMA_VERSION = 2025; + +/** + * Checks if the given regular expression pattern would be valid with the `u` flag. + * @param {number} ecmaVersion ECMAScript version to parse in. + * @param {string} pattern The regular expression pattern to verify. + * @param {"u"|"v"} flag The type of Unicode flag + * @returns {boolean} `true` if the pattern would be valid with the `u` flag. + * `false` if the pattern would be invalid with the `u` flag or the configured + * ecmaVersion doesn't support the `u` flag. + */ +function isValidWithUnicodeFlag(ecmaVersion, pattern, flag = "u") { + if (flag === "u" && ecmaVersion <= 5) { + // ecmaVersion <= 5 doesn't support the 'u' flag + return false; + } + if (flag === "v" && ecmaVersion <= 2023) { + return false; + } + + const validator = new RegExpValidator({ + ecmaVersion: Math.min(ecmaVersion, REGEXPP_LATEST_ECMA_VERSION), + }); + + try { + validator.validatePattern( + pattern, + void 0, + void 0, + flag === "u" + ? { + unicode: /* uFlag = */ true, + } + : { + unicodeSets: true, + }, + ); + } catch { + return false; + } + + return true; +} + +module.exports = { + isValidWithUnicodeFlag, + REGEXPP_LATEST_ECMA_VERSION, +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/index.js b/node_modules/eslint/lib/rules/utils/unicode/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0e7d5d53c148a28d410a63296161eb61999f33a1 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/index.js @@ -0,0 +1,16 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +const isCombiningCharacter = require("./is-combining-character"); +const isEmojiModifier = require("./is-emoji-modifier"); +const isRegionalIndicatorSymbol = require("./is-regional-indicator-symbol"); +const isSurrogatePair = require("./is-surrogate-pair"); + +module.exports = { + isCombiningCharacter, + isEmojiModifier, + isRegionalIndicatorSymbol, + isSurrogatePair, +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js b/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js new file mode 100644 index 0000000000000000000000000000000000000000..c26e291e34394c18b280bdd64a798d4195ddf69f --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js @@ -0,0 +1,13 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether a given character is a combining mark or not. + * @param {number} codePoint The character code to check. + * @returns {boolean} `true` if the character has the General Category of Combining Mark (M), consisting of `Mc`, `Me`, and `Mn`. + */ +module.exports = function isCombiningCharacter(codePoint) { + return /^\p{M}$/u.test(String.fromCodePoint(codePoint)); +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js b/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js new file mode 100644 index 0000000000000000000000000000000000000000..526ac91d6bd6779c323a1039933cade9b1290541 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js @@ -0,0 +1,13 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether a given character is an emoji modifier. + * @param {number} code The character code to check. + * @returns {boolean} `true` if the character is an emoji modifier. + */ +module.exports = function isEmojiModifier(code) { + return code >= 0x1f3fb && code <= 0x1f3ff; +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js b/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js new file mode 100644 index 0000000000000000000000000000000000000000..019d9da0afd0d6c9077bbd280c6603227cce1c0f --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js @@ -0,0 +1,13 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether a given character is a regional indicator symbol. + * @param {number} code The character code to check. + * @returns {boolean} `true` if the character is a regional indicator symbol. + */ +module.exports = function isRegionalIndicatorSymbol(code) { + return code >= 0x1f1e6 && code <= 0x1f1ff; +}; diff --git a/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js b/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js new file mode 100644 index 0000000000000000000000000000000000000000..fbe6a4017c6fb065d3b5e6275c5796700fa6e395 --- /dev/null +++ b/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js @@ -0,0 +1,14 @@ +/** + * @author Toru Nagashima + */ +"use strict"; + +/** + * Check whether given two characters are a surrogate pair. + * @param {number} lead The code of the lead character. + * @param {number} tail The code of the tail character. + * @returns {boolean} `true` if the character pair is a surrogate pair. + */ +module.exports = function isSurrogatePair(lead, tail) { + return lead >= 0xd800 && lead < 0xdc00 && tail >= 0xdc00 && tail < 0xe000; +}; diff --git a/node_modules/eslint/lib/rules/valid-typeof.js b/node_modules/eslint/lib/rules/valid-typeof.js new file mode 100644 index 0000000000000000000000000000000000000000..fd4f3d204802e56f1fa80862d2f86ff8b20ebd12 --- /dev/null +++ b/node_modules/eslint/lib/rules/valid-typeof.js @@ -0,0 +1,171 @@ +/** + * @fileoverview Ensures that the results of typeof are compared against a valid string + * @author Ian Christian Myers + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + requireStringLiterals: false, + }, + ], + + docs: { + description: + "Enforce comparing `typeof` expressions against valid strings", + recommended: true, + url: "https://eslint.org/docs/latest/rules/valid-typeof", + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + requireStringLiterals: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + messages: { + invalidValue: "Invalid typeof comparison value.", + notString: "Typeof comparisons should be to string literals.", + suggestString: 'Use `"{{type}}"` instead of `{{type}}`.', + }, + }, + + create(context) { + const VALID_TYPES = new Set([ + "symbol", + "undefined", + "object", + "boolean", + "number", + "string", + "function", + "bigint", + ]), + OPERATORS = new Set(["==", "===", "!=", "!=="]); + const sourceCode = context.sourceCode; + const [{ requireStringLiterals }] = context.options; + + let globalScope; + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return ( + variable && + variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node) + ); + } + + /** + * Determines whether a node is a typeof expression. + * @param {ASTNode} node The node + * @returns {boolean} `true` if the node is a typeof expression + */ + function isTypeofExpression(node) { + return ( + node.type === "UnaryExpression" && node.operator === "typeof" + ); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + UnaryExpression(node) { + if (isTypeofExpression(node)) { + const { parent } = node; + + if ( + parent.type === "BinaryExpression" && + OPERATORS.has(parent.operator) + ) { + const sibling = + parent.left === node ? parent.right : parent.left; + + if ( + sibling.type === "Literal" || + astUtils.isStaticTemplateLiteral(sibling) + ) { + const value = + sibling.type === "Literal" + ? sibling.value + : sibling.quasis[0].value.cooked; + + if (!VALID_TYPES.has(value)) { + context.report({ + node: sibling, + messageId: "invalidValue", + }); + } + } else if ( + sibling.type === "Identifier" && + sibling.name === "undefined" && + isReferenceToGlobalVariable(sibling) + ) { + context.report({ + node: sibling, + messageId: requireStringLiterals + ? "notString" + : "invalidValue", + suggest: [ + { + messageId: "suggestString", + data: { type: "undefined" }, + fix(fixer) { + return fixer.replaceText( + sibling, + '"undefined"', + ); + }, + }, + ], + }); + } else if ( + requireStringLiterals && + !isTypeofExpression(sibling) + ) { + context.report({ + node: sibling, + messageId: "notString", + }); + } + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/vars-on-top.js b/node_modules/eslint/lib/rules/vars-on-top.js new file mode 100644 index 0000000000000000000000000000000000000000..c790ccbd5cfabc1f753add1178673cd6be778615 --- /dev/null +++ b/node_modules/eslint/lib/rules/vars-on-top.js @@ -0,0 +1,165 @@ +/** + * @fileoverview Rule to enforce var declarations are only at the top of a function. + * @author Danny Fritz + * @author Gyandeep Singh + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require `var` declarations be placed at the top of their containing scope", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/vars-on-top", + }, + + schema: [], + messages: { + top: "All 'var' declarations must be at the top of the function scope.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Has AST suggesting a directive. + * @param {ASTNode} node any node + * @returns {boolean} whether the given node structurally represents a directive + */ + function looksLikeDirective(node) { + return ( + node.type === "ExpressionStatement" && + node.expression.type === "Literal" && + typeof node.expression.value === "string" + ); + } + + /** + * Check to see if its a ES6 import declaration + * @param {ASTNode} node any node + * @returns {boolean} whether the given node represents a import declaration + */ + function looksLikeImport(node) { + return ( + node.type === "ImportDeclaration" || + node.type === "ImportSpecifier" || + node.type === "ImportDefaultSpecifier" || + node.type === "ImportNamespaceSpecifier" + ); + } + + /** + * Checks whether a given node is a variable declaration or not. + * @param {ASTNode} node any node + * @returns {boolean} `true` if the node is a variable declaration. + */ + function isVariableDeclaration(node) { + return ( + node.type === "VariableDeclaration" || + (node.type === "ExportNamedDeclaration" && + node.declaration && + node.declaration.type === "VariableDeclaration") + ); + } + + /** + * Checks whether this variable is on top of the block body + * @param {ASTNode} node The node to check + * @param {ASTNode[]} statements collection of ASTNodes for the parent node block + * @returns {boolean} True if var is on top otherwise false + */ + function isVarOnTop(node, statements) { + const l = statements.length; + let i = 0; + + // Skip over directives and imports. Static blocks don't have either. + if (node.parent.type !== "StaticBlock") { + for (; i < l; ++i) { + if ( + !looksLikeDirective(statements[i]) && + !looksLikeImport(statements[i]) + ) { + break; + } + } + } + + for (; i < l; ++i) { + if (!isVariableDeclaration(statements[i])) { + return false; + } + if (statements[i] === node) { + return true; + } + } + + return false; + } + + /** + * Checks whether variable is on top at the global level + * @param {ASTNode} node The node to check + * @param {ASTNode} parent Parent of the node + * @returns {void} + */ + function globalVarCheck(node, parent) { + if (!isVarOnTop(node, parent.body)) { + context.report({ node, messageId: "top" }); + } + } + + /** + * Checks whether variable is on top at functional block scope level + * @param {ASTNode} node The node to check + * @returns {void} + */ + function blockScopeVarCheck(node) { + const { parent } = node; + + if ( + parent.type === "BlockStatement" && + /Function/u.test(parent.parent.type) && + isVarOnTop(node, parent.body) + ) { + return; + } + + if ( + parent.type === "StaticBlock" && + isVarOnTop(node, parent.body) + ) { + return; + } + + context.report({ node, messageId: "top" }); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "VariableDeclaration[kind='var']"(node) { + if (node.parent.type === "ExportNamedDeclaration") { + globalVarCheck(node.parent, node.parent.parent); + } else if (node.parent.type === "Program") { + globalVarCheck(node, node.parent); + } else { + blockScopeVarCheck(node); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/wrap-iife.js b/node_modules/eslint/lib/rules/wrap-iife.js new file mode 100644 index 0000000000000000000000000000000000000000..3ba53a15198e374b600821fe31c93a00d410e028 --- /dev/null +++ b/node_modules/eslint/lib/rules/wrap-iife.js @@ -0,0 +1,238 @@ +/** + * @fileoverview Rule to flag when IIFE is not wrapped in parens + * @author Ilya Volodin + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const eslintUtils = require("@eslint-community/eslint-utils"); + +//---------------------------------------------------------------------- +// Helpers +//---------------------------------------------------------------------- + +/** + * Check if the given node is callee of a `NewExpression` node + * @param {ASTNode} node node to check + * @returns {boolean} True if the node is callee of a `NewExpression` node + * @private + */ +function isCalleeOfNewExpression(node) { + const maybeCallee = + node.parent.type === "ChainExpression" ? node.parent : node; + + return ( + maybeCallee.parent.type === "NewExpression" && + maybeCallee.parent.callee === maybeCallee + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "wrap-iife", + url: "https://eslint.style/rules/wrap-iife", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require parentheses around immediate `function` invocations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/wrap-iife", + }, + + schema: [ + { + enum: ["outside", "inside", "any"], + }, + { + type: "object", + properties: { + functionPrototypeMethods: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + messages: { + wrapInvocation: + "Wrap an immediate function invocation in parentheses.", + wrapExpression: "Wrap only the function expression in parens.", + moveInvocation: + "Move the invocation into the parens that contain the function.", + }, + }, + + create(context) { + const style = context.options[0] || "outside"; + const includeFunctionPrototypeMethods = + context.options[1] && context.options[1].functionPrototypeMethods; + + const sourceCode = context.sourceCode; + + /** + * Check if the node is wrapped in any (). All parens count: grouping parens and parens for constructs such as if() + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if it is wrapped in any parens + * @private + */ + function isWrappedInAnyParens(node) { + return astUtils.isParenthesised(sourceCode, node); + } + + /** + * Check if the node is wrapped in grouping (). Parens for constructs such as if() don't count + * @param {ASTNode} node node to evaluate + * @returns {boolean} True if it is wrapped in grouping parens + * @private + */ + function isWrappedInGroupingParens(node) { + return eslintUtils.isParenthesized(1, node, sourceCode); + } + + /** + * Get the function node from an IIFE + * @param {ASTNode} node node to evaluate + * @returns {ASTNode} node that is the function expression of the given IIFE, or null if none exist + */ + function getFunctionNodeFromIIFE(node) { + const callee = astUtils.skipChainExpression(node.callee); + + if (callee.type === "FunctionExpression") { + return callee; + } + + if ( + includeFunctionPrototypeMethods && + callee.type === "MemberExpression" && + callee.object.type === "FunctionExpression" && + (astUtils.getStaticPropertyName(callee) === "call" || + astUtils.getStaticPropertyName(callee) === "apply") + ) { + return callee.object; + } + + return null; + } + + return { + CallExpression(node) { + const innerNode = getFunctionNodeFromIIFE(node); + + if (!innerNode) { + return; + } + + const isCallExpressionWrapped = isWrappedInAnyParens(node), + isFunctionExpressionWrapped = + isWrappedInAnyParens(innerNode); + + if (!isCallExpressionWrapped && !isFunctionExpressionWrapped) { + context.report({ + node, + messageId: "wrapInvocation", + fix(fixer) { + const nodeToSurround = + style === "inside" ? innerNode : node; + + return fixer.replaceText( + nodeToSurround, + `(${sourceCode.getText(nodeToSurround)})`, + ); + }, + }); + } else if (style === "inside" && !isFunctionExpressionWrapped) { + context.report({ + node, + messageId: "wrapExpression", + fix(fixer) { + // The outer call expression will always be wrapped at this point. + + if ( + isWrappedInGroupingParens(node) && + !isCalleeOfNewExpression(node) + ) { + /* + * Parenthesize the function expression and remove unnecessary grouping parens around the call expression. + * Replace the range between the end of the function expression and the end of the call expression. + * for example, in `(function(foo) {}(bar))`, the range `(bar))` should get replaced with `)(bar)`. + */ + + const parenAfter = + sourceCode.getTokenAfter(node); + + return fixer.replaceTextRange( + [innerNode.range[1], parenAfter.range[1]], + `)${sourceCode.getText().slice(innerNode.range[1], parenAfter.range[0])}`, + ); + } + + /* + * Call expression is wrapped in mandatory parens such as if(), or in necessary grouping parens. + * These parens cannot be removed, so just parenthesize the function expression. + */ + + return fixer.replaceText( + innerNode, + `(${sourceCode.getText(innerNode)})`, + ); + }, + }); + } else if (style === "outside" && !isCallExpressionWrapped) { + context.report({ + node, + messageId: "moveInvocation", + fix(fixer) { + /* + * The inner function expression will always be wrapped at this point. + * It's only necessary to replace the range between the end of the function expression + * and the call expression. For example, in `(function(foo) {})(bar)`, the range `)(bar)` + * should get replaced with `(bar))`. + */ + const parenAfter = + sourceCode.getTokenAfter(innerNode); + + return fixer.replaceTextRange( + [parenAfter.range[0], node.range[1]], + `${sourceCode.getText().slice(parenAfter.range[1], node.range[1])})`, + ); + }, + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/wrap-regex.js b/node_modules/eslint/lib/rules/wrap-regex.js new file mode 100644 index 0000000000000000000000000000000000000000..def392a4c17054e6abaf66a0aa2c0360a534f56b --- /dev/null +++ b/node_modules/eslint/lib/rules/wrap-regex.js @@ -0,0 +1,91 @@ +/** + * @fileoverview Rule to flag when regex literals are not wrapped in parens + * @author Matt DuVall + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "wrap-regex", + url: "https://eslint.style/rules/wrap-regex", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require parenthesis around regex literals", + recommended: false, + url: "https://eslint.org/docs/latest/rules/wrap-regex", + }, + + schema: [], + fixable: "code", + + messages: { + requireParens: + "Wrap the regexp literal in parens to disambiguate the slash.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + Literal(node) { + const token = sourceCode.getFirstToken(node), + nodeType = token.type; + + if (nodeType === "RegularExpression") { + const beforeToken = sourceCode.getTokenBefore(node); + const afterToken = sourceCode.getTokenAfter(node); + const { parent } = node; + + if ( + parent.type === "MemberExpression" && + parent.object === node && + !( + beforeToken && + beforeToken.value === "(" && + afterToken && + afterToken.value === ")" + ) + ) { + context.report({ + node, + messageId: "requireParens", + fix: fixer => + fixer.replaceText( + node, + `(${sourceCode.getText(node)})`, + ), + }); + } + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/yield-star-spacing.js b/node_modules/eslint/lib/rules/yield-star-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..d5670fd1f454faca38cfaee023cd6de2852e0eda --- /dev/null +++ b/node_modules/eslint/lib/rules/yield-star-spacing.js @@ -0,0 +1,158 @@ +/** + * @fileoverview Rule to check the spacing around the * in yield* expressions. + * @author Bryan Smith + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "yield-star-spacing", + url: "https://eslint.style/rules/yield-star-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require or disallow spacing around the `*` in `yield*` expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/yield-star-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["before", "after", "both", "neither"], + }, + { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + missingBefore: "Missing space before *.", + missingAfter: "Missing space after *.", + unexpectedBefore: "Unexpected space before *.", + unexpectedAfter: "Unexpected space after *.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const mode = (function (option) { + if (!option || typeof option === "string") { + return { + before: { before: true, after: false }, + after: { before: false, after: true }, + both: { before: true, after: true }, + neither: { before: false, after: false }, + }[option || "after"]; + } + return option; + })(context.options[0]); + + /** + * Checks the spacing between two tokens before or after the star token. + * @param {string} side Either "before" or "after". + * @param {Token} leftToken `function` keyword token if side is "before", or + * star token if side is "after". + * @param {Token} rightToken Star token if side is "before", or identifier + * token if side is "after". + * @returns {void} + */ + function checkSpacing(side, leftToken, rightToken) { + if ( + sourceCode.isSpaceBetween(leftToken, rightToken) !== mode[side] + ) { + const after = leftToken.value === "*"; + const spaceRequired = mode[side]; + const node = after ? leftToken : rightToken; + let messageId; + + if (spaceRequired) { + messageId = + side === "before" ? "missingBefore" : "missingAfter"; + } else { + messageId = + side === "before" + ? "unexpectedBefore" + : "unexpectedAfter"; + } + + context.report({ + node, + messageId, + fix(fixer) { + if (spaceRequired) { + if (after) { + return fixer.insertTextAfter(node, " "); + } + return fixer.insertTextBefore(node, " "); + } + return fixer.removeRange([ + leftToken.range[1], + rightToken.range[0], + ]); + }, + }); + } + } + + /** + * Enforces the spacing around the star if node is a yield* expression. + * @param {ASTNode} node A yield expression node. + * @returns {void} + */ + function checkExpression(node) { + if (!node.delegate) { + return; + } + + const tokens = sourceCode.getFirstTokens(node, 3); + const yieldToken = tokens[0]; + const starToken = tokens[1]; + const nextToken = tokens[2]; + + checkSpacing("before", yieldToken, starToken); + checkSpacing("after", starToken, nextToken); + } + + return { + YieldExpression: checkExpression, + }; + }, +}; diff --git a/node_modules/eslint/lib/rules/yoda.js b/node_modules/eslint/lib/rules/yoda.js new file mode 100644 index 0000000000000000000000000000000000000000..1ee74712da0962c87010fa0e50d56bb91c16ddde --- /dev/null +++ b/node_modules/eslint/lib/rules/yoda.js @@ -0,0 +1,362 @@ +/** + * @fileoverview Rule to require or disallow yoda comparisons + * @author Nicholas C. Zakas + */ +"use strict"; + +//-------------------------------------------------------------------------- +// Requirements +//-------------------------------------------------------------------------- + +const astUtils = require("./utils/ast-utils"); + +//-------------------------------------------------------------------------- +// Helpers +//-------------------------------------------------------------------------- + +/** + * Determines whether an operator is a comparison operator. + * @param {string} operator The operator to check. + * @returns {boolean} Whether or not it is a comparison operator. + */ +function isComparisonOperator(operator) { + return /^(?:==|===|!=|!==|<|>|<=|>=)$/u.test(operator); +} + +/** + * Determines whether an operator is an equality operator. + * @param {string} operator The operator to check. + * @returns {boolean} Whether or not it is an equality operator. + */ +function isEqualityOperator(operator) { + return /^(?:==|===)$/u.test(operator); +} + +/** + * Determines whether an operator is one used in a range test. + * Allowed operators are `<` and `<=`. + * @param {string} operator The operator to check. + * @returns {boolean} Whether the operator is used in range tests. + */ +function isRangeTestOperator(operator) { + return ["<", "<="].includes(operator); +} + +/** + * Determines whether a non-Literal node is a negative number that should be + * treated as if it were a single Literal node. + * @param {ASTNode} node Node to test. + * @returns {boolean} True if the node is a negative number that looks like a + * real literal and should be treated as such. + */ +function isNegativeNumericLiteral(node) { + return ( + node.type === "UnaryExpression" && + node.operator === "-" && + node.prefix && + astUtils.isNumericLiteral(node.argument) + ); +} + +/** + * Determines whether a non-Literal node should be treated as a single Literal node. + * @param {ASTNode} node Node to test + * @returns {boolean} True if the node should be treated as a single Literal node. + */ +function looksLikeLiteral(node) { + return ( + isNegativeNumericLiteral(node) || astUtils.isStaticTemplateLiteral(node) + ); +} + +/** + * Attempts to derive a Literal node from nodes that are treated like literals. + * @param {ASTNode} node Node to normalize. + * @returns {ASTNode} One of the following options. + * 1. The original node if the node is already a Literal + * 2. A normalized Literal node with the negative number as the value if the + * node represents a negative number literal. + * 3. A normalized Literal node with the string as the value if the node is + * a Template Literal without expression. + * 4. Otherwise `null`. + */ +function getNormalizedLiteral(node) { + if (node.type === "Literal") { + return node; + } + + if (isNegativeNumericLiteral(node)) { + return { + type: "Literal", + value: -node.argument.value, + raw: `-${node.argument.value}`, + }; + } + + if (astUtils.isStaticTemplateLiteral(node)) { + return { + type: "Literal", + value: node.quasis[0].value.cooked, + raw: node.quasis[0].value.raw, + }; + } + + return null; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + "never", + { + exceptRange: false, + onlyEquality: false, + }, + ], + + docs: { + description: 'Require or disallow "Yoda" conditions', + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/yoda", + }, + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + exceptRange: { + type: "boolean", + }, + onlyEquality: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + messages: { + expected: + "Expected literal to be on the {{expectedSide}} side of {{operator}}.", + }, + }, + + create(context) { + const [when, { exceptRange, onlyEquality }] = context.options; + const always = when === "always"; + const sourceCode = context.sourceCode; + + /** + * Determines whether node represents a range test. + * A range test is a "between" test like `(0 <= x && x < 1)` or an "outside" + * test like `(x < 0 || 1 <= x)`. It must be wrapped in parentheses, and + * both operators must be `<` or `<=`. Finally, the literal on the left side + * must be less than or equal to the literal on the right side so that the + * test makes any sense. + * @param {ASTNode} node LogicalExpression node to test. + * @returns {boolean} Whether node is a range test. + */ + function isRangeTest(node) { + const left = node.left, + right = node.right; + + /** + * Determines whether node is of the form `0 <= x && x < 1`. + * @returns {boolean} Whether node is a "between" range test. + */ + function isBetweenTest() { + if ( + node.operator === "&&" && + astUtils.isSameReference(left.right, right.left) + ) { + const leftLiteral = getNormalizedLiteral(left.left); + const rightLiteral = getNormalizedLiteral(right.right); + + if (leftLiteral === null && rightLiteral === null) { + return false; + } + + if (rightLiteral === null || leftLiteral === null) { + return true; + } + + if (leftLiteral.value <= rightLiteral.value) { + return true; + } + } + return false; + } + + /** + * Determines whether node is of the form `x < 0 || 1 <= x`. + * @returns {boolean} Whether node is an "outside" range test. + */ + function isOutsideTest() { + if ( + node.operator === "||" && + astUtils.isSameReference(left.left, right.right) + ) { + const leftLiteral = getNormalizedLiteral(left.right); + const rightLiteral = getNormalizedLiteral(right.left); + + if (leftLiteral === null && rightLiteral === null) { + return false; + } + + if (rightLiteral === null || leftLiteral === null) { + return true; + } + + if (leftLiteral.value <= rightLiteral.value) { + return true; + } + } + + return false; + } + + /** + * Determines whether node is wrapped in parentheses. + * @returns {boolean} Whether node is preceded immediately by an open + * paren token and followed immediately by a close + * paren token. + */ + function isParenWrapped() { + return astUtils.isParenthesised(sourceCode, node); + } + + return ( + node.type === "LogicalExpression" && + left.type === "BinaryExpression" && + right.type === "BinaryExpression" && + isRangeTestOperator(left.operator) && + isRangeTestOperator(right.operator) && + (isBetweenTest() || isOutsideTest()) && + isParenWrapped() + ); + } + + const OPERATOR_FLIP_MAP = { + "===": "===", + "!==": "!==", + "==": "==", + "!=": "!=", + "<": ">", + ">": "<", + "<=": ">=", + ">=": "<=", + }; + + /** + * Returns a string representation of a BinaryExpression node with its sides/operator flipped around. + * @param {ASTNode} node The BinaryExpression node + * @returns {string} A string representation of the node with the sides and operator flipped + */ + function getFlippedString(node) { + const operatorToken = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + const lastLeftToken = sourceCode.getTokenBefore(operatorToken); + const firstRightToken = sourceCode.getTokenAfter(operatorToken); + + const source = sourceCode.getText(); + + const leftText = source.slice( + node.range[0], + lastLeftToken.range[1], + ); + const textBeforeOperator = source.slice( + lastLeftToken.range[1], + operatorToken.range[0], + ); + const textAfterOperator = source.slice( + operatorToken.range[1], + firstRightToken.range[0], + ); + const rightText = source.slice( + firstRightToken.range[0], + node.range[1], + ); + + const tokenBefore = sourceCode.getTokenBefore(node); + const tokenAfter = sourceCode.getTokenAfter(node); + let prefix = ""; + let suffix = ""; + + if ( + tokenBefore && + tokenBefore.range[1] === node.range[0] && + !astUtils.canTokensBeAdjacent(tokenBefore, firstRightToken) + ) { + prefix = " "; + } + + if ( + tokenAfter && + node.range[1] === tokenAfter.range[0] && + !astUtils.canTokensBeAdjacent(lastLeftToken, tokenAfter) + ) { + suffix = " "; + } + + return ( + prefix + + rightText + + textBeforeOperator + + OPERATOR_FLIP_MAP[operatorToken.value] + + textAfterOperator + + leftText + + suffix + ); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + BinaryExpression(node) { + const expectedLiteral = always ? node.left : node.right; + const expectedNonLiteral = always ? node.right : node.left; + + // If `expectedLiteral` is not a literal, and `expectedNonLiteral` is a literal, raise an error. + if ( + (expectedNonLiteral.type === "Literal" || + looksLikeLiteral(expectedNonLiteral)) && + !( + expectedLiteral.type === "Literal" || + looksLikeLiteral(expectedLiteral) + ) && + !(!isEqualityOperator(node.operator) && onlyEquality) && + isComparisonOperator(node.operator) && + !(exceptRange && isRangeTest(node.parent)) + ) { + context.report({ + node, + messageId: "expected", + data: { + operator: node.operator, + expectedSide: always ? "left" : "right", + }, + fix: fixer => + fixer.replaceText(node, getFlippedString(node)), + }); + } + }, + }; + }, +}; diff --git a/node_modules/eslint/lib/services/parser-service.js b/node_modules/eslint/lib/services/parser-service.js new file mode 100644 index 0000000000000000000000000000000000000000..7aab036e3cde8c05a559ecceee2429cf1b9c4022 --- /dev/null +++ b/node_modules/eslint/lib/services/parser-service.js @@ -0,0 +1,64 @@ +/** + * @fileoverview ESLint Parser + * @author Nicholas C. Zakas + */ +/* eslint class-methods-use-this: off -- Anticipate future constructor arguments. */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** @typedef {import("../linter/vfile.js").VFile} VFile */ +/** @typedef {import("@eslint/core").Language} Language */ +/** @typedef {import("@eslint/core").LanguageOptions} LanguageOptions */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * The parser for ESLint. + */ +class ParserService { + /** + * Parses the given file synchronously. + * @param {VFile} file The file to parse. + * @param {{language:Language,languageOptions:LanguageOptions}} config The configuration to use. + * @returns {Object} An object with the parsed source code or errors. + * @throws {Error} If the parser returns a promise. + */ + parseSync(file, config) { + const { language, languageOptions } = config; + const result = language.parse(file, { languageOptions }); + + if (typeof result.then === "function") { + throw new Error("Unsupported: Language parser returned a promise."); + } + + if (result.ok) { + return { + ok: true, + sourceCode: language.createSourceCode(file, result, { + languageOptions, + }), + }; + } + + // if we made it to here there was an error + return { + ok: false, + errors: result.errors.map(error => ({ + ruleId: null, + fatal: true, + severity: 2, + message: `Parsing error: ${error.message}`, + line: error.line, + column: error.column, + })), + }; + } +} + +module.exports = { ParserService }; diff --git a/node_modules/eslint/lib/services/processor-service.js b/node_modules/eslint/lib/services/processor-service.js new file mode 100644 index 0000000000000000000000000000000000000000..6f079d7bdc695d4eaf41b1880c46003f233dd15b --- /dev/null +++ b/node_modules/eslint/lib/services/processor-service.js @@ -0,0 +1,100 @@ +/** + * @fileoverview ESLint Processor Service + * @author Nicholas C. Zakas + */ +/* eslint class-methods-use-this: off -- Anticipate future constructor arguments. */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const path = require("node:path"); +const { VFile } = require("../linter/vfile.js"); + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../linter/vfile.js").VFile} VFile */ +/** @typedef {import("@eslint/core").Language} Language */ +/** @typedef {import("eslint").Linter.Processor} Processor */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * The service that applies processors to files. + */ +class ProcessorService { + /** + * Preprocesses the given file synchronously. + * @param {VFile} file The file to preprocess. + * @param {{processor:Processor}} config The configuration to use. + * @returns {{ok:boolean, files?: Array, errors?: Array}} An array of preprocessed files or errors. + * @throws {Error} If the preprocessor returns a promise. + */ + preprocessSync(file, config) { + const { processor } = config; + let blocks; + + try { + blocks = processor.preprocess(file.rawBody, file.path); + } catch (ex) { + // If the message includes a leading line number, strip it: + const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`; + + return { + ok: false, + errors: [ + { + ruleId: null, + fatal: true, + severity: 2, + message, + line: ex.lineNumber, + column: ex.column, + }, + ], + }; + } + + if (typeof blocks.then === "function") { + throw new Error("Unsupported: Preprocessor returned a promise."); + } + + return { + ok: true, + files: blocks.map((block, i) => { + // Legacy behavior: return the block as a string + if (typeof block === "string") { + return block; + } + + const filePath = path.join(file.path, `${i}_${block.filename}`); + + return new VFile(filePath, block.text, { + physicalPath: file.physicalPath, + }); + }), + }; + } + + /** + * Postprocesses the given messages synchronously. + * @param {VFile} file The file to postprocess. + * @param {LintMessage[][]} messages The messages to postprocess. + * @param {{processor:Processor}} config The configuration to use. + * @returns {LintMessage[]} The postprocessed messages. + */ + postprocessSync(file, messages, config) { + const { processor } = config; + + return processor.postprocess(messages, file.path); + } +} + +module.exports = { ProcessorService }; diff --git a/node_modules/eslint/lib/services/suppressions-service.js b/node_modules/eslint/lib/services/suppressions-service.js new file mode 100644 index 0000000000000000000000000000000000000000..b5616eb43e29586961091b6a702bd7d74352397e --- /dev/null +++ b/node_modules/eslint/lib/services/suppressions-service.js @@ -0,0 +1,304 @@ +/** + * @fileoverview Manages the suppressed violations. + * @author Iacovos Constantinou + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const fs = require("node:fs"); +const path = require("node:path"); +const { calculateStatsPerFile } = require("../shared/message-counts"); +const stringify = require("json-stable-stringify-without-jsonify"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +// For VSCode IntelliSense +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").ESLint.LintResult} LintResult */ +/** @typedef {Record>} SuppressedViolations */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Manages the suppressed violations. + */ +class SuppressionsService { + static DEFAULT_SUPPRESSIONS_FILENAME = "eslint-suppressions.json"; + + filePath = ""; + cwd = ""; + + /** + * Creates a new instance of SuppressionsService. + * @param {Object} options The options. + * @param {string} [options.filePath] The location of the suppressions file. + * @param {string} [options.cwd] The current working directory. + */ + constructor({ filePath, cwd }) { + this.filePath = filePath; + this.cwd = cwd; + } + + /** + * Updates the suppressions file based on the current violations and the provided rules. + * If no rules are provided, all violations are suppressed. + * @param {LintResult[]|undefined} results The lint results. + * @param {string[]|undefined} rules The rules to suppress. + * @returns {Promise} + */ + async suppress(results, rules) { + const suppressions = await this.load(); + + for (const result of results) { + const relativeFilePath = this.getRelativeFilePath(result.filePath); + const violationsByRule = SuppressionsService.countViolationsByRule( + result.messages, + ); + + for (const ruleId in violationsByRule) { + if (rules && !rules.includes(ruleId)) { + continue; + } + + suppressions[relativeFilePath] ??= {}; + suppressions[relativeFilePath][ruleId] = + violationsByRule[ruleId]; + } + } + + return this.save(suppressions); + } + + /** + * Removes old, unused suppressions for violations that do not occur anymore. + * @param {LintResult[]} results The lint results. + * @returns {Promise} No return value. + */ + async prune(results) { + const suppressions = await this.load(); + const { unused } = this.applySuppressions(results, suppressions); + + for (const file in unused) { + if (!suppressions[file]) { + continue; + } + + for (const rule in unused[file]) { + if (!suppressions[file][rule]) { + continue; + } + + const suppressionsCount = suppressions[file][rule].count; + const violationsCount = unused[file][rule].count; + + if (suppressionsCount === violationsCount) { + // Remove unused rules + delete suppressions[file][rule]; + } else { + // Update the count to match the new number of violations + suppressions[file][rule].count -= violationsCount; + } + } + + // Cleanup files with no rules + if (Object.keys(suppressions[file]).length === 0) { + delete suppressions[file]; + } + } + + for (const file of Object.keys(suppressions)) { + const absolutePath = path.resolve(this.cwd, file); + + if (!fs.existsSync(absolutePath)) { + delete suppressions[file]; + } + } + + return this.save(suppressions); + } + + /** + * Checks the provided suppressions against the lint results. + * + * For each file, counts the number of violations per rule. + * For each rule in each file, compares the number of violations against the counter from the suppressions file. + * If the number of violations is less or equal to the counter, messages are moved to `LintResult#suppressedMessages` and ignored. + * Otherwise, all violations are reported as usual. + * @param {LintResult[]} results The lint results. + * @param {SuppressedViolations} suppressions The suppressions. + * @returns {{ + * results: LintResult[], + * unused: SuppressedViolations + * }} The updated results and the unused suppressions. + */ + applySuppressions(results, suppressions) { + /** + * We copy the results to avoid modifying the original objects + * We remove only result messages that are matched and hence suppressed + * We leave the rest untouched to minimize the risk of losing parts of the original data + */ + const filtered = structuredClone(results); + const unused = {}; + + for (const result of filtered) { + const relativeFilePath = this.getRelativeFilePath(result.filePath); + + if (!suppressions[relativeFilePath]) { + continue; + } + + const violationsByRule = SuppressionsService.countViolationsByRule( + result.messages, + ); + let wasSuppressed = false; + + for (const ruleId in violationsByRule) { + if (!suppressions[relativeFilePath][ruleId]) { + continue; + } + + const suppressionsCount = + suppressions[relativeFilePath][ruleId].count; + const violationsCount = violationsByRule[ruleId].count; + + // Suppress messages if the number of violations is less or equal to the suppressions count + if (violationsCount <= suppressionsCount) { + SuppressionsService.suppressMessagesByRule(result, ruleId); + wasSuppressed = true; + } + + // Update the count to match the new number of violations, otherwise remove the rule entirely + if (violationsCount < suppressionsCount) { + unused[relativeFilePath] ??= {}; + unused[relativeFilePath][ruleId] ??= {}; + unused[relativeFilePath][ruleId].count = + suppressionsCount - violationsCount; + } + } + + // Mark as unused all the suppressions that were not matched against a rule + for (const ruleId in suppressions[relativeFilePath]) { + if (violationsByRule[ruleId]) { + continue; + } + + unused[relativeFilePath] ??= {}; + unused[relativeFilePath][ruleId] = + suppressions[relativeFilePath][ruleId]; + } + + // Recalculate stats if messages were suppressed + if (wasSuppressed) { + Object.assign(result, calculateStatsPerFile(result.messages)); + } + } + + return { + results: filtered, + unused, + }; + } + + /** + * Loads the suppressions file. + * @throws {Error} If the suppressions file cannot be parsed. + * @returns {Promise} The suppressions. + */ + async load() { + try { + const data = await fs.promises.readFile(this.filePath, "utf8"); + + return JSON.parse(data); + } catch (err) { + if (err.code === "ENOENT") { + return {}; + } + throw new Error( + `Failed to parse suppressions file at ${this.filePath}`, + { + cause: err, + }, + ); + } + } + + /** + * Updates the suppressions file. + * @param {SuppressedViolations} suppressions The suppressions to save. + * @returns {Promise} + * @private + */ + save(suppressions) { + return fs.promises.writeFile( + this.filePath, + stringify(suppressions, { space: 2 }), + ); + } + + /** + * Counts the violations by rule, ignoring warnings. + * @param {LintMessage[]} messages The messages to count. + * @returns {Record} The number of violations by rule. + */ + static countViolationsByRule(messages) { + return messages.reduce((totals, message) => { + if (message.severity === 2 && message.ruleId) { + totals[message.ruleId] ??= { count: 0 }; + totals[message.ruleId].count++; + } + return totals; + }, {}); + } + + /** + * Returns the relative path of a file to the current working directory. + * Always in POSIX format for consistency and interoperability. + * @param {string} filePath The file path. + * @returns {string} The relative file path. + */ + getRelativeFilePath(filePath) { + return path + .relative(this.cwd, filePath) + .split(path.sep) + .join(path.posix.sep); + } + + /** + * Moves the messages matching the rule to `LintResult#suppressedMessages` and updates the stats. + * @param {LintResult} result The result to update. + * @param {string} ruleId The rule to suppress. + * @returns {void} + */ + static suppressMessagesByRule(result, ruleId) { + const suppressedMessages = result.messages.filter( + message => message.ruleId === ruleId, + ); + + result.suppressedMessages = result.suppressedMessages.concat( + suppressedMessages.map(message => { + message.suppressions = [ + { + kind: "file", + justification: "", + }, + ]; + + return message; + }), + ); + + result.messages = result.messages.filter( + message => message.ruleId !== ruleId, + ); + } +} + +module.exports = { SuppressionsService }; diff --git a/node_modules/eslint/lib/services/warning-service.js b/node_modules/eslint/lib/services/warning-service.js new file mode 100644 index 0000000000000000000000000000000000000000..a8fca1a5cc8bfe87506b4f243e3d439a3c0ffdb2 --- /dev/null +++ b/node_modules/eslint/lib/services/warning-service.js @@ -0,0 +1,87 @@ +/** + * @fileoverview Emits warnings for ESLint. + * @author Francesco Trotta + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A service that emits warnings for ESLint. + */ +class WarningService { + /** + * Creates a new instance of the service. + * @param {{ emitWarning?: ((warning: string, type: string) => void) | undefined }} [options] A function called internally to emit warnings using API provided by the runtime. + */ + constructor({ + emitWarning = globalThis.process?.emitWarning ?? (() => {}), + } = {}) { + this.emitWarning = emitWarning; + } + + /** + * Emits a warning when circular fixes are detected while fixing a file. + * This method is used by the Linter and is safe to call outside Node.js. + * @param {string} filename The name of the file being fixed. + * @returns {void} + */ + emitCircularFixesWarning(filename) { + this.emitWarning( + `Circular fixes detected while fixing ${filename}. It is likely that you have conflicting rules in your configuration.`, + "ESLintCircularFixesWarning", + ); + } + + /** + * Emits a warning when an empty config file has been loaded. + * @param {string} configFilePath The path to the config file. + * @returns {void} + */ + emitEmptyConfigWarning(configFilePath) { + this.emitWarning( + `Running ESLint with an empty config (from ${configFilePath}). Please double-check that this is what you want. If you want to run ESLint with an empty config, export [{}] to remove this warning.`, + "ESLintEmptyConfigWarning", + ); + } + + /** + * Emits a warning when an ".eslintignore" file is found. + * @returns {void} + */ + emitESLintIgnoreWarning() { + this.emitWarning( + 'The ".eslintignore" file is no longer supported. Switch to using the "ignores" property in "eslint.config.js": https://eslint.org/docs/latest/use/configure/migration-guide#ignore-files', + "ESLintIgnoreWarning", + ); + } + + /** + * Emits a warning when an inactive flag is used. + * This method is used by the Linter and is safe to call outside Node.js. + * @param {string} flag The name of the flag. + * @param {string} message The warning message. + * @returns {void} + */ + emitInactiveFlagWarning(flag, message) { + this.emitWarning(message, `ESLintInactiveFlag_${flag}`); + } + + /** + * Emits a warning when a suboptimal concurrency setting is detected. + * Currently, this is only used to warn when the net linting ratio is low. + * @param {string} notice A notice about how to improve performance. + * @returns {void} + */ + emitPoorConcurrencyWarning(notice) { + this.emitWarning( + `You may ${notice} to improve performance.`, + "ESLintPoorConcurrencyWarning", + ); + } +} + +module.exports = { WarningService }; diff --git a/node_modules/eslint/lib/shared/ajv.js b/node_modules/eslint/lib/shared/ajv.js new file mode 100644 index 0000000000000000000000000000000000000000..5c5c41bd7470bd190bd4efb5caab88c73ae01f56 --- /dev/null +++ b/node_modules/eslint/lib/shared/ajv.js @@ -0,0 +1,34 @@ +/** + * @fileoverview The instance of Ajv validator. + * @author Evgeny Poberezkin + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Ajv = require("ajv"), + metaSchema = require("ajv/lib/refs/json-schema-draft-04.json"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = (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's API + ajv._opts.defaultMeta = metaSchema.id; + + return ajv; +}; diff --git a/node_modules/eslint/lib/shared/assert.js b/node_modules/eslint/lib/shared/assert.js new file mode 100644 index 0000000000000000000000000000000000000000..4dcaf41f86c5d8b6558a0b38f7ef878b413d1d26 --- /dev/null +++ b/node_modules/eslint/lib/shared/assert.js @@ -0,0 +1,21 @@ +/** + * @fileoverview Assertion utilities equivalent to the Node.js node:asserts module. + * @author Josh Goldberg + */ + +"use strict"; + +/** + * Throws an error if the input is not truthy. + * @param {unknown} value The input that is checked for being truthy. + * @param {string} message Message to throw if the input is not truthy. + * @returns {void} + * @throws {Error} When the condition is not truthy. + */ +function ok(value, message = "Assertion failed.") { + if (!value) { + throw new Error(message); + } +} + +module.exports = ok; diff --git a/node_modules/eslint/lib/shared/ast-utils.js b/node_modules/eslint/lib/shared/ast-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..f7736828b77e98a3b795e850495ad41b72a6c913 --- /dev/null +++ b/node_modules/eslint/lib/shared/ast-utils.js @@ -0,0 +1,30 @@ +/** + * @fileoverview Common utils for AST. + * + * This file contains only shared items for core and rules. + * If you make a utility for rules, please see `../rules/utils/ast-utils.js`. + * + * @author Toru Nagashima + */ +"use strict"; + +const breakableTypePattern = + /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u; +const lineBreakPattern = /\r\n|[\r\n\u2028\u2029]/u; +const shebangPattern = /^#!([^\r\n]+)/u; + +/** + * Creates a version of the `lineBreakPattern` regex with the global flag. + * Global regexes are mutable, so this needs to be a function instead of a constant. + * @returns {RegExp} A global regular expression that matches line terminators + */ +function createGlobalLinebreakMatcher() { + return new RegExp(lineBreakPattern.source, "gu"); +} + +module.exports = { + breakableTypePattern, + lineBreakPattern, + createGlobalLinebreakMatcher, + shebangPattern, +}; diff --git a/node_modules/eslint/lib/shared/deep-merge-arrays.js b/node_modules/eslint/lib/shared/deep-merge-arrays.js new file mode 100644 index 0000000000000000000000000000000000000000..4a8289c46e7980d9ea58dafdd74444ee345fd8e9 --- /dev/null +++ b/node_modules/eslint/lib/shared/deep-merge-arrays.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Applies default rule options + * @author JoshuaKGoldberg + */ + +"use strict"; + +/** + * Check if the variable contains an object strictly rejecting arrays + * @param {unknown} value an object + * @returns {boolean} Whether value is an object + */ +function isObjectNotArray(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Deeply merges second on top of first, creating a new {} object if needed. + * @param {T} first Base, default value. + * @param {U} second User-specified value. + * @returns {T | U | (T & U)} Merged equivalent of second on top of first. + */ +function deepMergeObjects(first, second) { + if (second === void 0) { + return first; + } + + if (!isObjectNotArray(first) || !isObjectNotArray(second)) { + return second; + } + + const result = { ...first, ...second }; + + for (const key of Object.keys(second)) { + if (Object.prototype.propertyIsEnumerable.call(first, key)) { + result[key] = deepMergeObjects(first[key], second[key]); + } + } + + return result; +} + +/** + * Deeply merges second on top of first, creating a new [] array if needed. + * @param {T[]} first Base, default values. + * @param {U[]} second User-specified values. + * @returns {(T | U | (T & U))[]} Merged equivalent of second on top of first. + */ +function deepMergeArrays(first, second) { + if (!first || !second) { + return second || first || []; + } + + return [ + ...first.map((value, i) => + deepMergeObjects(value, i < second.length ? second[i] : void 0), + ), + ...second.slice(first.length), + ]; +} + +module.exports = { deepMergeArrays }; diff --git a/node_modules/eslint/lib/shared/directives.js b/node_modules/eslint/lib/shared/directives.js new file mode 100644 index 0000000000000000000000000000000000000000..f1dddf597d23043cb52d81aa8042031364afa294 --- /dev/null +++ b/node_modules/eslint/lib/shared/directives.js @@ -0,0 +1,16 @@ +/** + * @fileoverview Common utils for directives. + * + * This file contains only shared items for directives. + * If you make a utility for rules, please see `../rules/utils/ast-utils.js`. + * + * @author gfyoung + */ +"use strict"; + +const directivesPattern = + /^(eslint(?:-env|-enable|-disable(?:(?:-next)?-line)?)?|exported|globals?)(?:\s|$)/u; + +module.exports = { + directivesPattern, +}; diff --git a/node_modules/eslint/lib/shared/flags.js b/node_modules/eslint/lib/shared/flags.js new file mode 100644 index 0000000000000000000000000000000000000000..98c050456d02b96b69eb568013baa9a9367b0b6b --- /dev/null +++ b/node_modules/eslint/lib/shared/flags.js @@ -0,0 +1,89 @@ +/** + * @fileoverview Shared flags for ESLint. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @typedef {Object} InactiveFlagData + * @property {string} description Flag description + * @property {string | null} [replacedBy] Can be either: + * - An active flag (string) that enables the same feature. + * - `null` if the feature is now enabled by default. + * - Omitted if the feature has been abandoned. + */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * The set of flags that change ESLint behavior with a description. + * @type {Map} + */ +const activeFlags = new Map([ + ["test_only", "Used only for testing."], + ["test_only_2", "Used only for testing."], + [ + "unstable_native_nodejs_ts_config", + "Use native Node.js to load TypeScript configuration.", + ], +]); + +/** + * The set of flags that used to be active. + * @type {Map} + */ +const inactiveFlags = new Map([ + [ + "test_only_replaced", + { + description: + "Used only for testing flags that have been replaced by other flags.", + replacedBy: "test_only", + }, + ], + [ + "test_only_enabled_by_default", + { + description: + "Used only for testing flags whose features have been enabled by default.", + replacedBy: null, + }, + ], + [ + "test_only_abandoned", + { + description: + "Used only for testing flags whose features have been abandoned.", + }, + ], +]); + +/** + * Creates a message that describes the reason the flag is inactive. + * @param {InactiveFlagData} inactiveFlagData Data for the inactive flag. + * @returns {string} Message describing the reason the flag is inactive. + */ +function getInactivityReasonMessage({ replacedBy }) { + if (typeof replacedBy === "undefined") { + return "This feature has been abandoned."; + } + + if (typeof replacedBy === "string") { + return `This flag has been renamed '${replacedBy}' to reflect its stabilization. Please use '${replacedBy}' instead.`; + } + + // null + return "This feature is now enabled by default."; +} + +module.exports = { + activeFlags, + inactiveFlags, + getInactivityReasonMessage, +}; diff --git a/node_modules/eslint/lib/shared/logging.js b/node_modules/eslint/lib/shared/logging.js new file mode 100644 index 0000000000000000000000000000000000000000..3e8dfb0b071a65317f1d1b39fd6adeb8b7359b05 --- /dev/null +++ b/node_modules/eslint/lib/shared/logging.js @@ -0,0 +1,38 @@ +/** + * @fileoverview Handle logging for ESLint + * @author Gyandeep Singh + */ + +"use strict"; + +/* eslint no-console: "off" -- Logging util */ + +/* c8 ignore next */ +module.exports = { + /** + * Cover for console.info + * @param {...any} args The elements to log. + * @returns {void} + */ + info(...args) { + console.log(...args); + }, + + /** + * Cover for console.warn + * @param {...any} args The elements to log. + * @returns {void} + */ + warn(...args) { + console.warn(...args); + }, + + /** + * Cover for console.error + * @param {...any} args The elements to log. + * @returns {void} + */ + error(...args) { + console.error(...args); + }, +}; diff --git a/node_modules/eslint/lib/shared/message-counts.js b/node_modules/eslint/lib/shared/message-counts.js new file mode 100644 index 0000000000000000000000000000000000000000..a0d47e49bf7f1708ebe063832d935e274e544493 --- /dev/null +++ b/node_modules/eslint/lib/shared/message-counts.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Helpers for counting errors and warnings in lint messages. + * @author Nicholas C. Zakas + * @author Blake Sager + */ + +"use strict"; + +/** + * It will calculate the error and warning count for collection of messages per file + * @param {LintMessage[]} messages Collection of messages + * @returns {Object} Contains the stats + */ +function calculateStatsPerFile(messages) { + const stat = { + errorCount: 0, + fatalErrorCount: 0, + warningCount: 0, + fixableErrorCount: 0, + fixableWarningCount: 0, + }; + + for (let i = 0; i < messages.length; i++) { + const message = messages[i]; + + if (message.fatal || message.severity === 2) { + stat.errorCount++; + if (message.fatal) { + stat.fatalErrorCount++; + } + if (message.fix) { + stat.fixableErrorCount++; + } + } else { + stat.warningCount++; + if (message.fix) { + stat.fixableWarningCount++; + } + } + } + return stat; +} + +module.exports = { + calculateStatsPerFile, +}; diff --git a/node_modules/eslint/lib/shared/naming.js b/node_modules/eslint/lib/shared/naming.js new file mode 100644 index 0000000000000000000000000000000000000000..ee6a0311cfa3378650937bc063e70f92d91ba72e --- /dev/null +++ b/node_modules/eslint/lib/shared/naming.js @@ -0,0 +1,109 @@ +/** + * @fileoverview Common helpers for naming of plugins, formatters and configs + */ + +"use strict"; + +const NAMESPACE_REGEX = /^@.*\//u; + +/** + * 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 +//------------------------------------------------------------------------------ + +module.exports = { + normalizePackageName, + getShorthandName, + getNamespaceFromTerm, +}; diff --git a/node_modules/eslint/lib/shared/option-utils.js b/node_modules/eslint/lib/shared/option-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..0917ba5213fde11d1dc2c213bb466f4f6772030e --- /dev/null +++ b/node_modules/eslint/lib/shared/option-utils.js @@ -0,0 +1,63 @@ +/** + * @fileoverview Utilities to operate on option objects. + * @author Josh Goldberg + */ + +"use strict"; + +/** + * Determines whether any of input's properties are different + * from values that already exist in original. + * @template T + * @param {Partial} input New value. + * @param {T} original Original value. + * @returns {boolean} Whether input includes an explicit difference. + */ +function containsDifferentProperty(input, original) { + if (input === original) { + return false; + } + + if ( + typeof input !== typeof original || + Array.isArray(input) !== Array.isArray(original) + ) { + return true; + } + + if (Array.isArray(input)) { + return ( + input.length !== original.length || + input.some((value, i) => + containsDifferentProperty(value, original[i]), + ) + ); + } + + if (typeof input === "object") { + if (input === null || original === null) { + return true; + } + + const inputKeys = Object.keys(input); + const originalKeys = Object.keys(original); + + return ( + inputKeys.length !== originalKeys.length || + inputKeys.some( + inputKey => + !Object.hasOwn(original, inputKey) || + containsDifferentProperty( + input[inputKey], + original[inputKey], + ), + ) + ); + } + + return true; +} + +module.exports = { + containsDifferentProperty, +}; diff --git a/node_modules/eslint/lib/shared/relative-module-resolver.js b/node_modules/eslint/lib/shared/relative-module-resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..14e7eec16d8d9f5af6038640a9e9a40f10404cc3 --- /dev/null +++ b/node_modules/eslint/lib/shared/relative-module-resolver.js @@ -0,0 +1,28 @@ +/** + * Utility for resolving a module relative to another module + * @author Teddy Katz + */ + +"use strict"; + +const Module = require("node: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` + * @throws {Error} When the module cannot be resolved. + */ +function resolve(moduleName, relativeToPath) { + return createRequire(relativeToPath).resolve(moduleName); +} + +exports.resolve = resolve; diff --git a/node_modules/eslint/lib/shared/runtime-info.js b/node_modules/eslint/lib/shared/runtime-info.js new file mode 100644 index 0000000000000000000000000000000000000000..54fd7609da920c1d1d10ce969de89200b546e39b --- /dev/null +++ b/node_modules/eslint/lib/shared/runtime-info.js @@ -0,0 +1,177 @@ +/** + * @fileoverview Utility to get information about the execution environment. + * @author Kai Cataldo + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const path = require("node:path"); +const spawn = require("cross-spawn"); +const os = require("node:os"); +const log = require("../shared/logging"); +const packageJson = require("../../package.json"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Generates and returns execution environment information. + * @returns {string} A string that contains execution environment information. + */ +function environment() { + const cache = new Map(); + + /** + * Checks if a path is a child of a directory. + * @param {string} parentPath The parent path to check. + * @param {string} childPath The path to check. + * @returns {boolean} Whether or not the given path is a child of a directory. + */ + function isChildOfDirectory(parentPath, childPath) { + return !path.relative(parentPath, childPath).startsWith(".."); + } + + /** + * Synchronously executes a shell command and formats the result. + * @param {string} cmd The command to execute. + * @param {Array} args The arguments to be executed with the command. + * @throws {Error} As may be collected by `cross-spawn.sync`. + * @returns {string} The version returned by the command. + */ + function execCommand(cmd, args) { + const key = [cmd, ...args].join(" "); + + if (cache.has(key)) { + return cache.get(key); + } + + const process = spawn.sync(cmd, args, { encoding: "utf8" }); + + if (process.error) { + throw process.error; + } + + const result = process.stdout.trim(); + + cache.set(key, result); + return result; + } + + /** + * Normalizes a version number. + * @param {string} versionStr The string to normalize. + * @returns {string} The normalized version number. + */ + function normalizeVersionStr(versionStr) { + return versionStr.startsWith("v") ? versionStr : `v${versionStr}`; + } + + /** + * Gets bin version. + * @param {string} bin The bin to check. + * @throws {Error} As may be collected by `cross-spawn.sync`. + * @returns {string} The normalized version returned by the command. + */ + function getBinVersion(bin) { + const binArgs = ["--version"]; + + try { + return normalizeVersionStr(execCommand(bin, binArgs)); + } catch (e) { + log.error( + `Error finding ${bin} version running the command \`${bin} ${binArgs.join(" ")}\``, + ); + throw e; + } + } + + /** + * Gets installed npm package version. + * @param {string} pkg The package to check. + * @param {boolean} global Whether to check globally or not. + * @throws {Error} As may be collected by `cross-spawn.sync`. + * @returns {string} The normalized version returned by the command. + */ + function getNpmPackageVersion(pkg, { global = false } = {}) { + const npmBinArgs = ["bin", "-g"]; + const npmLsArgs = ["ls", "--depth=0", "--json", pkg]; + + if (global) { + npmLsArgs.push("-g"); + } + + try { + const parsedStdout = JSON.parse(execCommand("npm", npmLsArgs)); + + /* + * Checking globally returns an empty JSON object, while local checks + * include the name and version of the local project. + */ + if ( + Object.keys(parsedStdout).length === 0 || + !(parsedStdout.dependencies && parsedStdout.dependencies.eslint) + ) { + return "Not found"; + } + + const [, processBinPath] = process.argv; + let npmBinPath; + + try { + npmBinPath = execCommand("npm", npmBinArgs); + } catch (e) { + log.error( + `Error finding npm binary path when running command \`npm ${npmBinArgs.join(" ")}\``, + ); + throw e; + } + + const isGlobal = isChildOfDirectory(npmBinPath, processBinPath); + let pkgVersion = parsedStdout.dependencies.eslint.version; + + if ((global && isGlobal) || (!global && !isGlobal)) { + pkgVersion += " (Currently used)"; + } + + return normalizeVersionStr(pkgVersion); + } catch (e) { + log.error( + `Error finding ${pkg} version running the command \`npm ${npmLsArgs.join(" ")}\``, + ); + throw e; + } + } + + return [ + "Environment Info:", + "", + `Node version: ${process.version}`, + `npm version: ${getBinVersion("npm")}`, + `Local ESLint version: ${getNpmPackageVersion("eslint", { global: false })}`, + `Global ESLint version: ${getNpmPackageVersion("eslint", { global: true })}`, + `Operating System: ${os.platform()} ${os.release()}`, + ].join("\n"); +} + +/** + * Returns version of currently executing ESLint. + * @returns {string} The version from the currently executing ESLint's package.json. + */ +function version() { + return `v${packageJson.version}`; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + __esModule: true, // Indicate intent for imports, remove ambiguity for Knip (see: https://github.com/eslint/eslint/pull/18005#discussion_r1484422616) + environment, + version, +}; diff --git a/node_modules/eslint/lib/shared/serialization.js b/node_modules/eslint/lib/shared/serialization.js new file mode 100644 index 0000000000000000000000000000000000000000..01cacf5ee84eaf2fa11b0a96b47d3c208ae0f3f9 --- /dev/null +++ b/node_modules/eslint/lib/shared/serialization.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Serialization utils. + * @author Bryan Mishkin + */ + +"use strict"; + +/** + * Check if a value is a primitive or plain object created by the Object constructor. + * @param {any} val the value to check + * @returns {boolean} true if so + * @private + */ +function isSerializablePrimitiveOrPlainObject(val) { + return ( + val === null || + typeof val === "string" || + typeof val === "boolean" || + typeof val === "number" || + (typeof val === "object" && val.constructor === Object) || + Array.isArray(val) + ); +} + +/** + * Check if a value is serializable. + * Functions or objects like RegExp cannot be serialized by JSON.stringify(). + * Inspired by: https://stackoverflow.com/questions/30579940/reliable-way-to-check-if-objects-is-serializable-in-javascript + * @param {any} val The value + * @param {Set} seenObjects Objects already seen in this path from the root object. + * @returns {boolean} `true` if the value is serializable + */ +function isSerializable(val, seenObjects = new Set()) { + if (!isSerializablePrimitiveOrPlainObject(val)) { + return false; + } + if (typeof val === "object" && val !== null) { + if (seenObjects.has(val)) { + /* + * Since this is a depth-first traversal, encountering + * the same object again means there is a circular reference. + * Objects with circular references are not serializable. + */ + return false; + } + for (const property in val) { + if (Object.hasOwn(val, property)) { + if (!isSerializablePrimitiveOrPlainObject(val[property])) { + return false; + } + if ( + typeof val[property] === "object" && + val[property] !== null + ) { + if ( + /* + * We're creating a new Set of seen objects because we want to + * ensure that `val` doesn't appear again in this path, but it can appear + * in other paths. This allows for reusing objects in the graph, as long as + * there are no cycles. + */ + !isSerializable( + val[property], + new Set([...seenObjects, val]), + ) + ) { + return false; + } + } + } + } + } + return true; +} + +module.exports = { + isSerializable, +}; diff --git a/node_modules/eslint/lib/shared/severity.js b/node_modules/eslint/lib/shared/severity.js new file mode 100644 index 0000000000000000000000000000000000000000..382704b5a66fa04a5cc6adff686ed2a5e9e1df22 --- /dev/null +++ b/node_modules/eslint/lib/shared/severity.js @@ -0,0 +1,49 @@ +/** + * @fileoverview Helpers for severity values (e.g. normalizing different types). + * @author Bryan Mishkin + */ + +"use strict"; + +/** + * Convert severity value of different types to a string. + * @param {string|number} severity severity value + * @throws error if severity is invalid + * @returns {string} severity string + */ +function normalizeSeverityToString(severity) { + if ([2, "2", "error"].includes(severity)) { + return "error"; + } + if ([1, "1", "warn"].includes(severity)) { + return "warn"; + } + if ([0, "0", "off"].includes(severity)) { + return "off"; + } + throw new Error(`Invalid severity value: ${severity}`); +} + +/** + * Convert severity value of different types to a number. + * @param {string|number} severity severity value + * @throws error if severity is invalid + * @returns {number} severity number + */ +function normalizeSeverityToNumber(severity) { + if ([2, "2", "error"].includes(severity)) { + return 2; + } + if ([1, "1", "warn"].includes(severity)) { + return 1; + } + if ([0, "0", "off"].includes(severity)) { + return 0; + } + throw new Error(`Invalid severity value: ${severity}`); +} + +module.exports = { + normalizeSeverityToString, + normalizeSeverityToNumber, +}; diff --git a/node_modules/eslint/lib/shared/stats.js b/node_modules/eslint/lib/shared/stats.js new file mode 100644 index 0000000000000000000000000000000000000000..791b770833017787e68316d36092b85e6b63ab72 --- /dev/null +++ b/node_modules/eslint/lib/shared/stats.js @@ -0,0 +1,30 @@ +/** + * @fileoverview Provides helper functions to start/stop the time measurements + * that are provided by the ESLint 'stats' option. + * @author Mara Kiefer + */ +"use strict"; + +/** + * Start time measurement + * @returns {[number, number]} t variable for tracking time + */ +function startTime() { + return process.hrtime(); +} + +/** + * End time measurement + * @param {[number, number]} t Variable for tracking time + * @returns {number} The measured time in milliseconds + */ +function endTime(t) { + const time = process.hrtime(t); + + return time[0] * 1e3 + time[1] / 1e6; +} + +module.exports = { + startTime, + endTime, +}; diff --git a/node_modules/eslint/lib/shared/string-utils.js b/node_modules/eslint/lib/shared/string-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..954c5bfff4aeccdba32e1bdc15961b9c30b53a74 --- /dev/null +++ b/node_modules/eslint/lib/shared/string-utils.js @@ -0,0 +1,58 @@ +/** + * @fileoverview Utilities to operate on strings. + * @author Stephen Wade + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// eslint-disable-next-line no-control-regex -- intentionally including control characters +const ASCII_REGEX = /^[\u0000-\u007f]*$/u; + +/** @type {Intl.Segmenter | undefined} */ +let segmenter; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Converts the first letter of a string to uppercase. + * @param {string} string The string to operate on + * @returns {string} The converted string + */ +function upperCaseFirst(string) { + if (string.length <= 1) { + return string.toUpperCase(); + } + return string[0].toUpperCase() + string.slice(1); +} + +/** + * Counts graphemes in a given string. + * @param {string} value A string to count graphemes. + * @returns {number} The number of graphemes in `value`. + */ +function getGraphemeCount(value) { + if (ASCII_REGEX.test(value)) { + return value.length; + } + + segmenter ??= new Intl.Segmenter("en-US"); // en-US locale should be supported everywhere + let graphemeCount = 0; + + // eslint-disable-next-line no-unused-vars -- for-of needs a variable + for (const unused of segmenter.segment(value)) { + graphemeCount++; + } + + return graphemeCount; +} + +module.exports = { + upperCaseFirst, + getGraphemeCount, +}; diff --git a/node_modules/eslint/lib/shared/text-table.js b/node_modules/eslint/lib/shared/text-table.js new file mode 100644 index 0000000000000000000000000000000000000000..1dfd48166b5002b38ea4446f4ec55002475bfe00 --- /dev/null +++ b/node_modules/eslint/lib/shared/text-table.js @@ -0,0 +1,68 @@ +/** + * @fileoverview Optimized version of the `text-table` npm module to improve performance by replacing inefficient regex-based + * whitespace trimming with a modern built-in method. + * + * This modification addresses a performance issue reported in https://github.com/eslint/eslint/issues/18709 + * + * The `text-table` module is published under the MIT License. For the original source, refer to: + * https://www.npmjs.com/package/text-table. + */ + +/* + * + * This software is released under the MIT license: + * + * 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. + */ + +"use strict"; + +module.exports = function (rows_, opts) { + const hsep = " "; + const align = opts.align; + const stringLength = opts.stringLength; + + const sizes = rows_.reduce((acc, row) => { + row.forEach((c, ix) => { + const n = stringLength(c); + + if (!acc[ix] || n > acc[ix]) { + acc[ix] = n; + } + }); + return acc; + }, []); + + return rows_ + .map(row => + row + .map((c, ix) => { + const n = sizes[ix] - stringLength(c) || 0; + const s = Array(Math.max(n + 1, 1)).join(" "); + + if (align[ix] === "r") { + return s + c; + } + + return c + s; + }) + .join(hsep) + .trimEnd(), + ) + .join("\n"); +}; diff --git a/node_modules/eslint/lib/shared/translate-cli-options.js b/node_modules/eslint/lib/shared/translate-cli-options.js new file mode 100644 index 0000000000000000000000000000000000000000..c96a58ef0947e6045057073df9962c6689f03fbb --- /dev/null +++ b/node_modules/eslint/lib/shared/translate-cli-options.js @@ -0,0 +1,223 @@ +/** + * @fileoverview Translates CLI options into ESLint constructor options. + * @author Nicholas C. Zakas + * @author Francesco Trotta + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { normalizeSeverityToString } = require("./severity"); +const { getShorthandName, normalizePackageName } = require("./naming"); +const { ModuleImporter } = require("@humanwhocodes/module-importer"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("../types").ESLint.Options} ESLintOptions */ +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../options").ParsedCLIOptions} ParsedCLIOptions */ +/** @typedef {import("../types").ESLint.Plugin} Plugin */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Loads plugins with the specified names. + * @param {{ "import": (name: string) => Promise }} importer An object with an `import` method called once for each plugin. + * @param {string[]} pluginNames The names of the plugins to be loaded, with or without the "eslint-plugin-" prefix. + * @returns {Promise>} A mapping of plugin short names to implementations. + */ +async function loadPlugins(importer, pluginNames) { + const plugins = {}; + + await Promise.all( + pluginNames.map(async pluginName => { + const longName = normalizePackageName(pluginName, "eslint-plugin"); + const module = await importer.import(longName); + + if (!("default" in module)) { + throw new Error( + `"${longName}" cannot be used with the \`--plugin\` option because its default module does not provide a \`default\` export`, + ); + } + + const shortName = getShorthandName(pluginName, "eslint-plugin"); + + plugins[shortName] = module.default; + }), + ); + + return plugins; +} + +/** + * Predicate function for whether or not to apply fixes in quiet mode. + * If a message is a warning, do not apply a fix. + * @param {LintMessage} message The lint result. + * @returns {boolean} True if the lint message is an error (and thus should be + * autofixed), false otherwise. + */ +function quietFixPredicate(message) { + return message.severity === 2; +} + +/** + * Predicate function for whether or not to run a rule in quiet mode. + * If a rule is set to warning, do not run it. + * @param {{ ruleId: string; severity: number; }} rule The rule id and severity. + * @returns {boolean} True if the lint rule should run, false otherwise. + */ +function quietRuleFilter(rule) { + return rule.severity === 2; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Translates the CLI options into the options expected by the ESLint constructor. + * @param {ParsedCLIOptions} cliOptions The CLI options to translate. + * @returns {Promise} The options object for the ESLint constructor. + */ +async function translateOptions({ + cache, + cacheFile, + cacheLocation, + cacheStrategy, + concurrency, + config, + configLookup, + errorOnUnmatchedPattern, + ext, + fix, + fixDryRun, + fixType, + flag, + global, + ignore, + ignorePattern, + inlineConfig, + parser, + parserOptions, + plugin, + quiet, + reportUnusedDisableDirectives, + reportUnusedDisableDirectivesSeverity, + reportUnusedInlineConfigs, + rule, + stats, + warnIgnored, + passOnNoPatterns, + maxWarnings, +}) { + const importer = new ModuleImporter(); + + let overrideConfigFile = + typeof config === "string" ? config : !configLookup; + if (overrideConfigFile === false) { + overrideConfigFile = void 0; + } + + const languageOptions = {}; + + if (global) { + languageOptions.globals = global.reduce((obj, name) => { + if (name.endsWith(":true")) { + obj[name.slice(0, -5)] = "writable"; + } else { + obj[name] = "readonly"; + } + return obj; + }, {}); + } + + if (parserOptions) { + languageOptions.parserOptions = parserOptions; + } + + if (parser) { + languageOptions.parser = await importer.import(parser); + } + + const overrideConfig = [ + { + ...(Object.keys(languageOptions).length > 0 + ? { languageOptions } + : {}), + rules: rule ? rule : {}, + }, + ]; + + if ( + reportUnusedDisableDirectives || + reportUnusedDisableDirectivesSeverity !== void 0 + ) { + overrideConfig[0].linterOptions = { + reportUnusedDisableDirectives: reportUnusedDisableDirectives + ? "error" + : normalizeSeverityToString( + reportUnusedDisableDirectivesSeverity, + ), + }; + } + + if (reportUnusedInlineConfigs !== void 0) { + overrideConfig[0].linterOptions = { + ...overrideConfig[0].linterOptions, + reportUnusedInlineConfigs: normalizeSeverityToString( + reportUnusedInlineConfigs, + ), + }; + } + + if (plugin) { + overrideConfig[0].plugins = await loadPlugins(importer, plugin); + } + + if (ext) { + overrideConfig.push({ + files: ext.map( + extension => + `**/*${extension.startsWith(".") ? "" : "."}${extension}`, + ), + }); + } + + /* + * For performance reasons rules not marked as 'error' are filtered out in quiet mode. As maxWarnings + * requires rules set to 'warn' to be run, we only filter out 'warn' rules if maxWarnings is not specified. + */ + const ruleFilter = + quiet && maxWarnings === -1 ? quietRuleFilter : () => true; + + const options = { + allowInlineConfig: inlineConfig, + cache, + cacheLocation: cacheLocation || cacheFile, + cacheStrategy, + concurrency, + errorOnUnmatchedPattern, + fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true), + fixTypes: fixType, + flags: flag, + ignore, + ignorePatterns: ignorePattern, + overrideConfig, + overrideConfigFile, + passOnNoPatterns, + ruleFilter, + stats, + warnIgnored, + }; + + return options; +} + +module.exports = translateOptions; diff --git a/node_modules/eslint/lib/shared/traverser.js b/node_modules/eslint/lib/shared/traverser.js new file mode 100644 index 0000000000000000000000000000000000000000..e13b2cfa5e016c4f5f5c3f955425ce91b00df933 --- /dev/null +++ b/node_modules/eslint/lib/shared/traverser.js @@ -0,0 +1,202 @@ +/** + * @fileoverview Traverser to traverse AST trees. + * @author Nicholas C. Zakas + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const vk = require("eslint-visitor-keys"); +const debug = require("debug")("eslint:traverser"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Do nothing. + * @returns {void} + */ +function noop() { + // do nothing. +} + +/** + * Check whether the given value is an ASTNode or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is an ASTNode. + */ +function isNode(x) { + return x !== null && typeof x === "object" && typeof x.type === "string"; +} + +/** + * Get the visitor keys of a given node. + * @param {Object} visitorKeys The map of visitor keys. + * @param {ASTNode} node The node to get their visitor keys. + * @returns {string[]} The visitor keys of the node. + */ +function getVisitorKeys(visitorKeys, node) { + let keys = visitorKeys[node.type]; + + if (!keys) { + keys = vk.getKeys(node); + debug( + 'Unknown node type "%s": Estimated visitor keys %j', + node.type, + keys, + ); + } + + return keys; +} + +/** + * The traverser class to traverse AST trees. + */ +class Traverser { + constructor() { + this._current = null; + this._parents = []; + this._skipped = false; + this._broken = false; + this._visitorKeys = null; + this._enter = null; + this._leave = null; + } + + /** + * Gives current node. + * @returns {ASTNode} The current node. + */ + current() { + return this._current; + } + + /** + * Gives a copy of the ancestor nodes. + * @returns {ASTNode[]} The ancestor nodes. + */ + parents() { + return this._parents.slice(0); + } + + /** + * Break the current traversal. + * @returns {void} + */ + break() { + this._broken = true; + } + + /** + * Skip child nodes for the current traversal. + * @returns {void} + */ + skip() { + this._skipped = true; + } + + /** + * Traverse the given AST tree. + * @param {ASTNode} node The root node to traverse. + * @param {Object} options The option object. + * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`. + * @param {Function} [options.enter=noop] The callback function which is called on entering each node. + * @param {Function} [options.leave=noop] The callback function which is called on leaving each node. + * @returns {void} + */ + traverse(node, options) { + this._current = null; + this._parents = []; + this._skipped = false; + this._broken = false; + this._visitorKeys = options.visitorKeys || vk.KEYS; + this._enter = options.enter || noop; + this._leave = options.leave || noop; + this._traverse(node, null); + } + + /** + * Traverse the given AST tree recursively. + * @param {ASTNode} node The current node. + * @param {ASTNode|null} parent The parent node. + * @returns {void} + * @private + */ + _traverse(node, parent) { + if (!isNode(node)) { + return; + } + + this._current = node; + this._skipped = false; + this._enter(node, parent); + + if (!this._skipped && !this._broken) { + const keys = getVisitorKeys(this._visitorKeys, node); + + if (keys.length >= 1) { + this._parents.push(node); + for (let i = 0; i < keys.length && !this._broken; ++i) { + const child = node[keys[i]]; + + if (Array.isArray(child)) { + for ( + let j = 0; + j < child.length && !this._broken; + ++j + ) { + this._traverse(child[j], node); + } + } else { + this._traverse(child, node); + } + } + this._parents.pop(); + } + } + + if (!this._broken) { + this._leave(node, parent); + } + + this._current = parent; + } + + /** + * Calculates the keys to use for traversal. + * @param {ASTNode} node The node to read keys from. + * @returns {string[]} An array of keys to visit on the node. + * @private + */ + static getKeys(node) { + return vk.getKeys(node); + } + + /** + * Traverse the given AST tree. + * @param {ASTNode} node The root node to traverse. + * @param {Object} options The option object. + * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`. + * @param {Function} [options.enter=noop] The callback function which is called on entering each node. + * @param {Function} [options.leave=noop] The callback function which is called on leaving each node. + * @returns {void} + */ + static traverse(node, options) { + new Traverser().traverse(node, options); + } + + /** + * The default visitor keys. + * @type {Object} + */ + static get DEFAULT_VISITOR_KEYS() { + return vk.KEYS; + } +} + +module.exports = Traverser; diff --git a/node_modules/eslint/lib/types/config-api.d.ts b/node_modules/eslint/lib/types/config-api.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b3abd2fc9ba032f064b73fa88b30d63adb3b97a --- /dev/null +++ b/node_modules/eslint/lib/types/config-api.d.ts @@ -0,0 +1,13 @@ +/** + * @fileoverview typings for "eslint/config" module + * @author Nicholas C. Zakas + */ + +import { + type Config, + defineConfig, + globalIgnores, + includeIgnoreFile, +} from "@eslint/config-helpers"; + +export { type Config, defineConfig, globalIgnores, includeIgnoreFile }; diff --git a/node_modules/eslint/lib/types/index.d.ts b/node_modules/eslint/lib/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d270c0bb36384785e6afd2cd12c59a841f971c32 --- /dev/null +++ b/node_modules/eslint/lib/types/index.d.ts @@ -0,0 +1,1548 @@ +/** + * @fileoverview This file contains the core types for ESLint. It was initially extracted + * from the `@types/eslint` package. + */ + +/* + * MIT License + * Copyright (c) Microsoft Corporation. + * + * 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 + */ + +import * as ESTree from "estree"; +import type { + DeprecatedInfo, + LanguageOptions as GenericLanguageOptions, + RuleContext as CoreRuleContext, + RuleDefinition, + SourceRange, + TextSourceCode, + TraversalStep, + RulesConfig, + GlobalAccess, + GlobalsConfig, + LinterOptionsConfig, + EnvironmentConfig, + ObjectMetaProperties as CoreObjectMetaProperties, + Plugin as CorePlugin, + LintMessage as CoreLintMessage, + Processor as CoreProcessor, + ConfigObject, + LegacyConfigObject, + SeverityName, + SeverityLevel, + Severity as CoreSeverity, + EcmaVersion as CoreEcmaVersion, + ConfigOverride as CoreConfigOverride, + ProcessorFile as CoreProcessorFile, + RulesMeta, + RuleConfig, + RuleTextEditor, + RuleTextEdit, + RuleVisitor, + BaseConfig as CoreBaseConfig, + RuleFixer as CoreRuleFixer, + ViolationReportBase, + ViolationMessage, + ViolationLocation, + SuggestionMessage, + LintSuggestion as CoreLintSuggestion, + JavaScriptSourceType, + HasRules as CoreHasRules, + SuggestedEditBase, + SuggestedEdit, + ViolationReport, + MessagePlaceholderData, +} from "@eslint/core"; +import type { + CustomRuleDefinitionType, + CustomRuleTypeDefinitions, + CustomRuleVisitorWithExit, +} from "@eslint/plugin-kit"; + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +export namespace AST { + type TokenType = + | "Boolean" + | "Null" + | "Identifier" + | "PrivateIdentifier" + | "Keyword" + | "Punctuator" + | "JSXIdentifier" + | "JSXText" + | "Numeric" + | "String" + | "Template" + | "RegularExpression"; + + interface Token { + type: TokenType; + value: string; + range: Range; + loc: SourceLocation; + } + + interface SourceLocation { + start: ESTree.Position; + end: ESTree.Position; + } + + type Range = SourceRange; + + interface Program extends ESTree.Program { + comments: ESTree.Comment[]; + tokens: Token[]; + loc: SourceLocation; + range: Range; + } +} + +interface JSXIdentifier extends ESTree.BaseNode { + type: "JSXIdentifier"; + name: string; +} + +export namespace Scope { + interface ScopeManager { + scopes: Scope[]; + globalScope: Scope | null; + + acquire(node: ESTree.Node, inner?: boolean): Scope | null; + + getDeclaredVariables(node: ESTree.Node): Variable[]; + + addGlobals(names: ReadonlyArray): void; + } + + interface Scope { + type: + | "block" + | "catch" + | "class" + | "class-field-initializer" + | "class-static-block" + | "for" + | "function" + | "function-expression-name" + | "global" + | "module" + | "switch" + | "with"; + isStrict: boolean; + upper: Scope | null; + childScopes: Scope[]; + variableScope: Scope; + block: ESTree.Node; + variables: Variable[]; + set: Map; + references: Reference[]; + through: Reference[]; + functionExpressionScope: boolean; + implicit?: { + variables: Variable[]; + set: Map; + }; + } + + interface Variable { + name: string; + scope: Scope; + identifiers: ESTree.Identifier[]; + references: Reference[]; + defs: Definition[]; + } + + interface Reference { + identifier: ESTree.Identifier | JSXIdentifier; + from: Scope; + resolved: Variable | null; + writeExpr?: ESTree.Expression | null; + init?: boolean; + + isWrite(): boolean; + + isRead(): boolean; + + isWriteOnly(): boolean; + + isReadOnly(): boolean; + + isReadWrite(): boolean; + } + + type DefinitionType = + | { type: "CatchClause"; node: ESTree.CatchClause; parent: null } + | { + type: "ClassName"; + node: ESTree.ClassDeclaration | ESTree.ClassExpression; + parent: null; + } + | { + type: "FunctionName"; + node: ESTree.FunctionDeclaration | ESTree.FunctionExpression; + parent: null; + } + | { + type: "ImplicitGlobalVariable"; + node: + | ESTree.AssignmentExpression + | ESTree.ForInStatement + | ESTree.ForOfStatement; + parent: null; + } + | { + type: "ImportBinding"; + node: + | ESTree.ImportSpecifier + | ESTree.ImportDefaultSpecifier + | ESTree.ImportNamespaceSpecifier; + parent: ESTree.ImportDeclaration; + } + | { + type: "Parameter"; + node: + | ESTree.FunctionDeclaration + | ESTree.FunctionExpression + | ESTree.ArrowFunctionExpression; + parent: null; + } + | { + type: "Variable"; + node: ESTree.VariableDeclarator; + parent: ESTree.VariableDeclaration; + }; + + type Definition = DefinitionType & { name: ESTree.Identifier }; +} + +// #region SourceCode + +export class SourceCode implements TextSourceCode<{ + LangOptions: Linter.LanguageOptions; + RootNode: AST.Program; + SyntaxElementWithLoc: AST.Token | ESTree.Node; + ConfigNode: ESTree.Comment; +}> { + text: string; + ast: AST.Program; + lines: string[]; + hasBOM: boolean; + parserServices: SourceCode.ParserServices; + scopeManager: Scope.ScopeManager; + visitorKeys: SourceCode.VisitorKeys; + + constructor(text: string, ast: AST.Program); + constructor(config: SourceCode.Config); + + static splitLines(text: string): string[]; + + getLoc(syntaxElement: AST.Token | ESTree.Node): ESTree.SourceLocation; + getRange(syntaxElement: AST.Token | ESTree.Node): SourceRange; + + getText( + node?: ESTree.Node, + beforeCount?: number, + afterCount?: number, + ): string; + + getLines(): string[]; + + getAllComments(): ESTree.Comment[]; + + getAncestors(node: ESTree.Node): ESTree.Node[]; + + getDeclaredVariables(node: ESTree.Node): Scope.Variable[]; + + getNodeByRangeIndex(index: number): ESTree.Node | null; + + getLocFromIndex(index: number): ESTree.Position; + + getIndexFromLoc(location: ESTree.Position): number; + + // Inherited methods from TokenStore + // --------------------------------- + + getTokenByRangeStart( + offset: number, + options?: { includeComments: false }, + ): AST.Token | null; + getTokenByRangeStart( + offset: number, + options: { includeComments: boolean }, + ): AST.Token | ESTree.Comment | null; + + getFirstToken: SourceCode.UnaryNodeCursorWithSkipOptions; + + getFirstTokens: SourceCode.UnaryNodeCursorWithCountOptions; + + getLastToken: SourceCode.UnaryNodeCursorWithSkipOptions; + + getLastTokens: SourceCode.UnaryNodeCursorWithCountOptions; + + getTokenBefore: SourceCode.UnaryCursorWithSkipOptions; + + getTokensBefore: SourceCode.UnaryCursorWithCountOptions; + + getTokenAfter: SourceCode.UnaryCursorWithSkipOptions; + + getTokensAfter: SourceCode.UnaryCursorWithCountOptions; + + getFirstTokenBetween: SourceCode.BinaryCursorWithSkipOptions; + + getFirstTokensBetween: SourceCode.BinaryCursorWithCountOptions; + + getLastTokenBetween: SourceCode.BinaryCursorWithSkipOptions; + + getLastTokensBetween: SourceCode.BinaryCursorWithCountOptions; + + getTokensBetween: SourceCode.BinaryCursorWithCountOptions; + + getTokens: (( + node: ESTree.Node, + beforeCount?: number, + afterCount?: number, + ) => AST.Token[]) & + SourceCode.UnaryNodeCursorWithCountOptions; + + commentsExistBetween( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + ): boolean; + + getCommentsBefore(nodeOrToken: ESTree.Node | AST.Token): ESTree.Comment[]; + + getCommentsAfter(nodeOrToken: ESTree.Node | AST.Token): ESTree.Comment[]; + + getCommentsInside(node: ESTree.Node): ESTree.Comment[]; + + getScope(node: ESTree.Node): Scope.Scope; + + isSpaceBetween( + first: ESTree.Node | AST.Token, + second: ESTree.Node | AST.Token, + ): boolean; + + isGlobalReference(node: ESTree.Identifier): boolean; + + markVariableAsUsed(name: string, refNode?: ESTree.Node): boolean; + + traverse(): Iterable; +} + +export namespace SourceCode { + interface Config { + text: string; + ast: AST.Program; + hasBOM?: boolean | undefined; + parserServices?: ParserServices | null | undefined; + scopeManager?: Scope.ScopeManager | null | undefined; + visitorKeys?: VisitorKeys | null | undefined; + } + + type ParserServices = any; + + interface VisitorKeys { + [nodeType: string]: string[]; + } + + interface UnaryNodeCursorWithSkipOptions { + ( + node: ESTree.Node, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + skip?: number | undefined; + }, + ): T | null; + ( + node: ESTree.Node, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + skip?: number | undefined; + }, + ): T | null; + ( + node: ESTree.Node, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + skip?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token | null; + ( + node: ESTree.Node, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + skip?: number | undefined; + }, + ): AST.Token | ESTree.Comment | null; + } + + interface UnaryNodeCursorWithCountOptions { + ( + node: ESTree.Node, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + count?: number | undefined; + }, + ): T[]; + ( + node: ESTree.Node, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + count?: number | undefined; + }, + ): T[]; + ( + node: ESTree.Node, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + count?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token[]; + ( + node: ESTree.Node, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + count?: number | undefined; + }, + ): Array; + } + + interface UnaryCursorWithSkipOptions { + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + skip?: number | undefined; + }, + ): T | null; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + skip?: number | undefined; + }, + ): T | null; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + skip?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token | null; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + skip?: number | undefined; + }, + ): AST.Token | ESTree.Comment | null; + } + + interface UnaryCursorWithCountOptions { + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + count?: number | undefined; + }, + ): T[]; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + count?: number | undefined; + }, + ): T[]; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + count?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token[]; + ( + node: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + count?: number | undefined; + }, + ): Array; + } + + interface BinaryCursorWithSkipOptions { + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + skip?: number | undefined; + }, + ): T | null; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + skip?: number | undefined; + }, + ): T | null; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + skip?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token | null; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + skip?: number | undefined; + }, + ): AST.Token | ESTree.Comment | null; + } + + interface BinaryCursorWithCountOptions { + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: + | ((token: AST.Token) => token is T) + | { + filter: (token: AST.Token) => token is T; + includeComments?: false | undefined; + count?: number | undefined; + }, + ): T[]; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter: ( + tokenOrComment: AST.Token | ESTree.Comment, + ) => tokenOrComment is T; + includeComments: boolean; + count?: number | undefined; + }, + ): T[]; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options?: + | { + filter?: ((token: AST.Token) => boolean) | undefined; + includeComments?: false | undefined; + count?: number | undefined; + } + | ((token: AST.Token) => boolean) + | number, + ): AST.Token[]; + ( + left: ESTree.Node | AST.Token | ESTree.Comment, + right: ESTree.Node | AST.Token | ESTree.Comment, + options: { + filter?: + | ((token: AST.Token | ESTree.Comment) => boolean) + | undefined; + includeComments: boolean; + count?: number | undefined; + }, + ): Array; + } +} + +// #endregion + +export type JSSyntaxElement = { + type: string; + loc?: ESTree.SourceLocation | null | undefined; +}; + +export namespace Rule { + interface RuleModule extends RuleDefinition<{ + LangOptions: Linter.LanguageOptions; + Code: SourceCode; + RuleOptions: any[]; + Visitor: RuleListener; + Node: JSSyntaxElement; + MessageIds: string; + ExtRuleDocs: {}; + }> { + create(context: RuleContext): RuleListener; + } + + type NodeTypes = ESTree.Node["type"]; + + interface NodeListener extends CustomRuleVisitorWithExit< + { + [Node in Rule.Node as Node["type"]]?: + | ((node: Node) => void) + | undefined; + } & { + // A `Program` visitor's node type has no `parent` property. + Program?: ((node: AST.Program) => void) | undefined; + } + > {} + + interface NodeParentExtension { + parent: Node; + } + + type Node = + | (AST.Program & { parent: null }) + | (Exclude & NodeParentExtension); + + interface RuleListener extends NodeListener { + onCodePathStart?(codePath: CodePath, node: Node): void; + + onCodePathEnd?(codePath: CodePath, node: Node): void; + + onCodePathSegmentStart?(segment: CodePathSegment, node: Node): void; + + onCodePathSegmentEnd?(segment: CodePathSegment, node: Node): void; + + onUnreachableCodePathSegmentStart?( + segment: CodePathSegment, + node: Node, + ): void; + + onUnreachableCodePathSegmentEnd?( + segment: CodePathSegment, + node: Node, + ): void; + + onCodePathSegmentLoop?( + fromSegment: CodePathSegment, + toSegment: CodePathSegment, + node: Node, + ): void; + + [key: string]: + | ((codePath: CodePath, node: Node) => void) + | ((segment: CodePathSegment, node: Node) => void) + | (( + fromSegment: CodePathSegment, + toSegment: CodePathSegment, + node: Node, + ) => void) + | ((node: Node) => void) + | NodeListener[keyof NodeListener] + | undefined; + } + + type CodePathOrigin = + | "program" + | "function" + | "class-field-initializer" + | "class-static-block"; + + interface CodePathSegmentTraversalController { + skip(): void; + break(): void; + } + + type CodePathSegmentTraversalCallback = ( + this: CodePath, + segment: CodePathSegment, + controller: CodePathSegmentTraversalController, + ) => void; + + interface CodePathTraversalOptions { + first?: CodePathSegment | undefined; + last?: CodePathSegment | undefined; + } + + interface CodePath { + id: string; + origin: CodePathOrigin; + initialSegment: CodePathSegment; + finalSegments: CodePathSegment[]; + returnedSegments: CodePathSegment[]; + thrownSegments: CodePathSegment[]; + upper: CodePath | null; + childCodePaths: CodePath[]; + traverseSegments(callback: CodePathSegmentTraversalCallback): void; + traverseSegments( + options: CodePathTraversalOptions, + callback: CodePathSegmentTraversalCallback, + ): void; + } + + interface CodePathSegment { + id: string; + nextSegments: CodePathSegment[]; + prevSegments: CodePathSegment[]; + allNextSegments: CodePathSegment[]; + allPrevSegments: CodePathSegment[]; + reachable: boolean; + } + + type RuleMetaData = RulesMeta; + + interface RuleContext extends CoreRuleContext<{ + LangOptions: Linter.LanguageOptions; + Code: SourceCode; + RuleOptions: any[]; + Node: JSSyntaxElement; + MessageIds: string; + }> {} + + type ReportFixer = CoreRuleFixer; + + /** @deprecated Use `ReportDescriptorOptions` instead. */ + type ReportDescriptorOptionsBase = Omit; + + type SuggestionReportOptions = SuggestedEditBase; + type SuggestionDescriptorMessage = SuggestionMessage; + type SuggestionReportDescriptor = SuggestedEdit; + + // redundant with ReportDescriptorOptionsBase but kept for clarity + type ReportDescriptorOptions = ViolationReportBase; + + type ReportDescriptor = ViolationReport; + type ReportDescriptorMessage = ViolationMessage; + type ReportDescriptorLocation = ViolationLocation; + + type RuleFixer = RuleTextEditor; + type Fix = RuleTextEdit; +} + +export type JSRuleDefinitionTypeOptions = CustomRuleTypeDefinitions; + +export type JSRuleDefinition< + Options extends Partial = {}, +> = CustomRuleDefinitionType< + { + LangOptions: Linter.LanguageOptions; + Code: SourceCode; + Visitor: Rule.RuleListener; + Node: JSSyntaxElement; + }, + Options +>; + +// #region Linter + +export class Linter { + static readonly version: string; + + version: string; + + constructor(options?: { cwd?: string | undefined; configType?: "flat" }); + + verify( + code: SourceCode | string, + config: Linter.Config | Linter.Config[], + filename?: string, + ): Linter.LintMessage[]; + verify( + code: SourceCode | string, + config: Linter.Config | Linter.Config[], + options: Linter.LintOptions, + ): Linter.LintMessage[]; + + verifyAndFix( + code: string, + config: Linter.Config | Linter.Config[], + filename?: string, + ): Linter.FixReport; + verifyAndFix( + code: string, + config: Linter.Config | Linter.Config[], + options: Linter.FixOptions, + ): Linter.FixReport; + + getSourceCode(): SourceCode; + + getTimes(): Linter.Stats["times"]; + + getFixPassCount(): Linter.Stats["fixPasses"]; +} + +export namespace Linter { + /** + * The numeric severity level for a rule. + * + * - `0` means off. + * - `1` means warn. + * - `2` means error. + * + * @see [Rule Severities](https://eslint.org/docs/latest/use/configure/rules#rule-severities) + */ + type Severity = SeverityLevel; + + /** + * The human readable severity level for a rule. + * + * @see [Rule Severities](https://eslint.org/docs/latest/use/configure/rules#rule-severities) + */ + type StringSeverity = SeverityName; + + /** + * The numeric or human readable severity level for a rule. + * + * @see [Rule Severities](https://eslint.org/docs/latest/use/configure/rules#rule-severities) + */ + type RuleSeverity = CoreSeverity; + + /** + * An array containing the rule severity level, followed by the rule options. + * + * @see [Rules](https://eslint.org/docs/latest/use/configure/rules) + */ + type RuleSeverityAndOptions = [ + RuleSeverity, + ...Partial, + ]; + + /** + * The severity level for the rule or an array containing the rule severity level, followed by the rule options. + * + * @see [Rules](https://eslint.org/docs/latest/use/configure/rules) + */ + type RuleEntry = RuleConfig; + + /** + * The rules config object is a key/value map of rule names and their severity and options. + */ + type RulesRecord = RulesConfig; + + /** + * A configuration object that may have a `rules` block. + */ + type HasRules = + CoreHasRules; + + /** + * The ECMAScript version of the code being linted. + */ + type EcmaVersion = CoreEcmaVersion; + + /** + * The type of JavaScript source code. + */ + type SourceType = JavaScriptSourceType; + + /** + * ESLint legacy configuration. + * + * @see [ESLint Legacy Configuration](https://eslint.org/docs/latest/use/configure/) + */ + type BaseConfig< + Rules extends RulesConfig = RulesConfig, + OverrideRules extends RulesConfig = Rules, + > = CoreBaseConfig; + + /** + * The overwrites that apply more differing configuration to specific files or directories. + */ + type ConfigOverride = + CoreConfigOverride; + + /** + * ESLint legacy configuration. + * + * @see [ESLint Legacy Configuration](https://eslint.org/docs/latest/use/configure/) + */ + // https://github.com/eslint/eslint/blob/v8.57.0/conf/config-schema.js + type LegacyConfig< + Rules extends RulesConfig = RulesConfig, + OverrideRules extends RulesConfig = Rules, + > = LegacyConfigObject; + + /** + * Parser options. + * + * @see [Specifying Parser Options](https://eslint.org/docs/latest/use/configure/language-options#specifying-parser-options) + */ + interface ParserOptions { + /** + * Allow the use of reserved words as identifiers (if `ecmaVersion` is 3). + * + * @default false + */ + allowReserved?: boolean | undefined; + /** + * An object indicating which additional language features you'd like to use. + * + * @see https://eslint.org/docs/latest/use/configure/language-options#specifying-parser-options + */ + ecmaFeatures?: + | { + /** + * Allow `return` statements in the global scope. + * + * @default false + */ + globalReturn?: boolean | undefined; + /** + * Enable global [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) (if `ecmaVersion` is 5 or greater). + * + * @default false + */ + impliedStrict?: boolean | undefined; + /** + * Enable [JSX](https://facebook.github.io/jsx/). + * + * @default false + */ + jsx?: boolean | undefined; + [key: string]: any; + } + | undefined; + [key: string]: any; + } + + /** + * Options used for linting code with `Linter#verify` and `Linter#verifyAndFix`. + */ + interface LintOptions { + filename?: string | undefined; + preprocess?: ((code: string) => string[]) | undefined; + postprocess?: + | ((problemLists: LintMessage[][]) => LintMessage[]) + | undefined; + filterCodeBlock?: + | ((filename: string, text: string) => boolean) + | undefined; + disableFixes?: boolean | undefined; + allowInlineConfig?: boolean | undefined; + reportUnusedDisableDirectives?: boolean | undefined; + } + + type LintSuggestion = CoreLintSuggestion; + type LintMessage = CoreLintMessage; + + interface LintSuppression { + kind: string; + justification: string; + } + + interface SuppressedLintMessage extends LintMessage { + /** The suppression info. */ + suppressions: LintSuppression[]; + } + + interface FixOptions extends LintOptions { + fix?: boolean | undefined; + } + + interface FixReport { + fixed: boolean; + output: string; + messages: LintMessage[]; + } + + // Temporarily loosen type for just flat config files (see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/68232) + type NonESTreeParser = ESLint.ObjectMetaProperties & + ( + | { + parse(text: string, options?: any): unknown; + } + | { + parseForESLint( + text: string, + options?: any, + ): Omit & { + ast: unknown; + scopeManager?: unknown; + }; + } + ); + + type ESTreeParser = ESLint.ObjectMetaProperties & + ( + | { parse(text: string, options?: any): AST.Program } + | { parseForESLint(text: string, options?: any): ESLintParseResult } + ); + + type Parser = NonESTreeParser | ESTreeParser; + + interface ESLintParseResult { + /** The AST object. */ + ast: AST.Program; + + /** The services that the parser provides. */ + services?: SourceCode.ParserServices | undefined; + + /** The scope manager of the AST. */ + scopeManager?: Scope.ScopeManager | undefined; + + /** The visitor keys of the AST. */ + visitorKeys?: SourceCode.VisitorKeys | undefined; + } + + type ProcessorFile = CoreProcessorFile; + + // https://eslint.org/docs/latest/extend/plugins#processors-in-plugins + type Processor = + CoreProcessor; + + type Config = ConfigObject; + + /** @deprecated Use `Config` instead of `FlatConfig` */ + type FlatConfig = Config; + + type GlobalConf = GlobalAccess; + type Globals = GlobalsConfig; + + interface LanguageOptions extends GenericLanguageOptions { + /** + * The version of ECMAScript to support. May be any year (i.e., 2022) or + * version (i.e., 5). Set to "latest" for the most recent supported version. + * @default "latest" + */ + ecmaVersion?: EcmaVersion | undefined; + + /** + * The type of JavaScript source code. Possible values are "script" for + * traditional script files, "module" for ECMAScript modules (ESM), and + * "commonjs" for CommonJS files. (default: "module" for .js and .mjs + * files; "commonjs" for .cjs files) + */ + sourceType?: SourceType | undefined; + + /** + * An object specifying additional objects that should be added to the + * global scope during linting. + */ + globals?: Globals | undefined; + + /** + * An object containing a parse() or parseForESLint() method. + * If not configured, the default ESLint parser (Espree) will be used. + */ + parser?: Parser | undefined; + + /** + * An object specifying additional options that are passed directly to the + * parser() method on the parser. The available options are parser-dependent + */ + parserOptions?: Linter.ParserOptions | undefined; + } + + type LinterOptions = LinterOptionsConfig; + + /** + * Performance statistics. + */ + interface Stats { + /** + * The number of times ESLint has applied at least one fix after linting. + */ + fixPasses: number; + + /** + * The times spent on (parsing, fixing, linting) a file, where the linting refers to the timing information for each rule. + */ + times: { passes: TimePass[] }; + } + + interface TimePass { + /** + * The parse object containing all parse time information. + */ + parse: { total: number }; + + /** + * The rules object containing all lint time information for each rule. + */ + rules?: Record; + + /** + * The fix object containing all fix time information. + */ + fix: { total: number }; + + /** + * The total time that is spent on (parsing, fixing, linting) a file. + */ + total: number; + } +} + +// #endregion + +// #region ESLint + +export class ESLint { + static configType: "flat"; + + static readonly version: string; + + /** + * The default configuration that ESLint uses internally. This is provided for tooling that wants to calculate configurations using the same defaults as ESLint. + * Keep in mind that the default configuration may change from version to version, so you shouldn't rely on any particular keys or values to be present. + */ + static readonly defaultConfig: Linter.Config[]; + + static outputFixes(results: ESLint.LintResult[]): Promise; + + static getErrorResults(results: ESLint.LintResult[]): ESLint.LintResult[]; + + constructor(options?: ESLint.Options); + + lintFiles(patterns: string | string[]): Promise; + + lintText( + code: string, + options?: { + filePath?: string | undefined; + warnIgnored?: boolean | undefined; + }, + ): Promise; + + getRulesMetaForResults( + results: ESLint.LintResult[], + ): ESLint.LintResultData["rulesMeta"]; + + hasFlag(flag: string): boolean; + + calculateConfigForFile(filePath: string): Promise; + + findConfigFile(filePath?: string): Promise; + + isPathIgnored(filePath: string): Promise; + + loadFormatter(nameOrPath?: string): Promise; + + static fromOptionsModule(optionsURL: { + readonly href: string; + }): Promise; +} + +export namespace ESLint { + type ConfigData = Omit< + Linter.LegacyConfig, + "$schema" + >; + + type Environment = EnvironmentConfig; + type ObjectMetaProperties = CoreObjectMetaProperties; + type Plugin = CorePlugin; + + type FixType = "directive" | "problem" | "suggestion" | "layout"; + + type CacheStrategy = "content" | "metadata"; + + /** The options with which to configure the ESLint instance. */ + interface Options { + // File enumeration + + /** The value to use for the current working directory. */ + cwd?: string | undefined; + + /** If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`. */ + errorOnUnmatchedPattern?: boolean | undefined; + + /** + * Set to false to skip glob resolution of input file paths to lint (default: true). + * If false, each input file path is assumed to be a non-glob path to an existing file. + */ + globInputPaths?: boolean | undefined; + + /** False disables all ignore patterns except for the default ones. */ + ignore?: boolean | undefined; + + /** Ignore file patterns to use in addition to config ignores. These patterns are relative to `cwd`. */ + ignorePatterns?: string[] | null | undefined; + + /** When set to true, missing patterns cause the linting operation to short circuit and not report any failures. */ + passOnNoPatterns?: boolean | undefined; + + /** Show warnings when the file list includes ignored files. */ + warnIgnored?: boolean | undefined; + + // Linting + + /** Enable or disable inline configuration comments. */ + allowInlineConfig?: boolean | undefined; + + /** Base config, extended by all configs used with this instance. */ + baseConfig?: Linter.Config | Linter.Config[] | null | undefined; + + /** Override config, overrides all configs used with this instance. */ + overrideConfig?: Linter.Config | Linter.Config[] | null | undefined; + + /** + * Searches for default config file when falsy; doesn't do any config file lookup when `true`; considered to be a config filename when a string. + */ + overrideConfigFile?: string | true | null | undefined; + + /** An array of plugin implementations. */ + plugins?: Record | null | undefined; + + /** + * Default is `() => true`. A predicate function that filters rules to be run. + * This function is called with an object containing `ruleId` and `severity`, and returns `true` if the rule should be run. + */ + ruleFilter?: + | ((arg: { + ruleId: string; + severity: Exclude; + }) => boolean) + | undefined; + + /** True enables added statistics on lint results. */ + stats?: boolean | undefined; + + // Autofix + + /** Execute in autofix mode. If a function, should return a boolean. */ + fix?: boolean | ((message: Linter.LintMessage) => boolean) | undefined; + + /** Array of rule types to apply fixes for. */ + fixTypes?: FixType[] | null | undefined; + + // Cache-related + + /** Enable result caching. */ + cache?: boolean | undefined; + + /** The cache file to use instead of .eslintcache. */ + cacheLocation?: string | undefined; + + /** The strategy used to detect changed files. */ + cacheStrategy?: CacheStrategy | undefined; + + /** If true, apply suppressions automatically. Defaults to false. */ + applySuppressions?: boolean | undefined; + + /** Path to suppressions file. Relative to cwd. Defaults to eslint-suppressions.json in cwd. */ + suppressionsLocation?: string | undefined; + + // Other Options + + /** Maximum number of linting threads, "auto" to choose automatically, "off" for no multithreading. */ + concurrency?: number | "auto" | "off" | undefined; + + /** Array of feature flags to enable. */ + flags?: string[] | undefined; + } + + /** A linting result. */ + interface LintResult { + /** The path to the file that was linted. */ + filePath: string; + + /** All of the messages for the result. */ + messages: Linter.LintMessage[]; + + /** All of the suppressed messages for the result. */ + suppressedMessages: Linter.SuppressedLintMessage[]; + + /** Number of errors for the result. */ + errorCount: number; + + /** Number of fatal errors for the result. */ + fatalErrorCount: number; + + /** Number of warnings for the result. */ + warningCount: number; + + /** Number of fixable errors for the result. */ + fixableErrorCount: number; + + /** Number of fixable warnings for the result. */ + fixableWarningCount: number; + + /** The source code of the file that was linted, with as many fixes applied as possible. */ + output?: string | undefined; + + /** The source code of the file that was linted. */ + source?: string | undefined; + + /** The performance statistics collected with the `stats` flag. */ + stats?: Linter.Stats | undefined; + + /** The list of used deprecated rules. */ + usedDeprecatedRules: DeprecatedRuleUse[]; + } + + /** + * Information provided when the maximum warning threshold is exceeded. + */ + interface MaxWarningsExceeded { + /** + * Number of warnings to trigger nonzero exit code. + */ + maxWarnings: number; + + /** + * Number of warnings found while linting. + */ + foundWarnings: number; + } + + interface LintResultData extends ResultsMeta { + cwd: string; + rulesMeta: { + [ruleId: string]: Rule.RuleMetaData; + }; + } + + /** + * Information about deprecated rules. + */ + interface DeprecatedRuleUse { + /** + * The rule ID. + */ + ruleId: string; + + /** + * The rule IDs that replace this deprecated rule. + */ + replacedBy: string[]; + + /** + * The raw deprecated info provided by the rule. + * - Undefined if the rule's `meta.deprecated` property is a boolean. + * - Unset when using the legacy eslintrc configuration. + */ + info?: DeprecatedInfo | undefined; + } + + /** + * Metadata about results for formatters. + */ + interface ResultsMeta { + /** + * Whether or not to use color in the formatter output. + * - If `--color` was set, this property is `true`. + * - If `--no-color` was set, it is `false`. + * - If neither option was provided, the property is omitted. + */ + color?: boolean | undefined; + + /** + * Present if the maxWarnings threshold was exceeded. + */ + maxWarningsExceeded?: MaxWarningsExceeded | undefined; + } + + /** The type of an object resolved by {@link ESLint.loadFormatter}. */ + interface LoadedFormatter { + /** + * Used to call the underlying formatter. + * @param results An array of lint results to format. + * @param resultsMeta An object with optional `color` and `maxWarningsExceeded` properties that will be + * passed to the underlying formatter function along with other properties set by ESLint. + * This argument can be omitted if `color` and `maxWarningsExceeded` are not needed. + * @return The formatter output. + */ + format( + results: LintResult[], + resultsMeta?: ResultsMeta, + ): string | Promise; + } + + // The documented type name is `LoadedFormatter`, but `Formatter` has been historically more used. + type Formatter = LoadedFormatter; + + /** + * The expected signature of a custom formatter. + * @param results An array of lint results to format. + * @param context Additional information for the formatter. + * @return The formatter output. + */ + type FormatterFunction = ( + results: LintResult[], + context: LintResultData, + ) => string | Promise; + + // Docs reference the types by those name + type EditInfo = Rule.Fix; +} + +// #endregion + +/** + * Loads the correct `ESLint` constructor. + */ +export function loadESLint(): Promise; + +// #region RuleTester + +export class RuleTester { + static describe: ((...args: any) => any) | null; + static it: ((...args: any) => any) | null; + static itOnly: ((...args: any) => any) | null; + static setDefaultConfig(config: Linter.Config): void; + static getDefaultConfig(): Linter.Config; + static resetDefaultConfig(): void; + + constructor(config?: Linter.Config); + + run( + name: string, + rule: RuleDefinition, + tests: { + valid: Array; + invalid: RuleTester.InvalidTestCase[]; + /** + * Additional assertions for the "error" matchers of invalid test cases to enforce consistency. + */ + assertionOptions?: { + /** + * If true, each `errors` block must check the expected error + * message, either via a string in the `errors` array, or via + * `message`/`messageId` in an errors object. + * `"message"`/`"messageId"` can be used to further limit the + * message assertions to the respective versions. + */ + requireMessage?: boolean | "message" | "messageId"; + /** + * If true, each `errors` block must be an array of objects, + * that each check all location properties `line`, `column`, + * `endLine`, `endColumn`, the later may be omitted, if the + * error does not contain them. + */ + requireLocation?: boolean; + /** + * If true, each error and suggestion with a `messageId` must specify a `data` + * property if the referenced message contains placeholders. + * `"error"` and `"suggestion" limit the assertion to errors and suggestions respectively. + */ + requireData?: boolean | "error" | "suggestion"; + }; + }, + ): void; + + static only( + item: string | RuleTester.ValidTestCase | RuleTester.InvalidTestCase, + ): RuleTester.ValidTestCase | RuleTester.InvalidTestCase; +} + +export namespace RuleTester { + interface ValidTestCase extends Omit< + Linter.Config, + | "name" + | "basePath" + | "files" + | "ignores" + | "linterOptions" + | "plugins" + | "rules" + > { + name?: string; + code: string; + options?: any[]; + filename?: string | undefined; + only?: boolean; + before?: () => void; + after?: () => void; + } + + interface SuggestionOutput { + messageId?: string; + desc?: string; + data?: MessagePlaceholderData | undefined; + output: string; + } + + interface InvalidTestCase extends ValidTestCase { + errors: number | Array; + output?: string | null | undefined; + } + + interface TestCaseError { + message?: string | RegExp; + messageId?: string; + data?: MessagePlaceholderData | undefined; + line?: number | undefined; + column?: number | undefined; + endLine?: number | undefined; + endColumn?: number | undefined; + suggestions?: SuggestionOutput[] | number | undefined; + } +} + +// #endregion diff --git a/node_modules/eslint/lib/types/rules.d.ts b/node_modules/eslint/lib/types/rules.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b64c7d4bb0c972e0eeb21f1a7e42cdc8dfa2f0d --- /dev/null +++ b/node_modules/eslint/lib/types/rules.d.ts @@ -0,0 +1,5603 @@ +/** + * @fileoverview This file contains the rule types for ESLint. It was initially extracted + * from the `@types/eslint` package. + */ + +/* + * MIT License + * Copyright (c) Microsoft Corporation. + * + * 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 + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import { Linter } from "./index"; + +//----------------------------------------------------------------------------- +// Helper types +//----------------------------------------------------------------------------- + +interface NoRestrictedImportPathCommonOptions { + name: string; + message?: string; + allowTypeImports?: boolean; +} + +type EitherImportNamesOrAllowImportName = + | { importNames?: string[]; allowImportNames?: never } + | { allowImportNames?: string[]; importNames?: never }; + +type ValidNoRestrictedImportPathOptions = NoRestrictedImportPathCommonOptions & + EitherImportNamesOrAllowImportName; + +interface NoRestrictedImportPatternCommonOptions { + message?: string; + caseSensitive?: boolean; + allowTypeImports?: boolean; +} + +// Base type for group or regex constraint, ensuring mutual exclusivity +type EitherGroupOrRegEx = + | { group: string[]; regex?: never } + | { regex: string; group?: never }; + +// Base type for import name specifiers, ensuring mutual exclusivity +type EitherNameSpecifiers = + | { + importNames?: string[]; + importNamePattern?: string; + allowImportNames?: never; + allowImportNamePattern?: never; + } + | { + allowImportNames?: string[]; + importNames?: never; + importNamePattern?: never; + allowImportNamePattern?: never; + } + | { + allowImportNamePattern?: string; + importNames?: never; + allowImportNames?: never; + importNamePattern?: never; + }; + +// Adds oneOf and not constraints, ensuring group or regex are present and mutually exclusive sets for importNames, allowImportNames, etc., as per the schema. +type ValidNoRestrictedImportPatternOptions = + NoRestrictedImportPatternCommonOptions & + EitherGroupOrRegEx & + EitherNameSpecifiers; + +interface CapitalizedCommentsCommonOptions { + ignorePattern?: string; + /** + * @default false + */ + ignoreInlineComments?: boolean; + /** + * @default false + */ + ignoreConsecutiveComments?: boolean; +} + +//----------------------------------------------------------------------------- +// Public types +//----------------------------------------------------------------------------- + +export interface ESLintRules extends Linter.RulesRecord { + /** + * Rule to enforce getter and setter pairs in objects and classes. + * + * @since 0.22.0 + * @see https://eslint.org/docs/latest/rules/accessor-pairs + */ + "accessor-pairs": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + setWithoutGet: boolean; + /** + * @default false + */ + getWithoutSet: boolean; + /** + * @default true + */ + enforceForClassMembers: boolean; + /** + * @default false + */ + enforceForTSTypes: boolean; + }>, + ] + >; + + /** + * Rule to enforce linebreaks after opening and before closing array brackets. + * + * @since 4.0.0-alpha.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`array-bracket-newline`](https://eslint.style/rules/array-bracket-newline) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/array-bracket-newline + */ + "array-bracket-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | "consistent" + | Partial<{ + /** + * @default true + */ + multiline: boolean; + /** + * @default null + */ + minItems: number | null; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing inside array brackets. + * + * @since 0.24.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`array-bracket-spacing`](https://eslint.style/rules/array-bracket-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/array-bracket-spacing + */ + "array-bracket-spacing": + | Linter.RuleEntry< + [ + "never", + Partial<{ + /** + * @default false + */ + singleValue: boolean; + /** + * @default false + */ + objectsInArrays: boolean; + /** + * @default false + */ + arraysInArrays: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "always", + Partial<{ + /** + * @default true + */ + singleValue: boolean; + /** + * @default true + */ + objectsInArrays: boolean; + /** + * @default true + */ + arraysInArrays: boolean; + }>, + ] + >; + + /** + * Rule to enforce `return` statements in callbacks of array methods. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/latest/rules/array-callback-return + */ + "array-callback-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowImplicit: boolean; + /** + * @default false + */ + checkForEach: boolean; + /** + * @default false + */ + allowVoid: boolean; + }>, + ] + >; + + /** + * Rule to enforce line breaks after each array element. + * + * @since 4.0.0-rc.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`array-element-newline`](https://eslint.style/rules/array-element-newline) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/array-element-newline + */ + "array-element-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | "consistent" + | Partial<{ + /** + * @default true + */ + multiline: boolean; + /** + * @default null + */ + minItems: number | null; + }>, + ] + >; + + /** + * Rule to require braces around arrow function bodies. + * + * @since 1.8.0 + * @see https://eslint.org/docs/latest/rules/arrow-body-style + */ + "arrow-body-style": + | Linter.RuleEntry< + [ + "as-needed", + Partial<{ + /** + * @default false + */ + requireReturnForObjectLiteral: boolean; + }>, + ] + > + | Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require parentheses around arrow function arguments. + * + * @since 1.0.0-rc-1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`arrow-parens`](https://eslint.style/rules/arrow-parens) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/arrow-parens + */ + "arrow-parens": + | Linter.RuleEntry<["always"]> + | Linter.RuleEntry< + [ + "as-needed", + Partial<{ + /** + * @default false + */ + requireForBlockBody: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before and after the arrow in arrow functions. + * + * @since 1.0.0-rc-1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`arrow-spacing`](https://eslint.style/rules/arrow-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/arrow-spacing + */ + "arrow-spacing": Linter.RuleEntry<[]>; + + /** + * Rule to enforce the use of variables within the scope they are defined. + * + * @since 0.1.0 + * @see https://eslint.org/docs/latest/rules/block-scoped-var + */ + "block-scoped-var": Linter.RuleEntry<[]>; + + /** + * Rule to disallow or enforce spaces inside of blocks after opening block and before closing block. + * + * @since 1.2.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`block-spacing`](https://eslint.style/rules/block-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/block-spacing + */ + "block-spacing": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to enforce consistent brace style for blocks. + * + * @since 0.0.7 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`brace-style`](https://eslint.style/rules/brace-style) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/brace-style + */ + "brace-style": Linter.RuleEntry< + [ + "1tbs" | "stroustrup" | "allman", + Partial<{ + /** + * @default false + */ + allowSingleLine: boolean; + }>, + ] + >; + + /** + * Rule to require `return` statements after callbacks. + * + * @since 1.0.0-rc-1 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`callback-return`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/callback-return.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/callback-return + */ + "callback-return": Linter.RuleEntry<[string[]]>; + + /** + * Rule to enforce camelcase naming convention. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/camelcase + */ + camelcase: Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'always' + */ + properties: "always" | "never"; + /** + * @default false + */ + ignoreDestructuring: boolean; + /** + * @since 6.7.0 + * @default false + */ + ignoreImports: boolean; + /** + * @since 7.4.0 + * @default false + */ + ignoreGlobals: boolean; + /** + * @remarks + * Also accept for regular expression patterns + */ + allow: string[]; + }>, + ] + >; + + /** + * Rule to enforce or disallow capitalization of the first letter of a comment. + * + * @since 3.11.0 + * @see https://eslint.org/docs/latest/rules/capitalized-comments + */ + "capitalized-comments": Linter.RuleEntry< + [ + "always" | "never", + ( + | CapitalizedCommentsCommonOptions + | Partial<{ + line: CapitalizedCommentsCommonOptions; + block: CapitalizedCommentsCommonOptions; + }> + ), + ] + >; + + /** + * Rule to enforce that class methods utilize `this`. + * + * @since 3.4.0 + * @see https://eslint.org/docs/latest/rules/class-methods-use-this + */ + "class-methods-use-this": Linter.RuleEntry< + [ + Partial<{ + exceptMethods: string[]; + /** + * @default true + */ + enforceForClassFields: boolean; + /** + * @default false + */ + ignoreOverrideMethods: boolean; + ignoreClassesWithImplements: "all" | "public-fields"; + }>, + ] + >; + + /** + * Rule to require or disallow trailing commas. + * + * @since 0.16.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`comma-dangle`](https://eslint.style/rules/comma-dangle) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/comma-dangle + */ + "comma-dangle": Linter.RuleEntry< + [ + | "never" + | "always" + | "always-multiline" + | "only-multiline" + | Partial<{ + /** + * @default 'never' + */ + arrays: + | "never" + | "always" + | "always-multiline" + | "only-multiline"; + /** + * @default 'never' + */ + objects: + | "never" + | "always" + | "always-multiline" + | "only-multiline"; + /** + * @default 'never' + */ + imports: + | "never" + | "always" + | "always-multiline" + | "only-multiline"; + /** + * @default 'never' + */ + exports: + | "never" + | "always" + | "always-multiline" + | "only-multiline"; + /** + * @default 'never' + */ + functions: + | "never" + | "always" + | "always-multiline" + | "only-multiline"; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before and after commas. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`comma-spacing`](https://eslint.style/rules/comma-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/comma-spacing + */ + "comma-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + before: boolean; + /** + * @default true + */ + after: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent comma style. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`comma-style`](https://eslint.style/rules/comma-style) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/comma-style + */ + "comma-style": Linter.RuleEntry< + [ + "last" | "first", + Partial<{ + exceptions: Record; + }>, + ] + >; + + /** + * Rule to enforce a maximum cyclomatic complexity allowed in a program. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/complexity + */ + complexity: Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 20 + */ + max: number; + /** + * @deprecated + * @default 20 + */ + maximum: number; + /** + * @default "classic" + * @since 9.12.0 + */ + variant: "classic" | "modified"; + }> + | number, + ] + >; + + /** + * Rule to enforce consistent spacing inside computed property brackets. + * + * @since 0.23.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`computed-property-spacing`](https://eslint.style/rules/computed-property-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/computed-property-spacing + */ + "computed-property-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require `return` statements to either always or never specify values. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/consistent-return + */ + "consistent-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + treatUndefinedAsUnspecified: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent naming when capturing the current execution context. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/consistent-this + */ + "consistent-this": Linter.RuleEntry<[...string[]]>; + + /** + * Rule to require `super()` calls in constructors. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.24.0 + * @see https://eslint.org/docs/latest/rules/constructor-super + */ + "constructor-super": Linter.RuleEntry<[]>; + + /** + * Rule to enforce consistent brace style for all control statements. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/curly + */ + curly: Linter.RuleEntry< + ["all"] | ["multi" | "multi-line" | "multi-or-nest", "consistent"?] + >; + + /** + * Rule to require `default` cases in `switch` statements. + * + * @since 0.6.0 + * @see https://eslint.org/docs/latest/rules/default-case + */ + "default-case": Linter.RuleEntry< + [ + Partial<{ + /** + * @default '^no default$' + */ + commentPattern: string; + }>, + ] + >; + + /** + * Rule to enforce `default` clauses in `switch` statements to be last. + * + * @since 7.0.0-alpha.0 + * @see https://eslint.org/docs/latest/rules/default-case-last + */ + "default-case-last": Linter.RuleEntry<[]>; + + /** + * Rule to enforce default parameters to be last. + * + * @since 6.4.0 + * @see https://eslint.org/docs/latest/rules/default-param-last + */ + "default-param-last": Linter.RuleEntry<[]>; + + /** + * Rule to enforce consistent newlines before and after dots. + * + * @since 0.21.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`dot-location`](https://eslint.style/rules/dot-location) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/dot-location + */ + "dot-location": Linter.RuleEntry<["object" | "property"]>; + + /** + * Rule to enforce dot notation whenever possible. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/dot-notation + */ + "dot-notation": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + allowKeywords: boolean; + allowPattern: string; + }>, + ] + >; + + /** + * Rule to require or disallow newline at the end of files. + * + * @since 0.7.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`eol-last`](https://eslint.style/rules/eol-last) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/eol-last + */ + "eol-last": Linter.RuleEntry< + [ + "always" | "never", // | 'unix' | 'windows' + ] + >; + + /** + * Rule to require the use of `===` and `!==`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/eqeqeq + */ + eqeqeq: + | Linter.RuleEntry< + [ + "always", + Partial<{ + /** + * @default 'always' + */ + null: "always" | "never" | "ignore"; + }>, + ] + > + | Linter.RuleEntry<["smart" | "allow-null"]>; + + /** + * Rule to enforce `for` loop update clause moving the counter in the right direction. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 4.0.0-beta.0 + * @see https://eslint.org/docs/latest/rules/for-direction + */ + "for-direction": Linter.RuleEntry<[]>; + + /** + * Rule to require or disallow spacing between function identifiers and their invocations. + * + * @since 3.3.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`function-call-spacing`](https://eslint.style/rules/function-call-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/func-call-spacing + */ + "func-call-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require function names to match the name of the variable or property to which they are assigned. + * + * @since 3.8.0 + * @see https://eslint.org/docs/latest/rules/func-name-matching + */ + "func-name-matching": + | Linter.RuleEntry< + [ + "always" | "never", + Partial<{ + /** + * @default false + */ + considerPropertyDescriptor: boolean; + /** + * @default false + */ + includeCommonJSModuleExports: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + considerPropertyDescriptor: boolean; + /** + * @default false + */ + includeCommonJSModuleExports: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow named `function` expressions. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/func-names + */ + "func-names": Linter.RuleEntry< + [ + "always" | "as-needed" | "never", + Partial<{ + generators: "always" | "as-needed" | "never"; + }>, + ] + >; + + /** + * Rule to enforce the consistent use of either `function` declarations or expressions assigned to variables. + * + * @since 0.2.0 + * @see https://eslint.org/docs/latest/rules/func-style + */ + "func-style": Linter.RuleEntry< + [ + "expression" | "declaration", + Partial<{ + /** + * @default false + */ + allowArrowFunctions: boolean; + /** + * @default false + */ + allowTypeAnnotation: boolean; + overrides: { + namedExports: "declaration" | "expression" | "ignore"; + }; + }>, + ] + >; + + /** + * Rule to enforce line breaks between arguments of a function call. + * + * @since 6.2.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`function-call-argument-newline`](https://eslint.style/rules/function-call-argument-newline) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/function-call-argument-newline + */ + "function-call-argument-newline": Linter.RuleEntry< + [ + /** + * @default "always" + */ + "always" | "never" | "consistent", + ] + >; + + /** + * Rule to enforce consistent line breaks inside function parentheses. + * + * @since 4.6.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`function-paren-newline`](https://eslint.style/rules/function-paren-newline) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/function-paren-newline + */ + "function-paren-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | "multiline" + | "multiline-arguments" + | "consistent" + | Partial<{ + minItems: number; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing around `*` operators in generator functions. + * + * @since 0.17.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`generator-star-spacing`](https://eslint.style/rules/generator-star-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/generator-star-spacing + */ + "generator-star-spacing": Linter.RuleEntry< + [ + | Partial<{ + before: boolean; + after: boolean; + named: + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither"; + anonymous: + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither"; + method: + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither"; + }> + | "before" + | "after" + | "both" + | "neither", + ] + >; + + /** + * Rule to enforce `return` statements in getters. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 4.2.0 + * @see https://eslint.org/docs/latest/rules/getter-return + */ + "getter-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowImplicit: boolean; + }>, + ] + >; + + /** + * Rule to require `require()` calls to be placed at top-level module scope. + * + * @since 1.4.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`global-require`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/global-require.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/global-require + */ + "global-require": Linter.RuleEntry<[]>; + + /** + * Rule to require grouped accessor pairs in object literals and classes. + * + * @since 6.7.0 + * @see https://eslint.org/docs/latest/rules/grouped-accessor-pairs + */ + "grouped-accessor-pairs": Linter.RuleEntry< + [ + "anyOrder" | "getBeforeSet" | "setBeforeGet", + Partial<{ + /** + * @default false + */ + enforceForTSTypes: boolean; + }>, + ] + >; + + /** + * Rule to require `for-in` loops to include an `if` statement. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/guard-for-in + */ + "guard-for-in": Linter.RuleEntry<[]>; + + /** + * Rule to require error handling in callbacks. + * + * @since 0.4.5 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`handle-callback-err`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/handle-callback-err.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/handle-callback-err + */ + "handle-callback-err": Linter.RuleEntry<[string]>; + + /** + * Rule to disallow specified identifiers. + * + * @since 2.0.0-beta.2 + * @deprecated since 7.5.0. + * The rule was renamed. + * Please, use [`id-denylist`](https://eslint.org/docs/rules/id-denylist). + * @see https://eslint.org/docs/latest/rules/id-blacklist + */ + "id-blacklist": Linter.RuleEntry<[...string[]]>; + + /** + * Rule to disallow specified identifiers. + * + * @since 7.4.0 + * @see https://eslint.org/docs/latest/rules/id-denylist + */ + "id-denylist": Linter.RuleEntry; + + /** + * Rule to enforce minimum and maximum identifier lengths. + * + * @since 1.0.0 + * @see https://eslint.org/docs/latest/rules/id-length + */ + "id-length": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 2 + */ + min: number; + /** + * @default Infinity + */ + max: number; + /** + * @default 'always' + */ + properties: "always" | "never"; + exceptions: string[]; + exceptionPatterns: string[]; + }>, + ] + >; + + /** + * Rule to require identifiers to match a specified regular expression. + * + * @since 1.0.0 + * @see https://eslint.org/docs/latest/rules/id-match + */ + "id-match": Linter.RuleEntry< + [ + string, + Partial<{ + /** + * @default false + */ + properties: boolean; + /** + * @default false + */ + classFields: boolean; + /** + * @default false + */ + onlyDeclarations: boolean; + /** + * @default false + */ + ignoreDestructuring: boolean; + }>, + ] + >; + + /** + * Rule to enforce the location of arrow function bodies. + * + * @since 4.12.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`implicit-arrow-linebreak`](https://eslint.style/rules/implicit-arrow-linebreak) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/implicit-arrow-linebreak + */ + "implicit-arrow-linebreak": Linter.RuleEntry<["beside" | "below"]>; + + /** + * Rule to enforce consistent indentation. + * + * @since 0.14.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`indent`](https://eslint.style/rules/indent) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/indent + */ + indent: Linter.RuleEntry< + [ + number | "tab", + Partial<{ + /** + * @default 0 + */ + SwitchCase: number; + /** + * @default 1 + */ + VariableDeclarator: + | Partial<{ + /** + * @default 1 + */ + var: number | "first"; + /** + * @default 1 + */ + let: number | "first"; + /** + * @default 1 + */ + const: number | "first"; + }> + | number + | "first"; + /** + * @default 1 + */ + outerIIFEBody: number; + /** + * @default 1 + */ + MemberExpression: number | "off"; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionDeclaration: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionExpression: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { arguments: 1 } + */ + CallExpression: Partial<{ + /** + * @default 1 + */ + arguments: number | "first" | "off"; + }>; + /** + * @default 1 + */ + ArrayExpression: number | "first" | "off"; + /** + * @default 1 + */ + ObjectExpression: number | "first" | "off"; + /** + * @default 1 + */ + ImportDeclaration: number | "first" | "off"; + /** + * @default false + */ + flatTernaryExpressions: boolean; + ignoredNodes: string[]; + /** + * @default false + */ + ignoreComments: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent indentation. + * + * @since 4.0.0-alpha.0 + * @deprecated since 4.0.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`indent`](https://eslint.style/rules/indent) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/indent-legacy + */ + "indent-legacy": Linter.RuleEntry< + [ + number | "tab", + Partial<{ + /** + * @default 0 + */ + SwitchCase: number; + /** + * @default 1 + */ + VariableDeclarator: + | Partial<{ + /** + * @default 1 + */ + var: number | "first"; + /** + * @default 1 + */ + let: number | "first"; + /** + * @default 1 + */ + const: number | "first"; + }> + | number + | "first"; + /** + * @default 1 + */ + outerIIFEBody: number; + /** + * @default 1 + */ + MemberExpression: number | "off"; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionDeclaration: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { parameters: 1, body: 1 } + */ + FunctionExpression: Partial<{ + /** + * @default 1 + */ + parameters: number | "first" | "off"; + /** + * @default 1 + */ + body: number; + }>; + /** + * @default { arguments: 1 } + */ + CallExpression: Partial<{ + /** + * @default 1 + */ + arguments: number | "first" | "off"; + }>; + /** + * @default 1 + */ + ArrayExpression: number | "first" | "off"; + /** + * @default 1 + */ + ObjectExpression: number | "first" | "off"; + /** + * @default 1 + */ + ImportDeclaration: number | "first" | "off"; + /** + * @default false + */ + flatTernaryExpressions: boolean; + ignoredNodes: string[]; + /** + * @default false + */ + ignoreComments: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow initialization in variable declarations. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/init-declarations + */ + "init-declarations": + | Linter.RuleEntry<["always"]> + | Linter.RuleEntry< + [ + "never", + Partial<{ + ignoreForLoopInit: boolean; + }>, + ] + >; + + /** + * Rule to enforce the consistent use of either double or single quotes in JSX attributes. + * + * @since 1.4.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`jsx-quotes`](https://eslint.style/rules/jsx-quotes) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/jsx-quotes + */ + "jsx-quotes": Linter.RuleEntry<["prefer-double" | "prefer-single"]>; + + /** + * Rule to enforce consistent spacing between keys and values in object literal properties. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`key-spacing`](https://eslint.style/rules/key-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/key-spacing + */ + "key-spacing": Linter.RuleEntry< + [ + | Partial< + | { + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + align: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'colon' + */ + on: "value" | "colon"; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | "value" + | "colon"; + } + | { + singleLine?: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | undefined; + multiLine?: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + align: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'colon' + */ + on: "value" | "colon"; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | "value" + | "colon"; + }> + | undefined; + } + > + | { + align: Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'colon' + */ + on: "value" | "colon"; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }>; + singleLine?: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | undefined; + multiLine?: + | Partial<{ + /** + * @default false + */ + beforeColon: boolean; + /** + * @default true + */ + afterColon: boolean; + /** + * @default 'strict' + */ + mode: "strict" | "minimum"; + }> + | undefined; + }, + ] + >; + + /** + * Rule to enforce consistent spacing before and after keywords. + * + * @since 2.0.0-beta.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`keyword-spacing`](https://eslint.style/rules/keyword-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/keyword-spacing + */ + "keyword-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + before: boolean; + /** + * @default true + */ + after: boolean; + overrides: Record< + string, + Partial<{ + before: boolean; + after: boolean; + }> + >; + }>, + ] + >; + + /** + * Rule to enforce position of line comments. + * + * @since 3.5.0 + * @deprecated since 9.3.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`line-comment-position`](https://eslint.style/rules/line-comment-position) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/line-comment-position + */ + "line-comment-position": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'above' + */ + position: "above" | "beside"; + ignorePattern: string; + /** + * @default true + */ + applyDefaultIgnorePatterns: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent linebreak style. + * + * @since 0.21.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`linebreak-style`](https://eslint.style/rules/linebreak-style) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/linebreak-style + */ + "linebreak-style": Linter.RuleEntry<["unix" | "windows"]>; + + /** + * Rule to require empty lines around comments. + * + * @since 0.22.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`lines-around-comment`](https://eslint.style/rules/lines-around-comment) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/lines-around-comment + */ + "lines-around-comment": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + beforeBlockComment: boolean; + /** + * @default false + */ + afterBlockComment: boolean; + /** + * @default false + */ + beforeLineComment: boolean; + /** + * @default false + */ + afterLineComment: boolean; + /** + * @default false + */ + allowBlockStart: boolean; + /** + * @default false + */ + allowBlockEnd: boolean; + /** + * @default false + */ + allowObjectStart: boolean; + /** + * @default false + */ + allowObjectEnd: boolean; + /** + * @default false + */ + allowArrayStart: boolean; + /** + * @default false + */ + allowArrayEnd: boolean; + /** + * @default false + */ + allowClassStart: boolean; + /** + * @default false + */ + allowClassEnd: boolean; + ignorePattern: string; + /** + * @default true + */ + applyDefaultIgnorePatterns: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow newlines around directives. + * + * @since 3.5.0 + * @deprecated since 4.0.0. + * The rule was replaced with a more general rule. + * Please, use [`padding-line-between-statements`](https://eslint.style/rules/padding-line-between-statements) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/lines-around-directive + */ + "lines-around-directive": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require or disallow an empty line between class members. + * + * @since 4.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`lines-between-class-members`](https://eslint.style/rules/lines-between-class-members) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/lines-between-class-members + */ + "lines-between-class-members": Linter.RuleEntry< + [ + ( + | "always" + | "never" + | { + enforce: Array<{ + blankLine: "always" | "never"; + prev: "method" | "field" | "*"; + next: "method" | "field" | "*"; + }>; + } + ), + Partial<{ + /** + * @default false + */ + exceptAfterSingleLine: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow logical assignment operator shorthand. + * + * @since 8.24.0 + * @see https://eslint.org/docs/latest/rules/logical-assignment-operators + */ + "logical-assignment-operators": + | Linter.RuleEntry< + [ + "always", + Partial<{ + /** + * @default false + */ + enforceForIfStatements: boolean; + }>, + ] + > + | Linter.RuleEntry<["never"]>; + + /** + * Rule to enforce a maximum number of classes per file. + * + * @since 5.0.0-alpha.3 + * @see https://eslint.org/docs/latest/rules/max-classes-per-file + */ + "max-classes-per-file": Linter.RuleEntry< + [ + | number + | Partial<{ + /** + * @default false + */ + ignoreExpressions: boolean; + /** + * @default 1 + */ + max: number; + }>, + ] + >; + + /** + * Rule to enforce a maximum depth that blocks can be nested. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/max-depth + */ + "max-depth": Linter.RuleEntry< + [ + | number + | Partial<{ + /** + * @deprecated + * @default 4 + */ + maximum: number; + /** + * @default 4 + */ + max: number; + }>, + ] + >; + + /** + * Rule to enforce a maximum line length. + * + * @since 0.0.9 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`max-len`](https://eslint.style/rules/max-len) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/max-len + */ + "max-len": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 80 + */ + code: number; + /** + * @default 4 + */ + tabWidth: number; + comments: number; + ignorePattern: string; + /** + * @default false + */ + ignoreComments: boolean; + /** + * @default false + */ + ignoreTrailingComments: boolean; + /** + * @default false + */ + ignoreUrls: boolean; + /** + * @default false + */ + ignoreStrings: boolean; + /** + * @default false + */ + ignoreTemplateLiterals: boolean; + /** + * @default false + */ + ignoreRegExpLiterals: boolean; + }>, + ] + >; + + /** + * Rule to enforce a maximum number of lines per file. + * + * @since 2.12.0 + * @see https://eslint.org/docs/latest/rules/max-lines + */ + "max-lines": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 300 + */ + max: number; + /** + * @default false + */ + skipBlankLines: boolean; + /** + * @default false + */ + skipComments: boolean; + }> + | number, + ] + >; + + /** + * Rule to enforce a maximum number of lines of code in a function. + * + * @since 5.0.0 + * @see https://eslint.org/docs/latest/rules/max-lines-per-function + */ + "max-lines-per-function": Linter.RuleEntry< + [ + | number + | Partial<{ + /** + * @default 50 + */ + max: number; + /** + * @default false + */ + skipBlankLines: boolean; + /** + * @default false + */ + skipComments: boolean; + /** + * @default false + */ + IIFEs: boolean; + }>, + ] + >; + + /** + * Rule to enforce a maximum depth that callbacks can be nested. + * + * @since 0.2.0 + * @see https://eslint.org/docs/latest/rules/max-nested-callbacks + */ + "max-nested-callbacks": Linter.RuleEntry< + [ + | number + | Partial<{ + /** + * @deprecated + * @default 10 + */ + maximum: number; + /** + * @default 10 + */ + max: number; + }>, + ] + >; + + /** + * Rule to enforce a maximum number of parameters in function definitions. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/max-params + */ + "max-params": Linter.RuleEntry< + [ + | number + | Partial<{ + /** + * @deprecated + * @default 3 + */ + maximum: number; + /** + * @default 3 + */ + max: number; + /** + * @deprecated Replaced with `countThis' + * @default false + */ + countVoidThis: boolean; + /** + * @default "except-void" + */ + countThis: "always" | "never" | "except-void"; + }>, + ] + >; + + /** + * Rule to enforce a maximum number of statements allowed in function blocks. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/max-statements + */ + "max-statements": Linter.RuleEntry< + [ + ( + | number + | Partial<{ + /** + * @deprecated + * @default 10 + */ + maximum: number; + /** + * @default 10 + */ + max: number; + }> + ), + Partial<{ + /** + * @default false + */ + ignoreTopLevelFunctions: boolean; + }>, + ] + >; + + /** + * Rule to enforce a maximum number of statements allowed per line. + * + * @since 2.5.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`max-statements-per-line`](https://eslint.style/rules/max-statements-per-line) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/max-statements-per-line + */ + "max-statements-per-line": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 1 + */ + max: number; + }> + | number, + ] + >; + + /** + * Rule to enforce a particular style for multiline comments. + * + * @since 4.10.0 + * @deprecated since 9.3.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`multiline-comment-style`](https://eslint.style/rules/multiline-comment-style) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/multiline-comment-style + */ + "multiline-comment-style": Linter.RuleEntry< + ["starred-block" | "bare-block" | "separate-lines"] + >; + + /** + * Rule to enforce newlines between operands of ternary expressions. + * + * @since 3.1.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`multiline-ternary`](https://eslint.style/rules/multiline-ternary) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/multiline-ternary + */ + "multiline-ternary": Linter.RuleEntry< + ["always" | "always-multiline" | "never"] + >; + + /** + * Rule to require constructor names to begin with a capital letter. + * + * @since 0.0.3-0 + * @see https://eslint.org/docs/latest/rules/new-cap + */ + "new-cap": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + newIsCap: boolean; + /** + * @default true + */ + capIsNew: boolean; + newIsCapExceptions: string[]; + newIsCapExceptionPattern: string; + capIsNewExceptions: string[]; + capIsNewExceptionPattern: string; + /** + * @default true + */ + properties: boolean; + }>, + ] + >; + + /** + * Rule to enforce or disallow parentheses when invoking a constructor with no arguments. + * + * @since 0.0.6 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`new-parens`](https://eslint.style/rules/new-parens) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/new-parens + */ + "new-parens": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require or disallow an empty line after variable declarations. + * + * @since 0.18.0 + * @deprecated since 4.0.0. + * The rule was replaced with a more general rule. + * Please, use [`padding-line-between-statements`](https://eslint.style/rules/padding-line-between-statements) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/newline-after-var + */ + "newline-after-var": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to require an empty line before `return` statements. + * + * @since 2.3.0 + * @deprecated since 4.0.0. + * The rule was replaced with a more general rule. + * Please, use [`padding-line-between-statements`](https://eslint.style/rules/padding-line-between-statements) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/newline-before-return + */ + "newline-before-return": Linter.RuleEntry<[]>; + + /** + * Rule to require a newline after each call in a method chain. + * + * @since 2.0.0-rc.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`newline-per-chained-call`](https://eslint.style/rules/newline-per-chained-call) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/newline-per-chained-call + */ + "newline-per-chained-call": Linter.RuleEntry< + [ + { + /** + * @default 2 + */ + ignoreChainWithDepth: number; + }, + ] + >; + + /** + * Rule to disallow the use of `alert`, `confirm`, and `prompt`. + * + * @since 0.0.5 + * @see https://eslint.org/docs/latest/rules/no-alert + */ + "no-alert": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `Array` constructors. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-array-constructor + */ + "no-array-constructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow using an async function as a Promise executor. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 5.3.0 + * @see https://eslint.org/docs/latest/rules/no-async-promise-executor + */ + "no-async-promise-executor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `await` inside of loops. + * + * @since 3.12.0 + * @see https://eslint.org/docs/latest/rules/no-await-in-loop + */ + "no-await-in-loop": Linter.RuleEntry<[]>; + + /** + * Rule to disallow bitwise operators. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-bitwise + */ + "no-bitwise": Linter.RuleEntry< + [ + Partial<{ + /** + * @default [] + */ + allow: Array< + | "^" + | "|" + | "&" + | "<<" + | ">>" + | ">>>" + | "^=" + | "|=" + | "&=" + | "<<=" + | ">>=" + | ">>>=" + | "~" + >; + /** + * @default false + */ + int32Hint: boolean; + }>, + ] + >; + + /** + * Rule to disallow use of the `Buffer()` constructor. + * + * @since 4.0.0-alpha.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-deprecated-api`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-deprecated-api.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-buffer-constructor + */ + "no-buffer-constructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `arguments.caller` or `arguments.callee`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/no-caller + */ + "no-caller": Linter.RuleEntry<[]>; + + /** + * Rule to disallow lexical declarations in case clauses. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.9.0 + * @see https://eslint.org/docs/latest/rules/no-case-declarations + */ + "no-case-declarations": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `catch` clause parameters from shadowing variables in the outer scope. + * + * @since 0.0.9 + * @deprecated since 5.1.0. + * This rule was renamed. + * Please, use [`no-shadow`](https://eslint.org/docs/rules/no-shadow). + * @see https://eslint.org/docs/latest/rules/no-catch-shadow + */ + "no-catch-shadow": Linter.RuleEntry<[]>; + + /** + * Rule to disallow reassigning class members. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/no-class-assign + */ + "no-class-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow comparing against `-0`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 3.17.0 + * @see https://eslint.org/docs/latest/rules/no-compare-neg-zero + */ + "no-compare-neg-zero": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assignment operators in conditional expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-cond-assign + */ + "no-cond-assign": Linter.RuleEntry<["except-parens" | "always"]>; + + /** + * Rule to disallow arrow functions where they could be confused with comparisons. + * + * @since 2.0.0-alpha-2 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-confusing-arrow`](https://eslint.style/rules/no-confusing-arrow) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-confusing-arrow + */ + "no-confusing-arrow": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + allowParens: boolean; + }>, + ] + >; + + /** + * Rule to disallow the use of `console`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-console + */ + "no-console": Linter.RuleEntry< + [ + Partial<{ + allow: Array; + }>, + ] + >; + + /** + * Rule to disallow reassigning `const`, `using`, and `await using` variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/no-const-assign + */ + "no-const-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow expressions where the operation doesn't affect the value. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 8.14.0 + * @see https://eslint.org/docs/latest/rules/no-constant-binary-expression + */ + "no-constant-binary-expression": Linter.RuleEntry<[]>; + + /** + * Rule to disallow constant expressions in conditions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.1 + * @see https://eslint.org/docs/latest/rules/no-constant-condition + */ + "no-constant-condition": Linter.RuleEntry< + [ + { + /** + * @default "allExceptWhileTrue" + */ + checkLoops: "all" | "allExceptWhileTrue" | "none" | boolean; + }, + ] + >; + + /** + * Rule to disallow returning value from constructor. + * + * @since 6.7.0 + * @see https://eslint.org/docs/latest/rules/no-constructor-return + */ + "no-constructor-return": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `continue` statements. + * + * @since 0.19.0 + * @see https://eslint.org/docs/latest/rules/no-continue + */ + "no-continue": Linter.RuleEntry<[]>; + + /** + * Rule to disallow control characters in regular expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.1.0 + * @see https://eslint.org/docs/latest/rules/no-control-regex + */ + "no-control-regex": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `debugger`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-debugger + */ + "no-debugger": Linter.RuleEntry<[]>; + + /** + * Rule to disallow deleting variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-delete-var + */ + "no-delete-var": Linter.RuleEntry<[]>; + + /** + * Rule to disallow equal signs explicitly at the beginning of regular expressions. + * + * @since 0.1.0 + * @see https://eslint.org/docs/latest/rules/no-div-regex + */ + "no-div-regex": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate arguments in `function` definitions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.16.0 + * @see https://eslint.org/docs/latest/rules/no-dupe-args + */ + "no-dupe-args": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate class members. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.2.0 + * @see https://eslint.org/docs/latest/rules/no-dupe-class-members + */ + "no-dupe-class-members": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate conditions in if-else-if chains. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 6.7.0 + * @see https://eslint.org/docs/latest/rules/no-dupe-else-if + */ + "no-dupe-else-if": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate keys in object literals. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-dupe-keys + */ + "no-dupe-keys": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate case labels. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.17.0 + * @see https://eslint.org/docs/latest/rules/no-duplicate-case + */ + "no-duplicate-case": Linter.RuleEntry<[]>; + + /** + * Rule to disallow duplicate module imports. + * + * @since 2.5.0 + * @see https://eslint.org/docs/latest/rules/no-duplicate-imports + */ + "no-duplicate-imports": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + includeExports: boolean; + /** + * @default false + */ + allowSeparateTypeImports: boolean; + }>, + ] + >; + + /** + * Rule to disallow `else` blocks after `return` statements in `if` statements. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-else-return + */ + "no-else-return": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + allowElseIf: boolean; + }>, + ] + >; + + /** + * Rule to disallow empty block statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-empty + */ + "no-empty": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowEmptyCatch: boolean; + }>, + ] + >; + + /** + * Rule to disallow empty character classes in regular expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.22.0 + * @see https://eslint.org/docs/latest/rules/no-empty-character-class + */ + "no-empty-character-class": Linter.RuleEntry<[]>; + + /** + * Rule to disallow empty functions. + * + * @since 2.0.0 + * @see https://eslint.org/docs/latest/rules/no-empty-function + */ + "no-empty-function": Linter.RuleEntry< + [ + Partial<{ + /** + * @default [] + */ + allow: Array< + | "functions" + | "arrowFunctions" + | "generatorFunctions" + | "methods" + | "generatorMethods" + | "getters" + | "setters" + | "constructors" + | "asyncFunctions" + | "asyncMethods" + | "privateConstructors" + | "protectedConstructors" + | "decoratedFunctions" + | "overrideMethods" + >; + }>, + ] + >; + + /** + * Rule to disallow empty destructuring patterns. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.7.0 + * @see https://eslint.org/docs/latest/rules/no-empty-pattern + */ + "no-empty-pattern": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowObjectPatternsAsParameters: boolean; + }>, + ] + >; + + /** + * Rule to disallow empty static blocks. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 8.27.0 + * @see https://eslint.org/docs/latest/rules/no-empty-static-block + */ + "no-empty-static-block": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `null` comparisons without type-checking operators. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-eq-null + */ + "no-eq-null": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `eval()`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-eval + */ + "no-eval": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowIndirect: boolean; + }>, + ] + >; + + /** + * Rule to disallow reassigning exceptions in `catch` clauses. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-ex-assign + */ + "no-ex-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow extending native types. + * + * @since 0.1.4 + * @see https://eslint.org/docs/latest/rules/no-extend-native + */ + "no-extend-native": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to disallow unnecessary calls to `.bind()`. + * + * @since 0.8.0 + * @see https://eslint.org/docs/latest/rules/no-extra-bind + */ + "no-extra-bind": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary boolean casts. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-extra-boolean-cast + */ + "no-extra-boolean-cast": Linter.RuleEntry< + [ + | Partial<{ + /** + * @since 9.3.0 + * @default false + */ + enforceForInnerExpressions: boolean; + /** + * @deprecated + */ + enforceForLogicalOperands: never; + }> + | Partial<{ + /** + * @deprecated + * @since 7.0.0-alpha.2 + * @default false + */ + enforceForLogicalOperands: boolean; + enforceForInnerExpressions: never; + }>, + ] + >; + + /** + * Rule to disallow unnecessary labels. + * + * @since 2.0.0-rc.0 + * @see https://eslint.org/docs/latest/rules/no-extra-label + */ + "no-extra-label": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary parentheses. + * + * @since 0.1.4 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-extra-parens`](https://eslint.style/rules/no-extra-parens) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-extra-parens + */ + "no-extra-parens": + | Linter.RuleEntry< + [ + "all", + Partial<{ + /** + * @default true, + */ + conditionalAssign: boolean; + /** + * @default true + */ + returnAssign: boolean; + /** + * @default true + */ + nestedBinaryExpressions: boolean; + /** + * @default 'none' + */ + ignoreJSX: + | "none" + | "all" + | "multi-line" + | "single-line"; + /** + * @default true + */ + enforceForArrowConditionals: boolean; + }>, + ] + > + | Linter.RuleEntry<["functions"]>; + + /** + * Rule to disallow unnecessary semicolons. + * + * @since 0.0.9 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-extra-semi`](https://eslint.style/rules/no-extra-semi) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-extra-semi + */ + "no-extra-semi": Linter.RuleEntry<[]>; + + /** + * Rule to disallow fallthrough of `case` statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/no-fallthrough + */ + "no-fallthrough": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'falls?\s?through' + */ + commentPattern: string; + /** + * @default false + */ + allowEmptyCase: boolean; + /** + * @default false + */ + reportUnusedFallthroughComment: boolean; + }>, + ] + >; + + /** + * Rule to disallow leading or trailing decimal points in numeric literals. + * + * @since 0.0.6 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-floating-decimal`](https://eslint.style/rules/no-floating-decimal) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-floating-decimal + */ + "no-floating-decimal": Linter.RuleEntry<[]>; + + /** + * Rule to disallow reassigning `function` declarations. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-func-assign + */ + "no-func-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assignments to native objects or read-only global variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 3.3.0 + * @see https://eslint.org/docs/latest/rules/no-global-assign + */ + "no-global-assign": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to disallow shorthand type conversions. + * + * @since 1.0.0-rc-2 + * @see https://eslint.org/docs/latest/rules/no-implicit-coercion + */ + "no-implicit-coercion": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + boolean: boolean; + /** + * @default true + */ + number: boolean; + /** + * @default true + */ + string: boolean; + /** + * @default false + */ + disallowTemplateShorthand: boolean; + /** + * @default [] + */ + allow: Array<"~" | "!!" | "+" | "- -" | "-" | "*">; + }>, + ] + >; + + /** + * Rule to disallow declarations in the global scope. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/latest/rules/no-implicit-globals + */ + "no-implicit-globals": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + lexicalBindings: boolean; + }>, + ] + >; + + /** + * Rule to disallow the use of `eval()`-like methods. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/no-implied-eval + */ + "no-implied-eval": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assigning to imported bindings. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 6.4.0 + * @see https://eslint.org/docs/latest/rules/no-import-assign + */ + "no-import-assign": Linter.RuleEntry<[]>; + + /** + * Rule to disallow inline comments after code. + * + * @since 0.10.0 + * @see https://eslint.org/docs/latest/rules/no-inline-comments + */ + "no-inline-comments": Linter.RuleEntry< + [ + Partial<{ + ignorePattern: string; + }>, + ] + >; + + /** + * Rule to disallow variable or `function` declarations in nested blocks. + * + * @since 0.6.0 + * @see https://eslint.org/docs/latest/rules/no-inner-declarations + */ + "no-inner-declarations": Linter.RuleEntry< + [ + "functions" | "both", + Partial<{ + /** + * @default "allow" + */ + blockScopedFunctions: "allow" | "disallow"; + }>, + ] + >; + + /** + * Rule to disallow invalid regular expression strings in `RegExp` constructors. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.1.4 + * @see https://eslint.org/docs/latest/rules/no-invalid-regexp + */ + "no-invalid-regexp": Linter.RuleEntry< + [ + Partial<{ + allowConstructorFlags: string[]; + }>, + ] + >; + + /** + * Rule to disallow use of `this` in contexts where the value of `this` is `undefined`. + * + * @since 1.0.0-rc-2 + * @see https://eslint.org/docs/latest/rules/no-invalid-this + */ + "no-invalid-this": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + capIsConstructor: boolean; + }>, + ] + >; + + /** + * Rule to disallow irregular whitespace. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.9.0 + * @see https://eslint.org/docs/latest/rules/no-irregular-whitespace + */ + "no-irregular-whitespace": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + skipStrings: boolean; + /** + * @default false + */ + skipComments: boolean; + /** + * @default false + */ + skipRegExps: boolean; + /** + * @default false + */ + skipTemplates: boolean; + /** + * @default false + */ + skipJSXText: boolean; + }>, + ] + >; + + /** + * Rule to disallow the use of the `__iterator__` property. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-iterator + */ + "no-iterator": Linter.RuleEntry<[]>; + + /** + * Rule to disallow labels that share a name with a variable. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-label-var + */ + "no-label-var": Linter.RuleEntry<[]>; + + /** + * Rule to disallow labeled statements. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-labels + */ + "no-labels": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowLoop: boolean; + /** + * @default false + */ + allowSwitch: boolean; + }>, + ] + >; + + /** + * Rule to disallow unnecessary nested blocks. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-lone-blocks + */ + "no-lone-blocks": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `if` statements as the only statement in `else` blocks. + * + * @since 0.6.0 + * @see https://eslint.org/docs/latest/rules/no-lonely-if + */ + "no-lonely-if": Linter.RuleEntry<[]>; + + /** + * Rule to disallow function declarations that contain unsafe references inside loop statements. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-loop-func + */ + "no-loop-func": Linter.RuleEntry<[]>; + + /** + * Rule to disallow literal numbers that lose precision. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 7.1.0 + * @see https://eslint.org/docs/latest/rules/no-loss-of-precision + */ + "no-loss-of-precision": Linter.RuleEntry<[]>; + + /** + * Rule to disallow magic numbers. + * + * @since 1.7.0 + * @see https://eslint.org/docs/latest/rules/no-magic-numbers + */ + "no-magic-numbers": Linter.RuleEntry< + [ + Partial<{ + /** + * @default [] + */ + ignore: Array; + /** + * @default false + */ + ignoreArrayIndexes: boolean; + /** + * @default false + */ + ignoreDefaultValues: boolean; + /** + * @default false + */ + ignoreClassFieldInitialValues: boolean; + /** + * @default false + */ + enforceConst: boolean; + /** + * @default false + */ + detectObjects: boolean; + /** + * @default false + */ + ignoreEnums: boolean; + /** + * @default false + */ + ignoreNumericLiteralTypes: boolean; + /** + * @default false + */ + ignoreReadonlyClassProperties: boolean; + /** + * @default false + */ + ignoreTypeIndexes: boolean; + }>, + ] + >; + + /** + * Rule to disallow characters which are made with multiple code points in character class syntax. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 5.3.0 + * @see https://eslint.org/docs/latest/rules/no-misleading-character-class + */ + "no-misleading-character-class": Linter.RuleEntry< + [ + Partial<{ + /** + * @since 9.3.0 + * @default false + */ + allowEscape: boolean; + }>, + ] + >; + + /** + * Rule to disallow mixed binary operators. + * + * @since 2.12.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-mixed-operators`](https://eslint.style/rules/no-mixed-operators) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-mixed-operators + */ + "no-mixed-operators": Linter.RuleEntry< + [ + Partial<{ + /** + * @default + * [ + * ["+", "-", "*", "/", "%", "**"], + * ["&", "|", "^", "~", "<<", ">>", ">>>"], + * ["==", "!=", "===", "!==", ">", ">=", "<", "<="], + * ["&&", "||"], + * ["in", "instanceof"] + * ] + */ + groups: string[][]; + /** + * @default true + */ + allowSamePrecedence: boolean; + }>, + ] + >; + + /** + * Rule to disallow `require` calls to be mixed with regular variable declarations. + * + * @since 0.0.9 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-mixed-requires`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-mixed-requires.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-mixed-requires + */ + "no-mixed-requires": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + grouping: boolean; + /** + * @default false + */ + allowCall: boolean; + }>, + ] + >; + + /** + * Rule to disallow mixed spaces and tabs for indentation. + * + * @since 0.7.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-mixed-spaces-and-tabs`](https://eslint.style/rules/no-mixed-spaces-and-tabs) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-mixed-spaces-and-tabs + */ + "no-mixed-spaces-and-tabs": Linter.RuleEntry<["smart-tabs"]>; + + /** + * Rule to disallow use of chained assignment expressions. + * + * @since 3.14.0 + * @see https://eslint.org/docs/latest/rules/no-multi-assign + */ + "no-multi-assign": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreNonDeclaration: boolean; + }>, + ] + >; + + /** + * Rule to disallow multiple spaces. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-multi-spaces`](https://eslint.style/rules/no-multi-spaces) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-multi-spaces + */ + "no-multi-spaces": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreEOLComments: boolean; + /** + * @default { Property: true } + */ + exceptions: Record; + }>, + ] + >; + + /** + * Rule to disallow multiline strings. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-multi-str + */ + "no-multi-str": Linter.RuleEntry<[]>; + + /** + * Rule to disallow multiple empty lines. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-multiple-empty-lines`](https://eslint.style/rules/no-multiple-empty-lines) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-multiple-empty-lines + */ + "no-multiple-empty-lines": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default 2 + */ + max: number; + maxEOF: number; + maxBOF: number; + }> + | number, + ] + >; + + /** + * Rule to disallow assignments to native objects or read-only global variables. + * + * @since 0.0.9 + * @deprecated since 3.3.0. + * Renamed rule. + * Please, use [`no-global-assign`](https://eslint.org/docs/rules/no-global-assign). + * @see https://eslint.org/docs/latest/rules/no-native-reassign + */ + "no-native-reassign": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to disallow negated conditions. + * + * @since 1.6.0 + * @see https://eslint.org/docs/latest/rules/no-negated-condition + */ + "no-negated-condition": Linter.RuleEntry<[]>; + + /** + * Rule to disallow negating the left operand in `in` expressions. + * + * @since 0.1.2 + * @deprecated since 3.3.0. + * Renamed rule. + * Please, use [`no-unsafe-negation`](https://eslint.org/docs/rules/no-unsafe-negation). + * @see https://eslint.org/docs/latest/rules/no-negated-in-lhs + */ + "no-negated-in-lhs": Linter.RuleEntry<[]>; + + /** + * Rule to disallow nested ternary expressions. + * + * @since 0.2.0 + * @see https://eslint.org/docs/latest/rules/no-nested-ternary + */ + "no-nested-ternary": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators outside of assignments or comparisons. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/no-new + */ + "no-new": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with the `Function` object. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/no-new-func + */ + "no-new-func": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with global non-constructor functions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 8.27.0 + * @see https://eslint.org/docs/latest/rules/no-new-native-nonconstructor + */ + "no-new-native-nonconstructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `Object` constructors. + * + * @since 0.0.9 + * @deprecated since 8.50.0. + * The new rule flags more situations where object literal syntax can be used, and it does not report a problem when the `Object` constructor is invoked with an argument. + * Please, use [`no-object-constructor`](https://eslint.org/docs/rules/no-object-constructor). + * @see https://eslint.org/docs/latest/rules/no-new-object + */ + "no-new-object": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with calls to `require`. + * + * @since 0.6.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-new-require`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-new-require.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-new-require + */ + "no-new-require": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with the `Symbol` object. + * + * @since 2.0.0-beta.1 + * @deprecated since 9.0.0. + * The rule was replaced with a more general rule. + * Please, use [`no-new-native-nonconstructor`](https://eslint.org/docs/latest/rules/no-new-native-nonconstructor). + * @see https://eslint.org/docs/latest/rules/no-new-symbol + */ + "no-new-symbol": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `new` operators with the `String`, `Number`, and `Boolean` objects. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/no-new-wrappers + */ + "no-new-wrappers": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `\8` and `\9` escape sequences in string literals. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 7.14.0 + * @see https://eslint.org/docs/latest/rules/no-nonoctal-decimal-escape + */ + "no-nonoctal-decimal-escape": Linter.RuleEntry<[]>; + + /** + * Rule to disallow calling global object properties as functions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-obj-calls + */ + "no-obj-calls": Linter.RuleEntry<[]>; + + /** + * Rule to disallow calls to the `Object` constructor without an argument. + * + * @since 8.50.0 + * @see https://eslint.org/docs/latest/rules/no-object-constructor + */ + "no-object-constructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow octal literals. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/no-octal + */ + "no-octal": Linter.RuleEntry<[]>; + + /** + * Rule to disallow octal escape sequences in string literals. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-octal-escape + */ + "no-octal-escape": Linter.RuleEntry<[]>; + + /** + * Rule to disallow reassigning function parameters. + * + * @since 0.18.0 + * @see https://eslint.org/docs/latest/rules/no-param-reassign + */ + "no-param-reassign": Linter.RuleEntry< + [ + | { + props?: false; + } + | ({ + props: true; + } & Partial<{ + /** + * @default [] + */ + ignorePropertyModificationsFor: string[]; + /** + * @since 6.6.0 + * @default [] + */ + ignorePropertyModificationsForRegex: string[]; + }>), + ] + >; + + /** + * Rule to disallow string concatenation with `__dirname` and `__filename`. + * + * @since 0.4.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-path-concat`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-path-concat.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-path-concat + */ + "no-path-concat": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the unary operators `++` and `--`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-plusplus + */ + "no-plusplus": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowForLoopAfterthoughts: boolean; + }>, + ] + >; + + /** + * Rule to disallow the use of `process.env`. + * + * @since 0.9.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-process-env`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-process-env.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-process-env + */ + "no-process-env": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `process.exit()`. + * + * @since 0.4.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-process-exit`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-process-exit.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-process-exit + */ + "no-process-exit": Linter.RuleEntry<[]>; + + /** + * Rule to disallow returning values from Promise executor functions. + * + * @since 7.3.0 + * @see https://eslint.org/docs/latest/rules/no-promise-executor-return + */ + "no-promise-executor-return": Linter.RuleEntry< + [ + { + /** + * @default false + */ + allowVoid?: boolean; + }, + ] + >; + + /** + * Rule to disallow the use of the `__proto__` property. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-proto + */ + "no-proto": Linter.RuleEntry<[]>; + + /** + * Rule to disallow calling some `Object.prototype` methods directly on objects. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.11.0 + * @see https://eslint.org/docs/latest/rules/no-prototype-builtins + */ + "no-prototype-builtins": Linter.RuleEntry<[]>; + + /** + * Rule to disallow variable redeclaration. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-redeclare + */ + "no-redeclare": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + builtinGlobals: boolean; + }>, + ] + >; + + /** + * Rule to disallow multiple spaces in regular expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-regex-spaces + */ + "no-regex-spaces": Linter.RuleEntry<[]>; + + /** + * Rule to disallow specified names in exports. + * + * @since 7.0.0-alpha.0 + * @see https://eslint.org/docs/latest/rules/no-restricted-exports + */ + "no-restricted-exports": Linter.RuleEntry< + [ + Partial<{ + /** + * @default [] + */ + restrictedNamedExports: string[]; + /** + * @since 9.3.0 + */ + restrictedNamedExportsPattern: string; + /** + * @since 8.33.0 + */ + restrictDefaultExports: Partial<{ + /** + * @default false + */ + direct: boolean; + /** + * @default false + */ + named: boolean; + /** + * @default false + */ + defaultFrom: boolean; + /** + * @default false + */ + namedFrom: boolean; + /** + * @default false + */ + namespaceFrom: boolean; + }>; + }>, + ] + >; + + /** + * Rule to disallow specified global variables. + * + * @since 2.3.0 + * @see https://eslint.org/docs/latest/rules/no-restricted-globals + */ + "no-restricted-globals": Linter.RuleEntry< + [ + ...( + | Array< + | string + | { + name: string; + message?: string | undefined; + } + > + | Array<{ + globals: Array< + | string + | { + name: string; + message?: string | undefined; + } + >; + checkGlobalObject?: boolean; + globalObjects?: string[]; + }> + ), + ] + >; + + /** + * Rule to disallow specified modules when loaded by `import`. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/latest/rules/no-restricted-imports + */ + "no-restricted-imports": Linter.RuleEntry< + [ + ...Array< + | string + | ValidNoRestrictedImportPathOptions + | Partial<{ + paths: Array< + string | ValidNoRestrictedImportPathOptions + >; + patterns: + | Array + | Array; + }> + >, + ] + >; + + /** + * Rule to disallow specified modules when loaded by `require`. + * + * @since 0.6.0 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-restricted-require`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-restricted-require.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-restricted-modules + */ + "no-restricted-modules": Linter.RuleEntry< + [ + ...Array< + | string + | { + name: string; + message?: string | undefined; + } + | Partial<{ + paths: Array< + | string + | { + name: string; + message?: string | undefined; + } + >; + patterns: string[]; + }> + >, + ] + >; + + /** + * Rule to disallow certain properties on certain objects. + * + * @since 3.5.0 + * @see https://eslint.org/docs/latest/rules/no-restricted-properties + */ + "no-restricted-properties": Linter.RuleEntry< + [ + ...Array< + | { + object: string; + property?: string | undefined; + message?: string | undefined; + } + | { + property: string; + allowObjects?: string[]; + message?: string | undefined; + } + | { + object: string; + allowProperties?: string[]; + message?: string | undefined; + } + >, + ] + >; + + /** + * Rule to disallow specified syntax. + * + * @since 1.4.0 + * @see https://eslint.org/docs/latest/rules/no-restricted-syntax + */ + "no-restricted-syntax": Linter.RuleEntry< + [ + ...Array< + | string + | { + selector: string; + message?: string | undefined; + } + >, + ] + >; + + /** + * Rule to disallow assignment operators in `return` statements. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-return-assign + */ + "no-return-assign": Linter.RuleEntry<["except-parens" | "always"]>; + + /** + * Rule to disallow unnecessary `return await`. + * + * @since 3.10.0 + * @deprecated since 8.46.0. + * The original assumption of the rule no longer holds true because of engine optimization. + * @see https://eslint.org/docs/latest/rules/no-return-await + */ + "no-return-await": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `javascript:` URLs. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-script-url + */ + "no-script-url": Linter.RuleEntry<[]>; + + /** + * Rule to disallow assignments where both sides are exactly the same. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.0.0-rc.0 + * @see https://eslint.org/docs/latest/rules/no-self-assign + */ + "no-self-assign": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + props: boolean; + }>, + ] + >; + + /** + * Rule to disallow comparisons where both sides are exactly the same. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-self-compare + */ + "no-self-compare": Linter.RuleEntry<[]>; + + /** + * Rule to disallow comma operators. + * + * @since 0.5.1 + * @see https://eslint.org/docs/latest/rules/no-sequences + */ + "no-sequences": Linter.RuleEntry< + [ + Partial<{ + /** + * @since 7.23.0 + * @default true + */ + allowInParentheses: boolean; + }>, + ] + >; + + /** + * Rule to disallow returning values from setters. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 6.7.0 + * @see https://eslint.org/docs/latest/rules/no-setter-return + */ + "no-setter-return": Linter.RuleEntry<[]>; + + /** + * Rule to disallow variable declarations from shadowing variables declared in the outer scope. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-shadow + */ + "no-shadow": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + builtinGlobals: boolean; + /** + * @default 'functions' + */ + hoist: + | "functions" + | "all" + | "never" + | "types" + | "functions-and-types"; + allow: string[]; + /** + * @since 8.10.0 + * @default false + */ + ignoreOnInitialization: boolean; + /** + * @default true + */ + ignoreTypeValueShadow: boolean; + /** + * @default true + */ + ignoreFunctionTypeParameterNameValueShadow: boolean; + }>, + ] + >; + + /** + * Rule to disallow identifiers from shadowing restricted names. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.1.4 + * @see https://eslint.org/docs/latest/rules/no-shadow-restricted-names + */ + "no-shadow-restricted-names": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + reportGlobalThis: boolean; + }>, + ] + >; + + /** + * Rule to disallow spacing between function identifiers and their applications (deprecated). + * + * @since 0.1.2 + * @deprecated since 3.3.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`function-call-spacing`](https://eslint.style/rules/function-call-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-spaced-func + */ + "no-spaced-func": Linter.RuleEntry<[]>; + + /** + * Rule to disallow sparse arrays. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.4.0 + * @see https://eslint.org/docs/latest/rules/no-sparse-arrays + */ + "no-sparse-arrays": Linter.RuleEntry<[]>; + + /** + * Rule to disallow synchronous methods. + * + * @since 0.0.9 + * @deprecated since 7.0.0. + * Node.js rules were moved out of ESLint core. + * Please, use [`no-sync`](https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-sync.md) in [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n). + * @see https://eslint.org/docs/latest/rules/no-sync + */ + "no-sync": Linter.RuleEntry< + [ + { + /** + * @default false + */ + allowAtRootLevel: boolean; + }, + ] + >; + + /** + * Rule to disallow all tabs. + * + * @since 3.2.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-tabs`](https://eslint.style/rules/no-tabs) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-tabs + */ + "no-tabs": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowIndentationTabs: boolean; + }>, + ] + >; + + /** + * Rule to disallow template literal placeholder syntax in regular strings. + * + * @since 3.3.0 + * @see https://eslint.org/docs/latest/rules/no-template-curly-in-string + */ + "no-template-curly-in-string": Linter.RuleEntry<[]>; + + /** + * Rule to disallow ternary operators. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-ternary + */ + "no-ternary": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `this`/`super` before calling `super()` in constructors. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.24.0 + * @see https://eslint.org/docs/latest/rules/no-this-before-super + */ + "no-this-before-super": Linter.RuleEntry<[]>; + + /** + * Rule to disallow throwing literals as exceptions. + * + * @since 0.15.0 + * @see https://eslint.org/docs/latest/rules/no-throw-literal + */ + "no-throw-literal": Linter.RuleEntry<[]>; + + /** + * Rule to disallow trailing whitespace at the end of lines. + * + * @since 0.7.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-trailing-spaces`](https://eslint.style/rules/no-trailing-spaces) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-trailing-spaces + */ + "no-trailing-spaces": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + skipBlankLines: boolean; + /** + * @default false + */ + ignoreComments: boolean; + }>, + ] + >; + + /** + * Rule to disallow `let` or `var` variables that are read but never assigned. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 9.27.0 + * @see https://eslint.org/docs/latest/rules/no-unassigned-vars + */ + "no-unassigned-vars": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of undeclared variables unless mentioned in \/*global *\/ comments. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-undef + */ + "no-undef": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + typeof: boolean; + }>, + ] + >; + + /** + * Rule to disallow initializing variables to `undefined`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/no-undef-init + */ + "no-undef-init": Linter.RuleEntry<[]>; + + /** + * Rule to disallow the use of `undefined` as an identifier. + * + * @since 0.7.1 + * @see https://eslint.org/docs/latest/rules/no-undefined + */ + "no-undefined": Linter.RuleEntry<[]>; + + /** + * Rule to disallow dangling underscores in identifiers. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-underscore-dangle + */ + "no-underscore-dangle": Linter.RuleEntry< + [ + Partial<{ + allow: string[]; + /** + * @default false + */ + allowAfterThis: boolean; + /** + * @default false + */ + allowAfterSuper: boolean; + /** + * @since 6.7.0 + * @default false + */ + allowAfterThisConstructor: boolean; + /** + * @default false + */ + enforceInMethodNames: boolean; + /** + * @since 8.15.0 + * @default false + */ + enforceInClassFields: boolean; + /** + * @since 8.31.0 + * @default true + */ + allowInArrayDestructuring: boolean; + /** + * @since 8.31.0 + * @default true + */ + allowInObjectDestructuring: boolean; + /** + * @since 7.7.0 + * @default true + */ + allowFunctionParams: boolean; + }>, + ] + >; + + /** + * Rule to disallow confusing multiline expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.24.0 + * @see https://eslint.org/docs/latest/rules/no-unexpected-multiline + */ + "no-unexpected-multiline": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unmodified loop conditions. + * + * @since 2.0.0-alpha-2 + * @see https://eslint.org/docs/latest/rules/no-unmodified-loop-condition + */ + "no-unmodified-loop-condition": Linter.RuleEntry<[]>; + + /** + * Rule to disallow ternary operators when simpler alternatives exist. + * + * @since 0.21.0 + * @see https://eslint.org/docs/latest/rules/no-unneeded-ternary + */ + "no-unneeded-ternary": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + defaultAssignment: boolean; + }>, + ] + >; + + /** + * Rule to disallow unreachable code after `return`, `throw`, `continue`, and `break` statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/no-unreachable + */ + "no-unreachable": Linter.RuleEntry<[]>; + + /** + * Rule to disallow loops with a body that allows only one iteration. + * + * @since 7.3.0 + * @see https://eslint.org/docs/latest/rules/no-unreachable-loop + */ + "no-unreachable-loop": Linter.RuleEntry< + [ + Partial<{ + /** + * @default [] + */ + ignore: Array< + | "WhileStatement" + | "DoWhileStatement" + | "ForStatement" + | "ForInStatement" + | "ForOfStatement" + >; + }>, + ] + >; + + /** + * Rule to disallow control flow statements in `finally` blocks. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.9.0 + * @see https://eslint.org/docs/latest/rules/no-unsafe-finally + */ + "no-unsafe-finally": Linter.RuleEntry<[]>; + + /** + * Rule to disallow negating the left operand of relational operators. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 3.3.0 + * @see https://eslint.org/docs/latest/rules/no-unsafe-negation + */ + "no-unsafe-negation": Linter.RuleEntry< + [ + Partial<{ + /** + * @since 6.6.0 + * @default false + */ + enforceForOrderingRelations: boolean; + }>, + ] + >; + + /** + * Rule to disallow use of optional chaining in contexts where the `undefined` value is not allowed. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 7.15.0 + * @see https://eslint.org/docs/latest/rules/no-unsafe-optional-chaining + */ + "no-unsafe-optional-chaining": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + disallowArithmeticOperators: boolean; + }>, + ] + >; + + /** + * Rule to disallow unused expressions. + * + * @since 0.1.0 + * @see https://eslint.org/docs/latest/rules/no-unused-expressions + */ + "no-unused-expressions": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowShortCircuit: boolean; + /** + * @default false + */ + allowTernary: boolean; + /** + * @default false + */ + allowTaggedTemplates: boolean; + /** + * @since 7.20.0 + * @default false + */ + enforceForJSX: boolean; + /** + * @default false + */ + ignoreDirectives: boolean; + }>, + ] + >; + + /** + * Rule to disallow unused labels. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.0.0-rc.0 + * @see https://eslint.org/docs/latest/rules/no-unused-labels + */ + "no-unused-labels": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unused private class members. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 8.1.0 + * @see https://eslint.org/docs/latest/rules/no-unused-private-class-members + */ + "no-unused-private-class-members": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unused variables. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-unused-vars + */ + "no-unused-vars": Linter.RuleEntry< + [ + | "all" + | "local" + | Partial<{ + /** + * @default 'all' + */ + vars: "all" | "local"; + varsIgnorePattern: string; + /** + * @default 'after-used' + */ + args: "after-used" | "all" | "none"; + /** + * @default false + */ + ignoreRestSiblings: boolean; + argsIgnorePattern: string; + /** + * @default 'all' + */ + caughtErrors: "none" | "all"; + caughtErrorsIgnorePattern: string; + destructuredArrayIgnorePattern: string; + /** + * @default false + */ + ignoreClassWithStaticInitBlock: boolean; + /** + * @default false + */ + ignoreUsingDeclarations: boolean; + /** + * @default false + */ + reportUsedIgnorePattern: boolean; + }>, + ] + >; + + /** + * Rule to disallow the use of variables before they are defined. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/no-use-before-define + */ + "no-use-before-define": Linter.RuleEntry< + [ + | Partial<{ + /** + * @default true + */ + functions: boolean; + /** + * @default true + */ + classes: boolean; + /** + * @default true + */ + variables: boolean; + /** + * @default false + */ + allowNamedExports: boolean; + /** + * @default true + */ + enums: boolean; + /** + * @default true + */ + typedefs: boolean; + /** + * @default true + */ + ignoreTypeReferences: boolean; + }> + | "nofunc", + ] + >; + + /** + * Rule to disallow variable assignments when the value is not used. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 9.0.0-alpha.1 + * @see https://eslint.org/docs/latest/rules/no-useless-assignment + */ + "no-useless-assignment": Linter.RuleEntry<[]>; + + /** + * Rule to disallow useless backreferences in regular expressions. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 7.0.0-alpha.0 + * @see https://eslint.org/docs/latest/rules/no-useless-backreference + */ + "no-useless-backreference": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary calls to `.call()` and `.apply()`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/no-useless-call + */ + "no-useless-call": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary `catch` clauses. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 5.11.0 + * @see https://eslint.org/docs/latest/rules/no-useless-catch + */ + "no-useless-catch": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary computed property keys in objects and classes. + * + * @since 2.9.0 + * @see https://eslint.org/docs/latest/rules/no-useless-computed-key + */ + "no-useless-computed-key": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + enforceForClassMembers: boolean; + }>, + ] + >; + + /** + * Rule to disallow unnecessary concatenation of literals or template literals. + * + * @since 1.3.0 + * @see https://eslint.org/docs/latest/rules/no-useless-concat + */ + "no-useless-concat": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary constructors. + * + * @since 2.0.0-beta.1 + * @see https://eslint.org/docs/latest/rules/no-useless-constructor + */ + "no-useless-constructor": Linter.RuleEntry<[]>; + + /** + * Rule to disallow unnecessary escape characters. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 2.5.0 + * @see https://eslint.org/docs/latest/rules/no-useless-escape + */ + "no-useless-escape": Linter.RuleEntry< + [ + Partial<{ + allowRegexCharacters: string[]; + }>, + ] + >; + + /** + * Rule to disallow renaming import, export, and destructured assignments to the same name. + * + * @since 2.11.0 + * @see https://eslint.org/docs/latest/rules/no-useless-rename + */ + "no-useless-rename": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreImport: boolean; + /** + * @default false + */ + ignoreExport: boolean; + /** + * @default false + */ + ignoreDestructuring: boolean; + }>, + ] + >; + + /** + * Rule to disallow redundant return statements. + * + * @since 3.9.0 + * @see https://eslint.org/docs/latest/rules/no-useless-return + */ + "no-useless-return": Linter.RuleEntry<[]>; + + /** + * Rule to require `let` or `const` instead of `var`. + * + * @since 0.12.0 + * @see https://eslint.org/docs/latest/rules/no-var + */ + "no-var": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `void` operators. + * + * @since 0.8.0 + * @see https://eslint.org/docs/latest/rules/no-void + */ + "no-void": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowAsStatement: boolean; + }>, + ] + >; + + /** + * Rule to disallow specified warning terms in comments. + * + * @since 0.4.4 + * @see https://eslint.org/docs/latest/rules/no-warning-comments + */ + "no-warning-comments": Linter.RuleEntry< + [ + Partial<{ + /** + * @default ["todo", "fixme", "xxx"] + */ + terms: string[]; + /** + * @default 'start' + */ + location: "start" | "anywhere"; + decoration: string[]; + }>, + ] + >; + + /** + * Rule to disallow whitespace before properties. + * + * @since 2.0.0-beta.1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`no-whitespace-before-property`](https://eslint.style/rules/no-whitespace-before-property) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/no-whitespace-before-property + */ + "no-whitespace-before-property": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `with` statements. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.2 + * @see https://eslint.org/docs/latest/rules/no-with + */ + "no-with": Linter.RuleEntry<[]>; + + /** + * Rule to enforce the location of single-line statements. + * + * @since 3.17.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`nonblock-statement-body-position`](https://eslint.style/rules/nonblock-statement-body-position) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/nonblock-statement-body-position + */ + "nonblock-statement-body-position": Linter.RuleEntry< + [ + "beside" | "below" | "any", + Partial<{ + overrides: Record; + }>, + ] + >; + + /** + * Rule to enforce consistent line breaks after opening and before closing braces. + * + * @since 2.12.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`object-curly-newline`](https://eslint.style/rules/object-curly-newline) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/object-curly-newline + */ + "object-curly-newline": Linter.RuleEntry< + [ + | "always" + | "never" + | Partial<{ + /** + * @default false + */ + multiline: boolean; + minProperties: number; + /** + * @default true + */ + consistent: boolean; + }> + | Partial< + Record< + | "ObjectExpression" + | "ObjectPattern" + | "ImportDeclaration" + | "ExportDeclaration", + | "always" + | "never" + | Partial<{ + /** + * @default false + */ + multiline: boolean; + minProperties: number; + /** + * @default true + */ + consistent: boolean; + }> + > + >, + ] + >; + + /** + * Rule to enforce consistent spacing inside braces. + * + * @since 0.22.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`object-curly-spacing`](https://eslint.style/rules/object-curly-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/object-curly-spacing + */ + "object-curly-spacing": + | Linter.RuleEntry< + [ + "never", + { + /** + * @default false + */ + arraysInObjects: boolean; + /** + * @default false + */ + objectsInObjects: boolean; + }, + ] + > + | Linter.RuleEntry< + [ + "always", + { + /** + * @default true + */ + arraysInObjects: boolean; + /** + * @default true + */ + objectsInObjects: boolean; + }, + ] + >; + + /** + * Rule to enforce placing object properties on separate lines. + * + * @since 2.10.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`object-property-newline`](https://eslint.style/rules/object-property-newline) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/object-property-newline + */ + "object-property-newline": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowAllPropertiesOnSameLine: boolean; + }>, + ] + >; + + /** + * Rule to require or disallow method and property shorthand syntax for object literals. + * + * @since 0.20.0 + * @see https://eslint.org/docs/latest/rules/object-shorthand + */ + "object-shorthand": + | Linter.RuleEntry< + [ + "always" | "methods", + Partial<{ + /** + * @default false + */ + avoidQuotes: boolean; + /** + * @default false + */ + ignoreConstructors: boolean; + /** + * @since 8.22.0 + */ + methodsIgnorePattern: string; + /** + * @default false + */ + avoidExplicitReturnArrows: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "properties", + Partial<{ + /** + * @default false + */ + avoidQuotes: boolean; + }>, + ] + > + | Linter.RuleEntry<["never" | "consistent" | "consistent-as-needed"]>; + + /** + * Rule to enforce variables to be declared either together or separately in functions. + * + * @since 0.0.9 + * @see https://eslint.org/docs/latest/rules/one-var + */ + "one-var": Linter.RuleEntry< + [ + | "always" + | "never" + | "consecutive" + | Partial< + { + /** + * @default false + */ + separateRequires: boolean; + } & Record< + "var" | "let" | "const" | "using" | "awaitUsing", + "always" | "never" | "consecutive" + > + > + | Partial< + Record< + "initialized" | "uninitialized", + "always" | "never" | "consecutive" + > + >, + ] + >; + + /** + * Rule to require or disallow newlines around variable declarations. + * + * @since 2.0.0-beta.3 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`one-var-declaration-per-line`](https://eslint.style/rules/one-var-declaration-per-line) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/one-var-declaration-per-line + */ + "one-var-declaration-per-line": Linter.RuleEntry< + ["initializations" | "always"] + >; + + /** + * Rule to require or disallow assignment operator shorthand where possible. + * + * @since 0.10.0 + * @see https://eslint.org/docs/latest/rules/operator-assignment + */ + "operator-assignment": Linter.RuleEntry<["always" | "never"]>; + + /** + * Rule to enforce consistent linebreak style for operators. + * + * @since 0.19.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`operator-linebreak`](https://eslint.style/rules/operator-linebreak) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/operator-linebreak + */ + "operator-linebreak": Linter.RuleEntry< + [ + "after" | "before" | "none", + Partial<{ + overrides: Record; + }>, + ] + >; + + /** + * Rule to require or disallow padding within blocks. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`padded-blocks`](https://eslint.style/rules/padded-blocks) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/padded-blocks + */ + "padded-blocks": Linter.RuleEntry< + [ + ( + | "always" + | "never" + | Partial< + Record< + "blocks" | "classes" | "switches", + "always" | "never" + > + > + ), + { + /** + * @default false + */ + allowSingleLineBlocks: boolean; + }, + ] + >; + + /** + * Rule to require or disallow padding lines between statements. + * + * @since 4.0.0-beta.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`padding-line-between-statements`](https://eslint.style/rules/padding-line-between-statements) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/padding-line-between-statements + */ + "padding-line-between-statements": Linter.RuleEntry< + [ + ...Array< + { + blankLine: "any" | "never" | "always"; + } & Record<"prev" | "next", string | string[]> + >, + ] + >; + + /** + * Rule to require using arrow functions for callbacks. + * + * @since 1.2.0 + * @see https://eslint.org/docs/latest/rules/prefer-arrow-callback + */ + "prefer-arrow-callback": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowNamedFunctions: boolean; + /** + * @default true + */ + allowUnboundThis: boolean; + }>, + ] + >; + + /** + * Rule to require `const` declarations for variables that are never reassigned after declared. + * + * @since 0.23.0 + * @see https://eslint.org/docs/latest/rules/prefer-const + */ + "prefer-const": Linter.RuleEntry< + [ + Partial<{ + /** + * @default 'any' + */ + destructuring: "any" | "all"; + /** + * @default false + */ + ignoreReadBeforeAssign: boolean; + }>, + ] + >; + + /** + * Rule to require destructuring from arrays and/or objects. + * + * @since 3.13.0 + * @see https://eslint.org/docs/latest/rules/prefer-destructuring + */ + "prefer-destructuring": Linter.RuleEntry< + [ + Partial< + | { + VariableDeclarator: Partial<{ + array: boolean; + object: boolean; + }>; + AssignmentExpression: Partial<{ + array: boolean; + object: boolean; + }>; + } + | { + array: boolean; + object: boolean; + } + >, + Partial<{ + enforceForRenamedProperties: boolean; + }>, + ] + >; + + /** + * Rule to disallow the use of `Math.pow` in favor of the `**` operator. + * + * @since 6.7.0 + * @see https://eslint.org/docs/latest/rules/prefer-exponentiation-operator + */ + "prefer-exponentiation-operator": Linter.RuleEntry<[]>; + + /** + * Rule to enforce using named capture group in regular expression. + * + * @since 5.15.0 + * @see https://eslint.org/docs/latest/rules/prefer-named-capture-group + */ + "prefer-named-capture-group": Linter.RuleEntry<[]>; + + /** + * Rule to disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals. + * + * @since 3.5.0 + * @see https://eslint.org/docs/latest/rules/prefer-numeric-literals + */ + "prefer-numeric-literals": Linter.RuleEntry<[]>; + + /** + * Rule to disallow use of `Object.prototype.hasOwnProperty.call()` and prefer use of `Object.hasOwn()`. + * + * @since 8.5.0 + * @see https://eslint.org/docs/latest/rules/prefer-object-has-own + */ + "prefer-object-has-own": Linter.RuleEntry<[]>; + + /** + * Rule to disallow using `Object.assign` with an object literal as the first argument and prefer the use of object spread instead. + * + * @since 5.0.0-alpha.3 + * @see https://eslint.org/docs/latest/rules/prefer-object-spread + */ + "prefer-object-spread": Linter.RuleEntry<[]>; + + /** + * Rule to require using Error objects as Promise rejection reasons. + * + * @since 3.14.0 + * @see https://eslint.org/docs/latest/rules/prefer-promise-reject-errors + */ + "prefer-promise-reject-errors": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + allowEmptyReject: boolean; + }>, + ] + >; + + /** + * Rule to require `Reflect` methods where applicable. + * + * @since 1.0.0-rc-2 + * @deprecated since 3.9.0. + * The original intention of this rule was misguided. + * @see https://eslint.org/docs/latest/rules/prefer-reflect + */ + "prefer-reflect": Linter.RuleEntry< + [ + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to disallow use of the `RegExp` constructor in favor of regular expression literals. + * + * @since 6.4.0 + * @see https://eslint.org/docs/latest/rules/prefer-regex-literals + */ + "prefer-regex-literals": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + disallowRedundantWrapping: boolean; + }>, + ] + >; + + /** + * Rule to require rest parameters instead of `arguments`. + * + * @since 2.0.0-alpha-1 + * @see https://eslint.org/docs/latest/rules/prefer-rest-params + */ + "prefer-rest-params": Linter.RuleEntry<[]>; + + /** + * Rule to require spread operators instead of `.apply()`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/prefer-spread + */ + "prefer-spread": Linter.RuleEntry<[]>; + + /** + * Rule to require template literals instead of string concatenation. + * + * @since 1.2.0 + * @see https://eslint.org/docs/latest/rules/prefer-template + */ + "prefer-template": Linter.RuleEntry<[]>; + + /** + * Rule to disallow losing originally caught error when re-throwing custom errors. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 9.35.0 + * @see https://eslint.org/docs/latest/rules/preserve-caught-error + */ + "preserve-caught-error": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + requireCatchParameter: boolean; + }>, + ] + >; + + /** + * Rule to require quotes around object literal property names. + * + * @since 0.0.6 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`quote-props`](https://eslint.style/rules/quote-props) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/quote-props + */ + "quote-props": + | Linter.RuleEntry<["always" | "consistent"]> + | Linter.RuleEntry< + [ + "as-needed", + Partial<{ + /** + * @default false + */ + keywords: boolean; + /** + * @default true + */ + unnecessary: boolean; + /** + * @default false + */ + numbers: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "consistent-as-needed", + Partial<{ + /** + * @default false + */ + keywords: boolean; + }>, + ] + >; + + /** + * Rule to enforce the consistent use of either backticks, double, or single quotes. + * + * @since 0.0.7 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`quotes`](https://eslint.style/rules/quotes) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/quotes + */ + quotes: Linter.RuleEntry< + [ + "double" | "single" | "backtick", + Partial<{ + /** + * @default false + */ + avoidEscape: boolean; + /** + * @default false + */ + allowTemplateLiterals: boolean; + }>, + ] + >; + + /** + * Rule to enforce the use of the radix argument when using `parseInt()`. + * + * @since 0.0.7 + * @see https://eslint.org/docs/latest/rules/radix + */ + radix: Linter.RuleEntry<["always" | "as-needed"]>; + + /** + * Rule to disallow assignments that can lead to race conditions due to usage of `await` or `yield`. + * + * @since 5.3.0 + * @see https://eslint.org/docs/latest/rules/require-atomic-updates + */ + "require-atomic-updates": Linter.RuleEntry< + [ + Partial<{ + /** + * @since 8.3.0 + * @default false + */ + allowProperties: boolean; + }>, + ] + >; + + /** + * Rule to disallow async functions which have no `await` expression. + * + * @since 3.11.0 + * @see https://eslint.org/docs/latest/rules/require-await + */ + "require-await": Linter.RuleEntry<[]>; + + /** + * Rule to enforce the use of `u` or `v` flag on regular expressions. + * + * @since 5.3.0 + * @see https://eslint.org/docs/latest/rules/require-unicode-regexp + */ + "require-unicode-regexp": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + requireFlag: "u" | "v"; + }>, + ] + >; + + /** + * Rule to require generator functions to contain `yield`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 1.0.0-rc-1 + * @see https://eslint.org/docs/latest/rules/require-yield + */ + "require-yield": Linter.RuleEntry<[]>; + + /** + * Rule to enforce spacing between rest and spread operators and their expressions. + * + * @since 2.12.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`rest-spread-spacing`](https://eslint.style/rules/rest-spread-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/rest-spread-spacing + */ + "rest-spread-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require or disallow semicolons instead of ASI. + * + * @since 0.0.6 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`semi`](https://eslint.style/rules/semi) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/semi + */ + semi: + | Linter.RuleEntry< + [ + "always", + Partial<{ + /** + * @default false + */ + omitLastInOneLineBlock: boolean; + }>, + ] + > + | Linter.RuleEntry< + [ + "never", + Partial<{ + /** + * @default 'any' + */ + beforeStatementContinuationChars: + | "any" + | "always" + | "never"; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before and after semicolons. + * + * @since 0.16.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`semi-spacing`](https://eslint.style/rules/semi-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/semi-spacing + */ + "semi-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + before: boolean; + /** + * @default true + */ + after: boolean; + }>, + ] + >; + + /** + * Rule to enforce location of semicolons. + * + * @since 4.0.0-beta.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`semi-style`](https://eslint.style/rules/semi-style) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/semi-style + */ + "semi-style": Linter.RuleEntry<["last" | "first"]>; + + /** + * Rule to enforce sorted `import` declarations within modules. + * + * @since 2.0.0-beta.1 + * @see https://eslint.org/docs/latest/rules/sort-imports + */ + "sort-imports": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreCase: boolean; + /** + * @default false + */ + ignoreDeclarationSort: boolean; + /** + * @default false + */ + ignoreMemberSort: boolean; + /** + * @default ['none', 'all', 'multiple', 'single'] + */ + memberSyntaxSortOrder: Array< + "none" | "all" | "multiple" | "single" + >; + /** + * @default false + */ + allowSeparatedGroups: boolean; + }>, + ] + >; + + /** + * Rule to require object keys to be sorted. + * + * @since 3.3.0 + * @see https://eslint.org/docs/latest/rules/sort-keys + */ + "sort-keys": Linter.RuleEntry< + [ + "asc" | "desc", + Partial<{ + /** + * @default true + */ + caseSensitive: boolean; + /** + * @default 2 + */ + minKeys: number; + /** + * @default false + */ + natural: boolean; + /** + * @default false + */ + allowLineSeparatedGroups: boolean; + /** + * @default false + */ + ignoreComputedKeys: boolean; + }>, + ] + >; + + /** + * Rule to require variables within the same declaration block to be sorted. + * + * @since 0.2.0 + * @see https://eslint.org/docs/latest/rules/sort-vars + */ + "sort-vars": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + ignoreCase: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before blocks. + * + * @since 0.9.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`space-before-blocks`](https://eslint.style/rules/space-before-blocks) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/space-before-blocks + */ + "space-before-blocks": Linter.RuleEntry< + [ + | "always" + | "never" + | Partial< + Record< + "functions" | "keywords" | "classes", + "always" | "never" | "off" + > + >, + ] + >; + + /** + * Rule to enforce consistent spacing before `function` definition opening parenthesis. + * + * @since 0.18.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`space-before-function-paren`](https://eslint.style/rules/space-before-function-paren) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/space-before-function-paren + */ + "space-before-function-paren": Linter.RuleEntry< + [ + | "always" + | "never" + | Partial< + Record< + "anonymous" | "named" | "asyncArrow", + "always" | "never" | "ignore" + > + >, + ] + >; + + /** + * Rule to enforce consistent spacing inside parentheses. + * + * @since 0.8.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`space-in-parens`](https://eslint.style/rules/space-in-parens) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/space-in-parens + */ + "space-in-parens": Linter.RuleEntry< + [ + "never" | "always", + Partial<{ + exceptions: string[]; + }>, + ] + >; + + /** + * Rule to require spacing around infix operators. + * + * @since 0.2.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`space-infix-ops`](https://eslint.style/rules/space-infix-ops) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/space-infix-ops + */ + "space-infix-ops": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + int32Hint: boolean; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing before or after unary operators. + * + * @since 0.10.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`space-unary-ops`](https://eslint.style/rules/space-unary-ops) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/space-unary-ops + */ + "space-unary-ops": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + words: boolean; + /** + * @default false + */ + nonwords: boolean; + overrides: Record; + }>, + ] + >; + + /** + * Rule to enforce consistent spacing after the `//` or `/*` in a comment. + * + * @since 0.23.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`spaced-comment`](https://eslint.style/rules/spaced-comment) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/spaced-comment + */ + "spaced-comment": Linter.RuleEntry< + [ + "always" | "never", + { + exceptions: string[]; + markers: string[]; + line: { + exceptions: string[]; + markers: string[]; + }; + block: { + exceptions: string[]; + markers: string[]; + /** + * @default false + */ + balanced: boolean; + }; + }, + ] + >; + + /** + * Rule to require or disallow strict mode directives. + * + * @since 0.1.0 + * @see https://eslint.org/docs/latest/rules/strict + */ + strict: Linter.RuleEntry<["safe" | "global" | "function" | "never"]>; + + /** + * Rule to enforce spacing around colons of switch statements. + * + * @since 4.0.0-beta.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`switch-colon-spacing`](https://eslint.style/rules/switch-colon-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/switch-colon-spacing + */ + "switch-colon-spacing": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + before: boolean; + /** + * @default true + */ + after: boolean; + }>, + ] + >; + + /** + * Rule to require symbol descriptions. + * + * @since 3.4.0 + * @see https://eslint.org/docs/latest/rules/symbol-description + */ + "symbol-description": Linter.RuleEntry<[]>; + + /** + * Rule to require or disallow spacing around embedded expressions of template strings. + * + * @since 2.0.0-rc.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`template-curly-spacing`](https://eslint.style/rules/template-curly-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/template-curly-spacing + */ + "template-curly-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require or disallow spacing between template tags and their literals. + * + * @since 3.15.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`template-tag-spacing`](https://eslint.style/rules/template-tag-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/template-tag-spacing + */ + "template-tag-spacing": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require or disallow Unicode byte order mark (BOM). + * + * @since 2.11.0 + * @see https://eslint.org/docs/latest/rules/unicode-bom + */ + "unicode-bom": Linter.RuleEntry<["never" | "always"]>; + + /** + * Rule to require calls to `isNaN()` when checking for `NaN`. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.0.6 + * @see https://eslint.org/docs/latest/rules/use-isnan + */ + "use-isnan": Linter.RuleEntry< + [ + Partial<{ + /** + * @default true + */ + enforceForSwitchCase: boolean; + /** + * @default false + */ + enforceForIndexOf: boolean; + }>, + ] + >; + + /** + * Rule to enforce comparing `typeof` expressions against valid strings. + * + * @remarks + * Recommended by ESLint, the rule was enabled in `eslint:recommended`. + * + * @since 0.5.0 + * @see https://eslint.org/docs/latest/rules/valid-typeof + */ + "valid-typeof": Linter.RuleEntry< + [ + Partial<{ + /** + * @default false + */ + requireStringLiterals: boolean; + }>, + ] + >; + + /** + * Rule to require `var` declarations be placed at the top of their containing scope. + * + * @since 0.8.0 + * @see https://eslint.org/docs/latest/rules/vars-on-top + */ + "vars-on-top": Linter.RuleEntry<[]>; + + /** + * Rule to require parentheses around immediate `function` invocations. + * + * @since 0.0.9 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`wrap-iife`](https://eslint.style/rules/wrap-iife) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/wrap-iife + */ + "wrap-iife": Linter.RuleEntry< + [ + "outside" | "inside" | "any", + Partial<{ + /** + * @default false + */ + functionPrototypeMethods: boolean; + }>, + ] + >; + + /** + * Rule to require parenthesis around regex literals. + * + * @since 0.1.0 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`wrap-regex`](https://eslint.style/rules/wrap-regex) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/wrap-regex + */ + "wrap-regex": Linter.RuleEntry<[]>; + + /** + * Rule to require or disallow spacing around the `*` in `yield*` expressions. + * + * @since 2.0.0-alpha-1 + * @deprecated since 8.53.0. + * Formatting rules are being moved out of ESLint core. + * Please, use [`yield-star-spacing`](https://eslint.style/rules/yield-star-spacing) in [`@stylistic/eslint-plugin`](https://eslint.style). + * @see https://eslint.org/docs/latest/rules/yield-star-spacing + */ + "yield-star-spacing": Linter.RuleEntry< + [ + | Partial<{ + before: boolean; + after: boolean; + }> + | "before" + | "after" + | "both" + | "neither", + ] + >; + + /** + * Rule to require or disallow "Yoda" conditions. + * + * @since 0.7.1 + * @see https://eslint.org/docs/latest/rules/yoda + */ + yoda: + | Linter.RuleEntry< + [ + "never", + Partial<{ + exceptRange: boolean; + onlyEquality: boolean; + }>, + ] + > + | Linter.RuleEntry<["always"]>; +} diff --git a/node_modules/eslint/lib/types/universal.d.ts b/node_modules/eslint/lib/types/universal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..df4fdecda75df4a8ce63bd47c0e570d01339a649 --- /dev/null +++ b/node_modules/eslint/lib/types/universal.d.ts @@ -0,0 +1,6 @@ +/** + * @fileoverview typings for "eslint/universal" module + * @author 唯然 + */ + +export { Linter } from "./index"; diff --git a/node_modules/eslint/lib/types/use-at-your-own-risk.d.ts b/node_modules/eslint/lib/types/use-at-your-own-risk.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b8a0b678d55b1a38d2bcc063d7cf62a69c927cd --- /dev/null +++ b/node_modules/eslint/lib/types/use-at-your-own-risk.d.ts @@ -0,0 +1,34 @@ +/** + * @fileoverview This file contains the types for the use-at-your-own-risk + * entrypoint. It was initially extracted from the `@types/eslint` package. + */ + +/* + * MIT License + * Copyright (c) Microsoft Corporation. + * + * 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 + */ + +import { Rule } from "./index.js"; + +/** @deprecated */ +export const builtinRules: Map; + +/** @deprecated */ +export function shouldUseFlatConfig(): Promise; diff --git a/node_modules/eslint/lib/universal.js b/node_modules/eslint/lib/universal.js new file mode 100644 index 0000000000000000000000000000000000000000..51bac58453c98b3b65b93fc3498317afe1ace747 --- /dev/null +++ b/node_modules/eslint/lib/universal.js @@ -0,0 +1,10 @@ +/** + * @fileoverview exports for browsers + * @author 唯然 + */ + +"use strict"; + +const { Linter } = require("./linter/linter"); + +module.exports = { Linter }; diff --git a/node_modules/eslint/lib/unsupported-api.js b/node_modules/eslint/lib/unsupported-api.js new file mode 100644 index 0000000000000000000000000000000000000000..d46b4028013b69298450a163a3d9b0d04228c640 --- /dev/null +++ b/node_modules/eslint/lib/unsupported-api.js @@ -0,0 +1,21 @@ +/** + * @fileoverview APIs that are not officially supported by ESLint. + * These APIs may change or be removed at any time. Use at your + * own risk. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { shouldUseFlatConfig } = require("./eslint/eslint"); +const builtinRules = require("./rules"); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { builtinRules, shouldUseFlatConfig }; diff --git a/node_modules/eslint/messages/all-matched-files-ignored.js b/node_modules/eslint/messages/all-matched-files-ignored.js new file mode 100644 index 0000000000000000000000000000000000000000..9ae894e4462d8bd8a2406bf9eadfb9c8f5fd98da --- /dev/null +++ b/node_modules/eslint/messages/all-matched-files-ignored.js @@ -0,0 +1,21 @@ +"use strict"; + +module.exports = function (it) { + const { pattern } = it; + + return ` +You are linting "${pattern}", but all of the files matching the glob pattern "${pattern}" are ignored. + +If you don't want to lint these files, remove the pattern "${pattern}" from the list of arguments passed to ESLint. + +If you do want to lint these files, explicitly list one or more of the files from this glob that you'd like to lint to see more details about why they are ignored. + + * If the file is ignored because of a matching ignore pattern, check global ignores in your config file. + https://eslint.org/docs/latest/use/configure/ignore + + * If the file is ignored because no matching configuration was supplied, check file patterns in your config file. + https://eslint.org/docs/latest/use/configure/configuration-files#specify-files-with-arbitrary-extensions + + * If the file is ignored because it is located outside of the base path, change the location of your config file to be in a parent directory. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/config-file-missing.js b/node_modules/eslint/messages/config-file-missing.js new file mode 100644 index 0000000000000000000000000000000000000000..c4f8ecdbf1629e41affff3b3e3ee0ce29f771467 --- /dev/null +++ b/node_modules/eslint/messages/config-file-missing.js @@ -0,0 +1,16 @@ +"use strict"; + +module.exports = function () { + return ` +ESLint couldn't find an eslint.config.(js|mjs|cjs) file. + +From ESLint v9.0.0, the default configuration file is now eslint.config.js. +If you are using a .eslintrc.* file, please follow the migration guide +to update your configuration file to the new format: + +https://eslint.org/docs/latest/use/configure/migration-guide + +If you still have problems after following the migration guide, please stop by +https://eslint.org/chat/help to chat with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/config-plugin-missing.js b/node_modules/eslint/messages/config-plugin-missing.js new file mode 100644 index 0000000000000000000000000000000000000000..207367491ba3b9a403311d31e7af7d7cd7278439 --- /dev/null +++ b/node_modules/eslint/messages/config-plugin-missing.js @@ -0,0 +1,14 @@ +"use strict"; + +module.exports = function (it) { + const { pluginName, ruleId } = it; + + return ` +A configuration object specifies rule "${ruleId}", but could not find plugin "${pluginName}". + +Common causes of this problem include: + +1. The "${pluginName}" plugin is not defined in your configuration file. +2. The "${pluginName}" plugin is not defined within the same configuration object in which the "${ruleId}" rule is applied. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/config-serialize-function.js b/node_modules/eslint/messages/config-serialize-function.js new file mode 100644 index 0000000000000000000000000000000000000000..4300e47e452ac9a8f22ffb80fe45f5ffbcb011db --- /dev/null +++ b/node_modules/eslint/messages/config-serialize-function.js @@ -0,0 +1,30 @@ +"use strict"; + +module.exports = function ({ key, objectKey }) { + // special case for parsers + const isParser = + objectKey === "parser" && (key === "parse" || key === "parseForESLint"); + const parserMessage = ` + This typically happens when you're using a custom parser that does not +provide a "meta" property, which is how ESLint determines the serialized +representation. Please open an issue with the maintainer of the custom parser +and share this link: + +https://eslint.org/docs/latest/extend/custom-parsers#meta-data-in-custom-parsers +`.trim(); + + return ` +The requested operation requires ESLint to serialize configuration data, +but the configuration key "${objectKey}.${key}" contains a function value, +which cannot be serialized. + +${ + isParser + ? parserMessage + : "Please double-check your configuration for errors." +} + +If you still have problems, please stop by https://eslint.org/chat/help to chat +with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/eslintrc-incompat.js b/node_modules/eslint/messages/eslintrc-incompat.js new file mode 100644 index 0000000000000000000000000000000000000000..b6189ac187e7026c5fc12c4c326d25efa3bb62b7 --- /dev/null +++ b/node_modules/eslint/messages/eslintrc-incompat.js @@ -0,0 +1,117 @@ +"use strict"; + +/* eslint consistent-return: 0 -- no default case */ + +const messages = { + env: ` +A config object is using the "env" key, which is not supported in flat config system. + +Flat config uses "languageOptions.globals" to define global variables for your files. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#configure-language-options + +If you're not using "env" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config +`, + + extends: ` +A config object is using the "extends" key, which is not supported in flat config system. + +Instead of "extends", you can include config objects that you'd like to extend from directly in the flat config array. + +If you're using "extends" in your config file, please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#predefined-and-shareable-configs + +If you're not using "extends" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config +`, + + globals: ` +A config object is using the "globals" key, which is not supported in flat config system. + +Flat config uses "languageOptions.globals" to define global variables for your files. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#configure-language-options + +If you're not using "globals" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config +`, + + ignorePatterns: ` +A config object is using the "ignorePatterns" key, which is not supported in flat config system. + +Flat config uses "ignores" to specify files to ignore. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#ignore-files + +If you're not using "ignorePatterns" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config +`, + + noInlineConfig: ` +A config object is using the "noInlineConfig" key, which is not supported in flat config system. + +Flat config uses "linterOptions.noInlineConfig" to specify files to ignore. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#linter-options +`, + + overrides: ` +A config object is using the "overrides" key, which is not supported in flat config system. + +Flat config is an array that acts like the eslintrc "overrides" array. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#glob-based-configs + +If you're not using "overrides" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config +`, + + parser: ` +A config object is using the "parser" key, which is not supported in flat config system. + +Flat config uses "languageOptions.parser" to override the default parser. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#custom-parsers + +If you're not using "parser" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config +`, + + parserOptions: ` +A config object is using the "parserOptions" key, which is not supported in flat config system. + +Flat config uses "languageOptions.parserOptions" to specify parser options. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#configure-language-options + +If you're not using "parserOptions" directly (it may be coming from a plugin), please see the following: +https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config +`, + + reportUnusedDisableDirectives: ` +A config object is using the "reportUnusedDisableDirectives" key, which is not supported in flat config system. + +Flat config uses "linterOptions.reportUnusedDisableDirectives" to specify files to ignore. + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#linter-options +`, + + root: ` +A config object is using the "root" key, which is not supported in flat config system. + +Flat configs always act as if they are the root config file, so this key can be safely removed. +`, +}; + +module.exports = function ({ key }) { + return messages[key].trim(); +}; diff --git a/node_modules/eslint/messages/eslintrc-plugins.js b/node_modules/eslint/messages/eslintrc-plugins.js new file mode 100644 index 0000000000000000000000000000000000000000..c5ae55c78353eda4f4280049325a444d1a771d0e --- /dev/null +++ b/node_modules/eslint/messages/eslintrc-plugins.js @@ -0,0 +1,27 @@ +"use strict"; + +module.exports = function ({ plugins }) { + const isArrayOfStrings = typeof plugins[0] === "string"; + + return ` +A config object has a "plugins" key defined as an array${isArrayOfStrings ? " of strings" : ""}. It looks something like this: + + { + "plugins": ${JSON.stringify(plugins)} + } + +Flat config requires "plugins" to be an object, like this: + + { + plugins: { + ${isArrayOfStrings && plugins[0] ? plugins[0] : "namespace"}: pluginObject + } + } + +Please see the following page for information on how to convert your config object into the correct format: +https://eslint.org/docs/latest/use/configure/migration-guide#import-plugins-and-custom-parsers + +If you're using a shareable config that you cannot rewrite in flat config format, then use the compatibility utility: +https://eslint.org/docs/latest/use/configure/migration-guide#use-eslintrc-configs-in-flat-config +`; +}; diff --git a/node_modules/eslint/messages/extend-config-missing.js b/node_modules/eslint/messages/extend-config-missing.js new file mode 100644 index 0000000000000000000000000000000000000000..32e41e960c8c2eccf645d0811b677db3f8b5693a --- /dev/null +++ b/node_modules/eslint/messages/extend-config-missing.js @@ -0,0 +1,13 @@ +"use strict"; + +module.exports = function (it) { + const { configName, importerName } = it; + + return ` +ESLint couldn't find the config "${configName}" to extend from. Please check that the name of the config is correct. + +The config "${configName}" was referenced from the config file in "${importerName}". + +If you still have problems, please stop by https://eslint.org/chat/help to chat with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/failed-to-read-json.js b/node_modules/eslint/messages/failed-to-read-json.js new file mode 100644 index 0000000000000000000000000000000000000000..3244e842876711b616e65c746238ca9bc3506e23 --- /dev/null +++ b/node_modules/eslint/messages/failed-to-read-json.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports = function (it) { + const { path, message } = it; + + return ` +Failed to read JSON file at ${path}: + +${message} +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/file-not-found.js b/node_modules/eslint/messages/file-not-found.js new file mode 100644 index 0000000000000000000000000000000000000000..50e483bc1a3f35dc67d508bfd75746d3aae06a5e --- /dev/null +++ b/node_modules/eslint/messages/file-not-found.js @@ -0,0 +1,10 @@ +"use strict"; + +module.exports = function (it) { + const { pattern, globDisabled } = it; + + return ` +No files matching the pattern "${pattern}"${globDisabled ? " (with disabling globs)" : ""} were found. +Please check for typing mistakes in the pattern. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/invalid-rule-options.js b/node_modules/eslint/messages/invalid-rule-options.js new file mode 100644 index 0000000000000000000000000000000000000000..506d4c42ac8f014ea4a613ed3a3f089f352726b7 --- /dev/null +++ b/node_modules/eslint/messages/invalid-rule-options.js @@ -0,0 +1,17 @@ +"use strict"; + +const { stringifyValueForError } = require("./shared"); + +module.exports = function ({ ruleId, value }) { + return ` +Configuration for rule "${ruleId}" is invalid. Each rule must have a severity ("off", 0, "warn", 1, "error", or 2) and may be followed by additional options for the rule. + +You passed '${stringifyValueForError(value, 4)}', which doesn't contain a valid severity. + +If you're attempting to configure rule options, perhaps you meant: + + "${ruleId}": ["error", ${stringifyValueForError(value, 8)}] + +See https://eslint.org/docs/latest/use/configure/rules#use-configuration-files for configuring rules. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/invalid-rule-severity.js b/node_modules/eslint/messages/invalid-rule-severity.js new file mode 100644 index 0000000000000000000000000000000000000000..45b28f5793fb2371548bb4c5ffba560cd796f2a1 --- /dev/null +++ b/node_modules/eslint/messages/invalid-rule-severity.js @@ -0,0 +1,13 @@ +"use strict"; + +const { stringifyValueForError } = require("./shared"); + +module.exports = function ({ ruleId, value }) { + return ` +Configuration for rule "${ruleId}" is invalid. Expected severity of "off", 0, "warn", 1, "error", or 2. + +You passed '${stringifyValueForError(value, 4)}'. + +See https://eslint.org/docs/latest/use/configure/rules#use-configuration-files for configuring rules. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/no-config-found.js b/node_modules/eslint/messages/no-config-found.js new file mode 100644 index 0000000000000000000000000000000000000000..4421206dfa486e7eb134629219f0fc38af26335b --- /dev/null +++ b/node_modules/eslint/messages/no-config-found.js @@ -0,0 +1,15 @@ +"use strict"; + +module.exports = function (it) { + const { directoryPath } = it; + + return ` +ESLint couldn't find a configuration file. To set up a configuration file for this project, please run: + + npm init @eslint/config@latest + +ESLint looked for configuration files in ${directoryPath} and its ancestors. If it found none, it then looked in your home directory. + +If you think you already have a configuration file or if you need more help, please stop by the ESLint Discord server: https://eslint.org/chat +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/plugin-conflict.js b/node_modules/eslint/messages/plugin-conflict.js new file mode 100644 index 0000000000000000000000000000000000000000..d90df0cae7683bdb5415ec80d34b9f8a6a834157 --- /dev/null +++ b/node_modules/eslint/messages/plugin-conflict.js @@ -0,0 +1,22 @@ +"use strict"; + +module.exports = function (it) { + const { pluginId, plugins } = it; + + let result = `ESLint couldn't determine the plugin "${pluginId}" uniquely. +`; + + for (const { filePath, importerName } of plugins) { + result += ` +- ${filePath} (loaded in "${importerName}")`; + } + + result += ` + +Please remove the "plugins" setting from either config or remove either plugin installation. + +If you still can't figure out the problem, please see https://eslint.org/docs/latest/use/troubleshooting. +`; + + return result; +}; diff --git a/node_modules/eslint/messages/plugin-invalid.js b/node_modules/eslint/messages/plugin-invalid.js new file mode 100644 index 0000000000000000000000000000000000000000..fc9ff6ab5187cc92b761f25ad49792e49797e2e1 --- /dev/null +++ b/node_modules/eslint/messages/plugin-invalid.js @@ -0,0 +1,16 @@ +"use strict"; + +module.exports = function (it) { + const { configName, importerName } = it; + + return ` +"${configName}" is invalid syntax for a config specifier. + +* If your intention is to extend from a configuration exported from the plugin, add the configuration name after a slash: e.g. "${configName}/myConfig". +* If this is the name of a shareable config instead of a plugin, remove the "plugin:" prefix: i.e. "${configName.slice("plugin:".length)}". + +"${configName}" was referenced from the config file in "${importerName}". + +If you still can't figure out the problem, please see https://eslint.org/docs/latest/use/troubleshooting. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/plugin-missing.js b/node_modules/eslint/messages/plugin-missing.js new file mode 100644 index 0000000000000000000000000000000000000000..6152a6a4472177efb4a2a7357d708153214c0066 --- /dev/null +++ b/node_modules/eslint/messages/plugin-missing.js @@ -0,0 +1,19 @@ +"use strict"; + +module.exports = function (it) { + const { pluginName, resolvePluginsRelativeTo, importerName } = it; + + return ` +ESLint couldn't find the plugin "${pluginName}". + +(The package "${pluginName}" was not found when loaded as a Node module from the directory "${resolvePluginsRelativeTo}".) + +It's likely that the plugin isn't installed correctly. Try reinstalling by running the following: + + npm install ${pluginName}@latest --save-dev + +The plugin "${pluginName}" was referenced from the config file in "${importerName}". + +If you still can't figure out the problem, please see https://eslint.org/docs/latest/use/troubleshooting. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/rule-unsupported-language.js b/node_modules/eslint/messages/rule-unsupported-language.js new file mode 100644 index 0000000000000000000000000000000000000000..19e8dbd20a33e66710803c6af95b22f909a44de6 --- /dev/null +++ b/node_modules/eslint/messages/rule-unsupported-language.js @@ -0,0 +1,18 @@ +"use strict"; + +module.exports = function ({ ruleIds, language }) { + return ` +The following rules do not support the language "${language}": +${ruleIds.map(id => `\t- "${id}"`).join("\n")} + +To fix this error, either: +- Remove the rule from your configuration, or set its severity to "off". +- Use the "files" option to apply the rule only to files of the supported language, for example: + { + files: ["**/*.js"], + rules: { "${ruleIds[0]}": "error" } + } + +See https://eslint.org/docs/latest/use/configure/rules for more information. +`.trimStart(); +}; diff --git a/node_modules/eslint/messages/shared.js b/node_modules/eslint/messages/shared.js new file mode 100644 index 0000000000000000000000000000000000000000..4244ed6800263416b1fcfdacefdabe3834a3b2e8 --- /dev/null +++ b/node_modules/eslint/messages/shared.js @@ -0,0 +1,23 @@ +/** + * @fileoverview Shared utilities for error messages. + * @author Josh Goldberg + */ + +"use strict"; + +/** + * Converts a value to a string that may be printed in errors. + * @param {any} value The invalid value. + * @param {number} indentation How many spaces to indent + * @returns {string} The value, stringified. + */ +function stringifyValueForError(value, indentation) { + return value + ? JSON.stringify(value, null, 4).replace( + /\n/gu, + `\n${" ".repeat(indentation)}`, + ) + : `${value}`; +} + +module.exports = { stringifyValueForError }; diff --git a/node_modules/eslint/messages/whitespace-found.js b/node_modules/eslint/messages/whitespace-found.js new file mode 100644 index 0000000000000000000000000000000000000000..c61602165ed40d66708e5cc635e3ce69b236e856 --- /dev/null +++ b/node_modules/eslint/messages/whitespace-found.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports = function (it) { + const { pluginName } = it; + + return ` +ESLint couldn't find the plugin "${pluginName}". because there is whitespace in the name. Please check your configuration and remove all whitespace from the plugin name. + +If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. +`.trimStart(); +}; diff --git a/node_modules/eslint/package.json b/node_modules/eslint/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dc9e2260b13cb8273a27cde9dc69fcf16dbd80f2 --- /dev/null +++ b/node_modules/eslint/package.json @@ -0,0 +1,239 @@ +{ + "name": "eslint", + "version": "10.5.0", + "author": "Nicholas C. Zakas ", + "description": "An AST-based pattern checker for JavaScript.", + "type": "commonjs", + "bin": { + "eslint": "./bin/eslint.js" + }, + "main": "./lib/api.js", + "types": "./lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/api.js" + }, + "./config": { + "types": "./lib/types/config-api.d.ts", + "default": "./lib/config-api.js" + }, + "./package.json": "./package.json", + "./use-at-your-own-risk": { + "types": "./lib/types/use-at-your-own-risk.d.ts", + "default": "./lib/unsupported-api.js" + }, + "./rules": { + "types": "./lib/types/rules.d.ts" + }, + "./universal": { + "types": "./lib/types/universal.d.ts", + "default": "./lib/universal.js" + } + }, + "typesVersions": { + "*": { + "use-at-your-own-risk": [ + "./lib/types/use-at-your-own-risk.d.ts" + ], + "rules": [ + "./lib/types/rules.d.ts" + ], + "universal": [ + "./lib/types/universal.d.ts" + ], + "config": [ + "./lib/types/config-api.d.ts" + ] + } + }, + "scripts": { + "build:docs:update-links": "node tools/fetch-docs-links.js", + "build:site": "node Makefile.js gensite", + "build:webpack": "node Makefile.js webpack", + "build:readme": "node tools/update-readme.js", + "build:rules-index": "node Makefile.js generateRuleIndexPage", + "fmt": "prettier --write .", + "fmt:check": "prettier --check .", + "lint": "node Makefile.js lint", + "lint:docs:js": "node Makefile.js lintDocsJS", + "lint:docs:rule-examples": "node Makefile.js checkRuleExamples", + "lint:unused": "knip", + "lint:fix": "node Makefile.js lint -- fix", + "lint:fix:docs:js": "node Makefile.js lintDocsJS -- fix", + "lint:rule-types": "node tools/update-rule-type-headers.js --check", + "lint:types": "attw --pack", + "release:generate:alpha": "node Makefile.js generatePrerelease -- alpha", + "release:generate:beta": "node Makefile.js generatePrerelease -- beta", + "release:generate:latest": "node Makefile.js generateRelease -- latest", + "release:generate:maintenance": "node Makefile.js generateRelease -- maintenance", + "release:generate:rc": "node Makefile.js generatePrerelease -- rc", + "release:publish": "node Makefile.js publishRelease", + "test": "node Makefile.js test", + "test:browser": "node Makefile.js cypress", + "test:cli": "mocha", + "test:ecosystem": "node tools/test-ecosystem/index.mjs", + "test:ecosystem:update": "node tools/test-ecosystem/update.mjs", + "test:emfile": "node tools/check-emfile-handling.js", + "test:fuzz": "node Makefile.js fuzz", + "test:performance": "node Makefile.js perf", + "test:pnpm": "cd tests/pnpm && node check.js && pnpm install && pnpm exec tsc", + "test:types": "tsc -p tests/lib/types/tsconfig.json && npm run test:types --workspaces --if-present", + "test:types:5.3": "npx -p typescript@5.3 -y -- tsc -p tsconfig.types-legacy.json", + "test:types:5.x": "npx -p typescript@5.x -y -- tsc -p tsconfig.types.json", + "test:types:7.x": "npx -p @typescript/native-preview@latest -y -- tsgo -p tsconfig.types.json", + "test:types:all": "npm run test:types && npm run test:types:5.3 && npm run test:types:5.x && npm run test:types:7.x" + }, + "workspaces": [ + "packages/*" + ], + "gitHooks": { + "pre-commit": "lint-staged" + }, + "lint-staged": { + "*.{js,json,jsonc,json5,yml,yaml}": [ + "eslint --fix", + "prettier --write" + ], + "docs/src/**/*.md": [ + "markdownlint-cli2 --fix", + "prettier --write" + ], + "!({{*.,**/*.}{js,json,jsonc,json5,yml,yaml},docs/src/**/*.md})": "prettier --write --ignore-unknown", + "lib/rules/*.js": [ + "node tools/update-eslint-all.js", + "node tools/update-eslint-recommended.js", + "node tools/update-rule-type-headers.js", + "git add packages/js/src/configs/*.js lib/types/rules.d.ts" + ], + "docs/src/rules/*.md": [ + "node tools/check-rule-examples.js", + "node tools/fetch-docs-links.js", + "git add docs/src/_data/further_reading_links.json" + ], + "docs/**/*.svg": "npx -y svgo -r --multipass" + }, + "files": [ + "LICENSE", + "README.md", + "bin", + "conf", + "lib", + "messages" + ], + "repository": "eslint/eslint", + "funding": "https://eslint.org/donate", + "homepage": "https://eslint.org", + "bugs": "https://github.com/eslint/eslint/issues/", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.2", + "@eslint/config-array": "^0.23.5", + "@eslint/config-helpers": "^0.6.0", + "@eslint/core": "^1.2.1", + "@eslint/plugin-kit": "^0.7.2", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^9.1.2", + "eslint-visitor-keys": "^5.0.1", + "espree": "^11.2.0", + "esquery": "^1.7.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "minimatch": "^10.2.4", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.18.3", + "@babel/core": "^7.4.3", + "@babel/preset-env": "^7.4.3", + "@cypress/webpack-preprocessor": "^6.0.2", + "@eslint/eslintrc": "^3.3.5", + "@eslint/json": "^2.0.0", + "@types/esquery": "^1.5.4", + "@types/node": "^22.13.14", + "@typescript-eslint/parser": "^8.58.2", + "babel-loader": "^8.0.5", + "c8": "^11.0.0", + "chai": "^4.0.1", + "cheerio": "^0.22.0", + "common-tags": "^1.8.0", + "core-js": "^3.1.3", + "cypress": "^14.1.0", + "ejs": "^3.0.2", + "eslint": "file:.", + "eslint-config-eslint": "file:packages/eslint-config-eslint", + "eslint-plugin-eslint-plugin": "^7.3.2", + "eslint-plugin-expect-type": "^0.6.0", + "eslint-plugin-yml": "^1.14.0", + "eslint-release": "^3.3.0", + "eslint-rule-extender": "^0.0.1", + "eslump": "^3.0.0", + "esprima": "^4.0.1", + "fs-teardown": "^0.1.3", + "glob": "^10.0.0", + "globals": "^16.2.0", + "got": "^11.8.3", + "gray-matter": "^4.0.3", + "jiti": "^2.6.1", + "knip": "^6.13.1", + "lint-staged": "^11.0.0", + "markdown-it": "^12.2.0", + "markdown-it-container": "^3.0.0", + "markdownlint-cli2": "^0.22.0", + "marked": "^4.0.8", + "metascraper": "^5.25.7", + "metascraper-description": "^5.25.7", + "metascraper-image": "^5.29.3", + "metascraper-logo": "^5.25.7", + "metascraper-logo-favicon": "^5.25.7", + "metascraper-title": "^5.25.7", + "mocha": "^11.7.1", + "node-polyfill-webpack-plugin": "^1.0.3", + "npm-license": "^0.3.3", + "prettier": "3.8.3", + "progress": "^2.0.3", + "proxyquire": "^2.0.1", + "regenerator-runtime": "^0.14.0", + "semver": "^7.5.3", + "shelljs": "^0.10.0", + "sinon": "^11.0.0", + "typescript": "^6.0.3", + "webpack": "^5.23.0", + "webpack-cli": "^4.5.0", + "yorkie": "^2.0.0" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + }, + "keywords": [ + "ast", + "lint", + "javascript", + "ecmascript", + "espree" + ], + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } +} diff --git a/node_modules/espree/LICENSE b/node_modules/espree/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b18469ff2ffdfcf437456350a4bee3ba493f1970 --- /dev/null +++ b/node_modules/espree/LICENSE @@ -0,0 +1,25 @@ +BSD 2-Clause License + +Copyright (c) Open JS Foundation +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY 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. diff --git a/node_modules/espree/README.md b/node_modules/espree/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3e749f8eebce3f77909d206bece787c064e6681b --- /dev/null +++ b/node_modules/espree/README.md @@ -0,0 +1,261 @@ +[![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree) +[![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree) +[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/js/espree/actions) +[![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE) + +# Espree + +Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima. + +## Usage + +Install: + +``` +npm i espree +``` + +To use in an ESM file: + +```js +import * as espree from "espree"; + +const ast = espree.parse(code); +``` + +To use in a Common JS file: + +```js +const espree = require("espree"); + +const ast = espree.parse(code); +``` + +## API + +### `parse()` + +`parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters. + +- `code` [string]() - the code which needs to be parsed. +- `options (Optional)` [Object]() - read more about this [here](#options). + +```js +import * as espree from "espree"; + +const ast = espree.parse(code); +``` + +**Example :** + +```js +const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 }); +console.log(ast); +``` + +
Output +

+ +``` +Node { + type: 'Program', + start: 0, + end: 15, + body: [ + Node { + type: 'VariableDeclaration', + start: 0, + end: 15, + declarations: [Array], + kind: 'let' + } + ], + sourceType: 'script' +} +``` + +

+
+ +### `tokenize()` + +`tokenize` returns the tokens of a given code. It takes two parameters. + +- `code` [string]() - the code which needs to be parsed. +- `options (Optional)` [Object]() - read more about this [here](#options). + +Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array + +**Example :** + +```js +import * as espree from "espree"; + +const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 }); +console.log(tokens); +``` + +
Output +

+ +``` +Token { type: 'Keyword', value: 'let', start: 0, end: 3 }, +Token { type: 'Identifier', value: 'foo', start: 4, end: 7 }, +Token { type: 'Punctuator', value: '=', start: 8, end: 9 }, +Token { type: 'String', value: '"bar"', start: 10, end: 15 } +``` + +

+
+ +### `version` + +Returns the current `espree` version + +### `VisitorKeys` + +Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/js/tree/main/packages/eslint-visitor-keys) + +### `latestEcmaVersion` + +Returns the latest ECMAScript supported by `espree` + +### `supportedEcmaVersions` + +Returns an array of all supported ECMAScript versions + +## Options + +```js +const options = { + // attach range information to each node + range: false, + + // attach line/column location information to each node + loc: false, + + // create a top-level comments array containing all comments + comment: false, + + // create a top-level tokens array containing all tokens + tokens: false, + + // Set to 3, 5 (the default), 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 or 17 to specify the version of ECMAScript syntax you want to use. + // You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), 2021 (same as 12), 2022 (same as 13), 2023 (same as 14), 2024 (same as 15), 2025 (same as 16) or 2026 (same as 17) to use the year-based naming. + // You can also set "latest" to use the most recently supported version. + ecmaVersion: 3, + + allowReserved: true, // only allowed when ecmaVersion is 3 + + // specify which type of script you're parsing ("script", "module", or "commonjs") + sourceType: "script", + + // specify additional language features + ecmaFeatures: { + // enable JSX parsing + jsx: false, + + // enable return in global scope (set to true automatically when sourceType is "commonjs") + globalReturn: false, + + // enable implied strict mode (if ecmaVersion >= 5) + impliedStrict: false, + }, +}; +``` + +## Esprima Compatibility Going Forward + +The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same. + +Espree may also deviate from Esprima in the interface it exposes. + +## Contributing + +Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/js/issues). + +Espree is licensed under a permissive BSD 2-clause license. + +## Security Policy + +We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). + +## Build Commands + +- `npm test` - run all tests +- `npm run lint` - run all linting + +## Differences from Espree 2.x + +- The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics. +- Trailing whitespace no longer is counted as part of a node. +- `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`. +- The `esparse` and `esvalidate` binary scripts have been removed. +- There is no `tolerant` option. We will investigate adding this back in the future. + +## Known Incompatibilities + +In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change. + +### Esprima 1.2.2 + +- Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs. +- Espree does not parse `let` and `const` declarations by default. +- Error messages returned for parsing errors are different. +- There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn. + +### Esprima 2.x + +- Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2. + +## Frequently Asked Questions + +### Why another parser + +[ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration. + +We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API. + +With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima. + +### Have you tried working with Esprima? + +Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support. + +### Why don't you just use Acorn? + +Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint. + +We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better. + +### What ECMAScript features do you support? + +Espree supports all ECMAScript 2025 features and partially supports ECMAScript 2026 features. + +Because ECMAScript 2026 is still under development, we are implementing features as they are finalized. Currently, Espree supports: + +- [Explicit Resource Management](https://github.com/tc39/proposal-explicit-resource-management) + +See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized. + +### How do you determine which experimental features to support? + +In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features. + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Platinum Sponsors

+

Automattic

Gold Sponsors

+

Qlty Software

Silver Sponsors

+

Vite Liftoff StackBlitz

Bronze Sponsors

+

Cybozu SAP CrawlJobs Depot N-iX Ltd Icons8 Discord GitBook HeroCoders TestMu AI Open Source Office (Formerly LambdaTest)

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/espree/espree.js b/node_modules/espree/espree.js new file mode 100644 index 0000000000000000000000000000000000000000..b227d8c8085fba756143bec61d9602307bc377f7 --- /dev/null +++ b/node_modules/espree/espree.js @@ -0,0 +1,287 @@ +/** + * @fileoverview Main Espree file that converts Acorn into Esprima output. + * + * This file contains code from the following MIT-licensed projects: + * 1. Acorn + * 2. Babylon + * 3. Babel-ESLint + * + * This file also contains code from Esprima, which is BSD licensed. + * + * Acorn is Copyright 2012-2015 Acorn Contributors (https://github.com/marijnh/acorn/blob/master/AUTHORS) + * Babylon is Copyright 2014-2015 various contributors (https://github.com/babel/babel/blob/master/packages/babylon/AUTHORS) + * Babel-ESLint is Copyright 2014-2015 Sebastian McKenzie + * + * 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. + * + * 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 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. + * + * Esprima is Copyright (c) jQuery Foundation, Inc. and Contributors, 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. + * + * 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 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. + */ + +import * as acorn from "acorn"; +import jsx from "acorn-jsx"; +import espree from "./lib/espree.js"; +import { KEYS as VisitorKeys } from "eslint-visitor-keys"; +import { + getLatestEcmaVersion, + getSupportedEcmaVersions, +} from "./lib/options.js"; + +/** + * @import { EspreeParserCtor, EspreeParserJsxCtor } from "./lib/types.js"; + */ + +// ---------------------------------------------------------------------------- +// Types exported from file +// ---------------------------------------------------------------------------- +/** + * @typedef {3|5|6|7|8|9|10|11|12|13|14|15|16|17|2015|2016|2017|2018|2019|2020|2021|2022|2023|2024|2025|2026|'latest'} EcmaVersion + */ + +/** + * @typedef {{ + * type: string; + * value: any; + * start?: number; + * end?: number; + * loc?: acorn.SourceLocation; + * range?: [number, number]; + * regex?: {flags: string, pattern: string}; + * }} EspreeToken + */ + +/** + * @typedef {{ + * type: "Block" | "Hashbang" | "Line", + * value: string, + * range?: [number, number], + * start?: number, + * end?: number, + * loc?: { + * start: acorn.Position | undefined, + * end: acorn.Position | undefined + * } + * }} EspreeComment + */ + +/** + * @typedef {{ + * comments?: EspreeComment[] + * } & EspreeToken[]} EspreeTokens + */ + +/** + * `allowReserved` is as in `acorn.Options` + * + * `ecmaVersion` currently as in `acorn.Options` though optional + * + * `sourceType` as in `acorn.Options` but also allows `commonjs` + * + * `ecmaFeatures`, `range`, `loc`, `tokens` are not in `acorn.Options` + * + * `comment` is not in `acorn.Options` and doesn't err without it, but is used + */ +/** + * @typedef {{ + * allowReserved?: boolean, + * ecmaVersion?: EcmaVersion, + * sourceType?: "script"|"module"|"commonjs", + * ecmaFeatures?: { + * jsx?: boolean, + * globalReturn?: boolean, + * impliedStrict?: boolean + * }, + * range?: boolean, + * loc?: boolean, + * tokens?: boolean, + * comment?: boolean, + * }} Options + */ + +// To initialize lazily. +const parsers = { + /** @type {EspreeParserCtor|null} */ + _regular: null, + + /** @type {EspreeParserJsxCtor|null} */ + _jsx: null, + + /** + * Returns regular Parser + * @returns {EspreeParserCtor} Regular Acorn parser + */ + get regular() { + if (this._regular === null) { + const espreeParserFactory = /** @type {unknown} */ (espree()); + + this._regular = /** @type {EspreeParserCtor} */ ( + // Without conversion, types are incompatible, as + // acorn's has a protected constructor + /** @type {unknown} */ + ( + acorn.Parser.extend( + /** + * @type {( + * BaseParser: typeof acorn.Parser + * ) => typeof acorn.Parser} + */ (espreeParserFactory), + ) + ) + ); + } + return this._regular; + }, + + /** + * Returns JSX Parser + * @returns {EspreeParserJsxCtor} JSX Acorn parser + */ + get jsx() { + if (this._jsx === null) { + const espreeParserFactory = /** @type {unknown} */ (espree()); + const jsxFactory = jsx(); + + this._jsx = /** @type {EspreeParserJsxCtor} */ ( + // Without conversion, types are incompatible, as + // acorn's has a protected constructor + /** @type {unknown} */ + ( + acorn.Parser.extend( + jsxFactory, + + /** @type {(BaseParser: typeof acorn.Parser) => typeof acorn.Parser} */ + (espreeParserFactory), + ) + ) + ); + } + return this._jsx; + }, + + /** + * Gets the parser object based on the supplied options. + * @param {Options} [options] The parser options. + * @returns {EspreeParserJsxCtor|EspreeParserCtor} Regular or JSX Acorn parser + */ + get(options) { + const useJsx = Boolean( + options && options.ecmaFeatures && options.ecmaFeatures.jsx, + ); + + return useJsx ? this.jsx : this.regular; + }, +}; + +//------------------------------------------------------------------------------ +// Tokenizer +//------------------------------------------------------------------------------ + +/** + * Tokenizes the given code. + * @param {string} code The code to tokenize. + * @param {Options} [options] Options defining how to tokenize. + * @returns {EspreeTokens} An array of tokens. + * @throws {EnhancedSyntaxError} If the input code is invalid. + * @private + */ +export function tokenize(code, options) { + const Parser = parsers.get(options); + + // Ensure to collect tokens. + if (!options || options.tokens !== true) { + options = Object.assign({}, options, { tokens: true }); // eslint-disable-line no-param-reassign -- stylistic choice + } + + return /** @type {EspreeTokens} */ (new Parser(options, code).tokenize()); +} + +//------------------------------------------------------------------------------ +// Parser +//------------------------------------------------------------------------------ + +/** + * Parses the given code. + * @param {string} code The code to tokenize. + * @param {Options} [options] Options defining how to tokenize. + * @returns {acorn.Program} The "Program" AST node. + * @throws {EnhancedSyntaxError} If the input code is invalid. + */ +export function parse(code, options) { + const Parser = parsers.get(options); + + return new Parser(options, code).parse(); +} + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +/** @type {string} */ +export const version = "11.2.0"; // x-release-please-version +export const name = "espree"; + +// Derive node types from VisitorKeys +export const Syntax = /* #__PURE__ */ (function () { + let key, + /** @type {Record} */ + types = {}; + + if (typeof Object.create === "function") { + types = Object.create(null); + } + + for (key in VisitorKeys) { + if (Object.hasOwn(VisitorKeys, key)) { + types[key] = key; + } + } + + if (typeof Object.freeze === "function") { + Object.freeze(types); + } + + return types; +})(); + +export const latestEcmaVersion = /* #__PURE__ */ getLatestEcmaVersion(); + +export const supportedEcmaVersions = /* #__PURE__ */ getSupportedEcmaVersions(); + +export { KEYS as VisitorKeys } from "eslint-visitor-keys"; diff --git a/node_modules/espree/lib/espree.js b/node_modules/espree/lib/espree.js new file mode 100644 index 0000000000000000000000000000000000000000..1dc8a83764954bd570dd3cfa51b620856ec743dd --- /dev/null +++ b/node_modules/espree/lib/espree.js @@ -0,0 +1,493 @@ +/* eslint no-param-reassign: 0 -- stylistic choice */ + +import TokenTranslator from "./token-translator.js"; +import { normalizeOptions } from "./options.js"; + +/** + * @import { + * CommentType, + * EspreeParserCtor, + * EsprimaNode, + * AcornJsxParserCtorEnhanced, + * TokTypes + * } from "./types.js"; + * @import { + * Options, + * EspreeToken as EsprimaToken, + * EspreeTokens as EsprimaTokens, + * EspreeComment as EsprimaComment + * } from "../espree.js"; + * @import { NormalizedEcmaVersion } from "./options.js"; + * @import * as acorn from "acorn"; + */ + +/** + * @typedef {{ + * originalSourceType: "script" | "module" | "commonjs" | undefined + * tokens: EsprimaToken[] | null, + * comments: EsprimaComment[] | null, + * impliedStrict: boolean, + * ecmaVersion: NormalizedEcmaVersion, + * jsxAttrValueToken: boolean, + * lastToken: acorn.Token | null, + * templateElements: acorn.TemplateElement[] + * }} State + */ + +/** + * @typedef {{ + * sourceType?: "script"|"module"|"commonjs"; + * comments?: EsprimaComment[]; + * tokens?: EsprimaToken[]; + * body: acorn.Node[]; + * } & acorn.Program} EsprimaProgramNode + */ + +// ---------------------------------------------------------------------------- +// Types exported from file +// ---------------------------------------------------------------------------- +/** + * @typedef {{ + * index?: number; + * lineNumber?: number; + * column?: number; + * } & SyntaxError} EnhancedSyntaxError + */ + +// We add `jsxAttrValueToken` ourselves. +/** + * @typedef {{ + * jsxAttrValueToken?: acorn.TokenType; + * } & TokTypes} EnhancedTokTypes + */ + +const STATE = Symbol("espree's internal state"); +const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode"); + +/** + * Converts an Acorn comment to a Esprima comment. + * @param {boolean} block True if it's a block comment, false if not. + * @param {string} text The text of the comment. + * @param {number} start The index at which the comment starts. + * @param {number} end The index at which the comment ends. + * @param {acorn.Position | undefined} startLoc The location at which the comment starts. + * @param {acorn.Position | undefined} endLoc The location at which the comment ends. + * @param {string} code The source code being parsed. + * @returns {EsprimaComment} The comment object. + * @private + */ +function convertAcornCommentToEsprimaComment( + block, + text, + start, + end, + startLoc, + endLoc, + code, +) { + /** @type {CommentType} */ + let type; + + if (block) { + type = "Block"; + } else if (code.slice(start, start + 2) === "#!") { + type = "Hashbang"; + } else { + type = "Line"; + } + + /** + * @type {{ + * type: CommentType, + * value: string, + * start?: number, + * end?: number, + * range?: [number, number], + * loc?: { + * start: acorn.Position | undefined, + * end: acorn.Position | undefined + * } + * }} + */ + const comment = { + type, + value: text, + }; + + if (typeof start === "number") { + comment.start = start; + comment.end = end; + comment.range = [start, end]; + } + + if (typeof startLoc === "object") { + comment.loc = { + start: startLoc, + end: endLoc, + }; + } + + return comment; +} + +// eslint-disable-next-line arrow-body-style -- For TS +export default () => { + /** + * Returns the Espree parser. + * @param {AcornJsxParserCtorEnhanced} Parser The Acorn parser. The `acorn` property is missing from acorn's + * TypeScript but is present statically on the class. + * @returns {EspreeParserCtor} The Espree Parser constructor. + */ + return Parser => { + const tokTypes = /** @type {EnhancedTokTypes} */ ( + Object.assign({}, Parser.acorn.tokTypes) + ); + + if (Parser.acornJsx) { + Object.assign(tokTypes, Parser.acornJsx.tokTypes); + } + + return class Espree extends Parser { + /** + * @param {Options | null | undefined} opts The parser options + * @param {string | object} code The code which will be converted to a string. + */ + constructor(opts, code) { + if (typeof opts !== "object" || opts === null) { + opts = {}; + } + if (typeof code !== "string" && !(code instanceof String)) { + code = String(code); + } + + // save original source type in case of commonjs + const originalSourceType = opts.sourceType; + const options = normalizeOptions(opts); + const ecmaFeatures = options.ecmaFeatures || {}; + const tokenTranslator = + options.tokens === true + ? new TokenTranslator( + tokTypes, + + // @ts-expect-error Appears to be a TS bug since the type is indeed string|String + code, + ) + : null; + + /** + * Data that is unique to Espree and is not represented internally + * in Acorn. + * + * For ES2023 hashbangs, Espree will call `onComment()` during the + * constructor, so we must define state before having access to + * `this`. + * @type {State} + */ + const state = { + originalSourceType: + originalSourceType || options.sourceType, + tokens: tokenTranslator ? [] : null, + comments: options.comment === true ? [] : null, + impliedStrict: + ecmaFeatures.impliedStrict === true && + options.ecmaVersion >= 5, + ecmaVersion: options.ecmaVersion, + jsxAttrValueToken: false, + lastToken: null, + templateElements: [], + }; + + // Initialize acorn parser. + super( + { + // do not use spread, because we don't want to pass any unknown options to acorn + ecmaVersion: options.ecmaVersion, + sourceType: options.sourceType, + ranges: options.ranges, + locations: options.locations, + allowReserved: options.allowReserved, + + // Truthy value is true for backward compatibility. + allowReturnOutsideFunction: + options.allowReturnOutsideFunction, + + // Collect tokens + onToken(token) { + if (tokenTranslator) { + // Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state. + tokenTranslator.onToken( + token, + + /** + * @type {Omit & { + * tokens: EsprimaToken[] + * }} + */ + (state), + ); + } + if (token.type !== tokTypes.eof) { + state.lastToken = token; + } + }, + + // Collect comments + onComment(block, text, start, end, startLoc, endLoc) { + if (state.comments) { + const comment = + convertAcornCommentToEsprimaComment( + block, + text, + start, + end, + startLoc, + endLoc, + + // @ts-expect-error Appears to be a TS bug + // since the type is indeed string|String + code, + ); + + state.comments.push(comment); + } + }, + }, + // @ts-expect-error Appears to be a TS bug + // since the type is indeed string|String + code, + ); + + /* + * We put all of this data into a symbol property as a way to avoid + * potential naming conflicts with future versions of Acorn. + */ + this[STATE] = state; + } + + /** + * Returns Espree tokens. + * @returns {EsprimaTokens} The Esprima-compatible tokens + */ + tokenize() { + do { + this.next(); + } while (this.type !== tokTypes.eof); + + // Consume the final eof token + this.next(); + + const extra = this[STATE]; + const tokens = /** @type {EsprimaTokens} */ (extra.tokens); + + if (extra.comments) { + tokens.comments = extra.comments; + } + + return tokens; + } + + /** + * Calls parent. + * @param {acorn.Node} node The node + * @param {string} type The type + * @returns {acorn.Node} The altered Node + */ + finishNode(node, type) { + const result = super.finishNode(node, type); + + return this[ESPRIMA_FINISH_NODE](result); + } + + /** + * Calls parent. + * @param {acorn.Node} node The node + * @param {string} type The type + * @param {number} pos The position + * @param {acorn.Position} loc The location + * @returns {acorn.Node} The altered Node + */ + finishNodeAt(node, type, pos, loc) { + const result = super.finishNodeAt(node, type, pos, loc); + + return this[ESPRIMA_FINISH_NODE](result); + } + + /** + * Parses. + * @returns {EsprimaProgramNode} The program Node + */ + parse() { + const extra = this[STATE]; + const prog = super.parse(); + + const program = /** @type {EsprimaProgramNode} */ (prog); + + // @ts-expect-error TS bug? We've already converted to `EsprimaProgramNode` + program.sourceType = extra.originalSourceType; + + if (extra.comments) { + program.comments = extra.comments; + } + if (extra.tokens) { + program.tokens = extra.tokens; + } + + /* + * https://github.com/eslint/espree/issues/349 + * Ensure that template elements have correct range information. + * This is one location where Acorn produces a different value + * for its start and end properties vs. the values present in the + * range property. In order to avoid confusion, we set the start + * and end properties to the values that are present in range. + * This is done here, instead of in finishNode(), because Acorn + * uses the values of start and end internally while parsing, making + * it dangerous to change those values while parsing is ongoing. + * By waiting until the end of parsing, we can safely change these + * values without affect any other part of the process. + */ + this[STATE].templateElements.forEach(templateElement => { + const startOffset = -1; + const endOffset = templateElement.tail ? 1 : 2; + + templateElement.start += startOffset; + templateElement.end += endOffset; + + if (templateElement.range) { + templateElement.range[0] += startOffset; + templateElement.range[1] += endOffset; + } + + if (templateElement.loc) { + templateElement.loc.start.column += startOffset; + templateElement.loc.end.column += endOffset; + } + }); + + return program; + } + + /** + * Parses top level. + * @param {acorn.Node} node AST Node + * @returns {acorn.Node} The changed node + */ + parseTopLevel(node) { + if (this[STATE].impliedStrict) { + this.strict = true; + } + return super.parseTopLevel(node); + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {number} pos The position of the error. + * @param {string} message The error message. + * @throws {EnhancedSyntaxError} A syntax error. + * @returns {void} + */ + raise(pos, message) { + const loc = Parser.acorn.getLineInfo(this.input, pos); + const err = /** @type {EnhancedSyntaxError} */ ( + new SyntaxError(message) + ); + + err.index = pos; + err.lineNumber = loc.line; + err.column = loc.column + 1; // acorn uses 0-based columns + throw err; + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {number} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raiseRecoverable(pos, message) { + this.raise(pos, message); + } + + /** + * Overwrites the default unexpected method to throw Esprima-style errors. + * @param {number} pos The position of the error. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + unexpected(pos) { + let message = "Unexpected token"; + + if (pos !== null && pos !== void 0) { + this.pos = pos; + + if (this.options.locations) { + while (this.pos < this.lineStart) { + this.lineStart = + this.input.lastIndexOf( + "\n", + this.lineStart - 2, + ) + 1; + --this.curLine; + } + } + + this.nextToken(); + } + + if (this.end > this.start) { + message += ` ${this.input.slice(this.start, this.end)}`; + } + + this.raise(this.start, message); + } + + /** + * Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX + * uses regular tt.string without any distinction between this and regular JS + * strings. As such, we intercept an attempt to read a JSX string and set a flag + * on extra so that when tokens are converted, the next token will be switched + * to JSXText via onToken. + * @param {number} quote A character code + * @returns {void} + */ // eslint-disable-next-line camelcase -- required by API + jsx_readString(quote) { + const result = super.jsx_readString(quote); + + if (this.type === tokTypes.string) { + this[STATE].jsxAttrValueToken = true; + } + return result; + } + + /** + * Performs last-minute Esprima-specific compatibility checks and fixes. + * @param {acorn.Node} result The node to check. + * @returns {EsprimaNode} The finished node. + */ + [ESPRIMA_FINISH_NODE](result) { + // Acorn doesn't count the opening and closing backticks as part of templates + // so we have to adjust ranges/locations appropriately. + if (result.type === "TemplateElement") { + // save template element references to fix start/end later + this[STATE].templateElements.push( + /** @type {acorn.TemplateElement} */ + (result), + ); + } + + if ( + result.type.includes("Function") && + !("generator" in result) + ) { + /** + * @type {acorn.FunctionDeclaration|acorn.FunctionExpression| + * acorn.ArrowFunctionExpression} + */ + (result).generator = false; + } + + return result; + } + }; + }; +}; diff --git a/node_modules/espree/lib/options.js b/node_modules/espree/lib/options.js new file mode 100644 index 0000000000000000000000000000000000000000..1ef2271db3d6ceb0c66e0aa9985711c76b293301 --- /dev/null +++ b/node_modules/espree/lib/options.js @@ -0,0 +1,176 @@ +/** + * @fileoverview A collection of methods for processing Espree's options. + * @author Kai Cataldo + */ + +/** + * @import { EcmaVersion, Options } from "../espree.js"; + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SUPPORTED_VERSIONS = /** @type {const} */ ([ + 3, + 5, + 6, // 2015 + 7, // 2016 + 8, // 2017 + 9, // 2018 + 10, // 2019 + 11, // 2020 + 12, // 2021 + 13, // 2022 + 14, // 2023 + 15, // 2024 + 16, // 2025 + 17, // 2026 +]); + +/** + * @typedef {typeof SUPPORTED_VERSIONS[number]} NormalizedEcmaVersion + */ + +const LATEST_ECMA_VERSION = + /* eslint-disable jsdoc/valid-types -- Bug */ + /** @type {typeof SUPPORTED_VERSIONS extends readonly [...unknown[], infer L] ? L : never} */ ( + SUPPORTED_VERSIONS.at(-1) + /* eslint-enable jsdoc/valid-types -- Bug */ + ); + +/** + * Get the latest ECMAScript version supported by Espree. + * @returns {typeof LATEST_ECMA_VERSION} The latest ECMAScript version. + */ +export function getLatestEcmaVersion() { + return LATEST_ECMA_VERSION; +} + +/** + * Get the list of ECMAScript versions supported by Espree. + * @returns {[...typeof SUPPORTED_VERSIONS]} An array containing the supported ECMAScript versions. + */ +export function getSupportedEcmaVersions() { + return [...SUPPORTED_VERSIONS]; +} + +/** + * Normalize ECMAScript version from the initial config + * @param {EcmaVersion} ecmaVersion ECMAScript version from the initial config + * @throws {Error} throws an error if the ecmaVersion is invalid. + * @returns {NormalizedEcmaVersion} normalized ECMAScript version + */ +function normalizeEcmaVersion(ecmaVersion = 5) { + let version = + ecmaVersion === "latest" ? getLatestEcmaVersion() : ecmaVersion; + + if (typeof version !== "number") { + throw new Error( + `ecmaVersion must be a number or "latest". Received value of type ${typeof ecmaVersion} instead.`, + ); + } + + // Calculate ECMAScript edition number from official year version starting with + // ES2015, which corresponds with ES6 (or a difference of 2009). + if (version >= 2015) { + version -= 2009; + } + + if ( + !SUPPORTED_VERSIONS.includes( + /** @type {NormalizedEcmaVersion} */ + (version), + ) + ) { + throw new Error("Invalid ecmaVersion."); + } + + return /** @type {NormalizedEcmaVersion} */ (version); +} + +/** + * Normalize sourceType from the initial config + * @param {string} sourceType to normalize + * @throws {Error} throw an error if sourceType is invalid + * @returns {"script"|"module"|"commonjs"} normalized sourceType + */ +function normalizeSourceType(sourceType = "script") { + if ( + sourceType === "script" || + sourceType === "module" || + sourceType === "commonjs" + ) { + return sourceType; + } + + throw new Error("Invalid sourceType."); +} + +/** + * @typedef {{ + * ecmaVersion: NormalizedEcmaVersion, + * sourceType: "script"|"module"|"commonjs", + * range?: boolean, + * loc?: boolean, + * allowReserved: boolean | "never", + * ecmaFeatures?: { + * jsx?: boolean, + * globalReturn?: boolean, + * impliedStrict?: boolean + * }, + * ranges: boolean, + * locations: boolean, + * allowReturnOutsideFunction: boolean, + * tokens?: boolean, + * comment?: boolean + * }} NormalizedParserOptions + */ + +/** + * Normalize parserOptions + * @param {Options} options the parser options to normalize + * @throws {Error} throw an error if found invalid option. + * @returns {NormalizedParserOptions} normalized options + */ +export function normalizeOptions(options) { + const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion); + const sourceType = normalizeSourceType(options.sourceType); + const ranges = options.range === true; + const locations = options.loc === true; + + if (ecmaVersion !== 3 && options.allowReserved) { + // a value of `false` is intentionally allowed here, so a shared config can overwrite it when needed + throw new Error( + "`allowReserved` is only supported when ecmaVersion is 3", + ); + } + if ( + typeof options.allowReserved !== "undefined" && + typeof options.allowReserved !== "boolean" + ) { + throw new Error( + "`allowReserved`, when present, must be `true` or `false`", + ); + } + const allowReserved = + ecmaVersion === 3 ? options.allowReserved || "never" : false; + const ecmaFeatures = options.ecmaFeatures || {}; + const allowReturnOutsideFunction = + options.sourceType === "commonjs" || Boolean(ecmaFeatures.globalReturn); + + if (sourceType === "module" && ecmaVersion < 6) { + throw new Error( + "sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding `{ ecmaVersion: 2015 }` to the parser options.", + ); + } + + return Object.assign({}, options, { + ecmaVersion, + sourceType, + ranges, + locations, + allowReserved, + allowReturnOutsideFunction, + }); +} diff --git a/node_modules/espree/lib/token-translator.js b/node_modules/espree/lib/token-translator.js new file mode 100644 index 0000000000000000000000000000000000000000..96c133f8959b6b06e2633b29c7cca0e2f2db6de0 --- /dev/null +++ b/node_modules/espree/lib/token-translator.js @@ -0,0 +1,306 @@ +/** + * @fileoverview Translates tokens between Acorn format and Esprima format. + * @author Nicholas C. Zakas + */ + +/** + * @import * as acorn from "acorn"; + * @import { EnhancedTokTypes } from "./espree.js" + * @import { NormalizedEcmaVersion } from "./options.js"; + * @import { EspreeToken as EsprimaToken } from "../espree.js"; + */ +/** + * Based on the `acorn.Token` class, but without a fixed `type` (since we need + * it to be a string). Avoiding `type` lets us make one extending interface + * more strict and another more lax. + * + * We could make `value` more strict to `string` even though the original is + * `any`. + * + * `start` and `end` are required in `acorn.Token` + * + * `loc` and `range` are from `acorn.Token` + * + * Adds `regex`. + */ +/** + * @typedef {{ + * jsxAttrValueToken: boolean; + * ecmaVersion: NormalizedEcmaVersion; + * }} ExtraNoTokens + * @typedef {{ + * tokens: EsprimaToken[] + * } & ExtraNoTokens} Extra + */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +// Esprima Token Types +const Token = { + Boolean: "Boolean", + EOF: "", + Identifier: "Identifier", + PrivateIdentifier: "PrivateIdentifier", + Keyword: "Keyword", + Null: "Null", + Numeric: "Numeric", + Punctuator: "Punctuator", + String: "String", + RegularExpression: "RegularExpression", + Template: "Template", + JSXIdentifier: "JSXIdentifier", + JSXText: "JSXText", +}; + +/** + * Converts part of a template into an Esprima token. + * @param {acorn.Token[]} tokens The Acorn tokens representing the template. + * @param {string} code The source code. + * @returns {EsprimaToken} The Esprima equivalent of the template token. + * @private + */ +function convertTemplatePart(tokens, code) { + const firstToken = tokens[0], + lastTemplateToken = + /** @type {acorn.Token & { loc: acorn.SourceLocation, range: [number, number] }} */ ( + tokens.at(-1) + ); + + /** @type {EsprimaToken} */ + const token = { + type: Token.Template, + value: code.slice(firstToken.start, lastTemplateToken.end), + }; + + if (firstToken.loc) { + token.loc = { + start: firstToken.loc.start, + end: lastTemplateToken.loc.end, + }; + } + + if (firstToken.range) { + token.start = firstToken.range[0]; + token.end = lastTemplateToken.range[1]; + token.range = [token.start, token.end]; + } + + return token; +} + +/* eslint-disable jsdoc/check-types -- The API allows either */ +/** + * Contains logic to translate Acorn tokens into Esprima tokens. + */ +class TokenTranslator { + /** + * Contains logic to translate Acorn tokens into Esprima tokens. + * @param {EnhancedTokTypes} acornTokTypes The Acorn token types. + * @param {string|String} code The source code Acorn is parsing. This is necessary + * to correct the "value" property of some tokens. + */ + constructor(acornTokTypes, code) { + /* eslint-enable jsdoc/check-types -- The API allows either */ + + // token types + this._acornTokTypes = acornTokTypes; + + // token buffer for templates + /** @type {acorn.Token[]} */ + this._tokens = []; + + // track the last curly brace + this._curlyBrace = null; + + // the source code + this._code = code; + } + + /** + * Translates a single Esprima token to a single Acorn token. This may be + * inaccurate due to how templates are handled differently in Esprima and + * Acorn, but should be accurate for all other tokens. + * @param {acorn.Token} token The Acorn token to translate. + * @param {ExtraNoTokens} extra Espree extra object. + * @returns {EsprimaToken} The Esprima version of the token. + */ + translate(token, extra) { + const type = token.type, + tt = this._acornTokTypes, + // We use an unknown type because `acorn.Token` is a class whose + // `type` property we cannot override to our desired `string`; + // this also allows us to define a stricter `EsprimaToken` with + // a string-only `type` property + unknownTokenType = /** @type {unknown} */ (token), + newToken = /** @type {EsprimaToken} */ (unknownTokenType); + + if (type === tt.name) { + newToken.type = Token.Identifier; + + // TODO: See if this is an Acorn bug + if ("value" in token && token.value === "static") { + newToken.type = Token.Keyword; + } + + if ( + extra.ecmaVersion > 5 && + "value" in token && + (token.value === "yield" || token.value === "let") + ) { + newToken.type = Token.Keyword; + } + } else if (type === tt.privateId) { + newToken.type = Token.PrivateIdentifier; + } else if ( + type === tt.semi || + type === tt.comma || + type === tt.parenL || + type === tt.parenR || + type === tt.braceL || + type === tt.braceR || + type === tt.dot || + type === tt.bracketL || + type === tt.colon || + type === tt.question || + type === tt.bracketR || + type === tt.ellipsis || + type === tt.arrow || + type === tt.jsxTagStart || + type === tt.incDec || + type === tt.starstar || + type === tt.jsxTagEnd || + type === tt.prefix || + type === tt.questionDot || + ("binop" in type && type.binop && !type.keyword) || + ("isAssign" in type && type.isAssign) + ) { + newToken.type = Token.Punctuator; + newToken.value = this._code.slice(token.start, token.end); + } else if (type === tt.jsxName) { + newToken.type = Token.JSXIdentifier; + } else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) { + newToken.type = Token.JSXText; + } else if (type.keyword) { + if (type.keyword === "true" || type.keyword === "false") { + newToken.type = Token.Boolean; + } else if (type.keyword === "null") { + newToken.type = Token.Null; + } else { + newToken.type = Token.Keyword; + } + } else if (type === tt.num) { + newToken.type = Token.Numeric; + newToken.value = this._code.slice(token.start, token.end); + } else if (type === tt.string) { + if (extra.jsxAttrValueToken) { + extra.jsxAttrValueToken = false; + newToken.type = Token.JSXText; + } else { + newToken.type = Token.String; + } + + newToken.value = this._code.slice(token.start, token.end); + } else if (type === tt.regexp) { + newToken.type = Token.RegularExpression; + const value = /** @type {{flags: string, pattern: string}} */ ( + "value" in token && token.value + ); + + newToken.regex = { + flags: value.flags, + pattern: value.pattern, + }; + newToken.value = `/${value.pattern}/${value.flags}`; + } + + return newToken; + } + + /** + * Function to call during Acorn's onToken handler. + * @param {acorn.Token} token The Acorn token. + * @param {Extra} extra The Espree extra object. + * @returns {void} + */ + onToken(token, extra) { + const tt = this._acornTokTypes, + tokens = extra.tokens, + templateTokens = this._tokens; + + /** + * Flushes the buffered template tokens and resets the template + * tracking. + * @returns {void} + * @private + */ + const translateTemplateTokens = () => { + tokens.push(convertTemplatePart(this._tokens, this._code)); + this._tokens = []; + }; + + if (token.type === tt.eof) { + // might be one last curlyBrace + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + return; + } + + if (token.type === tt.backQuote) { + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + templateTokens.push(token); + + // it's the end + if (templateTokens.length > 1) { + translateTemplateTokens(); + } + + return; + } + if (token.type === tt.dollarBraceL) { + templateTokens.push(token); + translateTemplateTokens(); + return; + } + if (token.type === tt.braceR) { + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + // store new curly for later + this._curlyBrace = token; + return; + } + if (token.type === tt.template || token.type === tt.invalidTemplate) { + if (this._curlyBrace) { + templateTokens.push(this._curlyBrace); + this._curlyBrace = null; + } + + templateTokens.push(token); + return; + } + + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + tokens.push(this.translate(token, extra)); + } +} + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +export default TokenTranslator; diff --git a/node_modules/espree/lib/types.js b/node_modules/espree/lib/types.js new file mode 100644 index 0000000000000000000000000000000000000000..7a467805274bc7b0b4e883356ef8b619d2abb186 --- /dev/null +++ b/node_modules/espree/lib/types.js @@ -0,0 +1,118 @@ +/** + * @import * as acorn from "acorn"; + * @import { Options, EspreeTokens } from "../espree.js"; + */ + +/** + * @typedef {acorn.tokTypes & { + * jsxName: acorn.TokenType, + * jsxText: acorn.TokenType, + * jsxTagEnd: acorn.TokenType, + * jsxTagStart: acorn.TokenType + * }} TokTypes + */ + +/** + * @typedef {new ( + * token: string, + * isExpr: boolean, + * preserveSpace: boolean, + * override?: (parser: any) => void + * ) => void} TokContext + */ + +/** + * @typedef {{ + * tc_oTag: TokContext, + * tc_cTag: TokContext, + * tc_expr: TokContext + * }} TokContexts + */ + +/** + * @typedef {{ + * generator?: boolean + * } & acorn.Node} EsprimaNode + */ + +/** + * @typedef {"Block"|"Hashbang"|"Line"} CommentType + */ + +/** + * @typedef {{ + * tokenize: () => EspreeTokens, + * parse: () => acorn.Program + * }} EspreeParser + */ + +/* eslint-disable jsdoc/valid-types -- Waiting on jsdoc plugin update */ +/** + * @typedef {acorn.Parser & { + * jsx_readToken(): string; + * jsx_readNewLine(normalizeCRLF: boolean): void; + * jsx_readString(quote: number): void; + * jsx_readEntity(): string; + * jsx_readWord(): void; + * jsx_parseIdentifier(): acorn.Node; + * jsx_parseNamespacedName(): acorn.Node; + * jsx_parseElementName(): acorn.Node | string; + * jsx_parseAttributeValue(): acorn.Node; + * jsx_parseEmptyExpression(): acorn.Node; + * jsx_parseExpressionContainer(): acorn.Node; + * jsx_parseAttribute(): acorn.Node; + * jsx_parseOpeningElementAt(startPos: number, startLoc?: acorn.SourceLocation): acorn.Node; + * jsx_parseClosingElementAt(startPos: number, startLoc?: acorn.SourceLocation): acorn.Node; + * jsx_parseElementAt(startPos: number, startLoc?: acorn.SourceLocation): acorn.Node; + * jsx_parseText(): acorn.Node; + * jsx_parseElement(): acorn.Node; + * }} AcornJsxParser + */ + +/** + * We pick (statics) from acorn rather than plain extending to avoid complaint + * about base constructors needing the same return type (i.e., we return + * `AcornJsxParser` here) + * @typedef {Pick & { + * readonly acornJsx: { + * tokTypes: TokTypes; + * tokContexts: TokContexts + * }; + * new (options: acorn.Options, input: string, startPos?: number): AcornJsxParser; + * }} AcornJsxParserCtor + */ +/** + * @typedef {{ + * new (opts: Options | null | undefined, code: string | object): EspreeParser + * } & Pick} EspreeParserCtor + */ +/** + * @typedef {{ + * new (opts: Options | null | undefined, code: string | object): EspreeParser + * } & Pick} EspreeParserJsxCtor + */ + +/** + * @typedef {Pick & { + * acorn: { + * tokTypes: TokTypes, + * getLineInfo: (input: string, pos: number) => { + * line: number, + * column: number + * } + * } + * new (options: acorn.Options, input: string, startPos?: number): AcornJsxParser & { + * next: () => void, + * type: acorn.TokenType, + * curLine: number, + * start: number, + * end: number, + * finishNode (node: acorn.Node, type: string): acorn.Node, + * finishNodeAt (node: acorn.Node, type: string, pos: number, loc: acorn.Position): acorn.Node, + * parseTopLevel (node: acorn.Node): acorn.Node, + * nextToken (): void + * } + * }} AcornJsxParserCtorEnhanced + */ + +/* eslint-enable jsdoc/valid-types -- Bug in older versions */ diff --git a/node_modules/espree/package.json b/node_modules/espree/package.json new file mode 100644 index 0000000000000000000000000000000000000000..471f5bc579ed503d1d1866b028bd97f513c5d7db --- /dev/null +++ b/node_modules/espree/package.json @@ -0,0 +1,70 @@ +{ + "name": "espree", + "description": "An Esprima-compatible JavaScript parser built on Acorn", + "author": "Nicholas C. Zakas ", + "homepage": "https://github.com/eslint/js/blob/main/packages/espree/README.md", + "main": "dist/espree.cjs", + "types": "./dist/espree.d.cts", + "type": "module", + "exports": { + ".": { + "types": { + "import": "./dist/espree.d.ts", + "require": "./dist/espree.d.cts" + }, + "import": "./espree.js", + "require": "./dist/espree.cjs", + "default": "./dist/espree.cjs" + }, + "./package.json": "./package.json" + }, + "version": "11.2.0", + "files": [ + "lib", + "dist", + "espree.js" + ], + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/js.git", + "directory": "packages/espree" + }, + "bugs": { + "url": "https://github.com/eslint/js/issues" + }, + "funding": "https://opencollective.com/eslint", + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.16.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^5.0.1" + }, + "devDependencies": { + "shelljs": "^0.8.5", + "tsd": "^0.33.0" + }, + "keywords": [ + "ast", + "ecmascript", + "javascript", + "parser", + "syntax", + "acorn" + ], + "scripts": { + "build": "rollup -c rollup.config.js && npm run build:types && node -e \"fs.rmSync('dist/lib', { recursive: true })\"", + "build:debug": "npm run build -- -m", + "build:docs": "node tools/sync-docs.js", + "build:types": "tsc && tsc -p tsconfig-cjs.json", + "lint:types": "attw --pack", + "pretest": "npm run build", + "test": "npm run test:types && npm run test:cjs && npm run test:esm", + "test:cjs": "mocha --color --reporter progress --timeout 30000 \"tests/**/*.test.cjs\"", + "test:esm": "c8 mocha --color --reporter progress --timeout 30000 \"tests/**/*.test.js\"", + "test:types": "tsd --typings dist/espree.d.ts" + }, + "sideEffects": false +} diff --git a/node_modules/esquery/README.md b/node_modules/esquery/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6d5c39fda84e6e654033aca4f9acb54e54b8ea27 --- /dev/null +++ b/node_modules/esquery/README.md @@ -0,0 +1,27 @@ +ESQuery is a library for querying the AST output by Esprima for patterns of syntax using a CSS style selector system. Check out the demo: + +[demo](https://estools.github.io/esquery/) + +The following selectors are supported: +* AST node type: `ForStatement` +* [wildcard](http://dev.w3.org/csswg/selectors4/#universal-selector): `*` +* [attribute existence](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr]` +* [attribute value](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr="foo"]` or `[attr=123]` +* attribute regex: `[attr=/foo.*/]` or (with flags) `[attr=/foo.*/is]` +* attribute conditions: `[attr!="foo"]`, `[attr>2]`, `[attr<3]`, `[attr>=2]`, or `[attr<=3]` +* nested attribute: `[attr.level2="foo"]` +* field: `FunctionDeclaration > Identifier.id` +* [First](http://dev.w3.org/csswg/selectors4/#the-first-child-pseudo) or [last](http://dev.w3.org/csswg/selectors4/#the-last-child-pseudo) child: `:first-child` or `:last-child` +* [nth-child](http://dev.w3.org/csswg/selectors4/#the-nth-child-pseudo) (no ax+b support): `:nth-child(2)` +* [nth-last-child](http://dev.w3.org/csswg/selectors4/#the-nth-last-child-pseudo) (no ax+b support): `:nth-last-child(1)` +* [descendant](http://dev.w3.org/csswg/selectors4/#descendant-combinators): `ancestor descendant` +* [child](http://dev.w3.org/csswg/selectors4/#child-combinators): `parent > child` +* [following sibling](http://dev.w3.org/csswg/selectors4/#general-sibling-combinators): `node ~ sibling` +* [adjacent sibling](http://dev.w3.org/csswg/selectors4/#adjacent-sibling-combinators): `node + adjacent` +* [negation](http://dev.w3.org/csswg/selectors4/#negation-pseudo): `:not(ForStatement)` +* [has](https://drafts.csswg.org/selectors-4/#has-pseudo): `:has(ForStatement)`, `:has(> ForStatement)` +* [matches-any](http://dev.w3.org/csswg/selectors4/#matches): `:is([attr] > :first-child, :last-child)` +* [subject indicator](http://dev.w3.org/csswg/selectors4/#subject): `!IfStatement > [name="foo"]` +* class of AST node: `:statement`, `:expression`, `:declaration`, `:function`, or `:pattern` + +[![Build Status](https://travis-ci.org/estools/esquery.png?branch=master)](https://travis-ci.org/estools/esquery) diff --git a/node_modules/esquery/license.txt b/node_modules/esquery/license.txt new file mode 100644 index 0000000000000000000000000000000000000000..52f915e2688a40f34e1fa073aec37e43b9c5c1d6 --- /dev/null +++ b/node_modules/esquery/license.txt @@ -0,0 +1,24 @@ +Copyright (c) 2013, Joel Feenstra +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 ESQuery 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 JOEL FEENSTRA 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. diff --git a/node_modules/esquery/package.json b/node_modules/esquery/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b494042b776ec036dcc0ee99581273d72d0580d7 --- /dev/null +++ b/node_modules/esquery/package.json @@ -0,0 +1,78 @@ +{ + "name": "esquery", + "version": "1.7.0", + "author": "Joel Feenstra ", + "contributors": [], + "description": "A query library for ECMAScript AST using a CSS selector like query language.", + "main": "dist/esquery.min.js", + "module": "dist/esquery.esm.min.js", + "files": [ + "dist/*.js", + "dist/*.map", + "parser.js", + "license.txt", + "README.md" + ], + "nyc": { + "branches": 100, + "lines": 100, + "functions": 100, + "statements": 100, + "reporter": [ + "html", + "text" + ], + "exclude": [ + "parser.js", + "dist", + "tests" + ] + }, + "scripts": { + "prepublishOnly": "npm run build && npm test", + "build:parser": "rm parser.js && pegjs --cache --format umd -o \"parser.js\" \"grammar.pegjs\"", + "build:browser": "rollup -c", + "build": "npm run build:parser && npm run build:browser", + "mocha": "mocha --require chai/register-assert --require @babel/register tests", + "test": "nyc npm run mocha && npm run lint", + "test:ci": "npm run mocha", + "lint": "eslint ." + }, + "repository": { + "type": "git", + "url": "https://github.com/estools/esquery.git" + }, + "bugs": "https://github.com/estools/esquery/issues", + "homepage": "https://github.com/estools/esquery/", + "keywords": [ + "ast", + "ecmascript", + "javascript", + "query" + ], + "devDependencies": { + "@babel/core": "^7.9.0", + "@babel/preset-env": "^7.9.5", + "@babel/register": "^7.9.0", + "@rollup/plugin-commonjs": "^11.1.0", + "@rollup/plugin-json": "^4.0.2", + "@rollup/plugin-node-resolve": "^7.1.3", + "babel-plugin-transform-es2017-object-entries": "0.0.5", + "chai": "4.2.0", + "eslint": "^6.8.0", + "esprima": "~4.0.1", + "mocha": "7.1.1", + "nyc": "^15.0.1", + "pegjs": "~0.10.0", + "rollup": "^1.32.1", + "rollup-plugin-babel": "^4.4.0", + "rollup-plugin-terser": "^5.3.0" + }, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10" + }, + "dependencies": { + "estraverse": "^5.1.0" + } +} diff --git a/node_modules/esquery/parser.js b/node_modules/esquery/parser.js new file mode 100644 index 0000000000000000000000000000000000000000..c6fd7419e6959566fbeb2967a7c1b6ee69e4a730 --- /dev/null +++ b/node_modules/esquery/parser.js @@ -0,0 +1,2941 @@ +/* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ +(function(root, factory) { + if (typeof define === "function" && define.amd) { + define([], factory); + } else if (typeof module === "object" && module.exports) { + module.exports = factory(); + } +})(this, function() { + "use strict"; + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + + peg$subclass(peg$SyntaxError, Error); + + peg$SyntaxError.buildMessage = function(expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + + "class": function(expectation) { + var escapedParts = "", + i; + + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array + ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) + : classEscape(expectation.parts[i]); + } + + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + + any: function(expectation) { + return "any character"; + }, + + end: function(expectation) { + return "end of input"; + }, + + other: function(expectation) { + return expectation.description; + } + }; + + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + + function literalEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function classEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/\]/g, '\\]') + .replace(/\^/g, '\\^') + .replace(/-/g, '\\-') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, j; + + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); + } + + descriptions.sort(); + + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + + switch (descriptions.length) { + case 1: + return descriptions[0]; + + case 2: + return descriptions[0] + " or " + descriptions[1]; + + default: + return descriptions.slice(0, -1).join(", ") + + ", or " + + descriptions[descriptions.length - 1]; + } + } + + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + + var peg$FAILED = {}, + + peg$startRuleFunctions = { start: peg$parsestart }, + peg$startRuleFunction = peg$parsestart, + + peg$c0 = function(ss) { + return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss }; + }, + peg$c1 = function() { return void 0; }, + peg$c2 = " ", + peg$c3 = peg$literalExpectation(" ", false), + peg$c4 = /^[^ [\],():#!=><~+.]/, + peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false), + peg$c6 = function(i) { return i.join(''); }, + peg$c7 = ">", + peg$c8 = peg$literalExpectation(">", false), + peg$c9 = function() { return 'child'; }, + peg$c10 = "~", + peg$c11 = peg$literalExpectation("~", false), + peg$c12 = function() { return 'sibling'; }, + peg$c13 = "+", + peg$c14 = peg$literalExpectation("+", false), + peg$c15 = function() { return 'adjacent'; }, + peg$c16 = function() { return 'descendant'; }, + peg$c17 = ",", + peg$c18 = peg$literalExpectation(",", false), + peg$c19 = function(s, ss) { + return [s].concat(ss.map(function (s) { return s[3]; })); + }, + peg$c20 = function(op, s) { + if (!op) return s; + return { type: op, left: { type: 'exactNode' }, right: s }; + }, + peg$c21 = function(a, ops) { + return ops.reduce(function (memo, rhs) { + return { type: rhs[0], left: memo, right: rhs[1] }; + }, a); + }, + peg$c22 = "!", + peg$c23 = peg$literalExpectation("!", false), + peg$c24 = function(subject, as) { + const b = as.length === 1 ? as[0] : { type: 'compound', selectors: as }; + if(subject) b.subject = true; + return b; + }, + peg$c25 = "*", + peg$c26 = peg$literalExpectation("*", false), + peg$c27 = function(a) { return { type: 'wildcard', value: a }; }, + peg$c28 = "#", + peg$c29 = peg$literalExpectation("#", false), + peg$c30 = function(i) { return { type: 'identifier', value: i }; }, + peg$c31 = "[", + peg$c32 = peg$literalExpectation("[", false), + peg$c33 = "]", + peg$c34 = peg$literalExpectation("]", false), + peg$c35 = function(v) { return v; }, + peg$c36 = /^[>", "<", "!"], false, false), + peg$c38 = "=", + peg$c39 = peg$literalExpectation("=", false), + peg$c40 = function(a) { return (a || '') + '='; }, + peg$c41 = /^[><]/, + peg$c42 = peg$classExpectation([">", "<"], false, false), + peg$c43 = ".", + peg$c44 = peg$literalExpectation(".", false), + peg$c45 = function(a, as) { + return [].concat.apply([a], as).join(''); + }, + peg$c46 = function(name, op, value) { + return { type: 'attribute', name: name, operator: op, value: value }; + }, + peg$c47 = function(name) { return { type: 'attribute', name: name }; }, + peg$c48 = "\"", + peg$c49 = peg$literalExpectation("\"", false), + peg$c50 = /^[^\\"]/, + peg$c51 = peg$classExpectation(["\\", "\""], true, false), + peg$c52 = "\\", + peg$c53 = peg$literalExpectation("\\", false), + peg$c54 = peg$anyExpectation(), + peg$c55 = function(a, b) { return a + b; }, + peg$c56 = function(d) { + return { type: 'literal', value: strUnescape(d.join('')) }; + }, + peg$c57 = "'", + peg$c58 = peg$literalExpectation("'", false), + peg$c59 = /^[^\\']/, + peg$c60 = peg$classExpectation(["\\", "'"], true, false), + peg$c61 = /^[0-9]/, + peg$c62 = peg$classExpectation([["0", "9"]], false, false), + peg$c63 = function(a, b) { + // Can use `a.flat().join('')` once supported + const leadingDecimals = a ? [].concat.apply([], a).join('') : ''; + return { type: 'literal', value: parseFloat(leadingDecimals + b.join('')) }; + }, + peg$c64 = function(i) { return { type: 'literal', value: i }; }, + peg$c65 = "type(", + peg$c66 = peg$literalExpectation("type(", false), + peg$c67 = /^[^ )]/, + peg$c68 = peg$classExpectation([" ", ")"], true, false), + peg$c69 = ")", + peg$c70 = peg$literalExpectation(")", false), + peg$c71 = function(t) { return { type: 'type', value: t.join('') }; }, + peg$c72 = /^[imsu]/, + peg$c73 = peg$classExpectation(["i", "m", "s", "u"], false, false), + peg$c74 = "/", + peg$c75 = peg$literalExpectation("/", false), + peg$c76 = function(pattern, flgs) { + return { + type: 'regexp', value: new RegExp(pattern.join(''), flgs ? flgs.join('') : '') + }; + }, + peg$c77 = /^[^\]\\]/, + peg$c78 = peg$classExpectation(["]", "\\"], true, false), + peg$c79 = function(cs) { return '[' + cs.join('') + ']'; }, + peg$c80 = function(a) { return '\\' + a; }, + peg$c81 = /^[^\/\\[]/, + peg$c82 = peg$classExpectation(["/", "\\", "["], true, false), + peg$c83 = function(cs) { return cs.join(''); }, + peg$c84 = function(i, is) { + return { type: 'field', name: is.reduce(function(memo, p){ return memo + p[0] + p[1]; }, i)}; + }, + peg$c85 = ":not(", + peg$c86 = peg$literalExpectation(":not(", false), + peg$c87 = function(ss) { return { type: 'not', selectors: ss }; }, + peg$c88 = ":matches(", + peg$c89 = peg$literalExpectation(":matches(", false), + peg$c90 = function(ss) { return { type: 'matches', selectors: ss }; }, + peg$c91 = ":is(", + peg$c92 = peg$literalExpectation(":is(", false), + peg$c93 = ":has(", + peg$c94 = peg$literalExpectation(":has(", false), + peg$c95 = function(ss) { return { type: 'has', selectors: ss }; }, + peg$c96 = ":first-child", + peg$c97 = peg$literalExpectation(":first-child", false), + peg$c98 = function() { return nth(1); }, + peg$c99 = ":last-child", + peg$c100 = peg$literalExpectation(":last-child", false), + peg$c101 = function() { return nthLast(1); }, + peg$c102 = ":nth-child(", + peg$c103 = peg$literalExpectation(":nth-child(", false), + peg$c104 = function(n) { return nth(parseInt(n.join(''), 10)); }, + peg$c105 = ":nth-last-child(", + peg$c106 = peg$literalExpectation(":nth-last-child(", false), + peg$c107 = function(n) { return nthLast(parseInt(n.join(''), 10)); }, + peg$c108 = ":", + peg$c109 = peg$literalExpectation(":", false), + peg$c110 = function(c) { + return { type: 'class', name: c }; + }, + + peg$currPos = 0, + peg$savedPos = 0, + peg$posDetailsCache = [{ line: 1, column: 1 }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$resultsCache = {}, + + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$savedPos, peg$currPos); + } + + function location() { + return peg$computeLocation(peg$savedPos, peg$currPos); + } + + function expected(description, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) + + throw peg$buildStructuredError( + [peg$otherExpectation(description)], + input.substring(peg$savedPos, peg$currPos), + location + ); + } + + function error(message, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) + + throw peg$buildSimpleError(message, location); + } + + function peg$literalExpectation(text, ignoreCase) { + return { type: "literal", text: text, ignoreCase: ignoreCase }; + } + + function peg$classExpectation(parts, inverted, ignoreCase) { + return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; + } + + function peg$anyExpectation() { + return { type: "any" }; + } + + function peg$endExpectation() { + return { type: "end" }; + } + + function peg$otherExpectation(description) { + return { type: "other", description: description }; + } + + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], p; + + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; + } + + p++; + } + + peg$posDetailsCache[pos] = details; + return details; + } + } + + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + + peg$maxFailExpected.push(expected); + } + + function peg$buildSimpleError(message, location) { + return new peg$SyntaxError(message, null, null, location); + } + + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError( + peg$SyntaxError.buildMessage(expected, found), + expected, + found, + location + ); + } + + function peg$parsestart() { + var s0, s1, s2, s3; + + var key = peg$currPos * 36 + 0, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s2 = peg$parseselectors(); + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c0(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c1(); + } + s0 = s1; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parse_() { + var s0, s1; + + var key = peg$currPos * 36 + 1, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = []; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c3); } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c3); } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseidentifierName() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 2, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c5); } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c5); } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c6(s1); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsebinaryOp() { + var s0, s1, s2, s3; + + var key = peg$currPos * 36 + 3, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c9(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c10; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c11); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c12(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c13; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c14); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c15(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c3); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c16(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsehasSelectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + var key = peg$currPos * 36 + 4, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsehasSelector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseselectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + var key = peg$currPos * 36 + 5, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseselector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsehasSelector() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 6, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsebinaryOp(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseselector(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c20(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseselector() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 7, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsesequence(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c21(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesequence() { + var s0, s1, s2, s3; + + var key = peg$currPos * 36 + 8, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c23); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseatom(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseatom(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c24(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseatom() { + var s0; + + var key = peg$currPos * 36 + 9, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$parsewildcard(); + if (s0 === peg$FAILED) { + s0 = peg$parseidentifier(); + if (s0 === peg$FAILED) { + s0 = peg$parseattr(); + if (s0 === peg$FAILED) { + s0 = peg$parsefield(); + if (s0 === peg$FAILED) { + s0 = peg$parsenegation(); + if (s0 === peg$FAILED) { + s0 = peg$parsematches(); + if (s0 === peg$FAILED) { + s0 = peg$parseis(); + if (s0 === peg$FAILED) { + s0 = peg$parsehas(); + if (s0 === peg$FAILED) { + s0 = peg$parsefirstChild(); + if (s0 === peg$FAILED) { + s0 = peg$parselastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthLastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parseclass(); + } + } + } + } + } + } + } + } + } + } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsewildcard() { + var s0, s1; + + var key = peg$currPos * 36 + 10, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 42) { + s1 = peg$c25; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c26); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c27(s1); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseidentifier() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 11, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c28; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c29); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c30(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattr() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 12, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrValue(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c33; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c34); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c35(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrOps() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 13, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (peg$c36.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + if (peg$c41.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c42); } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrEqOps() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 14, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c23); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrName() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 15, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c45(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrValue() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 16, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrEqOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetype(); + if (s5 === peg$FAILED) { + s5 = peg$parseregex(); + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsestring(); + if (s5 === peg$FAILED) { + s5 = peg$parsenumber(); + if (s5 === peg$FAILED) { + s5 = peg$parsepath(); + } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c47(s1); + } + s0 = s1; + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 17, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c48; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c49); } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c51); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c51); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c48; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c49); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c57; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c58); } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c60); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c60); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c57; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c58); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenumber() { + var s0, s1, s2, s3; + + var key = peg$currPos * 36 + 18, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c43; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c63(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsepath() { + var s0, s1; + + var key = peg$currPos * 36 + 19, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c64(s1); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetype() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 20, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c65) { + s1 = peg$c65; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c66); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c68); } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c68); } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c71(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseflags() { + var s0, s1; + + var key = peg$currPos * 36 + 21, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = []; + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + } + } else { + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseregex() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 36 + 22, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c74; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c75); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsere_character_class(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_chars(); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsere_character_class(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_chars(); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s3 = peg$c74; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c75); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseflags(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c76(s2, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsere_character_class() { + var s0, s1, s2, s3; + + var key = peg$currPos * 36 + 23, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c77.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c77.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c33; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c34); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c79(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsere_escape() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 24, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c52; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c80(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsere_chars() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 25, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + if (peg$c81.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c82); } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c81.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c82); } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c83(s1); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefield() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 36 + 26, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c43; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c84(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenegation() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 27, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c85) { + s1 = peg$c85; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c86); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c87(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsematches() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 28, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c88) { + s1 = peg$c88; + peg$currPos += 9; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c89); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c90(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseis() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 29, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c91) { + s1 = peg$c91; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c92); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c90(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsehas() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 30, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c93) { + s1 = peg$c93; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c94); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehasSelectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c95(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefirstChild() { + var s0, s1; + + var key = peg$currPos * 36 + 31, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 12) === peg$c96) { + s1 = peg$c96; + peg$currPos += 12; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c97); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c98(); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parselastChild() { + var s0, s1; + + var key = peg$currPos * 36 + 32, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c99) { + s1 = peg$c99; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c100); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c101(); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenthChild() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 33, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c102) { + s1 = peg$c102; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c104(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenthLastChild() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 34, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 16) === peg$c105) { + s1 = peg$c105; + peg$currPos += 16; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c106); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c107(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseclass() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 35, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c108; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c109); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c110(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + + function nth(n) { return { type: 'nth-child', index: { type: 'literal', value: n } }; } + function nthLast(n) { return { type: 'nth-last-child', index: { type: 'literal', value: n } }; } + function strUnescape(s) { + return s.replace(/\\(.)/g, function(match, ch) { + switch(ch) { + case 'b': return '\b'; + case 'f': return '\f'; + case 'n': return '\n'; + case 'r': return '\r'; + case 't': return '\t'; + case 'v': return '\v'; + default: return ch; + } + }); + } + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + + throw peg$buildStructuredError( + peg$maxFailExpected, + peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, + peg$maxFailPos < input.length + ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) + : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) + ); + } + } + + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; +}); diff --git a/node_modules/esrecurse/.babelrc b/node_modules/esrecurse/.babelrc new file mode 100644 index 0000000000000000000000000000000000000000..a0765e185d3b6a76f50929c6e2482e3aa4526343 --- /dev/null +++ b/node_modules/esrecurse/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["es2015"] +} diff --git a/node_modules/esrecurse/README.md b/node_modules/esrecurse/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ffea6b434a4a633020ae0c35c729772069be0f16 --- /dev/null +++ b/node_modules/esrecurse/README.md @@ -0,0 +1,171 @@ +### Esrecurse [![Build Status](https://travis-ci.org/estools/esrecurse.svg?branch=master)](https://travis-ci.org/estools/esrecurse) + +Esrecurse ([esrecurse](https://github.com/estools/esrecurse)) is +[ECMAScript](https://www.ecma-international.org/publications/standards/Ecma-262.htm) +recursive traversing functionality. + +### Example Usage + +The following code will output all variables declared at the root of a file. + +```javascript +esrecurse.visit(ast, { + XXXStatement: function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); + } +}); +``` + +We can use `Visitor` instance. + +```javascript +var visitor = new esrecurse.Visitor({ + XXXStatement: function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); + } +}); + +visitor.visit(ast); +``` + +We can inherit `Visitor` instance easily. + +```javascript +class Derived extends esrecurse.Visitor { + constructor() + { + super(null); + } + + XXXStatement(node) { + } +} +``` + +```javascript +function DerivedVisitor() { + esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); +} +util.inherits(DerivedVisitor, esrecurse.Visitor); +DerivedVisitor.prototype.XXXStatement = function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); +}; +``` + +And you can invoke default visiting operation inside custom visit operation. + +```javascript +function DerivedVisitor() { + esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); +} +util.inherits(DerivedVisitor, esrecurse.Visitor); +DerivedVisitor.prototype.XXXStatement = function (node) { + // do something... + this.visitChildren(node); +}; +``` + +The `childVisitorKeys` option does customize the behaviour of `this.visitChildren(node)`. +We can use user-defined node types. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +esrecurse.visit( + ast, + { + Literal: function (node) { + // do something... + } + }, + { + // Extending the existing traversing rules. + childVisitorKeys: { + // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] + TestExpression: ['argument'] + } + } +); +``` + +We can use the `fallback` option as well. +If the `fallback` option is `"iteration"`, `esrecurse` would visit all enumerable properties of unknown nodes. +Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). + +```javascript +esrecurse.visit( + ast, + { + Literal: function (node) { + // do something... + } + }, + { + fallback: 'iteration' + } +); +``` + +If the `fallback` option is a function, `esrecurse` calls this function to determine the enumerable properties of unknown nodes. +Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). + +```javascript +esrecurse.visit( + ast, + { + Literal: function (node) { + // do something... + } + }, + { + fallback: function (node) { + return Object.keys(node).filter(function(key) { + return key !== 'argument' + }); + } + } +); +``` + +### License + +Copyright (C) 2014 [Yusuke Suzuki](https://github.com/Constellation) + (twitter: [@Constellation](https://twitter.com/Constellation)) and other contributors. + +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. + +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 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. diff --git a/node_modules/esrecurse/esrecurse.js b/node_modules/esrecurse/esrecurse.js new file mode 100644 index 0000000000000000000000000000000000000000..15d57dfd0218f66036a7cb5c5fe8e18c26d82267 --- /dev/null +++ b/node_modules/esrecurse/esrecurse.js @@ -0,0 +1,117 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + 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. + + 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 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. +*/ +(function () { + 'use strict'; + + var estraverse = require('estraverse'); + + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + + function isProperty(nodeType, key) { + return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties'; + } + + function Visitor(visitor, options) { + options = options || {}; + + this.__visitor = visitor || this; + this.__childVisitorKeys = options.childVisitorKeys + ? Object.assign({}, estraverse.VisitorKeys, options.childVisitorKeys) + : estraverse.VisitorKeys; + if (options.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof options.fallback === 'function') { + this.__fallback = options.fallback; + } + } + + /* Default method for visiting children. + * When you need to call default visiting operation inside custom visiting + * operation, you can use it with `this.visitChildren(node)`. + */ + Visitor.prototype.visitChildren = function (node) { + var type, children, i, iz, j, jz, child; + + if (node == null) { + return; + } + + type = node.type || estraverse.Syntax.Property; + + children = this.__childVisitorKeys[type]; + if (!children) { + if (this.__fallback) { + children = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + type + '.'); + } + } + + for (i = 0, iz = children.length; i < iz; ++i) { + child = node[children[i]]; + if (child) { + if (Array.isArray(child)) { + for (j = 0, jz = child.length; j < jz; ++j) { + if (child[j]) { + if (isNode(child[j]) || isProperty(type, children[i])) { + this.visit(child[j]); + } + } + } + } else if (isNode(child)) { + this.visit(child); + } + } + } + }; + + /* Dispatching node. */ + Visitor.prototype.visit = function (node) { + var type; + + if (node == null) { + return; + } + + type = node.type || estraverse.Syntax.Property; + if (this.__visitor[type]) { + this.__visitor[type].call(this, node); + return; + } + this.visitChildren(node); + }; + + exports.version = require('./package.json').version; + exports.Visitor = Visitor; + exports.visit = function (node, visitor, options) { + var v = new Visitor(visitor, options); + v.visit(node); + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esrecurse/gulpfile.babel.js b/node_modules/esrecurse/gulpfile.babel.js new file mode 100644 index 0000000000000000000000000000000000000000..aa881c9c3eaae5fac04467363abaac9e856bffde --- /dev/null +++ b/node_modules/esrecurse/gulpfile.babel.js @@ -0,0 +1,92 @@ +// Copyright (C) 2014 Yusuke Suzuki +// +// 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. +// +// 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 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. + +import gulp from 'gulp'; +import mocha from 'gulp-mocha'; +import eslint from 'gulp-eslint'; +import minimist from 'minimist'; +import git from 'gulp-git'; +import bump from 'gulp-bump'; +import filter from 'gulp-filter'; +import tagVersion from 'gulp-tag-version'; +import 'babel-register'; + +const SOURCE = [ + '*.js' +]; + +let ESLINT_OPTION = { + parser: 'babel-eslint', + parserOptions: { + 'sourceType': 'module' + }, + rules: { + 'quotes': 0, + 'eqeqeq': 0, + 'no-use-before-define': 0, + 'no-shadow': 0, + 'no-new': 0, + 'no-underscore-dangle': 0, + 'no-multi-spaces': 0, + 'no-native-reassign': 0, + 'no-loop-func': 0 + }, + env: { + 'node': true + } +}; + +gulp.task('test', function() { + let options = minimist(process.argv.slice(2), { + string: 'test', + default: { + test: 'test/*.js' + } + } + ); + return gulp.src(options.test).pipe(mocha({reporter: 'spec'})); +}); + +gulp.task('lint', () => + gulp.src(SOURCE) + .pipe(eslint(ESLINT_OPTION)) + .pipe(eslint.formatEach('stylish', process.stderr)) + .pipe(eslint.failOnError()) +); + +let inc = importance => + gulp.src(['./package.json']) + .pipe(bump({type: importance})) + .pipe(gulp.dest('./')) + .pipe(git.commit('Bumps package version')) + .pipe(filter('package.json')) + .pipe(tagVersion({ + prefix: '' + })) +; + +gulp.task('travis', [ 'lint', 'test' ]); +gulp.task('default', [ 'travis' ]); + +gulp.task('patch', [ ], () => inc('patch')); +gulp.task('minor', [ ], () => inc('minor')); +gulp.task('major', [ ], () => inc('major')); diff --git a/node_modules/esrecurse/package.json b/node_modules/esrecurse/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dec5b1bc1fd3ac43e74d7a575cc6bb98b453b2e3 --- /dev/null +++ b/node_modules/esrecurse/package.json @@ -0,0 +1,52 @@ +{ + "name": "esrecurse", + "description": "ECMAScript AST recursive visitor", + "homepage": "https://github.com/estools/esrecurse", + "main": "esrecurse.js", + "version": "4.3.0", + "engines": { + "node": ">=4.0" + }, + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "https://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/estools/esrecurse.git" + }, + "dependencies": { + "estraverse": "^5.2.0" + }, + "devDependencies": { + "babel-cli": "^6.24.1", + "babel-eslint": "^7.2.3", + "babel-preset-es2015": "^6.24.1", + "babel-register": "^6.24.1", + "chai": "^4.0.2", + "esprima": "^4.0.0", + "gulp": "^3.9.0", + "gulp-bump": "^2.7.0", + "gulp-eslint": "^4.0.0", + "gulp-filter": "^5.0.0", + "gulp-git": "^2.4.1", + "gulp-mocha": "^4.3.1", + "gulp-tag-version": "^1.2.1", + "jsdoc": "^3.3.0-alpha10", + "minimist": "^1.1.0" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "gulp travis", + "unit-test": "gulp test", + "lint": "gulp lint" + }, + "babel": { + "presets": [ + "es2015" + ] + } +} diff --git a/node_modules/estraverse/.jshintrc b/node_modules/estraverse/.jshintrc new file mode 100644 index 0000000000000000000000000000000000000000..f642dae7683b8155bd800db2aa3bfd574c2f7b64 --- /dev/null +++ b/node_modules/estraverse/.jshintrc @@ -0,0 +1,16 @@ +{ + "curly": true, + "eqeqeq": true, + "immed": true, + "eqnull": true, + "latedef": true, + "noarg": true, + "noempty": true, + "quotmark": "single", + "undef": true, + "unused": true, + "strict": true, + "trailing": true, + + "node": true +} diff --git a/node_modules/estraverse/LICENSE.BSD b/node_modules/estraverse/LICENSE.BSD new file mode 100644 index 0000000000000000000000000000000000000000..3e580c355a96e5ab8c4fb2ea4ada2d62287de41f --- /dev/null +++ b/node_modules/estraverse/LICENSE.BSD @@ -0,0 +1,19 @@ +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. + +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 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. diff --git a/node_modules/estraverse/README.md b/node_modules/estraverse/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ccd3377f3e9449547787f8f8f969def96e3f6d23 --- /dev/null +++ b/node_modules/estraverse/README.md @@ -0,0 +1,153 @@ +### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) + +Estraverse ([estraverse](http://github.com/estools/estraverse)) is +[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +traversal functions from [esmangle project](http://github.com/estools/esmangle). + +### Documentation + +You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). + +### Example Usage + +The following code will output all variables declared at the root of a file. + +```javascript +estraverse.traverse(ast, { + enter: function (node, parent) { + if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') + return estraverse.VisitorOption.Skip; + }, + leave: function (node, parent) { + if (node.type == 'VariableDeclarator') + console.log(node.id.name); + } +}); +``` + +We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. + +```javascript +estraverse.traverse(ast, { + enter: function (node) { + this.break(); + } +}); +``` + +And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. + +```javascript +result = estraverse.replace(tree, { + enter: function (node) { + // Replace it with replaced. + if (node.type === 'Literal') + return replaced; + } +}); +``` + +By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Extending the existing traversing rules. + keys: { + // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] + TestExpression: ['argument'] + } +}); +``` + +By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Iterating the child **nodes** of unknown nodes. + fallback: 'iteration' +}); +``` + +When `visitor.fallback` is a function, we can determine which keys to visit on each node. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Skip the `argument` property of each node + fallback: function(node) { + return Object.keys(node).filter(function(key) { + return key !== 'argument'; + }); + } +}); +``` + +### License + +Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +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. + +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 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. diff --git a/node_modules/estraverse/estraverse.js b/node_modules/estraverse/estraverse.js new file mode 100644 index 0000000000000000000000000000000000000000..f0d9af9b46bfebb6cda551de17beeb659c7a2f69 --- /dev/null +++ b/node_modules/estraverse/estraverse.js @@ -0,0 +1,805 @@ +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + 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. + + 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 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. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true*/ +(function clone(exports) { + 'use strict'; + + var Syntax, + VisitorOption, + VisitorKeys, + BREAK, + SKIP, + REMOVE; + + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ChainExpression: 'ChainExpression', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + PrivateIdentifier: 'PrivateIdentifier', + Program: 'Program', + Property: 'Property', + PropertyDefinition: 'PropertyDefinition', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ChainExpression: ['expression'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + PrivateIdentifier: [], + Program: ['body'], + Property: ['key', 'value'], + PropertyDefinition: ['key', 'value'], + RestElement: [ 'argument' ], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + function Controller() { } + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + + result = undefined; + + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; + + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } + + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; + + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + + function candidateExistsInLeaveList(leavelist, candidate) { + for (var i = leavelist.length - 1; i >= 0; --i) { + if (leavelist[i].node === candidate) { + return true; + } + } + return false; + } + + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || ret === SKIP) { + continue; + } + + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + + if (candidateExistsInLeaveList(leavelist, candidate[current2])) { + continue; + } + + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + if (candidateExistsInLeaveList(leavelist, candidate)) { + continue; + } + + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + + Controller.prototype.replace = function replace(root, visitor) { + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; + + function removeElem(element) { + var i, + key, + nextElem, + parent; + + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; + + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || target === SKIP) { + continue; + } + + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + + return outer.root; + }; + + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + function extendCommentRange(comment, tokens) { + var target; + + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + + comment.extendedRange = [comment.range[0], comment.range[1]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { return clone({}); }; + + return exports; +}(exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/estraverse/gulpfile.js b/node_modules/estraverse/gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..8772bbcca542a8dc43f1e08f55126ae24426f983 --- /dev/null +++ b/node_modules/estraverse/gulpfile.js @@ -0,0 +1,70 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + 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. + + 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 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. +*/ + +'use strict'; + +var gulp = require('gulp'), + git = require('gulp-git'), + bump = require('gulp-bump'), + filter = require('gulp-filter'), + tagVersion = require('gulp-tag-version'); + +var TEST = [ 'test/*.js' ]; +var POWERED = [ 'powered-test/*.js' ]; +var SOURCE = [ 'src/**/*.js' ]; + +/** + * Bumping version number and tagging the repository with it. + * Please read http://semver.org/ + * + * You can use the commands + * + * gulp patch # makes v0.1.0 -> v0.1.1 + * gulp feature # makes v0.1.1 -> v0.2.0 + * gulp release # makes v0.2.1 -> v1.0.0 + * + * To bump the version numbers accordingly after you did a patch, + * introduced a feature or made a backwards-incompatible release. + */ + +function inc(importance) { + // get all the files to bump version in + return gulp.src(['./package.json']) + // bump the version number in those files + .pipe(bump({type: importance})) + // save it back to filesystem + .pipe(gulp.dest('./')) + // commit the changed version number + .pipe(git.commit('Bumps package version')) + // read only one file to get the version number + .pipe(filter('package.json')) + // **tag it in the repository** + .pipe(tagVersion({ + prefix: '' + })); +} + +gulp.task('patch', [ ], function () { return inc('patch'); }) +gulp.task('minor', [ ], function () { return inc('minor'); }) +gulp.task('major', [ ], function () { return inc('major'); }) diff --git a/node_modules/estraverse/package.json b/node_modules/estraverse/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a86321850b4ec93883754e4de7b03227e1a9a379 --- /dev/null +++ b/node_modules/estraverse/package.json @@ -0,0 +1,40 @@ +{ + "name": "estraverse", + "description": "ECMAScript JS AST traversal functions", + "homepage": "https://github.com/estools/estraverse", + "main": "estraverse.js", + "version": "5.3.0", + "engines": { + "node": ">=4.0" + }, + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "http://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/estools/estraverse.git" + }, + "devDependencies": { + "babel-preset-env": "^1.6.1", + "babel-register": "^6.3.13", + "chai": "^2.1.1", + "espree": "^1.11.0", + "gulp": "^3.8.10", + "gulp-bump": "^0.2.2", + "gulp-filter": "^2.0.0", + "gulp-git": "^1.0.1", + "gulp-tag-version": "^1.3.0", + "jshint": "^2.5.6", + "mocha": "^2.1.0" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "npm run-script lint && npm run-script unit-test", + "lint": "jshint estraverse.js", + "unit-test": "mocha --compilers js:babel-register" + } +} diff --git a/node_modules/estree-util-is-identifier-name/index.d.ts b/node_modules/estree-util-is-identifier-name/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..11a112cd7257676975a76eae0a9ab9d504052e30 --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/index.d.ts @@ -0,0 +1,2 @@ +export type Options = import('./lib/index.js').Options; +export { cont, name, start } from "./lib/index.js"; diff --git a/node_modules/estree-util-is-identifier-name/index.js b/node_modules/estree-util-is-identifier-name/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a78d8fe5102db7f61d0cd7fd56bc2a749a863d54 --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/index.js @@ -0,0 +1,5 @@ +/** + * @typedef {import('./lib/index.js').Options} Options + */ + +export {cont, name, start} from './lib/index.js' diff --git a/node_modules/estree-util-is-identifier-name/lib/index.d.ts b/node_modules/estree-util-is-identifier-name/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe2cd4d1938017e8e3aea15ea7ce6e6869ff1433 --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/lib/index.d.ts @@ -0,0 +1,40 @@ +/** + * Checks if the given code point can start an identifier. + * + * @param {number | undefined} code + * Code point to check. + * @returns {boolean} + * Whether `code` can start an identifier. + */ +export function start(code: number | undefined): boolean; +/** + * Checks if the given code point can continue an identifier. + * + * @param {number | undefined} code + * Code point to check. + * @param {Options | null | undefined} [options] + * Configuration (optional). + * @returns {boolean} + * Whether `code` can continue an identifier. + */ +export function cont(code: number | undefined, options?: Options | null | undefined): boolean; +/** + * Checks if the given value is a valid identifier name. + * + * @param {string} name + * Identifier to check. + * @param {Options | null | undefined} [options] + * Configuration (optional). + * @returns {boolean} + * Whether `name` can be an identifier. + */ +export function name(name: string, options?: Options | null | undefined): boolean; +/** + * Configuration. + */ +export type Options = { + /** + * Support JSX identifiers (default: `false`). + */ + jsx?: boolean | null | undefined; +}; diff --git a/node_modules/estree-util-is-identifier-name/lib/index.js b/node_modules/estree-util-is-identifier-name/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d23d65dc7268113c1f28cb7b14d5961bc141f74b --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/lib/index.js @@ -0,0 +1,61 @@ +/** + * @typedef Options + * Configuration. + * @property {boolean | null | undefined} [jsx=false] + * Support JSX identifiers (default: `false`). + */ + +const startRe = /[$_\p{ID_Start}]/u +const contRe = /[$_\u{200C}\u{200D}\p{ID_Continue}]/u +const contReJsx = /[-$_\u{200C}\u{200D}\p{ID_Continue}]/u +const nameRe = /^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u +const nameReJsx = /^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u + +/** @type {Options} */ +const emptyOptions = {} + +/** + * Checks if the given code point can start an identifier. + * + * @param {number | undefined} code + * Code point to check. + * @returns {boolean} + * Whether `code` can start an identifier. + */ +// Note: `undefined` is supported so you can pass the result from `''.codePointAt`. +export function start(code) { + return code ? startRe.test(String.fromCodePoint(code)) : false +} + +/** + * Checks if the given code point can continue an identifier. + * + * @param {number | undefined} code + * Code point to check. + * @param {Options | null | undefined} [options] + * Configuration (optional). + * @returns {boolean} + * Whether `code` can continue an identifier. + */ +// Note: `undefined` is supported so you can pass the result from `''.codePointAt`. +export function cont(code, options) { + const settings = options || emptyOptions + const re = settings.jsx ? contReJsx : contRe + return code ? re.test(String.fromCodePoint(code)) : false +} + +/** + * Checks if the given value is a valid identifier name. + * + * @param {string} name + * Identifier to check. + * @param {Options | null | undefined} [options] + * Configuration (optional). + * @returns {boolean} + * Whether `name` can be an identifier. + */ +export function name(name, options) { + const settings = options || emptyOptions + const re = settings.jsx ? nameReJsx : nameRe + return re.test(name) +} diff --git a/node_modules/estree-util-is-identifier-name/license b/node_modules/estree-util-is-identifier-name/license new file mode 100644 index 0000000000000000000000000000000000000000..39372356c47d0f6e070ff62d84c69f4f5e8c16eb --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2020 Titus Wormer + +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. diff --git a/node_modules/estree-util-is-identifier-name/package.json b/node_modules/estree-util-is-identifier-name/package.json new file mode 100644 index 0000000000000000000000000000000000000000..463567c40a2a438e38fe17bd8f780551a7120ba4 --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/package.json @@ -0,0 +1,73 @@ +{ + "name": "estree-util-is-identifier-name", + "version": "3.0.0", + "description": "Check if something can be an ecmascript (javascript) identifier name", + "license": "MIT", + "keywords": [ + "estree", + "ast", + "ecmascript", + "javascript", + "tree", + "identifier", + "character" + ], + "repository": "syntax-tree/estree-util-is-identifier-name", + "bugs": "https://github.com/syntax-tree/estree-util-is-identifier-name/issues", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + }, + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "exports": "./index.js", + "files": [ + "lib/", + "index.d.ts", + "index.js" + ], + "devDependencies": { + "@types/node": "^20.0.0", + "c8": "^8.0.0", + "prettier": "^3.0.0", + "remark-cli": "^11.0.0", + "remark-preset-wooorm": "^9.0.0", + "type-coverage": "^2.0.0", + "typescript": "^5.0.0", + "xo": "^0.55.0" + }, + "scripts": { + "prepack": "npm run build && npm run format", + "build": "tsc --build --clean && tsc --build && type-coverage", + "format": "remark . -qfo && prettier . -w --log-level warn && xo --fix", + "test-api": "node --conditions development test.js", + "test-coverage": "c8 --100 --reporter lcov npm run test-api", + "test": "npm run build && npm run format && npm run test-coverage" + }, + "prettier": { + "bracketSpacing": false, + "semi": false, + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "none", + "useTabs": false + }, + "remarkConfig": { + "plugins": [ + "remark-preset-wooorm" + ] + }, + "typeCoverage": { + "atLeast": 100, + "detail": true, + "ignoreCatch": true, + "strict": true + }, + "xo": { + "prettier": true + } +} diff --git a/node_modules/estree-util-is-identifier-name/readme.md b/node_modules/estree-util-is-identifier-name/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..9dce944473c7e31723ba3271c6450383bae5783b --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/readme.md @@ -0,0 +1,225 @@ +# estree-util-is-identifier-name + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] +[![Sponsors][sponsors-badge]][collective] +[![Backers][backers-badge]][collective] +[![Chat][chat-badge]][chat] + +[estree][] utility to check if something can be an identifier. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`cont(code[, options])`](#contcode-options) + * [`name(name[, options])`](#namename-options) + * [`start(code)`](#startcode) + * [Options](#options) +* [Types](#types) +* [Compatibility](#compatibility) +* [Related](#related) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package is a utility that can be used to check if something can be an +identifier name. +For example, `a`, `_`, and `a1` are fine, but `1` and `-` are not. + +## When should I use this? + +You can use this utility when generating IDs from strings or parsing IDs. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install estree-util-is-identifier-name +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {cont, name, start} from 'https://esm.sh/estree-util-is-identifier-name@3' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {cont, name, start} from 'estree-util-is-identifier-name' + +name('$something69') // => true +name('69') // => false +name('var') // => true (this does not handle keywords) + +start(48) // => false (code point for `'0'`) +cont(48) // => true (code point for `'0'`) +``` + +## API + +This package exports the identifiers [`cont`][api-cont], +[`name`][api-name], and +[`start`][api-start]. +There is no default export. + +### `cont(code[, options])` + +Checks if the given code point can continue an identifier. + +###### Parameters + +* `code` (`number`) + — code point to check +* `options` ([`Options`][api-options], optional) + — configuration + +###### Returns + +Whether `code` can continue an identifier (`boolean`). + +### `name(name[, options])` + +Checks if the given value is a valid identifier name. + +###### Parameters + +* `name` (`string`) + — identifier to check +* `options` ([`Options`][api-options], optional) + — configuration + +###### Returns + +Whether `name` can be an identifier (`boolean`). + +### `start(code)` + +Checks if the given code point can start an identifier. + +###### Parameters + +* `code` (`number`) + — code point to check + +###### Returns + +Whether `code` can start an identifier (`boolean`). + +### Options + +Configuration (TypeScript type). + +###### Fields + +* `jsx` (`boolean`, default: `false`) + — support JSX identifiers. + +## Types + +This package is fully typed with [TypeScript][]. +It exports the additional type [`Options`][api-options]. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`estree-util-is-identifier-name@^3`, compatible with Node.js 16. + +## Related + +* [`goto-bus-stop/estree-is-identifier`](https://github.com/goto-bus-stop/estree-is-identifier) + — check if an AST node is an identifier + +## Contribute + +See [`contributing.md`][contributing] in [`syntax-tree/.github`][health] for +ways to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organization, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/syntax-tree/estree-util-is-identifier-name/workflows/main/badge.svg + +[build]: https://github.com/syntax-tree/estree-util-is-identifier-name/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/estree-util-is-identifier-name.svg + +[coverage]: https://codecov.io/github/syntax-tree/estree-util-is-identifier-name + +[downloads-badge]: https://img.shields.io/npm/dm/estree-util-is-identifier-name.svg + +[downloads]: https://www.npmjs.com/package/estree-util-is-identifier-name + +[size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=estree-util-is-identifier-name + +[size]: https://bundlejs.com/?q=estree-util-is-identifier-name + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[collective]: https://opencollective.com/unified + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/syntax-tree/unist/discussions + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[typescript]: https://www.typescriptlang.org + +[license]: license + +[author]: https://wooorm.com + +[health]: https://github.com/syntax-tree/.github + +[contributing]: https://github.com/syntax-tree/.github/blob/main/contributing.md + +[support]: https://github.com/syntax-tree/.github/blob/main/support.md + +[coc]: https://github.com/syntax-tree/.github/blob/main/code-of-conduct.md + +[estree]: https://github.com/estree/estree + +[api-cont]: #contcode-options + +[api-name]: #namename-options + +[api-start]: #startcode + +[api-options]: #options diff --git a/node_modules/estree-walker/LICENSE b/node_modules/estree-walker/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..63b62098eea9e1031659a145b1c6d752486ec0fe --- /dev/null +++ b/node_modules/estree-walker/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/contributors) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/estree-walker/README.md b/node_modules/estree-walker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d739d1bf1811736d657775bdfdd261801bc92809 --- /dev/null +++ b/node_modules/estree-walker/README.md @@ -0,0 +1,48 @@ +# estree-walker + +Simple utility for walking an [ESTree](https://github.com/estree/estree)-compliant AST, such as one generated by [acorn](https://github.com/marijnh/acorn). + + +## Installation + +```bash +npm i estree-walker +``` + + +## Usage + +```js +var walk = require('estree-walker').walk; +var acorn = require('acorn'); + +ast = acorn.parse(sourceCode, options); // https://github.com/acornjs/acorn + +walk(ast, { + enter(node, parent, prop, index) { + // some code happens + }, + leave(node, parent, prop, index) { + // some code happens + } +}); +``` + +Inside the `enter` function, calling `this.skip()` will prevent the node's children being walked, or the `leave` function (which is optional) being called. + +Call `this.replace(new_node)` in either `enter` or `leave` to replace the current node with a new one. + +Call `this.remove()` in either `enter` or `leave` to remove the current node. + +## Why not use estraverse? + +The ESTree spec is evolving to accommodate ES6/7. I've had a couple of experiences where [estraverse](https://github.com/estools/estraverse) was unable to handle an AST generated by recent versions of acorn, because it hard-codes visitor keys. + +estree-walker, by contrast, simply enumerates a node's properties to find child nodes (and child lists of nodes), and is therefore resistant to spec changes. It's also much smaller. (The performance, if you're wondering, is basically identical.) + +None of which should be taken as criticism of estraverse, which has more features and has been battle-tested in many more situations, and for which I'm very grateful. + + +## License + +MIT diff --git a/node_modules/estree-walker/package.json b/node_modules/estree-walker/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c9f54edd9f394c267429a4b1393d67df42fbbe45 --- /dev/null +++ b/node_modules/estree-walker/package.json @@ -0,0 +1,38 @@ +{ + "name": "estree-walker", + "description": "Traverse an ESTree-compliant AST", + "version": "3.0.3", + "private": false, + "author": "Rich Harris", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/Rich-Harris/estree-walker" + }, + "type": "module", + "module": "./src/index.js", + "exports": { + "./package.json": "./package.json", + ".": { + "types": "./types/index.d.ts", + "import": "./src/index.js" + } + }, + "types": "types/index.d.ts", + "scripts": { + "prepublishOnly": "tsc && npm test", + "test": "uvu test" + }, + "dependencies": { + "@types/estree": "^1.0.0" + }, + "devDependencies": { + "typescript": "^4.9.0", + "uvu": "^0.5.1" + }, + "files": [ + "src", + "types", + "README.md" + ] +} diff --git a/node_modules/estree-walker/src/async.js b/node_modules/estree-walker/src/async.js new file mode 100644 index 0000000000000000000000000000000000000000..f068c713c4cdb2e57a2e98829b75e0541d943b9d --- /dev/null +++ b/node_modules/estree-walker/src/async.js @@ -0,0 +1,152 @@ +import { WalkerBase } from './walker.js'; + +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => Promise} AsyncHandler + */ + +export class AsyncWalker extends WalkerBase { + /** + * + * @param {AsyncHandler} [enter] + * @param {AsyncHandler} [leave] + */ + constructor(enter, leave) { + super(); + + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {Node | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + + /** @type {AsyncHandler | undefined} */ + this.enter = enter; + + /** @type {AsyncHandler | undefined} */ + this.leave = leave; + } + + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Promise} + */ + async visit(node, parent, prop, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + + await this.enter.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const skipped = this.should_skip; + const removed = this.should_remove; + + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + + if (skipped) return node; + if (removed) return null; + } + + /** @type {keyof Node} */ + let key; + + for (key in node) { + /** @type {unknown} */ + const value = node[key]; + + if (value && typeof value === 'object') { + if (Array.isArray(value)) { + const nodes = /** @type {Array} */ (value); + for (let i = 0; i < nodes.length; i += 1) { + const item = nodes[i]; + if (isNode(item)) { + if (!(await this.visit(item, node, key, i))) { + // removed + i--; + } + } + } + } else if (isNode(value)) { + await this.visit(value, node, key, null); + } + } + } + + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + + await this.leave.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const removed = this.should_remove; + + this.replacement = _replacement; + this.should_remove = _should_remove; + + if (removed) return null; + } + } + + return node; + } +} + +/** + * Ducktype a node. + * + * @param {unknown} value + * @returns {value is Node} + */ +function isNode(value) { + return ( + value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string' + ); +} diff --git a/node_modules/estree-walker/src/index.js b/node_modules/estree-walker/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..933ea4f28ddb57cc53976aa5504d3ef39bbc0586 --- /dev/null +++ b/node_modules/estree-walker/src/index.js @@ -0,0 +1,34 @@ +import { SyncWalker } from './sync.js'; +import { AsyncWalker } from './async.js'; + +/** + * @typedef {import('estree').Node} Node + * @typedef {import('./sync.js').SyncHandler} SyncHandler + * @typedef {import('./async.js').AsyncHandler} AsyncHandler + */ + +/** + * @param {Node} ast + * @param {{ + * enter?: SyncHandler + * leave?: SyncHandler + * }} walker + * @returns {Node | null} + */ +export function walk(ast, { enter, leave }) { + const instance = new SyncWalker(enter, leave); + return instance.visit(ast, null); +} + +/** + * @param {Node} ast + * @param {{ + * enter?: AsyncHandler + * leave?: AsyncHandler + * }} walker + * @returns {Promise} + */ +export async function asyncWalk(ast, { enter, leave }) { + const instance = new AsyncWalker(enter, leave); + return await instance.visit(ast, null); +} diff --git a/node_modules/estree-walker/src/sync.js b/node_modules/estree-walker/src/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..171fb360a76998c7b0e10a4544715a1be095c267 --- /dev/null +++ b/node_modules/estree-walker/src/sync.js @@ -0,0 +1,152 @@ +import { WalkerBase } from './walker.js'; + +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => void} SyncHandler + */ + +export class SyncWalker extends WalkerBase { + /** + * + * @param {SyncHandler} [enter] + * @param {SyncHandler} [leave] + */ + constructor(enter, leave) { + super(); + + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {Node | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + + /** @type {SyncHandler | undefined} */ + this.enter = enter; + + /** @type {SyncHandler | undefined} */ + this.leave = leave; + } + + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Node | null} + */ + visit(node, parent, prop, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + + this.enter.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const skipped = this.should_skip; + const removed = this.should_remove; + + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + + if (skipped) return node; + if (removed) return null; + } + + /** @type {keyof Node} */ + let key; + + for (key in node) { + /** @type {unknown} */ + const value = node[key]; + + if (value && typeof value === 'object') { + if (Array.isArray(value)) { + const nodes = /** @type {Array} */ (value); + for (let i = 0; i < nodes.length; i += 1) { + const item = nodes[i]; + if (isNode(item)) { + if (!this.visit(item, node, key, i)) { + // removed + i--; + } + } + } + } else if (isNode(value)) { + this.visit(value, node, key, null); + } + } + } + + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + + this.leave.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const removed = this.should_remove; + + this.replacement = _replacement; + this.should_remove = _should_remove; + + if (removed) return null; + } + } + + return node; + } +} + +/** + * Ducktype a node. + * + * @param {unknown} value + * @returns {value is Node} + */ +function isNode(value) { + return ( + value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string' + ); +} diff --git a/node_modules/estree-walker/src/walker.js b/node_modules/estree-walker/src/walker.js new file mode 100644 index 0000000000000000000000000000000000000000..6dc6bd7bbe52ee4713bbfc89c25a8e884e1b205f --- /dev/null +++ b/node_modules/estree-walker/src/walker.js @@ -0,0 +1,61 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef {{ + * skip: () => void; + * remove: () => void; + * replace: (node: Node) => void; + * }} WalkerContext + */ + +export class WalkerBase { + constructor() { + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {Node | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + } + + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + * @param {Node} node + */ + replace(parent, prop, index, node) { + if (parent && prop) { + if (index != null) { + /** @type {Array} */ (parent[prop])[index] = node; + } else { + /** @type {Node} */ (parent[prop]) = node; + } + } + } + + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + */ + remove(parent, prop, index) { + if (parent && prop) { + if (index !== null && index !== undefined) { + /** @type {Array} */ (parent[prop]).splice(index, 1); + } else { + delete parent[prop]; + } + } + } +} diff --git a/node_modules/estree-walker/types/async.d.ts b/node_modules/estree-walker/types/async.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..db0825aa7bc81d386b07d4897636ad930ebe3bb5 --- /dev/null +++ b/node_modules/estree-walker/types/async.d.ts @@ -0,0 +1,36 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => Promise} AsyncHandler + */ +export class AsyncWalker extends WalkerBase { + /** + * + * @param {AsyncHandler} [enter] + * @param {AsyncHandler} [leave] + */ + constructor(enter?: AsyncHandler | undefined, leave?: AsyncHandler | undefined); + /** @type {AsyncHandler | undefined} */ + enter: AsyncHandler | undefined; + /** @type {AsyncHandler | undefined} */ + leave: AsyncHandler | undefined; + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Promise} + */ + visit(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Promise; +} +export type Node = import('estree').Node; +export type WalkerContext = import('./walker.js').WalkerContext; +export type AsyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => Promise; +import { WalkerBase } from "./walker.js"; diff --git a/node_modules/estree-walker/types/index.d.ts b/node_modules/estree-walker/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c25afed98bca5bb3bcffd542a532c121d182d4e1 --- /dev/null +++ b/node_modules/estree-walker/types/index.d.ts @@ -0,0 +1,32 @@ +/** + * @typedef {import('estree').Node} Node + * @typedef {import('./sync.js').SyncHandler} SyncHandler + * @typedef {import('./async.js').AsyncHandler} AsyncHandler + */ +/** + * @param {Node} ast + * @param {{ + * enter?: SyncHandler + * leave?: SyncHandler + * }} walker + * @returns {Node | null} + */ +export function walk(ast: Node, { enter, leave }: { + enter?: SyncHandler; + leave?: SyncHandler; +}): Node | null; +/** + * @param {Node} ast + * @param {{ + * enter?: AsyncHandler + * leave?: AsyncHandler + * }} walker + * @returns {Promise} + */ +export function asyncWalk(ast: Node, { enter, leave }: { + enter?: AsyncHandler; + leave?: AsyncHandler; +}): Promise; +export type Node = import('estree').Node; +export type SyncHandler = import('./sync.js').SyncHandler; +export type AsyncHandler = import('./async.js').AsyncHandler; diff --git a/node_modules/estree-walker/types/sync.d.ts b/node_modules/estree-walker/types/sync.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3612b7ff424a6a78edb67f8bb1738443fbabf2a7 --- /dev/null +++ b/node_modules/estree-walker/types/sync.d.ts @@ -0,0 +1,36 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => void} SyncHandler + */ +export class SyncWalker extends WalkerBase { + /** + * + * @param {SyncHandler} [enter] + * @param {SyncHandler} [leave] + */ + constructor(enter?: SyncHandler | undefined, leave?: SyncHandler | undefined); + /** @type {SyncHandler | undefined} */ + enter: SyncHandler | undefined; + /** @type {SyncHandler | undefined} */ + leave: SyncHandler | undefined; + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Node | null} + */ + visit(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Node | null; +} +export type Node = import('estree').Node; +export type WalkerContext = import('./walker.js').WalkerContext; +export type SyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => void; +import { WalkerBase } from "./walker.js"; diff --git a/node_modules/estree-walker/types/walker.d.ts b/node_modules/estree-walker/types/walker.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3fa29c193ab01bccf4c50495230f7c1a091c375 --- /dev/null +++ b/node_modules/estree-walker/types/walker.d.ts @@ -0,0 +1,39 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef {{ + * skip: () => void; + * remove: () => void; + * replace: (node: Node) => void; + * }} WalkerContext + */ +export class WalkerBase { + /** @type {boolean} */ + should_skip: boolean; + /** @type {boolean} */ + should_remove: boolean; + /** @type {Node | null} */ + replacement: Node | null; + /** @type {WalkerContext} */ + context: WalkerContext; + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + * @param {Node} node + */ + replace(parent: Parent | null | undefined, prop: keyof Parent | null | undefined, index: number | null | undefined, node: Node): void; + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + */ + remove(parent: Parent_1 | null | undefined, prop: keyof Parent_1 | null | undefined, index: number | null | undefined): void; +} +export type Node = import('estree').Node; +export type WalkerContext = { + skip: () => void; + remove: () => void; + replace: (node: Node) => void; +}; diff --git a/node_modules/esutils/LICENSE.BSD b/node_modules/esutils/LICENSE.BSD new file mode 100644 index 0000000000000000000000000000000000000000..3e580c355a96e5ab8c4fb2ea4ada2d62287de41f --- /dev/null +++ b/node_modules/esutils/LICENSE.BSD @@ -0,0 +1,19 @@ +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. + +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 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. diff --git a/node_modules/esutils/README.md b/node_modules/esutils/README.md new file mode 100644 index 0000000000000000000000000000000000000000..517526cfb99b972d9a9f34eecf6e8f4d34e77ede --- /dev/null +++ b/node_modules/esutils/README.md @@ -0,0 +1,174 @@ +### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils) +esutils ([esutils](http://github.com/estools/esutils)) is +utility box for ECMAScript language tools. + +### API + +### ast + +#### ast.isExpression(node) + +Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section +[11](https://es5.github.io/#x11). + +#### ast.isStatement(node) + +Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section +[12](https://es5.github.io/#x12). + +#### ast.isIterationStatement(node) + +Returns true if `node` is an IterationStatement as defined in ECMA262 edition +5.1 section [12.6](https://es5.github.io/#x12.6). + +#### ast.isSourceElement(node) + +Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 +section [14](https://es5.github.io/#x14). + +#### ast.trailingStatement(node) + +Returns `Statement?` if `node` has trailing `Statement`. +```js +if (cond) + consequent; +``` +When taking this `IfStatement`, returns `consequent;` statement. + +#### ast.isProblematicIfStatement(node) + +Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. +```js +{ + type: 'IfStatement', + consequent: { + type: 'WithStatement', + body: { + type: 'IfStatement', + consequent: {type: 'EmptyStatement'} + } + }, + alternate: {type: 'EmptyStatement'} +} +``` +The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. + + +### code + +#### code.isDecimalDigit(code) + +Return true if provided code is decimal digit. + +#### code.isHexDigit(code) + +Return true if provided code is hexadecimal digit. + +#### code.isOctalDigit(code) + +Return true if provided code is octal digit. + +#### code.isWhiteSpace(code) + +Return true if provided code is white space. White space characters are formally defined in ECMA262. + +#### code.isLineTerminator(code) + +Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. + +#### code.isIdentifierStart(code) + +Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. + +#### code.isIdentifierPart(code) + +Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. + +### keyword + +#### keyword.isKeywordES5(id, strict) + +Returns `true` if provided identifier string is a Keyword or Future Reserved Word +in ECMA262 edition 5.1. They are formally defined in ECMA262 sections +[7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), +respectively. If the `strict` flag is truthy, this function additionally checks whether +`id` is a Keyword or Future Reserved Word under strict mode. + +#### keyword.isKeywordES6(id, strict) + +Returns `true` if provided identifier string is a Keyword or Future Reserved Word +in ECMA262 edition 6. They are formally defined in ECMA262 sections +[11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and +[11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words), +respectively. If the `strict` flag is truthy, this function additionally checks whether +`id` is a Keyword or Future Reserved Word under strict mode. + +#### keyword.isReservedWordES5(id, strict) + +Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. +They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). +If the `strict` flag is truthy, this function additionally checks whether `id` +is a Reserved Word under strict mode. + +#### keyword.isReservedWordES6(id, strict) + +Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. +They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words). +If the `strict` flag is truthy, this function additionally checks whether `id` +is a Reserved Word under strict mode. + +#### keyword.isRestrictedWord(id) + +Returns `true` if provided identifier string is one of `eval` or `arguments`. +They are restricted in strict mode code throughout ECMA262 edition 5.1 and +in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors). + +#### keyword.isIdentifierNameES5(id) + +Return true if provided identifier string is an IdentifierName as specified in +ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). + +#### keyword.isIdentifierNameES6(id) + +Return true if provided identifier string is an IdentifierName as specified in +ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords). + +#### keyword.isIdentifierES5(id, strict) + +Return true if provided identifier string is an Identifier as specified in +ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` +flag is truthy, this function additionally checks whether `id` is an Identifier +under strict mode. + +#### keyword.isIdentifierES6(id, strict) + +Return true if provided identifier string is an Identifier as specified in +ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers). +If the `strict` flag is truthy, this function additionally checks whether `id` +is an Identifier under strict mode. + +### License + +Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +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. + +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 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. diff --git a/node_modules/esutils/lib/ast.js b/node_modules/esutils/lib/ast.js new file mode 100644 index 0000000000000000000000000000000000000000..8faadae1ce736d3766bd0f5cfb50e3d654851aad --- /dev/null +++ b/node_modules/esutils/lib/ast.js @@ -0,0 +1,144 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + 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. + + 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 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. +*/ + +(function () { + 'use strict'; + + function isExpression(node) { + if (node == null) { return false; } + switch (node.type) { + case 'ArrayExpression': + case 'AssignmentExpression': + case 'BinaryExpression': + case 'CallExpression': + case 'ConditionalExpression': + case 'FunctionExpression': + case 'Identifier': + case 'Literal': + case 'LogicalExpression': + case 'MemberExpression': + case 'NewExpression': + case 'ObjectExpression': + case 'SequenceExpression': + case 'ThisExpression': + case 'UnaryExpression': + case 'UpdateExpression': + return true; + } + return false; + } + + function isIterationStatement(node) { + if (node == null) { return false; } + switch (node.type) { + case 'DoWhileStatement': + case 'ForInStatement': + case 'ForStatement': + case 'WhileStatement': + return true; + } + return false; + } + + function isStatement(node) { + if (node == null) { return false; } + switch (node.type) { + case 'BlockStatement': + case 'BreakStatement': + case 'ContinueStatement': + case 'DebuggerStatement': + case 'DoWhileStatement': + case 'EmptyStatement': + case 'ExpressionStatement': + case 'ForInStatement': + case 'ForStatement': + case 'IfStatement': + case 'LabeledStatement': + case 'ReturnStatement': + case 'SwitchStatement': + case 'ThrowStatement': + case 'TryStatement': + case 'VariableDeclaration': + case 'WhileStatement': + case 'WithStatement': + return true; + } + return false; + } + + function isSourceElement(node) { + return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; + } + + function trailingStatement(node) { + switch (node.type) { + case 'IfStatement': + if (node.alternate != null) { + return node.alternate; + } + return node.consequent; + + case 'LabeledStatement': + case 'ForStatement': + case 'ForInStatement': + case 'WhileStatement': + case 'WithStatement': + return node.body; + } + return null; + } + + function isProblematicIfStatement(node) { + var current; + + if (node.type !== 'IfStatement') { + return false; + } + if (node.alternate == null) { + return false; + } + current = node.consequent; + do { + if (current.type === 'IfStatement') { + if (current.alternate == null) { + return true; + } + } + current = trailingStatement(current); + } while (current); + + return false; + } + + module.exports = { + isExpression: isExpression, + isStatement: isStatement, + isIterationStatement: isIterationStatement, + isSourceElement: isSourceElement, + isProblematicIfStatement: isProblematicIfStatement, + + trailingStatement: trailingStatement + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/lib/code.js b/node_modules/esutils/lib/code.js new file mode 100644 index 0000000000000000000000000000000000000000..23136af91f9fbc9233c1632a224cb55f8cf16354 --- /dev/null +++ b/node_modules/esutils/lib/code.js @@ -0,0 +1,135 @@ +/* + Copyright (C) 2013-2014 Yusuke Suzuki + Copyright (C) 2014 Ivan Nikulin + + 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. + + 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 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. +*/ + +(function () { + 'use strict'; + + var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; + + // See `tools/generate-identifier-regex.js`. + ES5Regex = { + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ + }; + + ES6Regex = { + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ + }; + + function isDecimalDigit(ch) { + return 0x30 <= ch && ch <= 0x39; // 0..9 + } + + function isHexDigit(ch) { + return 0x30 <= ch && ch <= 0x39 || // 0..9 + 0x61 <= ch && ch <= 0x66 || // a..f + 0x41 <= ch && ch <= 0x46; // A..F + } + + function isOctalDigit(ch) { + return ch >= 0x30 && ch <= 0x37; // 0..7 + } + + // 7.2 White Space + + NON_ASCII_WHITESPACES = [ + 0x1680, + 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, + 0x202F, 0x205F, + 0x3000, + 0xFEFF + ]; + + function isWhiteSpace(ch) { + return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || + ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; + } + + // 7.3 Line Terminators + + function isLineTerminator(ch) { + return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; + } + + // 7.6 Identifier Names and Identifiers + + function fromCodePoint(cp) { + if (cp <= 0xFFFF) { return String.fromCharCode(cp); } + var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); + var cu2 = String.fromCharCode(((cp - 0x10000) % 0x400) + 0xDC00); + return cu1 + cu2; + } + + IDENTIFIER_START = new Array(0x80); + for(ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_START[ch] = + ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + IDENTIFIER_PART = new Array(0x80); + for(ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_PART[ch] = + ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch >= 0x30 && ch <= 0x39 || // 0..9 + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + function isIdentifierStartES5(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES5(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + function isIdentifierStartES6(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES6(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + module.exports = { + isDecimalDigit: isDecimalDigit, + isHexDigit: isHexDigit, + isOctalDigit: isOctalDigit, + isWhiteSpace: isWhiteSpace, + isLineTerminator: isLineTerminator, + isIdentifierStartES5: isIdentifierStartES5, + isIdentifierPartES5: isIdentifierPartES5, + isIdentifierStartES6: isIdentifierStartES6, + isIdentifierPartES6: isIdentifierPartES6 + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/lib/keyword.js b/node_modules/esutils/lib/keyword.js new file mode 100644 index 0000000000000000000000000000000000000000..13c8c6a967caf0492670526699ecc3d0f653c368 --- /dev/null +++ b/node_modules/esutils/lib/keyword.js @@ -0,0 +1,165 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + 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. + + 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 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. +*/ + +(function () { + 'use strict'; + + var code = require('./code'); + + function isStrictModeReservedWordES6(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'let': + return true; + default: + return false; + } + } + + function isKeywordES5(id, strict) { + // yield should not be treated as keyword under non-strict mode. + if (!strict && id === 'yield') { + return false; + } + return isKeywordES6(id, strict); + } + + function isKeywordES6(id, strict) { + if (strict && isStrictModeReservedWordES6(id)) { + return true; + } + + switch (id.length) { + case 2: + return (id === 'if') || (id === 'in') || (id === 'do'); + case 3: + return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); + case 4: + return (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum'); + case 5: + return (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || + (id === 'class') || (id === 'super'); + case 6: + return (id === 'return') || (id === 'typeof') || (id === 'delete') || + (id === 'switch') || (id === 'export') || (id === 'import'); + case 7: + return (id === 'default') || (id === 'finally') || (id === 'extends'); + case 8: + return (id === 'function') || (id === 'continue') || (id === 'debugger'); + case 10: + return (id === 'instanceof'); + default: + return false; + } + } + + function isReservedWordES5(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); + } + + function isReservedWordES6(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + function isIdentifierNameES5(id) { + var i, iz, ch; + + if (id.length === 0) { return false; } + + ch = id.charCodeAt(0); + if (!code.isIdentifierStartES5(ch)) { + return false; + } + + for (i = 1, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (!code.isIdentifierPartES5(ch)) { + return false; + } + } + return true; + } + + function decodeUtf16(lead, trail) { + return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + } + + function isIdentifierNameES6(id) { + var i, iz, ch, lowCh, check; + + if (id.length === 0) { return false; } + + check = code.isIdentifierStartES6; + for (i = 0, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (0xD800 <= ch && ch <= 0xDBFF) { + ++i; + if (i >= iz) { return false; } + lowCh = id.charCodeAt(i); + if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { + return false; + } + ch = decodeUtf16(ch, lowCh); + } + if (!check(ch)) { + return false; + } + check = code.isIdentifierPartES6; + } + return true; + } + + function isIdentifierES5(id, strict) { + return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); + } + + function isIdentifierES6(id, strict) { + return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); + } + + module.exports = { + isKeywordES5: isKeywordES5, + isKeywordES6: isKeywordES6, + isReservedWordES5: isReservedWordES5, + isReservedWordES6: isReservedWordES6, + isRestrictedWord: isRestrictedWord, + isIdentifierNameES5: isIdentifierNameES5, + isIdentifierNameES6: isIdentifierNameES6, + isIdentifierES5: isIdentifierES5, + isIdentifierES6: isIdentifierES6 + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/lib/utils.js b/node_modules/esutils/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..ce18faa6bc80fa12d4af19681dd3fce62a90aff1 --- /dev/null +++ b/node_modules/esutils/lib/utils.js @@ -0,0 +1,33 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + 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. + + 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 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. +*/ + + +(function () { + 'use strict'; + + exports.ast = require('./ast'); + exports.code = require('./code'); + exports.keyword = require('./keyword'); +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/package.json b/node_modules/esutils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8396f4cee3f7e83d4be21fdc6fe1d038635065b8 --- /dev/null +++ b/node_modules/esutils/package.json @@ -0,0 +1,44 @@ +{ + "name": "esutils", + "description": "utility box for ECMAScript language tools", + "homepage": "https://github.com/estools/esutils", + "main": "lib/utils.js", + "version": "2.0.3", + "engines": { + "node": ">=0.10.0" + }, + "directories": { + "lib": "./lib" + }, + "files": [ + "LICENSE.BSD", + "README.md", + "lib" + ], + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "http://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/estools/esutils.git" + }, + "devDependencies": { + "chai": "~1.7.2", + "coffee-script": "~1.6.3", + "jshint": "2.6.3", + "mocha": "~2.2.1", + "regenerate": "~1.3.1", + "unicode-9.0.0": "~0.7.0" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "npm run-script lint && npm run-script unit-test", + "lint": "jshint lib/*.js", + "unit-test": "mocha --compilers coffee:coffee-script -R spec", + "generate-regex": "node tools/generate-identifier-regex.js" + } +} diff --git a/node_modules/eta/LICENSE b/node_modules/eta/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8862e61230d8886f4a57295e07af696ec136e051 --- /dev/null +++ b/node_modules/eta/LICENSE @@ -0,0 +1,7 @@ +Copyright 2025 Ben Gubler + +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. diff --git a/node_modules/eta/README.md b/node_modules/eta/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1e3ad288e80eb78a3d4b1244d85dc693b3b0eedb --- /dev/null +++ b/node_modules/eta/README.md @@ -0,0 +1,185 @@ +

+ +

+ +

eta (η)

+ +

+ Documentation - + Chat - + Playground +

+ + + +[![GitHub package.json version (main)](https://img.shields.io/github/package-json/v/bgub/eta/main?label=current%20version)](https://www.npmjs.com/package/eta) +[![GitHub Actions Status](https://github.com/bgub/eta/actions/workflows/ci.yml/badge.svg)](https://github.com/bgub/eta/actions) +[![Codecov](https://codecov.io/github/bgub/eta/branch/main/graph/badge.svg)](https://codecov.io/github/bgub/eta) +[![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://paypal.me/bengubler) + + + + + +**You're viewing the source for Eta v4** + + + +## Summary + +Eta is a lightweight and blazing fast embedded JS templating engine that works inside Node, Deno, and the browser. It's written in TypeScript and emphasizes great performance, configurability, and small bundle size. + +> 🎯 **Built with [ts-base](https://github.com/bgub/ts-base)** — A TypeScript library starter template featuring Biome, Vitest, tsdown, and automated releases. Check out ts-base for a modern TypeScript project setup! + +### 🌟 Features + +- 📦 0 dependencies +- 💡 Only ~3.5 KB minzipped +- ⚡️ Written in TypeScript +- ✨ Deno support (+ Node and browser) +- 🚀 Super Fast +- 🔧 Configurable + - Plugins, custom delimiters, caching +- 🔨 Powerful + - Precompilation, partials, async, blocks + - **Layout support**! +- 🔥 Reliable + - Better quotes/comments support + - _ex._ `<%= someval + "string %>" %>` compiles correctly, while it fails with doT or EJS + - Great error reporting +- ⚡️ Exports ES Modules +- 📝 Easy template syntax + +## Get Started + +_For more thorough documentation, visit [https://eta.js.org](https://eta.js.org)_ + +Install Eta + +```bash +npm install eta +``` + +In the root of your project, create `templates/simple.eta` + +```eta +Hi <%= it.name %>! +``` + +Then, in your JS file: + +```js +import { Eta } from "eta"; +// or use https://jsr.io/@bgub/eta + +const eta = new Eta({ views: path.join(__dirname, "templates") }); + +// Render a template + +const res = eta.render("./simple", { name: "Ben" }); +console.log(res); // Hi Ben! +``` + +## FAQs + +
+ + Where did Eta's name come from? + + +"Eta" means tiny in Esperanto. Plus, it can be used as an acronym for all sorts of cool phrases: "ECMAScript Template Awesomeness", "Embedded Templating Alternative", etc.... + +Additionally, Eta is a letter of the Greek alphabet (it stands for all sorts of cool things in various mathematical fields, including efficiency) and is three letters long (perfect for a file extension). + +
+ +
+ +## Integrations + +
+ + Visual Studio Code + + +[@shadowtime2000](https://github.com/shadowtime2000) created [eta-vscode](https://marketplace.visualstudio.com/items?itemName=shadowtime2000.eta-vscode). + +
+ +
+ + ESLint + + +[eslint-plugin-eta](https://github.com/eta-dev/eslint-plugin-eta) was created to provide an ESLint processor so you can lint your Eta templates. + +
+ +
+ + Webpack + + +Currently there is no official Webpack integration but [@clshortfuse](https://github.com/clshortfuse) shared the loader he uses: + +```javascript +{ + loader: 'html-loader', + options: { + preprocessor(content, loaderContext) { + return eta.render(content, {}, { filename: loaderContext.resourcePath }); + }, + }, +} +``` + +
+ +
+ + Node-RED + + +To operate with Eta templates in Node-RED: [@ralphwetzel/node-red-contrib-eta](https://flows.nodered.org/node/@ralphwetzel/node-red-contrib-eta) + + image + +
+ +
+ + Koa + + +To render Eta templates in [Koa](https://koajs.com) web framework: [@cedx/koa-eta](https://github.com/cedx/koa-eta/wiki) + +
+ +
+ + Vite + + +To use Eta templates in your Vite project: [@rinoshiyo/vite-plugin-eta](https://github.com/rinoshiyo/vite-plugin-eta) + +
+ +
+ +## Projects using `eta` + +- [Docusaurus v2](https://v2.docusaurus.io): open-source documentation framework that uses Eta to generate a SSR build +- [swagger-typescript-api](https://github.com/acacode/swagger-typescript-api): Open source typescript api codegenerator from Swagger. Uses Eta as codegenerator by templates +- [html-bundler-webpack-plugin](https://github.com/webdiscus/html-bundler-webpack-plugin): Webpack plugin make easily to bundle HTML pages from templates, source styles and scripts +- [SmartDeno](https://github.com/guildenstern70/SmartDeno): SmartDeno is an easy to setup web template using Deno & Oak +- [stc](https://github.com/long-woo/stc): OpenAPI (Swagger) and Apifox documentation converted to api. Use eta templates to generate code. +- [Add yours!](https://github.com/bgub/eta/edit/master/README.md) + +## Contributors + +Made with ❤️ by [bgub](https://github.com/bgub) and [many wonderful contributors](https://github.com/bgub/eta/graphs/contributors). Contributions of any kind are welcome! + +## Credits + +- Async support, file handling, and error formatting were based on code from [EJS](https://github.com/mde/ejs), which is licensed under the Apache-2.0 license. Code was modified and refactored to some extent. +- Syntax and some parts of compilation are heavily based off EJS, Nunjucks, and doT. diff --git a/node_modules/eta/package.json b/node_modules/eta/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4f81864644f1c25dedc662b71fb78274e7244617 --- /dev/null +++ b/node_modules/eta/package.json @@ -0,0 +1,75 @@ +{ + "name": "eta", + "version": "4.6.0", + "description": "Lightweight, fast, and powerful embedded JS template engine", + "keywords": [ + "handlebars", + "ejs", + "eta", + "template engine", + "embedded template engine", + "layouts", + "partials", + "typescript types" + ], + "homepage": "https://eta.js.org", + "type": "module", + "exports": { + ".": { + "types": { + "import": "./dist/index.d.mts", + "require": "./dist/index.d.cts" + }, + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + }, + "./core": { + "require": "./dist/core.js", + "import": "./dist/core.js", + "types": "./dist/core.d.ts" + }, + "./package.json": "./package.json" + }, + "main": "./dist/index.cjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.mts", + "sideEffects": false, + "files": [ + "dist" + ], + "scripts": { + "build": "tsdown", + "prepare": "npm run build", + "dev": "tsdown --watch", + "lint": "biome check --error-on-warnings", + "format": "biome format --write", + "test": "vitest run --coverage", + "size": "size-limit" + }, + "author": "Ben Gubler ", + "funding": "https://github.com/bgub/eta?sponsor=1", + "repository": "github:bgub/eta", + "bugs": { + "url": "https://github.com/bgub/eta/issues" + }, + "license": "MIT", + "engines": { + "node": ">=20" + }, + "size-limit": [ + { + "path": "dist/core.js", + "limit": "3.5 KB" + } + ], + "devDependencies": { + "@biomejs/biome": "2.3.5", + "@size-limit/preset-small-lib": "^11.2.0", + "@types/node": "^24.10.1", + "@vitest/coverage-istanbul": "4.0.8", + "size-limit": "^11.2.0", + "tsdown": "^0.16.4", + "typescript": "^5.9.3", + "vitest": "^4.0.8" + } +} diff --git a/node_modules/etag/HISTORY.md b/node_modules/etag/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..222b293dee9f8712b82a7e453c1f80e6e65348e7 --- /dev/null +++ b/node_modules/etag/HISTORY.md @@ -0,0 +1,83 @@ +1.8.1 / 2017-09-12 +================== + + * perf: replace regular expression with substring + +1.8.0 / 2017-02-18 +================== + + * Use SHA1 instead of MD5 for ETag hashing + - Improves performance for larger entities + - Works with FIPS 140-2 OpenSSL configuration + +1.7.0 / 2015-06-08 +================== + + * Always include entity length in ETags for hash length extensions + * Generate non-Stats ETags using MD5 only (no longer CRC32) + * Improve stat performance by removing hashing + * Remove base64 padding in ETags to shorten + * Use MD5 instead of MD4 in weak ETags over 1KB + +1.6.0 / 2015-05-10 +================== + + * Improve support for JXcore + * Remove requirement of `atime` in the stats object + * Support "fake" stats objects in environments without `fs` + +1.5.1 / 2014-11-19 +================== + + * deps: crc@3.2.1 + - Minor fixes + +1.5.0 / 2014-10-14 +================== + + * Improve string performance + * Slightly improve speed for weak ETags over 1KB + +1.4.0 / 2014-09-21 +================== + + * Support "fake" stats objects + * Support Node.js 0.6 + +1.3.1 / 2014-09-14 +================== + + * Use the (new and improved) `crc` for crc32 + +1.3.0 / 2014-08-29 +================== + + * Default strings to strong ETags + * Improve speed for weak ETags over 1KB + +1.2.1 / 2014-08-29 +================== + + * Use the (much faster) `buffer-crc32` for crc32 + +1.2.0 / 2014-08-24 +================== + + * Add support for file stat objects + +1.1.0 / 2014-08-24 +================== + + * Add fast-path for empty entity + * Add weak ETag generation + * Shrink size of generated ETags + +1.0.1 / 2014-08-24 +================== + + * Fix behavior of string containing Unicode + +1.0.0 / 2014-05-18 +================== + + * Initial release diff --git a/node_modules/etag/LICENSE b/node_modules/etag/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cab251c2b9a81318267600f68130faa3a290e5fd --- /dev/null +++ b/node_modules/etag/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 Douglas Christopher Wilson + +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. diff --git a/node_modules/etag/README.md b/node_modules/etag/README.md new file mode 100644 index 0000000000000000000000000000000000000000..09c2169e7b3ab576199dfe890b2f04cb645c5ac7 --- /dev/null +++ b/node_modules/etag/README.md @@ -0,0 +1,159 @@ +# etag + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create simple HTTP ETags + +This module generates HTTP ETags (as defined in RFC 7232) for use in +HTTP responses. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install etag +``` + +## API + + + +```js +var etag = require('etag') +``` + +### etag(entity, [options]) + +Generate a strong ETag for the given entity. This should be the complete +body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By +default, a strong ETag is generated except for `fs.Stats`, which will +generate a weak ETag (this can be overwritten by `options.weak`). + + + +```js +res.setHeader('ETag', etag(body)) +``` + +#### Options + +`etag` accepts these properties in the options object. + +##### weak + +Specifies if the generated ETag will include the weak validator mark (that +is, the leading `W/`). The actual entity tag is the same. The default value +is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +```bash +$ npm run-script bench + +> etag@1.8.1 bench nodejs-etag +> node benchmark/index.js + + http_parser@2.7.0 + node@6.11.1 + v8@5.1.281.103 + uv@1.11.0 + zlib@1.2.11 + ares@1.10.1-DEV + icu@58.2 + modules@48 + openssl@1.0.2k + +> node benchmark/body0-100b.js + + 100B body + + 4 tests completed. + + buffer - strong x 258,647 ops/sec ±1.07% (180 runs sampled) + buffer - weak x 263,812 ops/sec ±0.61% (184 runs sampled) + string - strong x 259,955 ops/sec ±1.19% (185 runs sampled) + string - weak x 264,356 ops/sec ±1.09% (184 runs sampled) + +> node benchmark/body1-1kb.js + + 1KB body + + 4 tests completed. + + buffer - strong x 189,018 ops/sec ±1.12% (182 runs sampled) + buffer - weak x 190,586 ops/sec ±0.81% (186 runs sampled) + string - strong x 144,272 ops/sec ±0.96% (188 runs sampled) + string - weak x 145,380 ops/sec ±1.43% (187 runs sampled) + +> node benchmark/body2-5kb.js + + 5KB body + + 4 tests completed. + + buffer - strong x 92,435 ops/sec ±0.42% (188 runs sampled) + buffer - weak x 92,373 ops/sec ±0.58% (189 runs sampled) + string - strong x 48,850 ops/sec ±0.56% (186 runs sampled) + string - weak x 49,380 ops/sec ±0.56% (190 runs sampled) + +> node benchmark/body3-10kb.js + + 10KB body + + 4 tests completed. + + buffer - strong x 55,989 ops/sec ±0.93% (188 runs sampled) + buffer - weak x 56,148 ops/sec ±0.55% (190 runs sampled) + string - strong x 27,345 ops/sec ±0.43% (188 runs sampled) + string - weak x 27,496 ops/sec ±0.45% (190 runs sampled) + +> node benchmark/body4-100kb.js + + 100KB body + + 4 tests completed. + + buffer - strong x 7,083 ops/sec ±0.22% (190 runs sampled) + buffer - weak x 7,115 ops/sec ±0.26% (191 runs sampled) + string - strong x 3,068 ops/sec ±0.34% (190 runs sampled) + string - weak x 3,096 ops/sec ±0.35% (190 runs sampled) + +> node benchmark/stats.js + + stat + + 4 tests completed. + + real - strong x 871,642 ops/sec ±0.34% (189 runs sampled) + real - weak x 867,613 ops/sec ±0.39% (190 runs sampled) + fake - strong x 401,051 ops/sec ±0.40% (189 runs sampled) + fake - weak x 400,100 ops/sec ±0.47% (188 runs sampled) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/etag.svg +[npm-url]: https://npmjs.org/package/etag +[node-version-image]: https://img.shields.io/node/v/etag.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/etag/master.svg +[travis-url]: https://travis-ci.org/jshttp/etag +[coveralls-image]: https://img.shields.io/coveralls/jshttp/etag/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master +[downloads-image]: https://img.shields.io/npm/dm/etag.svg +[downloads-url]: https://npmjs.org/package/etag diff --git a/node_modules/etag/index.js b/node_modules/etag/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2a585c91f07351e9566d50faec67a0272367ba81 --- /dev/null +++ b/node_modules/etag/index.js @@ -0,0 +1,131 @@ +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = etag + +/** + * Module dependencies. + * @private + */ + +var crypto = require('crypto') +var Stats = require('fs').Stats + +/** + * Module variables. + * @private + */ + +var toString = Object.prototype.toString + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } + + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + + return '"' + size + '-' + mtime + '"' +} diff --git a/node_modules/etag/package.json b/node_modules/etag/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b06ab803c0f80f56c5c88b8dc394468aee3485f4 --- /dev/null +++ b/node_modules/etag/package.json @@ -0,0 +1,47 @@ +{ + "name": "etag", + "description": "Create simple HTTP ETags", + "version": "1.8.1", + "contributors": [ + "Douglas Christopher Wilson ", + "David Björklund " + ], + "license": "MIT", + "keywords": [ + "etag", + "http", + "res" + ], + "repository": "jshttp/etag", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5", + "safe-buffer": "5.1.1", + "seedrandom": "2.4.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/node_modules/events-universal/LICENSE b/node_modules/events-universal/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/node_modules/events-universal/LICENSE @@ -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. diff --git a/node_modules/events-universal/README.md b/node_modules/events-universal/README.md new file mode 100644 index 0000000000000000000000000000000000000000..147c4ad247b3bc3c2f2d1a490f0c6bb7e6debb68 --- /dev/null +++ b/node_modules/events-universal/README.md @@ -0,0 +1,17 @@ +# events-universal + +Universal wrapper for the Node.js `events` module. + +``` +npm i events-universal +``` + +## Usage + +```js +const EventEmitter = require('events-universal') +``` + +## License + +Apache-2.0 diff --git a/node_modules/events-universal/bare.js b/node_modules/events-universal/bare.js new file mode 100644 index 0000000000000000000000000000000000000000..35e6abd566294bbe09afe5c90b612dd20219c8cb --- /dev/null +++ b/node_modules/events-universal/bare.js @@ -0,0 +1 @@ +module.exports = require('bare-events') diff --git a/node_modules/events-universal/default.js b/node_modules/events-universal/default.js new file mode 100644 index 0000000000000000000000000000000000000000..6f3af97c27f94c95426d4d0c114c8217194c934a --- /dev/null +++ b/node_modules/events-universal/default.js @@ -0,0 +1 @@ +module.exports = require('events') diff --git a/node_modules/events-universal/index.js b/node_modules/events-universal/index.js new file mode 100644 index 0000000000000000000000000000000000000000..35e6abd566294bbe09afe5c90b612dd20219c8cb --- /dev/null +++ b/node_modules/events-universal/index.js @@ -0,0 +1 @@ +module.exports = require('bare-events') diff --git a/node_modules/events-universal/package.json b/node_modules/events-universal/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0e973f39d432536b51a79b9937288c73f635f96b --- /dev/null +++ b/node_modules/events-universal/package.json @@ -0,0 +1,39 @@ +{ + "name": "events-universal", + "version": "1.0.1", + "description": "Universal wrapper for the Node.js events module", + "exports": { + "./package": "./package.json", + ".": { + "bare": "./bare.js", + "react-native": "./react-native.js", + "default": "./default.js" + } + }, + "files": [ + "index.js", + "default.js", + "bare.js", + "react-native.js" + ], + "scripts": { + "test": "prettier . --check" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/holepunchto/events-universal.git" + }, + "author": "Holepunch", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/holepunchto/events-universal/issues" + }, + "homepage": "https://github.com/holepunchto/events-universal#readme", + "dependencies": { + "bare-events": "^2.7.0" + }, + "devDependencies": { + "prettier": "^3.4.2", + "prettier-config-holepunch": "^1.0.0" + } +} diff --git a/node_modules/events-universal/react-native.js b/node_modules/events-universal/react-native.js new file mode 100644 index 0000000000000000000000000000000000000000..35e6abd566294bbe09afe5c90b612dd20219c8cb --- /dev/null +++ b/node_modules/events-universal/react-native.js @@ -0,0 +1 @@ +module.exports = require('bare-events') diff --git a/node_modules/events/.airtap.yml b/node_modules/events/.airtap.yml new file mode 100644 index 0000000000000000000000000000000000000000..c7a8a87d5e99d1b538b50bb40bd3e8a3d44b6f3b --- /dev/null +++ b/node_modules/events/.airtap.yml @@ -0,0 +1,15 @@ +sauce_connect: true +loopback: airtap.local +browsers: + - name: chrome + version: latest + - name: firefox + version: latest + - name: safari + version: 9..latest + - name: iphone + version: latest + - name: ie + version: 9..latest + - name: microsoftedge + version: 13..latest diff --git a/node_modules/events/.github/FUNDING.yml b/node_modules/events/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..8b8cb78ba90207e382cd5384d4a4bcc78e90113a --- /dev/null +++ b/node_modules/events/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/events +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/events/.travis.yml b/node_modules/events/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..486dc3c4c1df7fe432eb19fa9174b2e33b263e37 --- /dev/null +++ b/node_modules/events/.travis.yml @@ -0,0 +1,18 @@ +dist: xenial +os: linux +language: node_js +node_js: + - 'stable' + - 'lts/*' + - '0.12' +script: + - npm test + - if [ "${TRAVIS_PULL_REQUEST}" = "false" ] && [ "${TRAVIS_NODE_VERSION}" = "stable" ]; then npm run test:browsers; fi +addons: + sauce_connect: true + hosts: + - airtap.local +env: + global: + - secure: XcBiD8yReflut9q7leKsigDZ0mI3qTKH+QrNVY8DaqlomJOZw8aOrVuX9Jz12l86ZJ41nbxmKnRNkFzcVr9mbP9YaeTb3DpeOBWmvaoSfud9Wnc16VfXtc1FCcwDhSVcSiM3UtnrmFU5cH+Dw1LPh5PbfylYOS/nJxUvG0FFLqI= + - secure: jNWtEbqhUdQ0xXDHvCYfUbKYeJCi6a7B4LsrcxYCyWWn4NIgncE5x2YbB+FSUUFVYfz0dsn5RKP1oHB99f0laUEo18HBNkrAS/rtyOdVzcpJjbQ6kgSILGjnJD/Ty1B57Rcz3iyev5Y7bLZ6Y1FbDnk/i9/l0faOGz8vTC3Vdkc= diff --git a/node_modules/events/History.md b/node_modules/events/History.md new file mode 100644 index 0000000000000000000000000000000000000000..f48bf210da3ea23213ce37ebd13cd5788c9563c9 --- /dev/null +++ b/node_modules/events/History.md @@ -0,0 +1,118 @@ +# 3.3.0 + + - Support EventTarget emitters in `events.once` from Node.js 12.11.0. + + Now you can use the `events.once` function with objects that implement the EventTarget interface. This interface is used widely in + the DOM and other web APIs. + + ```js + var events = require('events'); + var assert = require('assert'); + + async function connect() { + var ws = new WebSocket('wss://example.com'); + await events.once(ws, 'open'); + assert(ws.readyState === WebSocket.OPEN); + } + + async function onClick() { + await events.once(document.body, 'click'); + alert('you clicked the page!'); + } + ``` + +# 3.2.0 + + - Add `events.once` from Node.js 11.13.0. + + To use this function, Promises must be supported in the environment. Use a polyfill like `es6-promise` if you support older browsers. + +# 3.1.0 (2020-01-08) + +`events` now matches the Node.js 11.12.0 API. + + - pass through return value in wrapped `emitter.once()` listeners + + Now, this works: + ```js + emitter.once('myevent', function () { return 1; }); + var listener = emitter.rawListeners('myevent')[0] + assert(listener() === 1); + ``` + Previously, `listener()` would return undefined regardless of the implementation. + + Ported from https://github.com/nodejs/node/commit/acc506c2d2771dab8d7bba6d3452bc5180dff7cf + + - Reduce code duplication in listener type check ([#67](https://github.com/Gozala/events/pull/67) by [@friederbluemle](https://github.com/friederbluemle)). + - Improve `emitter.once()` performance in some engines + +# 3.0.0 (2018-05-25) + +**This version drops support for IE8.** `events` no longer includes polyfills +for ES5 features. If you need to support older environments, use an ES5 shim +like [es5-shim](https://npmjs.com/package/es5-shim). Both the shim and sham +versions of es5-shim are necessary. + + - Update to events code from Node.js 10.x + - (semver major) Adds `off()` method + - Port more tests from Node.js + - Switch browser tests to airtap, making things more reliable + +# 2.1.0 (2018-05-25) + + - add Emitter#rawListeners from Node.js v9.4 + +# 2.0.0 (2018-02-02) + + - Update to events code from node.js 8.x + - Adds `prependListener()` and `prependOnceListener()` + - Adds `eventNames()` method + - (semver major) Unwrap `once()` listeners in `listeners()` + - copy tests from node.js + +Note that this version doubles the gzipped size, jumping from 1.1KB to 2.1KB, +due to new methods and runtime performance improvements. Be aware of that when +upgrading. + +# 1.1.1 (2016-06-22) + + - add more context to errors if they are not instanceof Error + +# 1.1.0 (2015-09-29) + + - add Emitter#listerCount (to match node v4 api) + +# 1.0.2 (2014-08-28) + + - remove un-reachable code + - update devDeps + +## 1.0.1 / 2014-05-11 + + - check for console.trace before using it + +## 1.0.0 / 2013-12-10 + + - Update to latest events code from node.js 0.10 + - copy tests from node.js + +## 0.4.0 / 2011-07-03 ## + + - Switching to graphquire@0.8.0 + +## 0.3.0 / 2011-07-03 ## + + - Switching to URL based module require. + +## 0.2.0 / 2011-06-10 ## + + - Simplified package structure. + - Graphquire for dependency management. + +## 0.1.1 / 2011-05-16 ## + + - Unhandled errors are logged via console.error + +## 0.1.0 / 2011-04-22 ## + + - Initial release diff --git a/node_modules/events/LICENSE b/node_modules/events/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..52ed3b0a63274d653474abc893d6f7221fc301fd --- /dev/null +++ b/node_modules/events/LICENSE @@ -0,0 +1,22 @@ +MIT + +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/events/Readme.md b/node_modules/events/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..80849c0b2d7c39727a540f369d764ee36ef5ee07 --- /dev/null +++ b/node_modules/events/Readme.md @@ -0,0 +1,50 @@ +# events [![Build Status](https://travis-ci.org/Gozala/events.png?branch=master)](https://travis-ci.org/Gozala/events) + +> Node's event emitter for all engines. + +This implements the Node.js [`events`][node.js docs] module for environments that do not have it, like browsers. + +> `events` currently matches the **Node.js 11.13.0** API. + +Note that the `events` module uses ES5 features. If you need to support very old browsers like IE8, use a shim like [`es5-shim`](https://www.npmjs.com/package/es5-shim). You need both the shim and the sham versions of `es5-shim`. + +This module is maintained, but only by very few people. If you'd like to help, let us know in the [Maintainer Needed](https://github.com/Gozala/events/issues/43) issue! + +## Install + +You usually do not have to install `events` yourself! If your code runs in Node.js, `events` is built in. If your code runs in the browser, bundlers like [browserify](https://github.com/browserify/browserify) or [webpack](https://github.com/webpack/webpack) also include the `events` module. + +But if none of those apply, with npm do: + +``` +npm install events +``` + +## Usage + +```javascript +var EventEmitter = require('events') + +var ee = new EventEmitter() +ee.on('message', function (text) { + console.log(text) +}) +ee.emit('message', 'hello world') +``` + +## API + +See the [Node.js EventEmitter docs][node.js docs]. `events` currently matches the Node.js 11.13.0 API. + +## Contributing + +PRs are very welcome! The main way to contribute to `events` is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js. +This module intends to provide exactly the same API as Node.js, so features that are not available in the core `events` module will not be accepted. Feature requests should instead be directed at [nodejs/node](https://github.com/nodejs/node) and will be added to this module once they are implemented in Node.js. + +If there is a difference in behaviour between Node.js's `events` module and this module, please open an issue! + +## License + +[MIT](./LICENSE) + +[node.js docs]: https://nodejs.org/dist/v11.13.0/docs/api/events.html diff --git a/node_modules/events/events.js b/node_modules/events/events.js new file mode 100644 index 0000000000000000000000000000000000000000..34b69a0b4a6e124e8de119540980bbb4d6cdf4d6 --- /dev/null +++ b/node_modules/events/events.js @@ -0,0 +1,497 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); +} + +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } +} + +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} diff --git a/node_modules/events/package.json b/node_modules/events/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b9580d88142d2921273599e2afaaec640906df6d --- /dev/null +++ b/node_modules/events/package.json @@ -0,0 +1,37 @@ +{ + "name": "events", + "version": "3.3.0", + "description": "Node's event emitter for all engines.", + "keywords": [ + "events", + "eventEmitter", + "eventDispatcher", + "listeners" + ], + "author": "Irakli Gozalishvili (http://jeditoolkit.com)", + "repository": { + "type": "git", + "url": "git://github.com/Gozala/events.git", + "web": "https://github.com/Gozala/events" + }, + "bugs": { + "url": "http://github.com/Gozala/events/issues/" + }, + "main": "./events.js", + "engines": { + "node": ">=0.8.x" + }, + "devDependencies": { + "airtap": "^1.0.0", + "functions-have-names": "^1.2.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "isarray": "^2.0.5", + "tape": "^5.0.0" + }, + "scripts": { + "test": "node tests/index.js", + "test:browsers": "airtap -- tests/index.js" + }, + "license": "MIT" +} diff --git a/node_modules/events/security.md b/node_modules/events/security.md new file mode 100644 index 0000000000000000000000000000000000000000..a14ace6a57db70992630a568df6a7bf57763d26b --- /dev/null +++ b/node_modules/events/security.md @@ -0,0 +1,10 @@ +# Security Policy + +## Supported Versions +Only the latest major version is supported at any given time. + +## Reporting a Vulnerability + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/node_modules/events/tests/add-listeners.js b/node_modules/events/tests/add-listeners.js new file mode 100644 index 0000000000000000000000000000000000000000..9b578272ba889e9732543badfc9077a59f974640 --- /dev/null +++ b/node_modules/events/tests/add-listeners.js @@ -0,0 +1,111 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('./common'); +var assert = require('assert'); +var EventEmitter = require('../'); + +{ + var ee = new EventEmitter(); + var events_new_listener_emitted = []; + var listeners_new_listener_emitted = []; + + // Sanity check + assert.strictEqual(ee.addListener, ee.on); + + ee.on('newListener', function(event, listener) { + // Don't track newListener listeners. + if (event === 'newListener') + return; + + events_new_listener_emitted.push(event); + listeners_new_listener_emitted.push(listener); + }); + + var hello = common.mustCall(function(a, b) { + assert.strictEqual('a', a); + assert.strictEqual('b', b); + }); + + ee.once('newListener', function(name, listener) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(listener, hello); + + var listeners = this.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + }); + + ee.on('hello', hello); + ee.once('foo', assert.fail); + + assert.ok(Array.isArray(events_new_listener_emitted)); + assert.strictEqual(events_new_listener_emitted.length, 2); + assert.strictEqual(events_new_listener_emitted[0], 'hello'); + assert.strictEqual(events_new_listener_emitted[1], 'foo'); + + assert.ok(Array.isArray(listeners_new_listener_emitted)); + assert.strictEqual(listeners_new_listener_emitted.length, 2); + assert.strictEqual(listeners_new_listener_emitted[0], hello); + assert.strictEqual(listeners_new_listener_emitted[1], assert.fail); + + ee.emit('hello', 'a', 'b'); +} + +// just make sure that this doesn't throw: +{ + var f = new EventEmitter(); + + f.setMaxListeners(0); +} + +{ + var listen1 = function() {}; + var listen2 = function() {}; + var ee = new EventEmitter(); + + ee.once('newListener', function() { + var listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + ee.once('newListener', function() { + var listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + }); + ee.on('hello', listen2); + }); + ee.on('hello', listen1); + // The order of listeners on an event is not always the order in which the + // listeners were added. + var listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 2); + assert.strictEqual(listeners[0], listen2); + assert.strictEqual(listeners[1], listen1); +} + +// Verify that the listener must be a function +assert.throws(function() { + var ee = new EventEmitter(); + + ee.on('foo', null); +}, /^TypeError: The "listener" argument must be of type Function. Received type object$/); diff --git a/node_modules/events/tests/check-listener-leaks.js b/node_modules/events/tests/check-listener-leaks.js new file mode 100644 index 0000000000000000000000000000000000000000..7fce48f37bf24cc63a3df3e88a558a03fdbde2fa --- /dev/null +++ b/node_modules/events/tests/check-listener-leaks.js @@ -0,0 +1,101 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('./common'); +var assert = require('assert'); +var events = require('../'); + +// Redirect warning output to tape. +var consoleWarn = console.warn; +console.warn = common.test.comment; + +common.test.on('end', function () { + console.warn = consoleWarn; +}); + +// default +{ + var e = new events.EventEmitter(); + + for (var i = 0; i < 10; i++) { + e.on('default', common.mustNotCall()); + } + assert.ok(!e._events['default'].hasOwnProperty('warned')); + e.on('default', common.mustNotCall()); + assert.ok(e._events['default'].warned); + + // specific + e.setMaxListeners(5); + for (var i = 0; i < 5; i++) { + e.on('specific', common.mustNotCall()); + } + assert.ok(!e._events['specific'].hasOwnProperty('warned')); + e.on('specific', common.mustNotCall()); + assert.ok(e._events['specific'].warned); + + // only one + e.setMaxListeners(1); + e.on('only one', common.mustNotCall()); + assert.ok(!e._events['only one'].hasOwnProperty('warned')); + e.on('only one', common.mustNotCall()); + assert.ok(e._events['only one'].hasOwnProperty('warned')); + + // unlimited + e.setMaxListeners(0); + for (var i = 0; i < 1000; i++) { + e.on('unlimited', common.mustNotCall()); + } + assert.ok(!e._events['unlimited'].hasOwnProperty('warned')); +} + +// process-wide +{ + events.EventEmitter.defaultMaxListeners = 42; + var e = new events.EventEmitter(); + + for (var i = 0; i < 42; ++i) { + e.on('fortytwo', common.mustNotCall()); + } + assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); + e.on('fortytwo', common.mustNotCall()); + assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); + delete e._events['fortytwo'].warned; + + events.EventEmitter.defaultMaxListeners = 44; + e.on('fortytwo', common.mustNotCall()); + assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); + e.on('fortytwo', common.mustNotCall()); + assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); +} + +// but _maxListeners still has precedence over defaultMaxListeners +{ + events.EventEmitter.defaultMaxListeners = 42; + var e = new events.EventEmitter(); + e.setMaxListeners(1); + e.on('uno', common.mustNotCall()); + assert.ok(!e._events['uno'].hasOwnProperty('warned')); + e.on('uno', common.mustNotCall()); + assert.ok(e._events['uno'].hasOwnProperty('warned')); + + // chainable + assert.strictEqual(e, e.setMaxListeners(1)); +} diff --git a/node_modules/events/tests/common.js b/node_modules/events/tests/common.js new file mode 100644 index 0000000000000000000000000000000000000000..49569b05f59d5a6c4956cc3bcea2dfd3d426d632 --- /dev/null +++ b/node_modules/events/tests/common.js @@ -0,0 +1,104 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var test = require('tape'); +var assert = require('assert'); + +var noop = function() {}; + +var mustCallChecks = []; + +function runCallChecks(exitCode) { + if (exitCode !== 0) return; + + var failed = filter(mustCallChecks, function(context) { + if ('minimum' in context) { + context.messageSegment = 'at least ' + context.minimum; + return context.actual < context.minimum; + } else { + context.messageSegment = 'exactly ' + context.exact; + return context.actual !== context.exact; + } + }); + + for (var i = 0; i < failed.length; i++) { + var context = failed[i]; + console.log('Mismatched %s function calls. Expected %s, actual %d.', + context.name, + context.messageSegment, + context.actual); + // IE8 has no .stack + if (context.stack) console.log(context.stack.split('\n').slice(2).join('\n')); + } + + assert.strictEqual(failed.length, 0); +} + +exports.mustCall = function(fn, exact) { + return _mustCallInner(fn, exact, 'exact'); +}; + +function _mustCallInner(fn, criteria, field) { + if (typeof criteria == 'undefined') criteria = 1; + + if (typeof fn === 'number') { + criteria = fn; + fn = noop; + } else if (fn === undefined) { + fn = noop; + } + + if (typeof criteria !== 'number') + throw new TypeError('Invalid ' + field + ' value: ' + criteria); + + var context = { + actual: 0, + stack: (new Error()).stack, + name: fn.name || '' + }; + + context[field] = criteria; + + // add the exit listener only once to avoid listener leak warnings + if (mustCallChecks.length === 0) test.onFinish(function() { runCallChecks(0); }); + + mustCallChecks.push(context); + + return function() { + context.actual++; + return fn.apply(this, arguments); + }; +} + +exports.mustNotCall = function(msg) { + return function mustNotCall() { + assert.fail(msg || 'function should not have been called'); + }; +}; + +function filter(arr, fn) { + if (arr.filter) return arr.filter(fn); + var filtered = []; + for (var i = 0; i < arr.length; i++) { + if (fn(arr[i], i, arr)) filtered.push(arr[i]); + } + return filtered +} diff --git a/node_modules/events/tests/errors.js b/node_modules/events/tests/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..a23df437f05d39628251c8fa9dfb72baf72b749e --- /dev/null +++ b/node_modules/events/tests/errors.js @@ -0,0 +1,13 @@ +'use strict'; +var assert = require('assert'); +var EventEmitter = require('../'); + +var EE = new EventEmitter(); + +assert.throws(function () { + EE.emit('error', 'Accepts a string'); +}, 'Error: Unhandled error. (Accepts a string)'); + +assert.throws(function () { + EE.emit('error', { message: 'Error!' }); +}, 'Unhandled error. ([object Object])'); diff --git a/node_modules/events/tests/events-list.js b/node_modules/events/tests/events-list.js new file mode 100644 index 0000000000000000000000000000000000000000..08aa62177e2c291efcbcc57a9010f4db8625a05c --- /dev/null +++ b/node_modules/events/tests/events-list.js @@ -0,0 +1,28 @@ +'use strict'; + +var EventEmitter = require('../'); +var assert = require('assert'); + +var EE = new EventEmitter(); +var m = function() {}; +EE.on('foo', function() {}); +assert.equal(1, EE.eventNames().length); +assert.equal('foo', EE.eventNames()[0]); +EE.on('bar', m); +assert.equal(2, EE.eventNames().length); +assert.equal('foo', EE.eventNames()[0]); +assert.equal('bar', EE.eventNames()[1]); +EE.removeListener('bar', m); +assert.equal(1, EE.eventNames().length); +assert.equal('foo', EE.eventNames()[0]); + +if (typeof Symbol !== 'undefined') { + var s = Symbol('s'); + EE.on(s, m); + assert.equal(2, EE.eventNames().length); + assert.equal('foo', EE.eventNames()[0]); + assert.equal(s, EE.eventNames()[1]); + EE.removeListener(s, m); + assert.equal(1, EE.eventNames().length); + assert.equal('foo', EE.eventNames()[0]); +} diff --git a/node_modules/events/tests/events-once.js b/node_modules/events/tests/events-once.js new file mode 100644 index 0000000000000000000000000000000000000000..dae864963daae6fbac8b459a6358008189e82197 --- /dev/null +++ b/node_modules/events/tests/events-once.js @@ -0,0 +1,234 @@ +'use strict'; + +var common = require('./common'); +var EventEmitter = require('../').EventEmitter; +var once = require('../').once; +var has = require('has'); +var assert = require('assert'); + +function Event(type) { + this.type = type; +} + +function EventTargetMock() { + this.events = {}; + + this.addEventListener = common.mustCall(this.addEventListener); + this.removeEventListener = common.mustCall(this.removeEventListener); +} + +EventTargetMock.prototype.addEventListener = function addEventListener(name, listener, options) { + if (!(name in this.events)) { + this.events[name] = { listeners: [], options: options || {} } + } + this.events[name].listeners.push(listener); +}; + +EventTargetMock.prototype.removeEventListener = function removeEventListener(name, callback) { + if (!(name in this.events)) { + return; + } + var event = this.events[name]; + var stack = event.listeners; + + for (var i = 0, l = stack.length; i < l; i++) { + if (stack[i] === callback) { + stack.splice(i, 1); + if (stack.length === 0) { + delete this.events[name]; + } + return; + } + } +}; + +EventTargetMock.prototype.dispatchEvent = function dispatchEvent(arg) { + if (!(arg.type in this.events)) { + return true; + } + + var event = this.events[arg.type]; + var stack = event.listeners.slice(); + + for (var i = 0, l = stack.length; i < l; i++) { + stack[i].call(null, arg); + if (event.options.once) { + this.removeEventListener(arg.type, stack[i]); + } + } + return !arg.defaultPrevented; +}; + +function onceAnEvent() { + var ee = new EventEmitter(); + + process.nextTick(function () { + ee.emit('myevent', 42); + }); + + return once(ee, 'myevent').then(function (args) { + var value = args[0] + assert.strictEqual(value, 42); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); + }); +} + +function onceAnEventWithTwoArgs() { + var ee = new EventEmitter(); + + process.nextTick(function () { + ee.emit('myevent', 42, 24); + }); + + return once(ee, 'myevent').then(function (value) { + assert.strictEqual(value.length, 2); + assert.strictEqual(value[0], 42); + assert.strictEqual(value[1], 24); + }); +} + +function catchesErrors() { + var ee = new EventEmitter(); + + var expected = new Error('kaboom'); + var err; + process.nextTick(function () { + ee.emit('error', expected); + }); + + return once(ee, 'myevent').then(function () { + throw new Error('should reject') + }, function (err) { + assert.strictEqual(err, expected); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); + }); +} + +function stopListeningAfterCatchingError() { + var ee = new EventEmitter(); + + var expected = new Error('kaboom'); + var err; + process.nextTick(function () { + ee.emit('error', expected); + ee.emit('myevent', 42, 24); + }); + + // process.on('multipleResolves', common.mustNotCall()); + + return once(ee, 'myevent').then(common.mustNotCall, function (err) { + // process.removeAllListeners('multipleResolves'); + assert.strictEqual(err, expected); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); + }); +} + +function onceError() { + var ee = new EventEmitter(); + + var expected = new Error('kaboom'); + process.nextTick(function () { + ee.emit('error', expected); + }); + + var promise = once(ee, 'error'); + assert.strictEqual(ee.listenerCount('error'), 1); + return promise.then(function (args) { + var err = args[0] + assert.strictEqual(err, expected); + assert.strictEqual(ee.listenerCount('error'), 0); + assert.strictEqual(ee.listenerCount('myevent'), 0); + }); +} + +function onceWithEventTarget() { + var et = new EventTargetMock(); + var event = new Event('myevent'); + process.nextTick(function () { + et.dispatchEvent(event); + }); + return once(et, 'myevent').then(function (args) { + var value = args[0]; + assert.strictEqual(value, event); + assert.strictEqual(has(et.events, 'myevent'), false); + }); +} + +function onceWithEventTargetError() { + var et = new EventTargetMock(); + var error = new Event('error'); + process.nextTick(function () { + et.dispatchEvent(error); + }); + return once(et, 'error').then(function (args) { + var err = args[0]; + assert.strictEqual(err, error); + assert.strictEqual(has(et.events, 'error'), false); + }); +} + +function prioritizesEventEmitter() { + var ee = new EventEmitter(); + ee.addEventListener = assert.fail; + ee.removeAllListeners = assert.fail; + process.nextTick(function () { + ee.emit('foo'); + }); + return once(ee, 'foo'); +} + +var allTests = [ + onceAnEvent(), + onceAnEventWithTwoArgs(), + catchesErrors(), + stopListeningAfterCatchingError(), + onceError(), + onceWithEventTarget(), + onceWithEventTargetError(), + prioritizesEventEmitter() +]; + +var hasBrowserEventTarget = false; +try { + hasBrowserEventTarget = typeof (new window.EventTarget().addEventListener) === 'function' && + new window.Event('xyz').type === 'xyz'; +} catch (err) {} + +if (hasBrowserEventTarget) { + var onceWithBrowserEventTarget = function onceWithBrowserEventTarget() { + var et = new window.EventTarget(); + var event = new window.Event('myevent'); + process.nextTick(function () { + et.dispatchEvent(event); + }); + return once(et, 'myevent').then(function (args) { + var value = args[0]; + assert.strictEqual(value, event); + assert.strictEqual(has(et.events, 'myevent'), false); + }); + } + + var onceWithBrowserEventTargetError = function onceWithBrowserEventTargetError() { + var et = new window.EventTarget(); + var error = new window.Event('error'); + process.nextTick(function () { + et.dispatchEvent(error); + }); + return once(et, 'error').then(function (args) { + var err = args[0]; + assert.strictEqual(err, error); + assert.strictEqual(has(et.events, 'error'), false); + }); + } + + common.test.comment('Testing with browser built-in EventTarget'); + allTests.push([ + onceWithBrowserEventTarget(), + onceWithBrowserEventTargetError() + ]); +} + +module.exports = Promise.all(allTests); diff --git a/node_modules/events/tests/index.js b/node_modules/events/tests/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2d739e670ca0287debfd9bcbc6164e862c74b133 --- /dev/null +++ b/node_modules/events/tests/index.js @@ -0,0 +1,64 @@ +var test = require('tape'); +var functionsHaveNames = require('functions-have-names'); +var hasSymbols = require('has-symbols'); + +require('./legacy-compat'); +var common = require('./common'); + +// we do this to easily wrap each file in a mocha test +// and also have browserify be able to statically analyze this file +var orig_require = require; +var require = function(file) { + test(file, function(t) { + // Store the tape object so tests can access it. + t.on('end', function () { delete common.test; }); + common.test = t; + + try { + var exp = orig_require(file); + if (exp && exp.then) { + exp.then(function () { t.end(); }, t.fail); + return; + } + } catch (err) { + t.fail(err); + } + t.end(); + }); +}; + +require('./add-listeners.js'); +require('./check-listener-leaks.js'); +require('./errors.js'); +require('./events-list.js'); +if (typeof Promise === 'function') { + require('./events-once.js'); +} else { + // Promise support is not available. + test('./events-once.js', { skip: true }, function () {}); +} +require('./listener-count.js'); +require('./listeners-side-effects.js'); +require('./listeners.js'); +require('./max-listeners.js'); +if (functionsHaveNames()) { + require('./method-names.js'); +} else { + // Function.name is not supported in IE + test('./method-names.js', { skip: true }, function () {}); +} +require('./modify-in-emit.js'); +require('./num-args.js'); +require('./once.js'); +require('./prepend.js'); +require('./set-max-listeners-side-effects.js'); +require('./special-event-names.js'); +require('./subclass.js'); +if (hasSymbols()) { + require('./symbols.js'); +} else { + // Symbol is not available. + test('./symbols.js', { skip: true }, function () {}); +} +require('./remove-all-listeners.js'); +require('./remove-listeners.js'); diff --git a/node_modules/events/tests/legacy-compat.js b/node_modules/events/tests/legacy-compat.js new file mode 100644 index 0000000000000000000000000000000000000000..a402be6e2f42d11acafd5dea42fabe0a21df06c6 --- /dev/null +++ b/node_modules/events/tests/legacy-compat.js @@ -0,0 +1,16 @@ +// sigh... life is hard +if (!global.console) { + console = {} +} + +var fns = ['log', 'error', 'trace']; +for (var i=0 ; ifoo should not be emitted'); +} + +e.once('foo', remove); +e.removeListener('foo', remove); +e.emit('foo'); + +e.once('e', common.mustCall(function() { + e.emit('e'); +})); + +e.once('e', common.mustCall()); + +e.emit('e'); + +// Verify that the listener must be a function +assert.throws(function() { + var ee = new EventEmitter(); + + ee.once('foo', null); +}, /^TypeError: The "listener" argument must be of type Function. Received type object$/); + +{ + // once() has different code paths based on the number of arguments being + // emitted. Verify that all of the cases are covered. + var maxArgs = 4; + + for (var i = 0; i <= maxArgs; ++i) { + var ee = new EventEmitter(); + var args = ['foo']; + + for (var j = 0; j < i; ++j) + args.push(j); + + ee.once('foo', common.mustCall(function() { + var params = Array.prototype.slice.call(arguments); + var restArgs = args.slice(1); + assert.ok(Array.isArray(params)); + assert.strictEqual(params.length, restArgs.length); + for (var index = 0; index < params.length; index++) { + var param = params[index]; + assert.strictEqual(param, restArgs[index]); + } + })); + + EventEmitter.prototype.emit.apply(ee, args); + } +} diff --git a/node_modules/events/tests/prepend.js b/node_modules/events/tests/prepend.js new file mode 100644 index 0000000000000000000000000000000000000000..79afde0bf3971c638041df756918c25f239e8d79 --- /dev/null +++ b/node_modules/events/tests/prepend.js @@ -0,0 +1,31 @@ +'use strict'; + +var common = require('./common'); +var EventEmitter = require('../'); +var assert = require('assert'); + +var myEE = new EventEmitter(); +var m = 0; +// This one comes last. +myEE.on('foo', common.mustCall(function () { + assert.strictEqual(m, 2); +})); + +// This one comes second. +myEE.prependListener('foo', common.mustCall(function () { + assert.strictEqual(m++, 1); +})); + +// This one comes first. +myEE.prependOnceListener('foo', + common.mustCall(function () { + assert.strictEqual(m++, 0); + })); + +myEE.emit('foo'); + +// Verify that the listener must be a function +assert.throws(function () { + var ee = new EventEmitter(); + ee.prependOnceListener('foo', null); +}, 'TypeError: The "listener" argument must be of type Function. Received type object'); diff --git a/node_modules/events/tests/remove-all-listeners.js b/node_modules/events/tests/remove-all-listeners.js new file mode 100644 index 0000000000000000000000000000000000000000..622941cfa604c0af52faabea35868f32ebf1237f --- /dev/null +++ b/node_modules/events/tests/remove-all-listeners.js @@ -0,0 +1,133 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('./common'); +var assert = require('assert'); +var events = require('../'); +var test = require('tape'); + +function expect(expected) { + var actual = []; + test.onFinish(function() { + var sortedActual = actual.sort(); + var sortedExpected = expected.sort(); + assert.strictEqual(sortedActual.length, sortedExpected.length); + for (var index = 0; index < sortedActual.length; index++) { + var value = sortedActual[index]; + assert.strictEqual(value, sortedExpected[index]); + } + }); + function listener(name) { + actual.push(name); + } + return common.mustCall(listener, expected.length); +} + +{ + var ee = new events.EventEmitter(); + var noop = common.mustNotCall(); + ee.on('foo', noop); + ee.on('bar', noop); + ee.on('baz', noop); + ee.on('baz', noop); + var fooListeners = ee.listeners('foo'); + var barListeners = ee.listeners('bar'); + var bazListeners = ee.listeners('baz'); + ee.on('removeListener', expect(['bar', 'baz', 'baz'])); + ee.removeAllListeners('bar'); + ee.removeAllListeners('baz'); + + var listeners = ee.listeners('foo'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 1); + assert.strictEqual(listeners[0], noop); + + listeners = ee.listeners('bar'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + listeners = ee.listeners('baz'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + // After calling removeAllListeners(), + // the old listeners array should stay unchanged. + assert.strictEqual(fooListeners.length, 1); + assert.strictEqual(fooListeners[0], noop); + assert.strictEqual(barListeners.length, 1); + assert.strictEqual(barListeners[0], noop); + assert.strictEqual(bazListeners.length, 2); + assert.strictEqual(bazListeners[0], noop); + assert.strictEqual(bazListeners[1], noop); + // After calling removeAllListeners(), + // new listeners arrays is different from the old. + assert.notStrictEqual(ee.listeners('bar'), barListeners); + assert.notStrictEqual(ee.listeners('baz'), bazListeners); +} + +{ + var ee = new events.EventEmitter(); + ee.on('foo', common.mustNotCall()); + ee.on('bar', common.mustNotCall()); + // Expect LIFO order + ee.on('removeListener', expect(['foo', 'bar', 'removeListener'])); + ee.on('removeListener', expect(['foo', 'bar'])); + ee.removeAllListeners(); + + var listeners = ee.listeners('foo'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + listeners = ee.listeners('bar'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); +} + +{ + var ee = new events.EventEmitter(); + ee.on('removeListener', common.mustNotCall()); + // Check for regression where removeAllListeners() throws when + // there exists a 'removeListener' listener, but there exists + // no listeners for the provided event type. + assert.doesNotThrow(function () { ee.removeAllListeners(ee, 'foo') }); +} + +{ + var ee = new events.EventEmitter(); + var expectLength = 2; + ee.on('removeListener', function() { + assert.strictEqual(expectLength--, this.listeners('baz').length); + }); + ee.on('baz', common.mustNotCall()); + ee.on('baz', common.mustNotCall()); + ee.on('baz', common.mustNotCall()); + assert.strictEqual(ee.listeners('baz').length, expectLength + 1); + ee.removeAllListeners('baz'); + assert.strictEqual(ee.listeners('baz').length, 0); +} + +{ + var ee = new events.EventEmitter(); + assert.strictEqual(ee, ee.removeAllListeners()); +} + +{ + var ee = new events.EventEmitter(); + ee._events = undefined; + assert.strictEqual(ee, ee.removeAllListeners()); +} diff --git a/node_modules/events/tests/remove-listeners.js b/node_modules/events/tests/remove-listeners.js new file mode 100644 index 0000000000000000000000000000000000000000..18e4d1651fa2546a810774fd59147aee25624154 --- /dev/null +++ b/node_modules/events/tests/remove-listeners.js @@ -0,0 +1,212 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('./common'); +var assert = require('assert'); +var EventEmitter = require('../'); + +var listener1 = function listener1() {}; +var listener2 = function listener2() {}; + +{ + var ee = new EventEmitter(); + ee.on('hello', listener1); + ee.on('removeListener', common.mustCall(function(name, cb) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(cb, listener1); + })); + ee.removeListener('hello', listener1); + var listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); +} + +{ + var ee = new EventEmitter(); + ee.on('hello', listener1); + ee.on('removeListener', common.mustNotCall()); + ee.removeListener('hello', listener2); + + var listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 1); + assert.strictEqual(listeners[0], listener1); +} + +{ + var ee = new EventEmitter(); + ee.on('hello', listener1); + ee.on('hello', listener2); + + var listeners; + ee.once('removeListener', common.mustCall(function(name, cb) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(cb, listener1); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 1); + assert.strictEqual(listeners[0], listener2); + })); + ee.removeListener('hello', listener1); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 1); + assert.strictEqual(listeners[0], listener2); + ee.once('removeListener', common.mustCall(function(name, cb) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(cb, listener2); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + })); + ee.removeListener('hello', listener2); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); +} + +{ + var ee = new EventEmitter(); + + function remove1() { + assert.fail('remove1 should not have been called'); + } + + function remove2() { + assert.fail('remove2 should not have been called'); + } + + ee.on('removeListener', common.mustCall(function(name, cb) { + if (cb !== remove1) return; + this.removeListener('quux', remove2); + this.emit('quux'); + }, 2)); + ee.on('quux', remove1); + ee.on('quux', remove2); + ee.removeListener('quux', remove1); +} + +{ + var ee = new EventEmitter(); + ee.on('hello', listener1); + ee.on('hello', listener2); + + var listeners; + ee.once('removeListener', common.mustCall(function(name, cb) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(cb, listener1); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 1); + assert.strictEqual(listeners[0], listener2); + ee.once('removeListener', common.mustCall(function(name, cb) { + assert.strictEqual(name, 'hello'); + assert.strictEqual(cb, listener2); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + })); + ee.removeListener('hello', listener2); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); + })); + ee.removeListener('hello', listener1); + listeners = ee.listeners('hello'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 0); +} + +{ + var ee = new EventEmitter(); + var listener3 = common.mustCall(function() { + ee.removeListener('hello', listener4); + }, 2); + var listener4 = common.mustCall(); + + ee.on('hello', listener3); + ee.on('hello', listener4); + + // listener4 will still be called although it is removed by listener 3. + ee.emit('hello'); + // This is so because the interal listener array at time of emit + // was [listener3,listener4] + + // Interal listener array [listener3] + ee.emit('hello'); +} + +{ + var ee = new EventEmitter(); + + ee.once('hello', listener1); + ee.on('removeListener', common.mustCall(function(eventName, listener) { + assert.strictEqual(eventName, 'hello'); + assert.strictEqual(listener, listener1); + })); + ee.emit('hello'); +} + +{ + var ee = new EventEmitter(); + + assert.strictEqual(ee, ee.removeListener('foo', function() {})); +} + +// Verify that the removed listener must be a function +assert.throws(function() { + var ee = new EventEmitter(); + + ee.removeListener('foo', null); +}, /^TypeError: The "listener" argument must be of type Function\. Received type object$/); + +{ + var ee = new EventEmitter(); + var listener = function() {}; + ee._events = undefined; + var e = ee.removeListener('foo', listener); + assert.strictEqual(e, ee); +} + +{ + var ee = new EventEmitter(); + + ee.on('foo', listener1); + ee.on('foo', listener2); + var listeners = ee.listeners('foo'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 2); + assert.strictEqual(listeners[0], listener1); + assert.strictEqual(listeners[1], listener2); + + ee.removeListener('foo', listener1); + assert.strictEqual(ee._events.foo, listener2); + + ee.on('foo', listener1); + listeners = ee.listeners('foo'); + assert.ok(Array.isArray(listeners)); + assert.strictEqual(listeners.length, 2); + assert.strictEqual(listeners[0], listener2); + assert.strictEqual(listeners[1], listener1); + + ee.removeListener('foo', listener1); + assert.strictEqual(ee._events.foo, listener2); +} diff --git a/node_modules/events/tests/set-max-listeners-side-effects.js b/node_modules/events/tests/set-max-listeners-side-effects.js new file mode 100644 index 0000000000000000000000000000000000000000..13dbb671e9024280b2e9be42206a23b2db355074 --- /dev/null +++ b/node_modules/events/tests/set-max-listeners-side-effects.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +require('./common'); +var assert = require('assert'); +var events = require('../'); + +var e = new events.EventEmitter(); + +if (Object.create) assert.ok(!(e._events instanceof Object)); +assert.strictEqual(Object.keys(e._events).length, 0); +e.setMaxListeners(5); +assert.strictEqual(Object.keys(e._events).length, 0); diff --git a/node_modules/events/tests/special-event-names.js b/node_modules/events/tests/special-event-names.js new file mode 100644 index 0000000000000000000000000000000000000000..a2f0b744a706c9ae6181a9723b2b92492df7e4d1 --- /dev/null +++ b/node_modules/events/tests/special-event-names.js @@ -0,0 +1,45 @@ +'use strict'; + +var common = require('./common'); +var EventEmitter = require('../'); +var assert = require('assert'); + +var ee = new EventEmitter(); +var handler = function() {}; + +assert.strictEqual(ee.eventNames().length, 0); + +assert.strictEqual(ee._events.hasOwnProperty, undefined); +assert.strictEqual(ee._events.toString, undefined); + +ee.on('__defineGetter__', handler); +ee.on('toString', handler); +ee.on('__proto__', handler); + +assert.strictEqual(ee.eventNames()[0], '__defineGetter__'); +assert.strictEqual(ee.eventNames()[1], 'toString'); + +assert.strictEqual(ee.listeners('__defineGetter__').length, 1); +assert.strictEqual(ee.listeners('__defineGetter__')[0], handler); +assert.strictEqual(ee.listeners('toString').length, 1); +assert.strictEqual(ee.listeners('toString')[0], handler); + +// Only run __proto__ tests if that property can actually be set +if ({ __proto__: 'ok' }.__proto__ === 'ok') { + assert.strictEqual(ee.eventNames().length, 3); + assert.strictEqual(ee.eventNames()[2], '__proto__'); + assert.strictEqual(ee.listeners('__proto__').length, 1); + assert.strictEqual(ee.listeners('__proto__')[0], handler); + + ee.on('__proto__', common.mustCall(function(val) { + assert.strictEqual(val, 1); + })); + ee.emit('__proto__', 1); + + process.on('__proto__', common.mustCall(function(val) { + assert.strictEqual(val, 1); + })); + process.emit('__proto__', 1); +} else { + console.log('# skipped __proto__') +} diff --git a/node_modules/events/tests/subclass.js b/node_modules/events/tests/subclass.js new file mode 100644 index 0000000000000000000000000000000000000000..bd033fff4d26696cddcb6a87f25da89d67a04e59 --- /dev/null +++ b/node_modules/events/tests/subclass.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('./common'); +var test = require('tape'); +var assert = require('assert'); +var EventEmitter = require('../').EventEmitter; +var util = require('util'); + +util.inherits(MyEE, EventEmitter); + +function MyEE(cb) { + this.once(1, cb); + this.emit(1); + this.removeAllListeners(); + EventEmitter.call(this); +} + +var myee = new MyEE(common.mustCall()); + + +util.inherits(ErrorEE, EventEmitter); +function ErrorEE() { + this.emit('error', new Error('blerg')); +} + +assert.throws(function() { + new ErrorEE(); +}, /blerg/); + +test.onFinish(function() { + assert.ok(!(myee._events instanceof Object)); + assert.strictEqual(Object.keys(myee._events).length, 0); +}); + + +function MyEE2() { + EventEmitter.call(this); +} + +MyEE2.prototype = new EventEmitter(); + +var ee1 = new MyEE2(); +var ee2 = new MyEE2(); + +ee1.on('x', function() {}); + +assert.strictEqual(ee2.listenerCount('x'), 0); diff --git a/node_modules/events/tests/symbols.js b/node_modules/events/tests/symbols.js new file mode 100644 index 0000000000000000000000000000000000000000..0721f0ec0b5d6ef520f30eb3c711551eaabd2204 --- /dev/null +++ b/node_modules/events/tests/symbols.js @@ -0,0 +1,25 @@ +'use strict'; + +var common = require('./common'); +var EventEmitter = require('../'); +var assert = require('assert'); + +var ee = new EventEmitter(); +var foo = Symbol('foo'); +var listener = common.mustCall(); + +ee.on(foo, listener); +assert.strictEqual(ee.listeners(foo).length, 1); +assert.strictEqual(ee.listeners(foo)[0], listener); + +ee.emit(foo); + +ee.removeAllListeners(); +assert.strictEqual(ee.listeners(foo).length, 0); + +ee.on(foo, listener); +assert.strictEqual(ee.listeners(foo).length, 1); +assert.strictEqual(ee.listeners(foo)[0], listener); + +ee.removeListener(foo, listener); +assert.strictEqual(ee.listeners(foo).length, 0); diff --git a/node_modules/eventsource-parser/LICENSE b/node_modules/eventsource-parser/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..747ce3cf546a561c493b341b418afca7166bf2d5 --- /dev/null +++ b/node_modules/eventsource-parser/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Espen Hovlandsdal + +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. diff --git a/node_modules/eventsource-parser/README.md b/node_modules/eventsource-parser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ca4026eb103eb73d0ac37c7613f6e1d34ddc600a --- /dev/null +++ b/node_modules/eventsource-parser/README.md @@ -0,0 +1,157 @@ +# eventsource-parser + +[![npm version](https://img.shields.io/npm/v/eventsource-parser.svg?style=flat-square)](https://www.npmjs.com/package/eventsource-parser)[![npm bundle size](https://img.shields.io/bundlephobia/minzip/eventsource-parser?style=flat-square)](https://bundlephobia.com/result?p=eventsource-parser)[![npm weekly downloads](https://img.shields.io/npm/dw/eventsource-parser.svg?style=flat-square)](https://www.npmjs.com/package/eventsource-parser) + +A streaming parser for [server-sent events/eventsource](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events), without any assumptions about how the actual stream of data is retrieved. It is intended to be a building block for [clients](https://github.com/rexxars/eventsource-client) and polyfills in javascript environments such as browsers, node.js and deno. + +If you are looking for a modern client implementation, see [eventsource-client](https://github.com/rexxars/eventsource-client). + +You create an instance of the parser, and _feed_ it chunks of data - partial or complete, and the parse emits parsed messages once it receives a complete message. A [TransformStream variant](#stream-usage) is also available for environments that support it (modern browsers, Node 18 and higher). + +Other modules in the EventSource family: + +- [eventsource-client](https://github.com/rexxars/eventsource-client): modern, feature rich eventsource client for browsers, node.js, bun, deno and other modern JavaScript environments. +- [eventsource-encoder](https://github.com/rexxars/eventsource-encoder): encodes messages in the EventSource/Server-Sent Events format. +- [eventsource](https://github.com/eventsource/eventsource): Node.js polyfill for the WhatWG EventSource API. + +> [!NOTE] +> Migrating from eventsource-parser 1.x/2.x? See the [migration guide](./MIGRATE-v3.md). + +## Installation + +```bash +npm install --save eventsource-parser +``` + +## Usage + +```ts +import {createParser, type EventSourceMessage} from 'eventsource-parser' + +function onEvent(event: EventSourceMessage) { + console.log('Received event!') + console.log('id: %s', event.id || '') + console.log('event: %s', event.event || '') + console.log('data: %s', event.data) +} + +const parser = createParser({onEvent}) +const sseStream = getSomeReadableStream() + +for await (const chunk of sseStream) { + parser.feed(chunk) +} + +// If you want to re-use the parser for a new stream of events, make sure to reset it! +parser.reset() +console.log('Done!') +``` + +### Retry intervals + +If the server sends a `retry` field in the event stream, the parser will call any `onRetry` callback specified to the `createParser` function: + +```ts +const parser = createParser({ + onRetry(retryInterval) { + console.log('Server requested retry interval of %dms', retryInterval) + }, + onEvent(event) { + // … + }, +}) +``` + +### Parse errors + +If the parser encounters an error while parsing, it will call any `onError` callback provided to the `createParser` function: + +```ts +import {type ParseError} from 'eventsource-parser' + +const parser = createParser({ + onError(error: ParseError) { + console.error('Error parsing event:', error) + if (error.type === 'invalid-field') { + console.error('Field name:', error.field) + console.error('Field value:', error.value) + console.error('Line:', error.line) + } else if (error.type === 'invalid-retry') { + console.error('Invalid retry interval:', error.value) + } + }, + onEvent(event) { + // … + }, +}) +``` + +Note that `invalid-field` errors will usually be called for any invalid data - not only data shaped as `field: value`. This is because the EventSource specification says to treat anything prior to a `:` as the field name. Use the `error.line` property to get the full line that caused the error. + +> [!NOTE] +> When encountering the end of a stream, calling `.reset({consume: true})` on the parser to flush any remaining data and reset the parser state. This will trigger the `onError` callback if the pending data is not a valid event. + +### Comments + +The parser will ignore comments (lines starting with `:`) by default. If you want to handle comments, you can provide an `onComment` callback to the `createParser` function: + +```ts +const parser = createParser({ + onComment(comment) { + console.log('Received comment:', comment) + }, + onEvent(event) { + // … + }, +}) +``` + +> [!NOTE] +> Leading whitespace is not stripped from comments, eg `: comment` will give ` comment` as the comment value, not `comment` (note the leading space). + +### Limiting buffered memory (`maxBufferSize`) + +By default the parser buffers data indefinitely until a server completes an event. A server (or proxy) that never terminates a line, or that keeps appending `data:` lines without ever sending a blank line to dispatch the event, can therefore grow the parser's buffers without bound. + +Pass a `maxBufferSize` (in characters) to `createParser` to cap this. If the combined size of the pending line buffer and the in-progress event's data buffer exceeds the limit, the parser emits a `ParseError` with `type: 'max-buffer-size-exceeded'` and becomes terminated: subsequent calls to `feed()` will throw until `reset()` is called. + +```ts +const parser = createParser({ + maxBufferSize: 1024 * 1024, // 1 MB + onEvent(event) { + // … + }, + onError(error) { + if (error.type === 'max-buffer-size-exceeded') { + // Stream peer is misbehaving — typically you'd close the connection. + } + }, +}) +``` + +The same option is available on the [stream variant](#stream-usage); the stream is always errored when this limit is exceeded, regardless of the `onError` setting (since the underlying parser is unrecoverable without a `reset()`). + +## Stream usage + +```ts +import {EventSourceParserStream} from 'eventsource-parser/stream' + +const eventStream = response.body + .pipeThrough(new TextDecoderStream()) + .pipeThrough(new EventSourceParserStream()) +``` + +The stream constructor accepts a subset of the `createParser` options (`onComment`, `onRetry`, `maxBufferSize`) plus an `onError` that can either be a function or set to `'terminate'` to error the stream on parse errors. Events are delivered through the stream itself rather than via an `onEvent` callback: + +```ts +new EventSourceParserStream({ + maxBufferSize: 1024 * 1024, + onError: 'terminate', +}) +``` + +Note that the TransformStream is exposed under a separate export (`eventsource-parser/stream`), in order to maximize compatibility with environments that do not have the `TransformStream` constructor available. + +## License + +MIT © [Espen Hovlandsdal](https://espen.codes/) diff --git a/node_modules/eventsource-parser/package.json b/node_modules/eventsource-parser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6a50dea28c5e72ed8d0b41189aa00f896d77f8a2 --- /dev/null +++ b/node_modules/eventsource-parser/package.json @@ -0,0 +1,92 @@ +{ + "name": "eventsource-parser", + "version": "3.1.0", + "description": "Streaming, source-agnostic EventSource/Server-Sent Events parser", + "keywords": [ + "eventsource", + "server-sent-events", + "sse" + ], + "homepage": "https://github.com/rexxars/eventsource-parser#readme", + "bugs": { + "url": "https://github.com/rexxars/eventsource-parser/issues" + }, + "license": "MIT", + "author": "Espen Hovlandsdal ", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/rexxars/eventsource-parser.git" + }, + "files": [ + "dist", + "!dist/stats.html", + "!dist/index.min.js", + "src", + "stream.js" + ], + "type": "module", + "sideEffects": false, + "main": "./dist/index.cjs", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "source": "./src/index.ts", + "import": "./dist/index.js", + "require": "./dist/index.cjs", + "default": "./dist/index.js" + }, + "./stream": { + "source": "./src/stream.ts", + "import": "./dist/stream.js", + "require": "./dist/stream.cjs", + "default": "./dist/stream.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "build": "pkg-utils build && pkg-utils --strict", + "clean": "rimraf dist coverage", + "check": "npm run clean && npm run format && npm run lint && npm run build && vitest run", + "format": "oxfmt", + "format:check": "oxfmt --check", + "bench": "node --expose-gc --experimental-strip-types --no-warnings=ExperimentalWarning bench/parse.bench.ts", + "bundle-size": "node --experimental-strip-types --no-warnings=ExperimentalWarning scripts/bundle-size.ts", + "knip": "knip", + "lint": "oxlint && tsc --noEmit", + "posttest": "npm run lint", + "prebuild": "npm run clean", + "prepublishOnly": "npm run build", + "test": "npm run test:node", + "test:bun": "bun test", + "test:deno": "deno run --allow-write --allow-net --allow-run --allow-sys --allow-ffi --allow-env --allow-read npm:vitest", + "test:node": "vitest --reporter=verbose" + }, + "devDependencies": { + "@sanity/pkg-utils": "^10.4.18", + "@sanity/semantic-release-preset": "^6.0.0", + "@sanity/tsconfig": "^2.1.0", + "@types/node": "^20.19.0", + "eventsource-encoder": "^1.0.2", + "knip": "^6.7.0", + "mitata": "^1.0.34", + "oxfmt": "^0.47.0", + "oxlint": "^1.62.0", + "rimraf": "^6.1.3", + "rollup-plugin-visualizer": "^6.0.3", + "semantic-release": "^25.0.3", + "terser": "^5.46.2", + "typescript": "^5.9.3", + "vitest": "^4.1.5" + }, + "browserslist": [ + "node >= 18", + "chrome >= 71", + "safari >= 14.1", + "firefox >= 105", + "edge >= 79" + ], + "engines": { + "node": ">=18.0.0" + } +} diff --git a/node_modules/eventsource-parser/src/errors.ts b/node_modules/eventsource-parser/src/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..cfb38834709c0af180004e68af35472d7e16c90e --- /dev/null +++ b/node_modules/eventsource-parser/src/errors.ts @@ -0,0 +1,44 @@ +/** + * The type of error that occurred. + * @public + */ +export type ErrorType = 'invalid-retry' | 'unknown-field' | 'max-buffer-size-exceeded' + +/** + * Error thrown when encountering an issue during parsing. + * + * @public + */ +export class ParseError extends Error { + /** + * The type of error that occurred. + */ + type: ErrorType + + /** + * In the case of an unknown field encountered in the stream, this will be the field name. + */ + field?: string | undefined + + /** + * In the case of an unknown field encountered in the stream, this will be the value of the field. + */ + value?: string | undefined + + /** + * The line that caused the error, if available. + */ + line?: string | undefined + + constructor( + message: string, + options: {type: ErrorType; field?: string; value?: string; line?: string}, + ) { + super(message) + this.name = 'ParseError' + this.type = options.type + this.field = options.field + this.value = options.value + this.line = options.line + } +} diff --git a/node_modules/eventsource-parser/src/index.ts b/node_modules/eventsource-parser/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..1202c41602ebc2709cdbac89bc58398097417f66 --- /dev/null +++ b/node_modules/eventsource-parser/src/index.ts @@ -0,0 +1,8 @@ +export {type ErrorType, ParseError} from './errors.ts' +export {createParser} from './parse.ts' +export type { + EventSourceMessage, + EventSourceParser, + ParserCallbacks, + ParserConfig, +} from './types.ts' diff --git a/node_modules/eventsource-parser/src/parse.ts b/node_modules/eventsource-parser/src/parse.ts new file mode 100644 index 0000000000000000000000000000000000000000..00e2791871e31a10033ea3644879688e8518612f --- /dev/null +++ b/node_modules/eventsource-parser/src/parse.ts @@ -0,0 +1,437 @@ +/** + * EventSource/Server-Sent Events parser + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html + */ +import {ParseError} from './errors.ts' +import type {EventSourceParser, ParserConfig} from './types.ts' + +// ASCII codes used in the hot parsing paths. +const LF = 10 +const CR = 13 +const SPACE = 32 + +// oxlint-disable-next-line no-unused-vars +function noop(_arg: unknown) { + // intentional noop +} + +/** + * Creates a new EventSource parser. + * + * @param config - Parser configuration. Accepts callbacks (see {@link ParserCallbacks}) + * and options like `maxBufferSize` (see {@link ParserConfig}). + * + * @returns A new EventSource parser, with `feed` and `reset` methods. + * @public + */ +export function createParser(config: ParserConfig): EventSourceParser { + if (typeof config === 'function') { + throw new TypeError( + '`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?', + ) + } + + const {onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize} = config + + // Trailing bytes from prior `feed()` calls that did not yet form a complete line. + // Stored as an array of fragments and only joined when a line terminator arrives. + // Concatenating per-feed (`prefix + chunk`) is O(N²) when a single SSE line spans + // many chunks (e.g. a large `data:` payload streamed in tiny slices, or an MCP-style + // server that emits one giant content block). Buffering as fragments + joining once + // makes the same workload linear. + const pendingFragments: string[] = [] + + // Running total of `pendingFragments` lengths, kept in sync with the array so the + // `maxBufferSize` check doesn't have to walk the fragment list on every feed. + let pendingFragmentsLength = 0 + + let isFirstChunk = true + let id: string | undefined + let data = '' + let dataLines = 0 + let eventType: string | undefined + + // Set after a `maxBufferSize` overflow. Once tripped, `feed()` throws until + // `reset()` is called — see the comment on `maxBufferSize` in `ParserConfig`. + let terminated = false + + /** + * Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do + * not yet form a complete line are held back and prepended to the next chunk, + * so callers can pass arbitrary slices of the stream without worrying about + * line boundaries. + * + * Per the SSE spec, a UTF-8 BOM (0xEF 0xBB 0xBF) at the start of the very + * first chunk is stripped before parsing. + * + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream + */ + function feed(chunk: string) { + if (terminated) { + throw new Error( + 'Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.', + ) + } + + if (isFirstChunk) { + isFirstChunk = false + // Match and strip UTF-8 BOM from the start of the stream, if present. + // (Per the spec, this is only valid at the very start of the stream) + if ( + chunk.charCodeAt(0) === 0xef && + chunk.charCodeAt(1) === 0xbb && + chunk.charCodeAt(2) === 0xbf + ) { + chunk = chunk.slice(3) + } + } + + // Hot path: no buffered prefix from a prior partial line. Hand the chunk + // straight to `processLines`, exactly like the original implementation. + // Zero new work in the common case (every chunk ends with `\n\n`). + if (pendingFragments.length === 0) { + const trailing = processLines(chunk) + if (trailing !== '') { + pendingFragments.push(trailing) + pendingFragmentsLength = trailing.length + } + checkBufferSize() + return + } + + // We have a buffered prefix. If this chunk also has no terminator, append + // to the buffer without concatenating — that's the O(N²) trap we're + // avoiding (large single `data:` payload split across many tiny chunks). + if (chunk.indexOf('\n') === -1 && chunk.indexOf('\r') === -1) { + pendingFragments.push(chunk) + pendingFragmentsLength += chunk.length + checkBufferSize() + return + } + + // Terminator arrived. Join the accumulated fragments + this chunk once, + // process, and buffer any new trailing partial line. + pendingFragments.push(chunk) + const input = pendingFragments.join('') + pendingFragments.length = 0 + pendingFragmentsLength = 0 + const trailing = processLines(input) + if (trailing !== '') { + pendingFragments.push(trailing) + pendingFragmentsLength = trailing.length + } + checkBufferSize() + } + + function checkBufferSize() { + if (maxBufferSize === undefined) return + if (pendingFragmentsLength + data.length <= maxBufferSize) return + + terminated = true + pendingFragments.length = 0 + pendingFragmentsLength = 0 + id = undefined + data = '' + dataLines = 0 + eventType = undefined + onError( + new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, { + type: 'max-buffer-size-exceeded', + }), + ) + } + + /** + * Splits `chunk` into SSE lines and dispatches each to the appropriate handler. + * Returns any trailing bytes that did not terminate with a line break, so the + * caller can prepend them to the next chunk. + * + * The SSE spec permits three line terminators: `\n`, `\r`, and `\r\n`. Real-world + * streams almost always use plain `\n`, so we take a fast path when no `\r` is + * present in the chunk. The slow path is spec-correct but does more work per line. + */ + function processLines(chunk: string): string { + let searchIndex = 0 + + // Fast path: LF-only chunk (the common case for typical SSE servers). + // We can scan forward with a single `indexOf('\n')` per line and inline + // the hot-path branches for `data:` and `event:` without the CR bookkeeping + // the slow path needs. + if (chunk.indexOf('\r') === -1) { + let lfIndex = chunk.indexOf('\n', searchIndex) + while (lfIndex !== -1) { + // Blank line: end-of-event marker. Dispatch the accumulated event (if any) + // and reset the buffered fields. This is hoisted out of `parseLine` because + // it's the single most common line shape after `data:` lines. + if (searchIndex === lfIndex) { + if (dataLines > 0) { + onEvent({id, event: eventType, data}) + } + id = undefined + data = '' + dataLines = 0 + eventType = undefined + searchIndex = lfIndex + 1 + lfIndex = chunk.indexOf('\n', searchIndex) + continue + } + const firstCharCode = chunk.charCodeAt(searchIndex) + if (isDataPrefix(chunk, searchIndex, firstCharCode)) { + // `data:` line — append the value to the event's data buffer. + // 'data:'.length === 5, 'data: '.length === 6 + const valueStart = + chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5 + const value = chunk.slice(valueStart, lfIndex) + // Fast path within a fast path: if this is the first data line AND the + // next char is another LF (i.e. `data:foo\n\n`), dispatch immediately + // without ever writing to the `data` buffer. This is the shape of a + // typical single-line SSE event (ChatGPT-style streams, etc.) and is + // hot enough to be worth the duplication. + if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) { + onEvent({id, event: eventType, data: value}) + id = undefined + data = '' + eventType = undefined + searchIndex = lfIndex + 2 + lfIndex = chunk.indexOf('\n', searchIndex) + continue + } + // Multi-line data: concatenate with newline separator per spec. + data = dataLines === 0 ? value : `${data}\n${value}` + dataLines++ + } else if (isEventPrefix(chunk, searchIndex, firstCharCode)) { + // `event:` line — set the event type for the next dispatch. Per spec, + // an empty value resets `event type` to its default (undefined here). + // 'event:'.length === 6, 'event: '.length === 7 + eventType = + chunk.slice( + chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, + lfIndex, + ) || undefined + } else { + // Everything else: `id:`, `retry:`, comment lines (`:` prefix), unknown + // fields, or malformed lines. These are rarer and go through the full + // per-line parser, which handles the SSE field grammar in detail. + parseLine(chunk, searchIndex, lfIndex) + } + searchIndex = lfIndex + 1 + lfIndex = chunk.indexOf('\n', searchIndex) + } + return chunk.slice(searchIndex) + } + + // Slow path: the chunk contains at least one `\r`, so lines may be terminated + // by `\r`, `\n`, or `\r\n`. We locate the next terminator by looking at both + // the nearest `\r` and `\n` and picking whichever comes first. + while (searchIndex < chunk.length) { + const crIndex = chunk.indexOf('\r', searchIndex) + const lfIndex = chunk.indexOf('\n', searchIndex) + + let lineEnd = -1 + if (crIndex !== -1 && lfIndex !== -1) { + lineEnd = crIndex < lfIndex ? crIndex : lfIndex + } else if (crIndex !== -1) { + // A trailing `\r` at the very end of the chunk is ambiguous: it could be + // a bare-CR terminator, or the first half of a `\r\n` whose `\n` arrives + // in the next chunk. Defer until we see more input. + if (crIndex === chunk.length - 1) { + lineEnd = -1 + } else { + lineEnd = crIndex + } + } else if (lfIndex !== -1) { + lineEnd = lfIndex + } + + if (lineEnd === -1) { + break + } + + parseLine(chunk, searchIndex, lineEnd) + searchIndex = lineEnd + 1 + // If we just consumed a `\r` and the next char is `\n`, skip it so the + // pair is treated as a single terminator rather than an empty line. + if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) { + searchIndex++ + } + } + + return chunk.slice(searchIndex) + } + + function parseLine(chunk: string, start: number, end: number) { + if (start === end) { + dispatchEvent() + return + } + + const firstCharCode = chunk.charCodeAt(start) + + if (isDataPrefix(chunk, start, firstCharCode)) { + // 'data:'.length === 5, 'data: '.length === 6 + const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5 + const value = chunk.slice(valueStart, end) + data = dataLines === 0 ? value : `${data}\n${value}` + dataLines++ + return + } + + if (isEventPrefix(chunk, start, firstCharCode)) { + // 'event:'.length === 6, 'event: '.length === 7 + eventType = + chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined + return + } + + // Fast path for "id:" — 'i' = 105, 'd' = 100, ':' = 58 + if ( + firstCharCode === 105 && + chunk.charCodeAt(start + 1) === 100 && + chunk.charCodeAt(start + 2) === 58 + ) { + // 'id:'.length === 3, 'id: '.length === 4 + const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end) + id = value.includes('\0') ? undefined : value + return + } + + // Comment line — ':' = 58 + if (firstCharCode === 58) { + if (onComment) { + const line = chunk.slice(start, end) + // skip ':' (+1), or ': ' (+2) when a space follows + onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1)) + } + return + } + + const line = chunk.slice(start, end) + const fieldSeparatorIndex = line.indexOf(':') + if (fieldSeparatorIndex === -1) { + processField(line, '', line) + return + } + + const field = line.slice(0, fieldSeparatorIndex) + // skip ':' (+1), or ': ' (+2) when a space follows + const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1 + const value = line.slice(fieldSeparatorIndex + offset) + processField(field, value, line) + } + + function processField(field: string, value: string, line: string) { + // Field names must be compared literally, with no case folding performed. + switch (field) { + case 'event': + // Set the `event type` buffer to field value + eventType = value || undefined + break + case 'data': + data = dataLines === 0 ? value : `${data}\n${value}` + dataLines++ + break + case 'id': + // If the field value does not contain U+0000 NULL, then set the `ID` buffer to + // the field value. Otherwise, ignore the field. + id = value.includes('\0') ? undefined : value + break + case 'retry': + // If the field value consists of only ASCII digits, then interpret the field value as an + // integer in base ten, and set the event stream's reconnection time to that integer. + // Otherwise, ignore the field. + if (/^\d+$/.test(value)) { + onRetry(parseInt(value, 10)) + } else { + onError( + new ParseError(`Invalid \`retry\` value: "${value}"`, { + type: 'invalid-retry', + value, + line, + }), + ) + } + break + default: + // Otherwise, the field is ignored. + onError( + new ParseError( + `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}…` : field}"`, + {type: 'unknown-field', field, value, line}, + ), + ) + break + } + } + + function dispatchEvent() { + if (dataLines > 0) { + onEvent({ + id, + event: eventType, + data, + }) + } + + id = undefined + data = '' + dataLines = 0 + eventType = undefined + } + + function reset(options: {consume?: boolean} = {}) { + if (options.consume && pendingFragments.length > 0) { + const incompleteLine = pendingFragments.join('') + parseLine(incompleteLine, 0, incompleteLine.length) + } + + isFirstChunk = true + id = undefined + data = '' + dataLines = 0 + eventType = undefined + pendingFragments.length = 0 + pendingFragmentsLength = 0 + terminated = false + } + + return {feed, reset} +} + +/** + * Checks if `chunk` starts with the literal `data:` at index `i`. + * + * Equivalent to `chunk.startsWith('data:', i)`, but benchmarks show this + * hand-unrolled char-code comparison is ~20% faster on common event types. + * The caller passes `firstCharCode` (the code at `i`) so it can be reused + * across prefix checks. + * + * ASCII: 'd' = 100, 'a' = 97, 't' = 116, 'a' = 97, ':' = 58 + */ +function isDataPrefix(chunk: string, i: number, firstCharCode: number): boolean { + return ( + firstCharCode === 100 && + chunk.charCodeAt(i + 1) === 97 && + chunk.charCodeAt(i + 2) === 116 && + chunk.charCodeAt(i + 3) === 97 && + chunk.charCodeAt(i + 4) === 58 + ) +} + +/** + * Checks if `chunk` starts with the literal `event:` at index `i`. + * + * See {@link isDataPrefix} for why this is hand-unrolled rather than using + * `String.prototype.startsWith`. + * + * ASCII: 'e' = 101, 'v' = 118, 'e' = 101, 'n' = 110, 't' = 116, ':' = 58 + */ +function isEventPrefix(chunk: string, i: number, firstCharCode: number): boolean { + return ( + firstCharCode === 101 && + chunk.charCodeAt(i + 1) === 118 && + chunk.charCodeAt(i + 2) === 101 && + chunk.charCodeAt(i + 3) === 110 && + chunk.charCodeAt(i + 4) === 116 && + chunk.charCodeAt(i + 5) === 58 + ) +} diff --git a/node_modules/eventsource-parser/src/stream.ts b/node_modules/eventsource-parser/src/stream.ts new file mode 100644 index 0000000000000000000000000000000000000000..a436b3ca799956f9557f93df88ccd56f3a0e1963 --- /dev/null +++ b/node_modules/eventsource-parser/src/stream.ts @@ -0,0 +1,107 @@ +import {createParser} from './parse.ts' +import type {EventSourceMessage, EventSourceParser} from './types.ts' + +/** + * Options for the EventSourceParserStream. + * + * @public + */ +export interface StreamOptions { + /** + * Behavior when a parsing error occurs. + * + * - A custom function can be provided to handle the error. + * - `'terminate'` will error the stream and stop parsing. + * - Any other value will ignore the error and continue parsing. + * + * @defaultValue `undefined` + */ + onError?: ('terminate' | ((error: Error) => void)) | undefined + + /** + * Callback for when a reconnection interval is sent from the server. + * + * @param retry - The number of milliseconds to wait before reconnecting. + */ + onRetry?: ((retry: number) => void) | undefined + + /** + * Callback for when a comment is encountered in the stream. + * + * @param comment - The comment encountered in the stream. + */ + onComment?: ((comment: string) => void) | undefined + + /** + * Maximum number of characters the parser is allowed to buffer across calls to `feed()`. + * See {@link ParserConfig.maxBufferSize} for details. + * + * When the limit is exceeded, the stream is always errored (regardless of the `onError` + * setting) since the underlying parser is unrecoverable without a `reset()`. + * + * @defaultValue `undefined` (unbounded) + */ + maxBufferSize?: number | undefined +} + +/** + * A TransformStream that ingests a stream of strings and produces a stream of `EventSourceMessage`. + * + * @example Basic usage + * ``` + * const eventStream = + * response.body + * .pipeThrough(new TextDecoderStream()) + * .pipeThrough(new EventSourceParserStream()) + * ``` + * + * @example Terminate stream on parsing errors + * ``` + * const eventStream = + * response.body + * .pipeThrough(new TextDecoderStream()) + * .pipeThrough(new EventSourceParserStream({onError: 'terminate'})) + * ``` + * + * @public + */ +export class EventSourceParserStream extends TransformStream { + constructor({onError, onRetry, onComment, maxBufferSize}: StreamOptions = {}) { + let parser!: EventSourceParser + + super({ + start(controller) { + parser = createParser({ + onEvent: (event) => { + controller.enqueue(event) + }, + onError(error) { + if (typeof onError === 'function') { + onError(error) + } + + // `max-buffer-size-exceeded` is fatal — the parser is unusable until + // `reset()`, which the stream wrapper has no way to call. Always + // terminate the stream in that case so consumers see the meaningful + // `ParseError` instead of an opaque "cannot feed terminated parser" + // throw from the next chunk. + if (onError === 'terminate' || error.type === 'max-buffer-size-exceeded') { + controller.error(error) + } + + // Ignore by default + }, + onRetry, + onComment, + maxBufferSize, + }) + }, + transform(chunk) { + parser.feed(chunk) + }, + }) + } +} + +export {type ErrorType, ParseError} from './errors.ts' +export type {EventSourceMessage} from './types.ts' diff --git a/node_modules/eventsource-parser/src/types.ts b/node_modules/eventsource-parser/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..fd668d04ca248d39933d0740b9a693ac07d947a3 --- /dev/null +++ b/node_modules/eventsource-parser/src/types.ts @@ -0,0 +1,122 @@ +import type {ParseError} from './errors.ts' + +/** + * EventSource parser instance. + * + * Needs to be reset between reconnections/when switching data source, using the `reset()` method. + * + * @public + */ +export interface EventSourceParser { + /** + * Feeds the parser another chunk. The method _does not_ return a parsed message. + * Instead, callbacks passed when creating the parser will be triggered once we see enough data + * for a valid/invalid parsing step (see {@link ParserCallbacks}). + * + * @param chunk - The chunk to parse. Can be a partial, eg in the case of streaming messages. + * @public + */ + feed(chunk: string): void + + /** + * Resets the parser state. This is required when you have a new stream of messages - + * for instance in the case of a client being disconnected and reconnecting. + * + * Previously received, incomplete data will NOT be parsed unless you pass `consume: true`, + * which tells the parser to attempt to consume any incomplete data as if it ended with a newline + * character. This is useful for cases when a server sends a non-EventSource message that you + * want to be able to react to in an `onError` callback. + * + * @public + */ + reset(options?: {consume?: boolean}): void +} + +/** + * A parsed EventSource message event + * + * @public + */ +export interface EventSourceMessage { + /** + * The event type sent from the server. Note that this differs from the browser `EventSource` + * implementation in that browsers will default this to `message`, whereas this parser will + * leave this as `undefined` if not explicitly declared. + */ + event?: string | undefined + + /** + * ID of the message, if any was provided by the server. Can be used by clients to keep the + * last received message ID in sync when reconnecting. + */ + id?: string | undefined + + /** + * The data received for this message + */ + data: string +} + +/** + * Callbacks that can be passed to the parser to handle different types of parsed messages + * and errors. + * + * @public + */ +export interface ParserCallbacks { + /** + * Callback for when a new event/message is parsed from the stream. + * This is the main callback that clients will use to handle incoming messages. + * + * @param event - The parsed event/message + */ + onEvent?: ((event: EventSourceMessage) => void) | undefined + + /** + * Callback for when the server sends a new reconnection interval through the `retry` field. + * + * @param retry - The number of milliseconds to wait before reconnecting. + */ + onRetry?: ((retry: number) => void) | undefined + + /** + * Callback for when a comment is encountered in the stream. + * + * @param comment - The comment encountered in the stream. + */ + onComment?: ((comment: string) => void) | undefined + + /** + * Callback for when an error occurs during parsing. This is a catch-all for any errors + * that occur during parsing, and can be used to handle them in a custom way. Most clients + * tend to silently ignore any errors and instead retry, but it can be helpful to log/debug. + * + * @param error - The error that occurred during parsing + */ + onError?: ((error: ParseError) => void) | undefined +} + +/** + * Configuration accepted by {@link createParser}. Extends {@link ParserCallbacks} with + * additional options that control parser behavior. + * + * @public + */ +export interface ParserConfig extends ParserCallbacks { + /** + * Maximum number of characters the parser is allowed to buffer across calls to `feed()`. + * + * Two unbounded surfaces exist in a streaming SSE parser: + * - A partial line that has not yet been terminated by `\n`, `\r`, or `\r\n`. + * - A multi-line event whose terminating blank line has not yet arrived (each `data:` + * field gets appended to the buffered event). + * + * When the combined size of these buffers exceeds `maxBufferSize`, the parser emits a + * `ParseError` with `type: 'max-buffer-size-exceeded'` to `onError` and becomes + * terminated — subsequent calls to `feed()` will throw until `reset()` is called. + * This protects against unbounded memory growth from malformed or malicious streams. + * + * @defaultValue `undefined` (unbounded) + */ + maxBufferSize?: number | undefined +} diff --git a/node_modules/eventsource-parser/stream.js b/node_modules/eventsource-parser/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..98d74bcf3171552c303b891c5203a6d45d42f984 --- /dev/null +++ b/node_modules/eventsource-parser/stream.js @@ -0,0 +1,2 @@ +/* included for compatibility with react-native without package exports support */ +module.exports = require('./dist/stream.cjs') diff --git a/node_modules/eventsource/LICENSE b/node_modules/eventsource/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..505b0d90b58db0410e2965ed55f8ec03582e16ea --- /dev/null +++ b/node_modules/eventsource/LICENSE @@ -0,0 +1,22 @@ +The MIT License + +Copyright (c) EventSource GitHub organisation + +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. diff --git a/node_modules/eventsource/README.md b/node_modules/eventsource/README.md new file mode 100644 index 0000000000000000000000000000000000000000..500a96b933f8c1d0d288dec76418c61c6a9a4055 --- /dev/null +++ b/node_modules/eventsource/README.md @@ -0,0 +1,167 @@ +# eventsource + +[![npm version](https://img.shields.io/npm/v/eventsource.svg?style=flat-square)](https://www.npmjs.com/package/eventsource)[![npm bundle size](https://img.shields.io/bundlephobia/minzip/eventsource?style=flat-square)](https://bundlephobia.com/result?p=eventsource)[![npm weekly downloads](https://img.shields.io/npm/dw/eventsource.svg?style=flat-square)](https://www.npmjs.com/package/eventsource) + +WhatWG/W3C-compatible [server-sent events/eventsource](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) client. The module attempts to implement an absolute minimal amount of features/changes beyond the specification. + +If you're looking for a modern alternative with a less constrained API, check out the [`eventsource-client` package](https://www.npmjs.com/package/eventsource-client). + +## Installation + +```bash +npm install --save eventsource +``` + +## Supported engines + +- Node.js >= 18 +- Chrome >= 63 +- Safari >= 11.3 +- Firefox >= 65 +- Edge >= 79 +- Deno >= 1.30 +- Bun >= 1.1.23 + +Basically, any environment that supports: + +- [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch) +- [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) +- [TextDecoderStream](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoderStream) +- [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) +- [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event), [MessageEvent](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent), [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) + +If you need to support older runtimes, try the `2.x` branch/version range (note: 2.x branch is primarily targetted at Node.js, not browsers). + +## Usage + +```ts +import {EventSource} from 'eventsource' + +const es = new EventSource('https://my-server.com/sse') + +/* + * This will listen for events with the field `event: notice`. + */ +es.addEventListener('notice', (event) => { + console.log(event.data) +}) + +/* + * This will listen for events with the field `event: update`. + */ +es.addEventListener('update', (event) => { + console.log(event.data) +}) + +/* + * The event "message" is a special case, as it will capture events _without_ an + * event field, as well as events that have the specific type `event: message`. + * It will not trigger on any other event type. + */ +es.addEventListener('message', (event) => { + console.log(event.data) +}) + +/** + * To explicitly close the connection, call the `close` method. + * This will prevent any reconnection from happening. + */ +setTimeout(() => { + es.close() +}, 10_000) +``` + +### TypeScript + +Make sure you have configured your TSConfig so it matches the environment you are targetting. If you are targetting browsers, this would be `dom`: + +```jsonc +{ + "compilerOptions": { + "lib": ["dom"], + }, +} +``` + +If you're using Node.js, ensure you have `@types/node` installed (and it is version 18 or higher). Cloudflare workers have `@cloudflare/workers-types` etc. + +The following errors are caused by targetting an environment that does not have the necessary types available: + +``` +error TS2304: Cannot find name 'Event'. +error TS2304: Cannot find name 'EventTarget'. +error TS2304: Cannot find name 'MessageEvent'. +``` + +## Migrating from v1 / v2 + +See [MIGRATION.md](MIGRATION.md#v2-to-v3) for a detailed migration guide. + +## Extensions to the WhatWG/W3C API + +### Message and code properties on errors + +The `error` event has a `message` and `code` property that can be used to get more information about the error. In the specification, the Event + +```ts +es.addEventListener('error', (err) => { + if (err.code === 401 || err.code === 403) { + console.log('not authorized') + } +}) +``` + +### Specify `fetch` implementation + +The `EventSource` constructor accepts an optional `fetch` property in the second argument that can be used to specify the `fetch` implementation to use. + +This can be useful in environments where the global `fetch` function is not available - but it can also be used to alter the request/response behaviour. + +#### Setting HTTP request headers + +```ts +const es = new EventSource('https://my-server.com/sse', { + fetch: (input, init) => + fetch(input, { + ...init, + headers: { + ...init.headers, + Authorization: 'Bearer myToken', + }, + }), +}) +``` + +#### HTTP/HTTPS proxy + +Use a package like [`node-fetch-native`](https://github.com/unjs/node-fetch-native) to add proxy support, either through environment variables or explicit configuration. + +```ts +// npm install node-fetch-native --save +import {fetch} from 'node-fetch-native/proxy' + +const es = new EventSource('https://my-server.com/sse', { + fetch: (input, init) => fetch(input, init), +}) +``` + +#### Allow unauthorized HTTPS requests + +Use a package like [`undici`](https://github.com/nodejs/undici) for more control of fetch options through the use of an [`Agent`](https://undici.nodejs.org/#/docs/api/Agent.md). + +```ts +// npm install undici --save +import {fetch, Agent} from 'undici' + +await fetch('https://my-server.com/sse', { + dispatcher: new Agent({ + connect: { + rejectUnauthorized: false, + }, + }), +}) +``` + +## License + +MIT-licensed. See [LICENSE](LICENSE). diff --git a/node_modules/eventsource/package.json b/node_modules/eventsource/package.json new file mode 100644 index 0000000000000000000000000000000000000000..351e4e135068ea7611fa3f5f025b7a4a90b886bf --- /dev/null +++ b/node_modules/eventsource/package.json @@ -0,0 +1,130 @@ +{ + "name": "eventsource", + "version": "3.0.7", + "description": "WhatWG/W3C compliant EventSource client for Node.js and browsers", + "sideEffects": false, + "type": "module", + "main": "./dist/index.cjs", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "deno": "./dist/index.js", + "bun": "./dist/index.js", + "source": "./src/index.ts", + "import": "./dist/index.js", + "require": "./dist/index.cjs", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "build": "pkg-utils build && pkg-utils --strict", + "build:watch": "pkg-utils watch", + "clean": "rimraf dist coverage", + "lint": "eslint . && tsc --noEmit", + "posttest": "npm run lint", + "prebuild": "npm run clean", + "prepare": "npm run build", + "test": "npm run test:node && npm run test:browser", + "test:browser": "tsx test/browser/client.browser.test.ts", + "test:bun": "bun run test/bun/client.bun.test.ts", + "test:deno": "deno run --allow-net --allow-read --allow-env --unstable-sloppy-imports test/deno/client.deno.test.ts", + "test:node": "tsx test/node/client.node.test.ts" + }, + "files": [ + "!dist/stats.html", + "dist", + "src" + ], + "repository": { + "type": "git", + "url": "git://git@github.com/EventSource/eventsource.git" + }, + "keywords": [ + "sse", + "eventsource", + "server-sent-events" + ], + "author": "Espen Hovlandsdal ", + "contributors": [ + "Aslak Hellesøy ", + "Einar Otto Stangvik " + ], + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "browserslist": [ + "node >= 18", + "chrome >= 71", + "safari >= 14.1", + "firefox >= 105", + "edge >= 79" + ], + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "devDependencies": { + "@sanity/pkg-utils": "^7.1.0", + "@sanity/semantic-release-preset": "^5.0.0", + "@tsconfig/strictest": "^2.0.5", + "@types/sinon": "^17.0.3", + "@typescript-eslint/eslint-plugin": "^6.11.0", + "@typescript-eslint/parser": "^6.11.0", + "esbuild": "^0.25.1", + "eslint": "^8.57.0", + "eslint-config-prettier": "^9.1.0", + "eslint-config-sanity": "^7.1.3", + "eventsource-encoder": "^1.0.0", + "playwright": "^1.48.2", + "prettier": "^3.5.3", + "rimraf": "^5.0.5", + "rollup-plugin-visualizer": "^5.12.0", + "semantic-release": "^24.2.0", + "sinon": "^17.0.1", + "tsx": "^4.19.2", + "typescript": "^5.8.2", + "undici": "^6.20.1" + }, + "overrides": { + "cross-spawn": "7.0.6" + }, + "bugs": { + "url": "https://github.com/EventSource/eventsource/issues" + }, + "homepage": "https://github.com/EventSource/eventsource#readme", + "prettier": { + "semi": false, + "printWidth": 100, + "bracketSpacing": false, + "singleQuote": true + }, + "eslintConfig": { + "parserOptions": { + "ecmaVersion": 9, + "sourceType": "module", + "ecmaFeatures": { + "modules": true + } + }, + "extends": [ + "sanity", + "sanity/typescript", + "prettier" + ], + "ignorePatterns": [ + "lib/**/" + ], + "globals": { + "globalThis": false + }, + "rules": { + "no-undef": "off", + "no-empty": "off" + } + }, + "publishConfig": { + "provenance": true + } +} diff --git a/node_modules/eventsource/src/EventSource.ts b/node_modules/eventsource/src/EventSource.ts new file mode 100644 index 0000000000000000000000000000000000000000..468a13ec3d1416ac00a662024ce94cda42df13b1 --- /dev/null +++ b/node_modules/eventsource/src/EventSource.ts @@ -0,0 +1,596 @@ +import {createParser, type EventSourceMessage, type EventSourceParser} from 'eventsource-parser' + +import {ErrorEvent, flattenError, syntaxError} from './errors.js' +import type { + AddEventListenerOptions, + EventListenerOptions, + EventListenerOrEventListenerObject, + EventSourceEventMap, + EventSourceFetchInit, + EventSourceInit, + FetchLike, + FetchLikeResponse, +} from './types.js' + +/** + * An `EventSource` instance opens a persistent connection to an HTTP server, which sends events + * in `text/event-stream` format. The connection remains open until closed by calling `.close()`. + * + * @public + * @example + * ```js + * const eventSource = new EventSource('https://example.com/stream') + * eventSource.addEventListener('error', (error) => { + * console.error(error) + * }) + * eventSource.addEventListener('message', (event) => { + * console.log('Received message:', event.data) + * }) + * ``` + */ +export class EventSource extends EventTarget { + /** + * ReadyState representing an EventSource currently trying to connect + * + * @public + */ + static CONNECTING = 0 as const + + /** + * ReadyState representing an EventSource connection that is open (eg connected) + * + * @public + */ + static OPEN = 1 as const + + /** + * ReadyState representing an EventSource connection that is closed (eg disconnected) + * + * @public + */ + static CLOSED = 2 as const + + /** + * ReadyState representing an EventSource currently trying to connect + * + * @public + */ + readonly CONNECTING = 0 as const + + /** + * ReadyState representing an EventSource connection that is open (eg connected) + * + * @public + */ + readonly OPEN = 1 as const + + /** + * ReadyState representing an EventSource connection that is closed (eg disconnected) + * + * @public + */ + readonly CLOSED = 2 as const + + /** + * Returns the state of this EventSource object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + * + * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface, + * defined in the TypeScript `dom` library. + * + * @public + */ + public get readyState(): number { + return this.#readyState + } + + /** + * Returns the URL providing the event stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + * + * @public + */ + public get url(): string { + return this.#url.href + } + + /** + * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + public get withCredentials(): boolean { + return this.#withCredentials + } + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + public get onerror(): ((ev: ErrorEvent) => unknown) | null { + return this.#onError + } + public set onerror(value: ((ev: ErrorEvent) => unknown) | null) { + this.#onError = value + } + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + public get onmessage(): ((ev: MessageEvent) => unknown) | null { + return this.#onMessage + } + public set onmessage(value: ((ev: MessageEvent) => unknown) | null) { + this.#onMessage = value + } + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + public get onopen(): ((ev: Event) => unknown) | null { + return this.#onOpen + } + public set onopen(value: ((ev: Event) => unknown) | null) { + this.#onOpen = value + } + + override addEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => unknown, + options?: boolean | AddEventListenerOptions, + ): void + override addEventListener( + type: string, + listener: (this: EventSource, event: MessageEvent) => unknown, + options?: boolean | AddEventListenerOptions, + ): void + override addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void + override addEventListener( + type: string, + listener: + | ((this: EventSource, event: MessageEvent) => unknown) + | EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void { + const listen = listener as (this: EventSource, event: Event) => unknown + super.addEventListener(type, listen, options) + } + + override removeEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => unknown, + options?: boolean | EventListenerOptions, + ): void + override removeEventListener( + type: string, + listener: (this: EventSource, event: MessageEvent) => unknown, + options?: boolean | EventListenerOptions, + ): void + override removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void + override removeEventListener( + type: string, + listener: + | ((this: EventSource, event: MessageEvent) => unknown) + | EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void { + const listen = listener as (this: EventSource, event: Event) => unknown + super.removeEventListener(type, listen, options) + } + + constructor(url: string | URL, eventSourceInitDict?: EventSourceInit) { + super() + + try { + if (url instanceof URL) { + this.#url = url + } else if (typeof url === 'string') { + this.#url = new URL(url, getBaseURL()) + } else { + throw new Error('Invalid URL') + } + } catch (err) { + throw syntaxError('An invalid or illegal string was specified') + } + + this.#parser = createParser({ + onEvent: this.#onEvent, + onRetry: this.#onRetryChange, + }) + + this.#readyState = this.CONNECTING + this.#reconnectInterval = 3000 + this.#fetch = eventSourceInitDict?.fetch ?? globalThis.fetch + this.#withCredentials = eventSourceInitDict?.withCredentials ?? false + + this.#connect() + } + + /** + * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + * + * @public + */ + close(): void { + if (this.#reconnectTimer) clearTimeout(this.#reconnectTimer) + if (this.#readyState === this.CLOSED) return + if (this.#controller) this.#controller.abort() + this.#readyState = this.CLOSED + this.#controller = undefined + } + + // PRIVATES FOLLOW + + /** + * Current connection state + * + * @internal + */ + #readyState: number + + /** + * Original URL used to connect. + * + * Note that this will stay the same even after a redirect. + * + * @internal + */ + #url: URL + + /** + * The destination URL after a redirect. Is reset on reconnection. + * + * @internal + */ + #redirectUrl: URL | undefined + + /** + * Whether to include credentials in the request + * + * @internal + */ + #withCredentials: boolean + + /** + * The fetch implementation to use + * + * @internal + */ + #fetch: FetchLike + + /** + * The reconnection time in milliseconds + * + * @internal + */ + #reconnectInterval: number + + /** + * Reference to an ongoing reconnect attempt, if any + * + * @internal + */ + #reconnectTimer: ReturnType | undefined + + /** + * The last event ID seen by the EventSource, which will be sent as `Last-Event-ID` in the + * request headers on a reconnection attempt. + * + * @internal + */ + #lastEventId: string | null = null + + /** + * The AbortController instance used to abort the fetch request + * + * @internal + */ + #controller: AbortController | undefined + + /** + * Instance of an EventSource parser (`eventsource-parser` npm module) + * + * @internal + */ + #parser: EventSourceParser + + /** + * Holds the current error handler, attached through `onerror` property directly. + * Note that `addEventListener('error', …)` will not be stored here. + * + * @internal + */ + #onError: ((ev: ErrorEvent) => unknown) | null = null + + /** + * Holds the current message handler, attached through `onmessage` property directly. + * Note that `addEventListener('message', …)` will not be stored here. + * + * @internal + */ + #onMessage: ((ev: MessageEvent) => unknown) | null = null + + /** + * Holds the current open handler, attached through `onopen` property directly. + * Note that `addEventListener('open', …)` will not be stored here. + * + * @internal + */ + #onOpen: ((ev: Event) => unknown) | null = null + + /** + * Connect to the given URL and start receiving events + * + * @internal + */ + #connect() { + this.#readyState = this.CONNECTING + this.#controller = new AbortController() + + // Browser tests are failing if we directly call `this.#fetch()`, thus the indirection. + const fetch = this.#fetch + fetch(this.#url, this.#getRequestOptions()) + .then(this.#onFetchResponse) + .catch(this.#onFetchError) + } + + /** + * Handles the fetch response + * + * @param response - The Fetch(ish) response + * @internal + */ + #onFetchResponse = async (response: FetchLikeResponse) => { + this.#parser.reset() + + const {body, redirected, status, headers} = response + + // [spec] a client can be told to stop reconnecting using the HTTP 204 No Content response code. + if (status === 204) { + // We still need to emit an error event - this mirrors the browser behavior, + // and without it there is no way to tell the user that the connection was closed. + this.#failConnection('Server sent HTTP 204, not reconnecting', 204) + this.close() + return + } + + // [spec] …Event stream requests can be redirected using HTTP 301 and 307 redirects as with + // [spec] normal HTTP requests. + // Spec does not say anything about other redirect codes (302, 308), but this seems an + // unintended omission, rather than a feature. Browsers will happily redirect on other 3xxs's. + if (redirected) { + this.#redirectUrl = new URL(response.url) + } else { + this.#redirectUrl = undefined + } + + // [spec] if res's status is not 200, …, then fail the connection. + if (status !== 200) { + this.#failConnection(`Non-200 status code (${status})`, status) + return + } + + // [spec] …or if res's `Content-Type` is not `text/event-stream`, then fail the connection. + const contentType = headers.get('content-type') || '' + if (!contentType.startsWith('text/event-stream')) { + this.#failConnection('Invalid content type, expected "text/event-stream"', status) + return + } + + // [spec] …if the readyState attribute is set to a value other than CLOSED… + if (this.#readyState === this.CLOSED) { + return + } + + // [spec] …sets the readyState attribute to OPEN and fires an event + // [spec] …named open at the EventSource object. + this.#readyState = this.OPEN + + const openEvent = new Event('open') + this.#onOpen?.(openEvent) + this.dispatchEvent(openEvent) + + // Ensure that the response stream is a web stream + if (typeof body !== 'object' || !body || !('getReader' in body)) { + this.#failConnection('Invalid response body, expected a web ReadableStream', status) + this.close() // This should only happen if `fetch` provided is "faulty" - don't reconnect + return + } + + const decoder = new TextDecoder() + + const reader = body.getReader() + let open = true + + do { + const {done, value} = await reader.read() + if (value) { + this.#parser.feed(decoder.decode(value, {stream: !done})) + } + + if (!done) { + continue + } + + open = false + this.#parser.reset() + + this.#scheduleReconnect() + } while (open) + } + + /** + * Handles rejected requests for the EventSource endpoint + * + * @param err - The error from `fetch()` + * @internal + */ + #onFetchError = (err: Error & {type?: string}) => { + this.#controller = undefined + + // We expect abort errors when the user manually calls `close()` - ignore those + if (err.name === 'AbortError' || err.type === 'aborted') { + return + } + + this.#scheduleReconnect(flattenError(err)) + } + + /** + * Get request options for the `fetch()` request + * + * @returns The request options + * @internal + */ + #getRequestOptions(): EventSourceFetchInit { + const lastEvent = this.#lastEventId ? {'Last-Event-ID': this.#lastEventId} : undefined + + const init: EventSourceFetchInit = { + // [spec] Let `corsAttributeState` be `Anonymous`… + // [spec] …will have their mode set to "cors"… + mode: 'cors', + redirect: 'follow', + headers: {Accept: 'text/event-stream', ...lastEvent}, + cache: 'no-store', + signal: this.#controller?.signal, + } + + // Some environments crash if attempting to set `credentials` where it is not supported, + // eg on Cloudflare Workers. To avoid this, we only set it in browser-like environments. + if ('window' in globalThis) { + // [spec] …and their credentials mode set to "same-origin" + // [spec] …if the `withCredentials` attribute is `true`, set the credentials mode to "include"… + init.credentials = this.withCredentials ? 'include' : 'same-origin' + } + + return init + } + + /** + * Called by EventSourceParser instance when an event has successfully been parsed + * and is ready to be processed. + * + * @param event - The parsed event + * @internal + */ + #onEvent = (event: EventSourceMessage) => { + if (typeof event.id === 'string') { + this.#lastEventId = event.id + } + + const messageEvent = new MessageEvent(event.event || 'message', { + data: event.data, + origin: this.#redirectUrl ? this.#redirectUrl.origin : this.#url.origin, + lastEventId: event.id || '', + }) + + // The `onmessage` property of the EventSource instance only triggers on messages without an + // `event` field, or ones that explicitly set `message`. + if (this.#onMessage && (!event.event || event.event === 'message')) { + this.#onMessage(messageEvent) + } + + this.dispatchEvent(messageEvent) + } + + /** + * Called by EventSourceParser instance when a new reconnection interval is received + * from the EventSource endpoint. + * + * @param value - The new reconnection interval in milliseconds + * @internal + */ + #onRetryChange = (value: number) => { + this.#reconnectInterval = value + } + + /** + * Handles the process referred to in the EventSource specification as "failing a connection". + * + * @param error - The error causing the connection to fail + * @param code - The HTTP status code, if available + * @internal + */ + #failConnection(message?: string, code?: number) { + // [spec] …if the readyState attribute is set to a value other than CLOSED, + // [spec] sets the readyState attribute to CLOSED… + if (this.#readyState !== this.CLOSED) { + this.#readyState = this.CLOSED + } + + // [spec] …and fires an event named `error` at the `EventSource` object. + // [spec] Once the user agent has failed the connection, it does not attempt to reconnect. + // [spec] > Implementations are especially encouraged to report detailed information + // [spec] > to their development consoles whenever an error event is fired, since little + // [spec] > to no information can be made available in the events themselves. + // Printing to console is not very programatically helpful, though, so we emit a custom event. + const errorEvent = new ErrorEvent('error', {code, message}) + + this.#onError?.(errorEvent) + this.dispatchEvent(errorEvent) + } + + /** + * Schedules a reconnection attempt against the EventSource endpoint. + * + * @param message - The error causing the connection to fail + * @param code - The HTTP status code, if available + * @internal + */ + #scheduleReconnect(message?: string, code?: number) { + // [spec] If the readyState attribute is set to CLOSED, abort the task. + if (this.#readyState === this.CLOSED) { + return + } + + // [spec] Set the readyState attribute to CONNECTING. + this.#readyState = this.CONNECTING + + // [spec] Fire an event named `error` at the EventSource object. + const errorEvent = new ErrorEvent('error', {code, message}) + this.#onError?.(errorEvent) + this.dispatchEvent(errorEvent) + + // [spec] Wait a delay equal to the reconnection time of the event source. + this.#reconnectTimer = setTimeout(this.#reconnect, this.#reconnectInterval) + } + + /** + * Reconnects to the EventSource endpoint after a disconnect/failure + * + * @internal + */ + #reconnect = () => { + this.#reconnectTimer = undefined + + // [spec] If the EventSource's readyState attribute is not set to CONNECTING, then return. + if (this.#readyState !== this.CONNECTING) { + return + } + + this.#connect() + } +} + +/** + * According to spec, when constructing a URL: + * > 1. Let baseURL be environment's base URL, if environment is a Document object + * > 2. Return the result of applying the URL parser to url, with baseURL. + * + * Thus we should use `document.baseURI` if available, since it can be set through a base tag. + * + * @returns The base URL, if available - otherwise `undefined` + * @internal + */ +function getBaseURL(): string | undefined { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const doc = 'document' in globalThis ? (globalThis as any).document : undefined + return doc && typeof doc === 'object' && 'baseURI' in doc && typeof doc.baseURI === 'string' + ? doc.baseURI + : undefined +} diff --git a/node_modules/eventsource/src/errors.ts b/node_modules/eventsource/src/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..a39f75dabe540935b914f628441739ea96df5bec --- /dev/null +++ b/node_modules/eventsource/src/errors.ts @@ -0,0 +1,141 @@ +/** + * An extended version of the `Event` emitted by the `EventSource` object when an error occurs. + * While the spec does not include any additional properties, we intentionally go beyond the spec + * and provide some (minimal) additional information to aid in debugging. + * + * @public + */ +export class ErrorEvent extends Event { + /** + * HTTP status code, if this was triggered by an HTTP error + * Note: this is not part of the spec, but is included for better error handling. + * + * @public + */ + public code?: number | undefined + + /** + * Optional message attached to the error. + * Note: this is not part of the spec, but is included for better error handling. + * + * @public + */ + public message?: string | undefined + + /** + * Constructs a new `ErrorEvent` instance. This is typically not called directly, + * but rather emitted by the `EventSource` object when an error occurs. + * + * @param type - The type of the event (should be "error") + * @param errorEventInitDict - Optional properties to include in the error event + */ + constructor( + type: string, + errorEventInitDict?: {message?: string | undefined; code?: number | undefined}, + ) { + super(type) + this.code = errorEventInitDict?.code ?? undefined + this.message = errorEventInitDict?.message ?? undefined + } + + /** + * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance, + * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, + * we explicitly include the properties in the `inspect` method. + * + * This is automatically called by Node.js when you `console.log` an instance of this class. + * + * @param _depth - The current depth + * @param options - The options passed to `util.inspect` + * @param inspect - The inspect function to use (prevents having to import it from `util`) + * @returns A string representation of the error + */ + [Symbol.for('nodejs.util.inspect.custom')]( + _depth: number, + options: {colors: boolean}, + inspect: (obj: unknown, inspectOptions: {colors: boolean}) => string, + ): string { + return inspect(inspectableError(this), options) + } + + /** + * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance, + * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, + * we explicitly include the properties in the `inspect` method. + * + * This is automatically called by Deno when you `console.log` an instance of this class. + * + * @param inspect - The inspect function to use (prevents having to import it from `util`) + * @param options - The options passed to `Deno.inspect` + * @returns A string representation of the error + */ + [Symbol.for('Deno.customInspect')]( + inspect: (obj: unknown, inspectOptions: {colors: boolean}) => string, + options: {colors: boolean}, + ): string { + return inspect(inspectableError(this), options) + } +} + +/** + * For environments where DOMException may not exist, we will use a SyntaxError instead. + * While this isn't strictly according to spec, it is very close. + * + * @param message - The message to include in the error + * @returns A `DOMException` or `SyntaxError` instance + * @internal + */ +export function syntaxError(message: string): SyntaxError { + // If someone can figure out a way to make this work without depending on DOM/Node.js typings, + // and without casting to `any`, please send a PR 🙏 + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const DomException = (globalThis as any).DOMException + if (typeof DomException === 'function') { + return new DomException(message, 'SyntaxError') + } + + return new SyntaxError(message) +} + +/** + * Flatten an error into a single error message string. + * Unwraps nested errors and joins them with a comma. + * + * @param err - The error to flatten + * @returns A string representation of the error + * @internal + */ +export function flattenError(err: unknown): string { + if (!(err instanceof Error)) { + return `${err}` + } + + if ('errors' in err && Array.isArray(err.errors)) { + return err.errors.map(flattenError).join(', ') + } + + if ('cause' in err && err.cause instanceof Error) { + return `${err}: ${flattenError(err.cause)}` + } + + return err.message +} + +/** + * Convert an `ErrorEvent` instance into a plain object for inspection. + * + * @param err - The `ErrorEvent` instance to inspect + * @returns A plain object representation of the error + * @internal + */ +function inspectableError(err: ErrorEvent) { + return { + type: err.type, + message: err.message, + code: err.code, + defaultPrevented: err.defaultPrevented, + cancelable: err.cancelable, + timeStamp: err.timeStamp, + } +} diff --git a/node_modules/eventsource/src/index.ts b/node_modules/eventsource/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6b621619754667e246a98ffceda79bbee690949 --- /dev/null +++ b/node_modules/eventsource/src/index.ts @@ -0,0 +1,3 @@ +export {ErrorEvent} from './errors.js' +export {EventSource} from './EventSource.js' +export type * from './types.js' diff --git a/node_modules/eventsource/src/types.ts b/node_modules/eventsource/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..46d907a0dfe4cfcabbcfa96291637d540894fef7 --- /dev/null +++ b/node_modules/eventsource/src/types.ts @@ -0,0 +1,152 @@ +import type {ErrorEvent} from './errors.js' + +/** + * Stripped down version of `fetch()`, only defining the parts we care about. + * This ensures it should work with "most" fetch implementations. + * + * @public + */ +export type FetchLike = ( + url: string | URL, + init: EventSourceFetchInit, +) => Promise + +/** + * Subset of `RequestInit` used for `fetch()` calls made by the `EventSource` class. + * As we know that we will be passing certain values, we can be more specific and have + * users not have to do optional chaining and similar for things that will always be there. + * + * @public + */ +export interface EventSourceFetchInit { + /** An AbortSignal to set request's signal. Typed as `any` because of polyfill inconsistencies. */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + signal: {aborted: boolean} | any + + /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers: { + [key: string]: string + Accept: 'text/event-stream' + } + + /** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. */ + mode: 'cors' | 'no-cors' | 'same-origin' + + /** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. */ + credentials?: 'include' | 'omit' | 'same-origin' + + /** Controls how the request is cached. */ + cache: 'no-store' + + /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect: 'error' | 'follow' | 'manual' +} + +/** + * @public + * @deprecated Use `EventSourceFetchInit` instead. + * This type is only here for backwards compatibility and will be removed in a future version. + */ +export type FetchLikeInit = EventSourceFetchInit + +/** + * Stripped down version of `ReadableStreamDefaultReader`, only defining the parts we care about. + * + * @public + */ +export interface ReaderLike { + read(): Promise<{done: false; value: unknown} | {done: true; value?: undefined}> + cancel(): Promise +} + +/** + * Minimal version of the `Response` type returned by `fetch()`. + * + * @public + */ +export interface FetchLikeResponse { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + readonly body: {getReader(): ReaderLike} | Response['body'] | null + readonly url: string + readonly status: number + readonly redirected: boolean + readonly headers: {get(name: string): string | null} +} + +/** + * Mirrors the official DOM typings, with the exception of the extended ErrorEvent. + * + * @public + */ +export interface EventSourceEventMap { + error: ErrorEvent + message: MessageEvent + open: Event +} + +/** + * Mirrors the official DOM typings (for the most part) + * + * @public + */ +export interface EventSourceInit { + /** + * A boolean value, defaulting to `false`, indicating if CORS should be set to `include` credentials. + */ + withCredentials?: boolean + + /** + * Optional fetch implementation to use. Defaults to `globalThis.fetch`. + * Can also be used for advanced use cases like mocking, proxying, custom certs etc. + */ + fetch?: FetchLike +} + +/** + * Mirrors the official DOM typings (sorta). + * + * @public + */ +export interface EventListenerOptions { + /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ + capture?: boolean +} + +/** + * Mirrors the official DOM typings (sorta). + * + * @public + */ +export interface AddEventListenerOptions extends EventListenerOptions { + /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ + once?: boolean + /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ + passive?: boolean + /** The listener will be removed when the given AbortSignal object's `abort()` method is called. */ + signal?: AbortSignal +} + +/** + * Mirrors the official DOM typings. + * + * @public + */ +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +/** + * Mirrors the official DOM typings. + * + * @public + */ +export interface EventListener { + (evt: Event | MessageEvent): void +} + +/** + * Mirrors the official DOM typings. + * + * @public + */ +export interface EventListenerObject { + handleEvent(object: Event): void +} diff --git a/node_modules/exif-parser/.npmignore b/node_modules/exif-parser/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..76add878f8dd778c3381fb3da45c8140db7db510 --- /dev/null +++ b/node_modules/exif-parser/.npmignore @@ -0,0 +1,2 @@ +node_modules +dist \ No newline at end of file diff --git a/node_modules/exif-parser/CHANGELOG.md b/node_modules/exif-parser/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..2cfc4033d62ea6aad535d38b9e5322c7fa94e152 --- /dev/null +++ b/node_modules/exif-parser/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog + +## 0.1.11 - July 9th 2017 + + - On nodejs, decode strings using UTF-8 instead of ASCII. Ideally we'd do this in the browser (UTF-16 currently) as well but that is a bit more work. + +## 0.1.10 - July 9th 2017 + +- Ignore unknown tag formats instead of failing. There seem to be images with format 0 that otherwise contain valid data. +- Fix bug in date parsing to not rely on the current date. This broke when the current date was the 31st of the month. +- In case a tag appears more than once, take the first, not the last. For example some pictures taken on an iPhone suffer from duplicate Orientation tags, where the first one is the wrong one. +- treat ModifyDate tag as a date value + +## 0.1.9 - April 9th 2015 + +- parse ISO 8601 dates with timezone offset diff --git a/node_modules/exif-parser/LICENSE.md b/node_modules/exif-parser/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..e8f2aab9fe3262c924c54cc053506257f7fefc16 --- /dev/null +++ b/node_modules/exif-parser/LICENSE.md @@ -0,0 +1,23 @@ +The MIT License +=============== + +Copyright (c) 2010 Bruno Windels , Daniel Leinich . + +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. \ No newline at end of file diff --git a/node_modules/exif-parser/Makefile b/node_modules/exif-parser/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..06e4f760daf2b64fbdaeecceaf305ac4c77fc368 --- /dev/null +++ b/node_modules/exif-parser/Makefile @@ -0,0 +1,16 @@ +VERSION=$(shell node --eval "console.log(require('./package.json').version)") +BUNDLE=dist/exif-parser-$(VERSION).js +MIN_BUNDLE=dist/exif-parser-$(VERSION)-min.js +BROWSERIFY=node_modules/.bin/browserify +UGLIFY=node_modules/.bin/uglifyjs + +build-browser-bundle: setup + @echo "building $(BUNDLE) ..." + @mkdir -p dist/ + @$(BROWSERIFY) --bare browser-global.js -o $(BUNDLE) + @echo "building $(MIN_BUNDLE) ..." + @$(UGLIFY) $(BUNDLE) -o $(MIN_BUNDLE) --compress +setup: + @npm install --no-optional --loglevel error --development +clean: + @rm -rf dist/ \ No newline at end of file diff --git a/node_modules/exif-parser/README.md b/node_modules/exif-parser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3b2404d073656007a51c957b41f6586c6ed92115 --- /dev/null +++ b/node_modules/exif-parser/README.md @@ -0,0 +1,83 @@ +exif-parser +======== +exif-parser is a parser for image metadata in the exif format, the most popular metadata format for jpeg and tiff images. It is written in pure javascript and has no external dependencies. It can also get the size of jpeg images and the size of the jpeg thumbnail embedded in the exif data. It can also extract the embedded thumbnail image. + +### Installing + + npm install exif-parser + +You can also build a browser bundle to include it with a ` +: + +``` + +Bundle size + +| Bundle Name | Size | +| ------------------ | ---- | +| fxbuilder.min.js | 6.5K | +| fxparser.min.js | 20K | +| fxp.min.js | 26K | +| fxvalidator.min.js | 5.7K | + +## Documents + + + + + + + +
v3v4 and v5v6
+ documents +
    +
  1. Getting Started
  2. +
  3. XML Parser
  4. +
  5. XML Builder
  6. +
  7. XML Validator
  8. +
  9. Entities
  10. +
  11. HTML Document Parsing
  12. +
  13. PI Tag processing
  14. +
  15. Path Expression
  16. +
    +
  1. Getting Started +
+ +**note**: +- Version 6 is released with version 4 for experimental use. Based on its demand, it'll be developed and the features can be different in final release. +- Version 5 has the same functionalities as version 4. + +## Performance +negative means error + +### XML Parser + + + + +* Y-axis: requests per second +* X-axis: File size + +### XML Builder + + +* Y-axis: requests per second + + + +--- + +## Usage Trend + +[Usage Trend of fast-xml-parser](https://npm-compare.com/fast-xml-parser#timeRange=THREE_YEARS) + + + NPM Usage Trend of fast-xml-parser + + +# Supporters +#### Contributors + +This project exists thanks to [all](graphs/contributors) the people who contribute. [[Contribute](docs/CONTRIBUTING.md)]. + + + + +#### Backers from Open collective + +Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/fast-xml-parser#backer)] + + + + + +# License +* MIT License + +![Donate $5](static/img/donation_quote.png) diff --git a/node_modules/fast-xml-parser/lib/fxbuilder.min.js b/node_modules/fast-xml-parser/lib/fxbuilder.min.js new file mode 100644 index 0000000000000000000000000000000000000000..77931c16fa3dc036cd86711e1e62f6f505e042b2 --- /dev/null +++ b/node_modules/fast-xml-parser/lib/fxbuilder.min.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.XMLBuilder=e():t.XMLBuilder=e()}(this,()=>(()=>{"use strict";var t={d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{default:()=>C});class i{constructor(t,e={},i){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=i,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let i=0,s="";for(;i0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const i=e[e.length-1];return void 0!==i.values&&t in i.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class n{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new s(this)}push(t,e=null,i=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const s=this.path.length;this.siblingStacks[s]||(this.siblingStacks[s]=new Map);const n=this.siblingStacks[s],r=i?`${i}:${t}`:t,o=n.get(r)||0;let a=0;for(const t of n.values())a+=t;n.set(r,o+1);const h={tag:t,position:a,counter:o};null!=i&&(h.namespace=i),null!=e&&(h.values=e),this.path.push(h)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const i=t||this.separator;if(i===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e=0&&e>=0;){const s=t[i];if("deep-wildcard"===s.type){if(i--,i<0)return!0;const s=t[i];let n=!1;for(let t=e;t>=0;t--)if(this._matchSegment(s,this.path[t],t===this.path.length-1)){e=t-1,i--,n=!0;break}if(!n)return!1}else{if(!this._matchSegment(s,this.path[e],e===this.path.length-1))return!1;e--,i--}}return i<0}_matchSegment(t,e,i){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!i)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!i)return!1;const s=e.counter??0;if("first"===t.position&&0!==s)return!1;if("odd"===t.position&&s%2!=1)return!1;if("even"===t.position&&s%2!=0)return!1;if("nth"===t.position&&s!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}function r(t){return String(t).replace(/--/g,"- -").replace(/--/g,"- -").replace(/-$/,"- ")}function o(t){return String(t).replace(/\]\]>/g,"]]]]>")}function a(t){return String(t).replace(/"/g,""").replace(/'/g,"'")}const h=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�",p=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",u=p+"\\-\\.\\d·̀-ͯ҇‿-⁀",l=(t,e,i="")=>{const s=`[${t.replace(":","")}][${e.replace(":","")}]*`;return{name:new RegExp(`^[${t}][${e}]*$`,i),ncName:new RegExp(`^${s}$`,i),qName:new RegExp(`^${s}(?::${s})?$`,i),nmToken:new RegExp(`^[${e}]+$`,i),nmTokens:new RegExp(`^[${e}]+(?:\\s+[${e}]+)*$`,i)}},c=l(h,h+"\\-\\.\\d·̀-ͯ‿-⁀"),g=l(p,u,"u"),d=(t,{xmlVersion:e="1.0"}={})=>((t="1.0")=>"1.1"===t?g:c)(e).qName.test(t);function f(t,e,i,s,n){return i.sanitizeName?d(t,{xmlVersion:n})?t:i.sanitizeName(t,{isAttribute:e,matcher:s.readOnly()}):t}function m(t,e){let s="";e.format&&(s="\n");const r=[];if(e.stopNodes&&Array.isArray(e.stopNodes))for(let t=0;te.maxNestedTags)throw new Error("Maximum nested tags exceeded");if(!Array.isArray(t)){if(null!=t){let i=t.toString();return i=S(i,e),i}return""}for(let u=0;u`,p=!1,s.pop();continue}if(g===e.commentPropName){h+=i+`\x3c!--${r(l[c][0][e.textNodeName])}--\x3e`,p=!0,s.pop();continue}if("?"===g[0]){h+=("?xml"===g?"":i)+`<${g}${$(l[":@"],e,m,s,a)}?>`,p=!0,s.pop();continue}let y=i;""!==y&&(y+=e.indentBy);const v=i+`<${g}${$(l[":@"],e,m,s,a)}`;let w;w=m?x(l[c],e):b(l[c],e,y,s,n,a),-1!==e.unpairedTags.indexOf(g)?e.suppressUnpairedNode?h+=v+">":h+=v+"/>":w&&0!==w.length||!e.suppressEmptyNode?w&&w.endsWith(">")?h+=v+`>${w}${i}`:(h+=v+">",w&&""!==i&&(w.includes("/>")||w.includes("`):h+=v+"/>",p=!0,s.pop()}return h}function N(t,e){if(!t||e.ignoreAttributes)return null;const i={};let s=!1;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n.startsWith(e.attributeNamePrefix)?n.substr(e.attributeNamePrefix.length):n]=a(t[n]),s=!0);return s?i:null}function x(t,e){if(!Array.isArray(t))return null!=t?t.toString():"";let i="";for(let s=0;s${s}`:i+=`<${r}${t}/>`}}}return i}function y(t,e){let i="";if(t&&!e.ignoreAttributes)for(let s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=t[s];!0===n&&e.suppressBooleanAttributes?i+=` ${s.substr(e.attributeNamePrefix.length)}`:i+=` ${s.substr(e.attributeNamePrefix.length)}="${a(n)}"`}return i}function A(t){const e=Object.keys(t);for(let i=0;i0&&e.processEntities)for(let i=0;i","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1,maxNestedTags:100,jPath:!0,sanitizeName:!1};function w(t){if(this.options=Object.assign({},v,t),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let t=0;t{for(const i of e){if("string"==typeof i&&t===i)return!0;if(i instanceof RegExp&&i.test(t))return!0}}:()=>!1,this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=j),this.processTextOrObjNode=O,this.options.format?(this.indentate=_,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function E(t,e,i,s,n){return i.sanitizeName?d(t,{xmlVersion:n})?t:i.sanitizeName(t,{isAttribute:e,matcher:s.readOnly()}):t}function O(t,e,i,s,n){const r=this.extractAttributes(t);if(s.push(e,r),this.checkStopNode(s)){const n=this.buildRawContent(t),r=this.buildAttributesForStopNode(t);return s.pop(),this.buildObjectNode(n,e,r,i)}const o=this.j2x(t,i+1,s,n);return s.pop(),"?"===e[0]?this.buildTextValNode("",e,o.attrStr,i,s):void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,o.attrStr,i,s):this.buildObjectNode(o.val,e,o.attrStr,i)}function _(t){return this.options.indentBy.repeat(t)}function j(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}w.prototype.build=function(t){if(this.options.preserveOrder)return m(t,this.options);{Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t});const e=new n,i=function(t,e){const i=t["?xml"];if(i&&"object"==typeof i){if(e.attributesGroupName&&i[e.attributesGroupName]){const t=i[e.attributesGroupName][e.attributeNamePrefix+"version"];if(t)return t}const t=i[e.attributeNamePrefix+"version"];if(t)return t}return"1.0"}(t,this.options);return this.j2x(t,0,e,i).val}},w.prototype.j2x=function(t,e,i,s){let n="",r="";if(this.options.maxNestedTags&&i.getDepth()>=this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");const o=this.options.jPath?i.toString():i,a=this.checkStopNode(i);for(let h in t){if(!Object.prototype.hasOwnProperty.call(t,h))continue;const p=h===this.options.textNodeName||h===this.options.cdataPropName||h===this.options.commentPropName||this.options.attributesGroupName&&h===this.options.attributesGroupName||this.isAttribute(h)||"?"===h[0]?h:E(h,!1,this.options,i,s);if(void 0===t[h])this.isAttribute(h)&&(r+="");else if(null===t[h])this.isAttribute(h)||p===this.options.cdataPropName||p===this.options.commentPropName?r+="":"?"===p[0]?r+=this.indentate(e)+"<"+p+"?"+this.tagEndChar:r+=this.indentate(e)+"<"+p+"/"+this.tagEndChar;else if(t[h]instanceof Date)r+=this.buildTextValNode(t[h],p,"",e,i);else if("object"!=typeof t[h]){const u=this.isAttribute(h);if(u&&!this.ignoreAttributesFn(u,o)){const e=E(u,!0,this.options,i,s);n+=this.buildAttrPairStr(e,""+t[h],a)}else if(!u)if(h===this.options.textNodeName){let e=this.options.tagValueProcessor(h,""+t[h]);r+=this.replaceEntitiesValue(e)}else{i.push(p);const s=this.checkStopNode(i);if(i.pop(),s){const i=""+t[h];r+=""===i?this.indentate(e)+"<"+p+this.closeTag(p)+this.tagEndChar:this.indentate(e)+"<"+p+">"+i+""+t+"${t}`;else if("object"==typeof t&&null!==t){const s=this.buildRawContent(t),n=this.buildAttributesForStopNode(t);e+=""===s?`<${i}${n}/>`:`<${i}${n}>${s}`}}else if("object"==typeof s&&null!==s){const t=this.buildRawContent(s),n=this.buildAttributesForStopNode(s);e+=""===t?`<${i}${n}/>`:`<${i}${n}>${t}`}else e+=`<${i}>${s}`}return e},w.prototype.buildAttributesForStopNode=function(t){if(!t||"object"!=typeof t)return"";let e="";if(this.options.attributesGroupName&&t[this.options.attributesGroupName]){const i=t[this.options.attributesGroupName];for(let t in i){if(!Object.prototype.hasOwnProperty.call(i,t))continue;const s=t.startsWith(this.options.attributeNamePrefix)?t.substring(this.options.attributeNamePrefix.length):t,n=i[t];!0===n&&this.options.suppressBooleanAttributes?e+=" "+s:e+=" "+s+'="'+n+'"'}}else for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;const s=this.isAttribute(i);if(s){const n=t[i];!0===n&&this.options.suppressBooleanAttributes?e+=" "+s:e+=" "+s+'="'+n+'"'}}return e},w.prototype.buildObjectNode=function(t,e,i,s){if(""===t)return"?"===e[0]?this.indentate(s)+"<"+e+i+"?"+this.tagEndChar:this.indentate(s)+"<"+e+i+this.closeTag(e)+this.tagEndChar;if("?"===e[0])return this.indentate(s)+"<"+e+i+"?"+this.tagEndChar;{let n=""+t+n}},w.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>`+this.newLine}if(!1!==this.options.commentPropName&&e===this.options.commentPropName){const e=r(t);return this.indentate(s)+`\x3c!--${e}--\x3e`+this.newLine}if("?"===e[0])return this.indentate(s)+"<"+e+i+"?"+this.tagEndChar;{let n=this.options.tagValueProcessor(e,t);return n=this.replaceEntitiesValue(n),""===n?this.indentate(s)+"<"+e+i+this.closeTag(e)+this.tagEndChar:this.indentate(s)+"<"+e+i+">"+n+"0&&this.options.processEntities)for(let e=0;e {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Expression - Parses and stores a tag pattern expression\n * \n * Patterns are parsed once and stored in an optimized structure for fast matching.\n * \n * @example\n * const expr = new Expression(\"root.users.user\");\n * const expr2 = new Expression(\"..user[id]:first\");\n * const expr3 = new Expression(\"root/users/user\", { separator: '/' });\n */\nexport default class Expression {\n /**\n * Create a new Expression\n * @param {string} pattern - Pattern string (e.g., \"root.users.user\", \"..user[id]\")\n * @param {Object} options - Configuration options\n * @param {string} options.separator - Path separator (default: '.')\n */\n constructor(pattern, options = {}, data) {\n this.pattern = pattern;\n this.separator = options.separator || '.';\n this.segments = this._parse(pattern);\n this.data = data;\n // Cache expensive checks for performance (O(1) instead of O(n))\n this._hasDeepWildcard = this.segments.some(seg => seg.type === 'deep-wildcard');\n this._hasAttributeCondition = this.segments.some(seg => seg.attrName !== undefined);\n this._hasPositionSelector = this.segments.some(seg => seg.position !== undefined);\n }\n\n /**\n * Parse pattern string into segments\n * @private\n * @param {string} pattern - Pattern to parse\n * @returns {Array} Array of segment objects\n */\n _parse(pattern) {\n const segments = [];\n\n // Split by separator but handle \"..\" specially\n let i = 0;\n let currentPart = '';\n\n while (i < pattern.length) {\n if (pattern[i] === this.separator) {\n // Check if next char is also separator (deep wildcard)\n if (i + 1 < pattern.length && pattern[i + 1] === this.separator) {\n // Flush current part if any\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n currentPart = '';\n }\n // Add deep wildcard\n segments.push({ type: 'deep-wildcard' });\n i += 2; // Skip both separators\n } else {\n // Regular separator\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n currentPart = '';\n i++;\n }\n } else {\n currentPart += pattern[i];\n i++;\n }\n }\n\n // Flush remaining part\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n\n return segments;\n }\n\n /**\n * Parse a single segment\n * @private\n * @param {string} part - Segment string (e.g., \"user\", \"ns::user\", \"user[id]\", \"ns::user:first\")\n * @returns {Object} Segment object\n */\n _parseSegment(part) {\n const segment = { type: 'tag' };\n\n // NEW NAMESPACE SYNTAX (v2.0):\n // ============================\n // Namespace uses DOUBLE colon (::)\n // Position uses SINGLE colon (:)\n // \n // Examples:\n // \"user\" → tag\n // \"user:first\" → tag + position\n // \"user[id]\" → tag + attribute\n // \"user[id]:first\" → tag + attribute + position\n // \"ns::user\" → namespace + tag\n // \"ns::user:first\" → namespace + tag + position\n // \"ns::user[id]\" → namespace + tag + attribute\n // \"ns::user[id]:first\" → namespace + tag + attribute + position\n // \"ns::first\" → namespace + tag named \"first\" (NO ambiguity!)\n //\n // This eliminates all ambiguity:\n // :: = namespace separator\n // : = position selector\n // [] = attributes\n\n // Step 1: Extract brackets [attr] or [attr=value]\n let bracketContent = null;\n let withoutBrackets = part;\n\n const bracketMatch = part.match(/^([^\\[]+)(\\[[^\\]]*\\])(.*)$/);\n if (bracketMatch) {\n withoutBrackets = bracketMatch[1] + bracketMatch[3];\n if (bracketMatch[2]) {\n const content = bracketMatch[2].slice(1, -1);\n if (content) {\n bracketContent = content;\n }\n }\n }\n\n // Step 2: Check for namespace (double colon ::)\n let namespace = undefined;\n let tagAndPosition = withoutBrackets;\n\n if (withoutBrackets.includes('::')) {\n const nsIndex = withoutBrackets.indexOf('::');\n namespace = withoutBrackets.substring(0, nsIndex).trim();\n tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim(); // Skip ::\n\n if (!namespace) {\n throw new Error(`Invalid namespace in pattern: ${part}`);\n }\n }\n\n // Step 3: Parse tag and position (single colon :)\n let tag = undefined;\n let positionMatch = null;\n\n if (tagAndPosition.includes(':')) {\n const colonIndex = tagAndPosition.lastIndexOf(':'); // Use last colon for position\n const tagPart = tagAndPosition.substring(0, colonIndex).trim();\n const posPart = tagAndPosition.substring(colonIndex + 1).trim();\n\n // Verify position is a valid keyword\n const isPositionKeyword = ['first', 'last', 'odd', 'even'].includes(posPart) ||\n /^nth\\(\\d+\\)$/.test(posPart);\n\n if (isPositionKeyword) {\n tag = tagPart;\n positionMatch = posPart;\n } else {\n // Not a valid position keyword, treat whole thing as tag\n tag = tagAndPosition;\n }\n } else {\n tag = tagAndPosition;\n }\n\n if (!tag) {\n throw new Error(`Invalid segment pattern: ${part}`);\n }\n\n segment.tag = tag;\n if (namespace) {\n segment.namespace = namespace;\n }\n\n // Step 4: Parse attributes\n if (bracketContent) {\n if (bracketContent.includes('=')) {\n const eqIndex = bracketContent.indexOf('=');\n segment.attrName = bracketContent.substring(0, eqIndex).trim();\n segment.attrValue = bracketContent.substring(eqIndex + 1).trim();\n } else {\n segment.attrName = bracketContent.trim();\n }\n }\n\n // Step 5: Parse position selector\n if (positionMatch) {\n const nthMatch = positionMatch.match(/^nth\\((\\d+)\\)$/);\n if (nthMatch) {\n segment.position = 'nth';\n segment.positionValue = parseInt(nthMatch[1], 10);\n } else {\n segment.position = positionMatch;\n }\n }\n\n return segment;\n }\n\n /**\n * Get the number of segments\n * @returns {number}\n */\n get length() {\n return this.segments.length;\n }\n\n /**\n * Check if expression contains deep wildcard\n * @returns {boolean}\n */\n hasDeepWildcard() {\n return this._hasDeepWildcard;\n }\n\n /**\n * Check if expression has attribute conditions\n * @returns {boolean}\n */\n hasAttributeCondition() {\n return this._hasAttributeCondition;\n }\n\n /**\n * Check if expression has position selectors\n * @returns {boolean}\n */\n hasPositionSelector() {\n return this._hasPositionSelector;\n }\n\n /**\n * Get string representation\n * @returns {string}\n */\n toString() {\n return this.pattern;\n }\n}","import ExpressionSet from \"./ExpressionSet.js\";\n\n/**\n * MatcherView - A lightweight read-only view over a Matcher's internal state.\n *\n * Created once by Matcher and reused across all callbacks. Holds a direct\n * reference to the parent Matcher so it always reflects current parser state\n * with zero copying or freezing overhead.\n *\n * Users receive this via {@link Matcher#readOnly} or directly from parser\n * callbacks. It exposes all query and matching methods but has no mutation\n * methods — misuse is caught at the TypeScript level rather than at runtime.\n *\n * @example\n * const matcher = new Matcher();\n * const view = matcher.readOnly();\n *\n * matcher.push(\"root\", {});\n * view.getCurrentTag(); // \"root\"\n * view.getDepth(); // 1\n */\nexport class MatcherView {\n /**\n * @param {Matcher} matcher - The parent Matcher instance to read from.\n */\n constructor(matcher) {\n this._matcher = matcher;\n }\n\n /**\n * Get the path separator used by the parent matcher.\n * @returns {string}\n */\n get separator() {\n return this._matcher.separator;\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return undefined;\n return path[path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return false;\n const current = path[path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this._matcher.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n return this._matcher.toString(separator, includeNamespace);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this._matcher.path.map(n => n.tag);\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n return this._matcher.matches(expression);\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this._matcher);\n }\n}\n\n/**\n * Matcher - Tracks current path in XML/JSON tree and matches against Expressions.\n *\n * The matcher maintains a stack of nodes representing the current path from root to\n * current tag. It only stores attribute values for the current (top) node to minimize\n * memory usage. Sibling tracking is used to auto-calculate position and counter.\n *\n * Use {@link Matcher#readOnly} to obtain a {@link MatcherView} safe to pass to\n * user callbacks — it always reflects current state with no Proxy overhead.\n *\n * @example\n * const matcher = new Matcher();\n * matcher.push(\"root\", {});\n * matcher.push(\"users\", {});\n * matcher.push(\"user\", { id: \"123\", type: \"admin\" });\n *\n * const expr = new Expression(\"root.users.user\");\n * matcher.matches(expr); // true\n */\nexport default class Matcher {\n /**\n * Create a new Matcher.\n * @param {Object} [options={}]\n * @param {string} [options.separator='.'] - Default path separator\n */\n constructor(options = {}) {\n this.separator = options.separator || '.';\n this.path = [];\n this.siblingStacks = [];\n // Each path node: { tag, values, position, counter, namespace? }\n // values only present for current (last) node\n // Each siblingStacks entry: Map tracking occurrences at each level\n this._pathStringCache = null;\n this._view = new MatcherView(this);\n }\n\n /**\n * Push a new tag onto the path.\n * @param {string} tagName\n * @param {Object|null} [attrValues=null]\n * @param {string|null} [namespace=null]\n */\n push(tagName, attrValues = null, namespace = null) {\n this._pathStringCache = null;\n\n // Remove values from previous current node (now becoming ancestor)\n if (this.path.length > 0) {\n this.path[this.path.length - 1].values = undefined;\n }\n\n // Get or create sibling tracking for current level\n const currentLevel = this.path.length;\n if (!this.siblingStacks[currentLevel]) {\n this.siblingStacks[currentLevel] = new Map();\n }\n\n const siblings = this.siblingStacks[currentLevel];\n\n // Create a unique key for sibling tracking that includes namespace\n const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;\n\n // Calculate counter (how many times this tag appeared at this level)\n const counter = siblings.get(siblingKey) || 0;\n\n // Calculate position (total children at this level so far)\n let position = 0;\n for (const count of siblings.values()) {\n position += count;\n }\n\n // Update sibling count for this tag\n siblings.set(siblingKey, counter + 1);\n\n // Create new node\n const node = {\n tag: tagName,\n position: position,\n counter: counter\n };\n\n if (namespace !== null && namespace !== undefined) {\n node.namespace = namespace;\n }\n\n if (attrValues !== null && attrValues !== undefined) {\n node.values = attrValues;\n }\n\n this.path.push(node);\n }\n\n /**\n * Pop the last tag from the path.\n * @returns {Object|undefined} The popped node\n */\n pop() {\n if (this.path.length === 0) return undefined;\n this._pathStringCache = null;\n\n const node = this.path.pop();\n\n if (this.siblingStacks.length > this.path.length + 1) {\n this.siblingStacks.length = this.path.length + 1;\n }\n\n return node;\n }\n\n /**\n * Update current node's attribute values.\n * Useful when attributes are parsed after push.\n * @param {Object} attrValues\n */\n updateCurrent(attrValues) {\n if (this.path.length > 0) {\n const current = this.path[this.path.length - 1];\n if (attrValues !== null && attrValues !== undefined) {\n current.values = attrValues;\n }\n }\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n if (this.path.length === 0) return undefined;\n return this.path[this.path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n if (this.path.length === 0) return false;\n const current = this.path[this.path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n const sep = separator || this.separator;\n const isDefault = (sep === this.separator && includeNamespace === true);\n\n if (isDefault) {\n if (this._pathStringCache !== null) {\n return this._pathStringCache;\n }\n const result = this.path.map(n =>\n (n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n this._pathStringCache = result;\n return result;\n }\n\n return this.path.map(n =>\n (includeNamespace && n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this.path.map(n => n.tag);\n }\n\n /**\n * Reset the path to empty.\n */\n reset() {\n this._pathStringCache = null;\n this.path = [];\n this.siblingStacks = [];\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n const segments = expression.segments;\n\n if (segments.length === 0) {\n return false;\n }\n\n if (expression.hasDeepWildcard()) {\n return this._matchWithDeepWildcard(segments);\n }\n\n return this._matchSimple(segments);\n }\n\n /**\n * @private\n */\n _matchSimple(segments) {\n if (this.path.length !== segments.length) {\n return false;\n }\n\n for (let i = 0; i < segments.length; i++) {\n if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * @private\n */\n _matchWithDeepWildcard(segments) {\n let pathIdx = this.path.length - 1;\n let segIdx = segments.length - 1;\n\n while (segIdx >= 0 && pathIdx >= 0) {\n const segment = segments[segIdx];\n\n if (segment.type === 'deep-wildcard') {\n segIdx--;\n\n if (segIdx < 0) {\n return true;\n }\n\n const nextSeg = segments[segIdx];\n let found = false;\n\n for (let i = pathIdx; i >= 0; i--) {\n if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) {\n pathIdx = i - 1;\n segIdx--;\n found = true;\n break;\n }\n }\n\n if (!found) {\n return false;\n }\n } else {\n if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) {\n return false;\n }\n pathIdx--;\n segIdx--;\n }\n }\n\n return segIdx < 0;\n }\n\n /**\n * @private\n */\n _matchSegment(segment, node, isCurrentNode) {\n if (segment.tag !== '*' && segment.tag !== node.tag) {\n return false;\n }\n\n if (segment.namespace !== undefined) {\n if (segment.namespace !== '*' && segment.namespace !== node.namespace) {\n return false;\n }\n }\n\n if (segment.attrName !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n if (!node.values || !(segment.attrName in node.values)) {\n return false;\n }\n\n if (segment.attrValue !== undefined) {\n if (String(node.values[segment.attrName]) !== String(segment.attrValue)) {\n return false;\n }\n }\n }\n\n if (segment.position !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n const counter = node.counter ?? 0;\n\n if (segment.position === 'first' && counter !== 0) {\n return false;\n } else if (segment.position === 'odd' && counter % 2 !== 1) {\n return false;\n } else if (segment.position === 'even' && counter % 2 !== 0) {\n return false;\n } else if (segment.position === 'nth' && counter !== segment.positionValue) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this);\n }\n\n /**\n * Create a snapshot of current state.\n * @returns {Object}\n */\n snapshot() {\n return {\n path: this.path.map(node => ({ ...node })),\n siblingStacks: this.siblingStacks.map(map => new Map(map))\n };\n }\n\n /**\n * Restore state from snapshot.\n * @param {Object} snapshot\n */\n restore(snapshot) {\n this._pathStringCache = null;\n this.path = snapshot.path.map(node => ({ ...node }));\n this.siblingStacks = snapshot.siblingStacks.map(map => new Map(map));\n }\n\n /**\n * Return the read-only {@link MatcherView} for this matcher.\n *\n * The same instance is returned on every call — no allocation occurs.\n * It always reflects the current parser state and is safe to pass to\n * user callbacks without risk of accidental mutation.\n *\n * @returns {MatcherView}\n *\n * @example\n * const view = matcher.readOnly();\n * // pass view to callbacks — it stays in sync automatically\n * view.matches(expr); // ✓\n * view.getCurrentTag(); // ✓\n * // view.push(...) // ✗ method does not exist — caught by TypeScript\n */\n readOnly() {\n return this._view;\n }\n}","\n\nexport function safeComment(val) {\n return String(val)\n .replace(/--/g, '- -') // -- is illegal anywhere in comment content\n .replace(/--/g, '- -') // handle the scenario when 2 consiucative dashes appears \n .replace(/-$/, '- '); // trailing - would form -- with the closing -->\n}\n\nexport function safeCdata(val) {\n return String(val).replace(/\\]\\]>/g, ']]]]>')\n}\n\nexport function escapeAttribute(val) {\n return String(val).replace(/\"/g, '"').replace(/'/g, ''')\n}","/**\n * xml-naming\n * Validates XML Name productions as defined in the XML 1.0 and 1.1 specifications.\n * Covers: Name, NCName, QName, NMToken, NMTokens\n *\n * XML 1.0 spec: https://www.w3.org/TR/xml/#NT-Name\n * XML 1.1 spec: https://www.w3.org/TR/xml11/#NT-NameStartChar\n * XML NS spec: https://www.w3.org/TR/xml-names/#NT-NCName\n */\n\n// ---------------------------------------------------------------------------\n// Character class strings — XML 1.0\n//\n// NameStartChar ::= \":\" | [A-Z] | \"_\" | [a-z]\n// | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF]\n// | [#x370-#x37D] | [#x37F-#x1FFF] <- split to exclude #x0487\n// | [#x200C-#x200D]\n// | [#x2070-#x218F] | [#x2C00-#x2FEF]\n// | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD]\n//\n// NameChar ::= NameStartChar | \"-\" | \".\" | [0-9]\n// | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]\n//\n// Note: \\u0487 (Combining Cyrillic Millions Sign) was added in Unicode 4.0,\n// after XML 1.0 was defined against Unicode 2.0. It falls inside the range\n// \\u037F-\\u1FFF but must be excluded. We split that range into\n// \\u037F-\\u0486 and \\u0488-\\u1FFF to exclude it explicitly.\n// ---------------------------------------------------------------------------\n\nconst nameStartChar10 =\n ':A-Za-z_' +\n '\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF' +\n '\\u0370-\\u037D' +\n '\\u037F-\\u0486\\u0488-\\u1FFF' + // split to exclude \\u0487\n '\\u200C-\\u200D' +\n '\\u2070-\\u218F' +\n '\\u2C00-\\u2FEF' +\n '\\u3001-\\uD7FF' +\n '\\uF900-\\uFDCF' +\n '\\uFDF0-\\uFFFD';\n\nconst nameChar10 =\n nameStartChar10 +\n '\\\\-\\\\.\\\\d' +\n '\\u00B7' +\n '\\u0300-\\u036F' +\n '\\u203F-\\u2040';\n\n// ---------------------------------------------------------------------------\n// Character class strings — XML 1.1\n//\n// Differences from XML 1.0:\n//\n// NameStartChar:\n// 1.0 has split ranges: \\u00C0-\\u00D6, \\u00D8-\\u00F6, \\u00F8-\\u02FF\n// 1.1 merges them into: \\u00C0-\\u02FF\n// (\\u00D7 x and \\u00F7 / are division symbols, excluded in both versions)\n//\n// 1.0 tops out at \\uFFFD (BMP only)\n// 1.1 adds \\u{10000}-\\u{EFFFF} (supplementary planes)\n// These require the /u flag on the RegExp — see buildRegexes below.\n//\n// NameChar:\n// 1.1 adds \\u0487 (Combining Cyrillic Millions Sign, added in Unicode 4.0)\n// ---------------------------------------------------------------------------\n\nconst nameStartChar11 =\n ':A-Za-z_' +\n '\\u00C0-\\u02FF' + // merged — 1.0 had three split ranges here\n '\\u0370-\\u037D' +\n '\\u037F-\\u0486\\u0488-\\u1FFF' + // split to exclude \\u0487 (combining mark, never a NameStartChar)\n '\\u200C-\\u200D' +\n '\\u2070-\\u218F' +\n '\\u2C00-\\u2FEF' +\n '\\u3001-\\uD7FF' +\n '\\uF900-\\uFDCF' +\n '\\uFDF0-\\uFFFD' +\n '\\u{10000}-\\u{EFFFF}'; // supplementary planes — REQUIRES /u flag on RegExp\n\nconst nameChar11 =\n nameStartChar11 +\n '\\\\-\\\\.\\\\d' +\n '\\u00B7' +\n '\\u0300-\\u036F' +\n '\\u0487' + // Combining Cyrillic Millions Sign — valid in 1.1, not 1.0\n '\\u203F-\\u2040';\n\n// ---------------------------------------------------------------------------\n// Regex builders\n//\n// XML 1.0 regexes: no flags — BMP only, standard JS regex behaviour.\n// XML 1.1 regexes: /u flag — required for \\u{10000}-\\u{EFFFF} to match actual\n// supplementary code points rather than lone surrogates (which are illegal XML).\n// ---------------------------------------------------------------------------\n\nconst buildRegexes = (startChar, char, flags = '') => {\n const ncStart = startChar.replace(':', '');\n const ncChar = char.replace(':', '');\n const ncNamePat = `[${ncStart}][${ncChar}]*`;\n\n return {\n name: new RegExp(`^[${startChar}][${char}]*$`, flags),\n ncName: new RegExp(`^${ncNamePat}$`, flags),\n qName: new RegExp(`^${ncNamePat}(?::${ncNamePat})?$`, flags),\n nmToken: new RegExp(`^[${char}]+$`, flags),\n nmTokens: new RegExp(`^[${char}]+(?:\\\\s+[${char}]+)*$`, flags),\n };\n};\n\nconst regexes10 = buildRegexes(nameStartChar10, nameChar10); // no /u — BMP only\nconst regexes11 = buildRegexes(nameStartChar11, nameChar11, 'u'); // /u — enables \\u{10000}-\\u{EFFFF}\n\nconst getRegexes = (xmlVersion = '1.0') =>\n xmlVersion === '1.1' ? regexes11 : regexes10;\n\n// ---------------------------------------------------------------------------\n// Boolean validators\n// ---------------------------------------------------------------------------\n\n/**\n * Returns true if the string is a valid XML Name.\n * Colons are allowed anywhere (Name production).\n * Used for: DOCTYPE entity names, notation names, DTD element declarations.\n */\nexport const name = (str, { xmlVersion = '1.0' } = {}) =>\n getRegexes(xmlVersion).name.test(str);\n\n/**\n * Returns true if the string is a valid NCName (Non-Colonized Name).\n * Colons are not permitted.\n * Used for: namespace prefixes, local names, SVG id attributes.\n */\nexport const ncName = (str, { xmlVersion = '1.0' } = {}) =>\n getRegexes(xmlVersion).ncName.test(str);\n\n/**\n * Returns true if the string is a valid QName (Qualified Name).\n * Allows exactly one colon as a prefix separator: prefix:localName.\n * Used for: element and attribute names in namespace-aware XML/SVG.\n */\nexport const qName = (str, { xmlVersion = '1.0' } = {}) =>\n getRegexes(xmlVersion).qName.test(str);\n\n/**\n * Returns true if the string is a valid NMToken.\n * Like Name but no restriction on the first character.\n * Used for: DTD NMTOKEN attribute values.\n */\nexport const nmToken = (str, { xmlVersion = '1.0' } = {}) =>\n getRegexes(xmlVersion).nmToken.test(str);\n\n/**\n * Returns true if the string is a valid NMTokens value.\n * A whitespace-separated list of NMToken values.\n * Used for: DTD NMTOKENS attribute values.\n */\nexport const nmTokens = (str, { xmlVersion = '1.0' } = {}) =>\n getRegexes(xmlVersion).nmTokens.test(str);\n\n// ---------------------------------------------------------------------------\n// Diagnostic validator\n// ---------------------------------------------------------------------------\n\nconst PRODUCTIONS = ['name', 'ncName', 'qName', 'nmToken', 'nmTokens'];\n\n/**\n * Validates a string against a named production and returns a detailed result.\n *\n * @param {string} str\n * @param {'name'|'ncName'|'qName'|'nmToken'|'nmTokens'} production\n * @param {{ xmlVersion?: '1.0'|'1.1' }} [opts]\n * @returns {{ valid: boolean, production: string, input: string, reason?: string, position?: number }}\n */\nexport const validate = (str, production, { xmlVersion = '1.0' } = {}) => {\n if (!PRODUCTIONS.includes(production)) {\n throw new TypeError(\n `Unknown production \"${production}\". Must be one of: ${PRODUCTIONS.join(', ')}`\n );\n }\n\n const validators = { name, ncName, qName, nmToken, nmTokens };\n const isValid = validators[production](str, { xmlVersion });\n\n if (isValid) return { valid: true, production, input: str };\n\n let reason = 'Does not match the production rules';\n let position;\n\n if (str.length === 0) {\n reason = 'Input is empty';\n } else if (production === 'ncName' && str.includes(':')) {\n position = str.indexOf(':');\n reason = 'Colon is not allowed in NCName';\n } else if (production === 'qName' && str.startsWith(':')) {\n reason = 'QName cannot start with a colon';\n position = 0;\n } else if (production === 'qName' && str.endsWith(':')) {\n reason = 'QName cannot end with a colon';\n position = str.length - 1;\n } else if (production === 'qName' && (str.match(/:/g) || []).length > 1) {\n reason = 'QName can have at most one colon';\n position = str.lastIndexOf(':');\n } else if (\n ['name', 'ncName', 'qName'].includes(production) &&\n !/^[:A-Za-z_\\u00C0-\\uFFFD]/.test(str[0])\n ) {\n reason = `First character \"${str[0]}\" is not a valid NameStartChar`;\n position = 0;\n } else {\n for (let i = 0; i < str.length; i++) {\n if (!/[\\w\\-\\\\.:\\u00B7\\u00C0-\\uFFFD]/.test(str[i])) {\n reason = `Character \"${str[i]}\" at position ${i} is not a valid NameChar`;\n position = i;\n break;\n }\n }\n }\n\n return { valid: false, production, input: str, reason, position };\n};\n\n// ---------------------------------------------------------------------------\n// Batch validator\n// ---------------------------------------------------------------------------\n\n/**\n * Validates an array of strings against a named production.\n *\n * @param {string[]} strings\n * @param {'name'|'ncName'|'qName'|'nmToken'|'nmTokens'} production\n * @param {{ xmlVersion?: '1.0'|'1.1' }} [opts]\n * @returns {Array<{ valid: boolean, production: string, input: string, reason?: string, position?: number }>}\n */\nexport const validateAll = (strings, production, opts = {}) =>\n strings.map(str => validate(str, production, opts));\n\n// ---------------------------------------------------------------------------\n// Sanitizer\n// ---------------------------------------------------------------------------\n\n/**\n * Transforms an invalid string into the nearest valid XML name for the given production.\n *\n * @param {string} str\n * @param {'name'|'ncName'|'qName'|'nmToken'|'nmTokens'} production\n * @param {{ replacement?: string }} [opts]\n * @returns {string}\n */\nexport const sanitize = (str, production = 'name', { replacement = '_' } = {}) => {\n if (!str) return replacement;\n\n let result = str;\n\n // Strip colons for NCName\n if (production === 'ncName') {\n result = result.replace(/:/g, '');\n }\n\n // Replace illegal characters\n result = result.replace(/[^\\w\\-\\.:\\u00B7\\u00C0-\\uFFFD]/g, replacement);\n\n // Fix invalid start character for Name / NCName / QName\n if (production !== 'nmToken' && production !== 'nmTokens') {\n if (/^[\\-\\.\\d]/.test(result)) {\n result = replacement + result;\n }\n }\n\n return result || replacement;\n};","import { Expression, Matcher } from 'path-expression-matcher';\nimport { safeComment, safeCdata, escapeAttribute } from \"./util.js\";\nimport { qName } from 'xml-naming';\n\nconst EOL = \"\\n\";\n\n/**\n * Detect XML version from the first element of the ordered array input.\n * The first element must be a ?xml processing instruction with a version attribute.\n * Returns '1.0' if not found.\n *\n * @param {array} jArray\n * @param {object} options\n */\nfunction detectXmlVersionFromArray(jArray, options) {\n if (!Array.isArray(jArray) || jArray.length === 0) return '1.0';\n const first = jArray[0];\n const firstKey = propName(first);\n if (firstKey === '?xml') {\n const attrs = first[':@'];\n if (attrs) {\n const versionKey = options.attributeNamePrefix + 'version';\n if (attrs[versionKey]) return attrs[versionKey];\n }\n }\n return '1.0';\n}\n\n/**\n * Resolve a tag or attribute name through sanitizeName if configured.\n * Validation via xml-naming's qName is performed first; the sanitizeName\n * callback is invoked only when the name is invalid. If sanitizeName is\n * false (default), no validation occurs and the name is used as-is.\n *\n * @param {string} name - raw name from the JS object\n * @param {boolean} isAttribute - true when resolving an attribute name\n * @param {object} options\n * @param {Matcher} matcher - current matcher state (readonly from callback perspective)\n * @param {string} xmlVersion - '1.0' or '1.1', forwarded to xml-naming\n */\nfunction resolveTagName(name, isAttribute, options, matcher, xmlVersion) {\n if (!options.sanitizeName) return name;\n if (qName(name, { xmlVersion })) return name;\n return options.sanitizeName(name, { isAttribute, matcher: matcher.readOnly() });\n}\n\n/**\n * @param {array} jArray\n * @param {any} options\n * @returns\n */\nexport default function toXml(jArray, options) {\n let indentation = \"\";\n if (options.format) {\n indentation = EOL;\n }\n\n // Pre-compile stopNode expressions for pattern matching\n const stopNodeExpressions = [];\n if (options.stopNodes && Array.isArray(options.stopNodes)) {\n for (let i = 0; i < options.stopNodes.length; i++) {\n const node = options.stopNodes[i];\n if (typeof node === 'string') {\n stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n stopNodeExpressions.push(node);\n }\n }\n }\n\n // Detect XML version for use in name validation\n const xmlVersion = detectXmlVersionFromArray(jArray, options);\n\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n\n return arrToStr(jArray, options, indentation, matcher, stopNodeExpressions, xmlVersion);\n}\n\nfunction arrToStr(arr, options, indentation, matcher, stopNodeExpressions, xmlVersion) {\n let xmlStr = \"\";\n let isPreviousElementTag = false;\n\n if (options.maxNestedTags && matcher.getDepth() > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n\n if (!Array.isArray(arr)) {\n // Non-array values (e.g. string tag values) should be treated as text content\n if (arr !== undefined && arr !== null) {\n let text = arr.toString();\n text = replaceEntitiesValue(text, options);\n return text;\n }\n return \"\";\n }\n\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const rawTagName = propName(tagObj);\n if (rawTagName === undefined) continue;\n\n // Special names are exempt from sanitizeName: internal conventions and PI tags\n // are not user-supplied XML element names.\n const isSpecialName = rawTagName === options.textNodeName\n || rawTagName === options.cdataPropName\n || rawTagName === options.commentPropName\n || rawTagName[0] === '?';\n\n // Resolve tag name (may transform it; may throw for invalid names)\n const tagName = isSpecialName\n ? rawTagName\n : resolveTagName(rawTagName, false, options, matcher, xmlVersion);\n\n // Extract attributes from \":@\" property\n const attrValues = extractAttributeValues(tagObj[\":@\"], options);\n\n // Push resolved tag to matcher WITH attributes\n matcher.push(tagName, attrValues);\n\n // Check if this is a stop node using Expression matching\n const isStopNode = checkStopNode(matcher, stopNodeExpressions);\n\n if (tagName === options.textNodeName) {\n let tagText = tagObj[rawTagName];\n if (!isStopNode) {\n tagText = options.tagValueProcessor(tagName, tagText);\n tagText = replaceEntitiesValue(tagText, options);\n }\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += tagText;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.cdataPropName) {\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n const val = tagObj[rawTagName][0][options.textNodeName];\n const safeVal = safeCdata(val);\n xmlStr += ``;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.commentPropName) {\n const val = tagObj[rawTagName][0][options.textNodeName];\n const safeVal = safeComment(val);\n xmlStr += indentation + ``;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n } else if (tagName[0] === \"?\") {\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode, matcher, xmlVersion);\n const tempInd = tagName === \"?xml\" ? \"\" : indentation;\n // Text node content on PI/XML declaration tags is intentionally ignored.\n // Only attributes are valid on these tags per the XML spec.\n xmlStr += tempInd + `<${tagName}${attStr}?>`;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n }\n\n let newIdentation = indentation;\n if (newIdentation !== \"\") {\n newIdentation += options.indentBy;\n }\n\n // Pass isStopNode to attr_to_str so attributes are also not processed for stopNodes\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode, matcher, xmlVersion);\n const tagStart = indentation + `<${tagName}${attStr}`;\n\n // If this is a stopNode, get raw content without processing\n let tagValue;\n if (isStopNode) {\n tagValue = getRawContent(tagObj[rawTagName], options);\n } else {\n tagValue = arrToStr(tagObj[rawTagName], options, newIdentation, matcher, stopNodeExpressions, xmlVersion);\n }\n\n if (options.unpairedTags.indexOf(tagName) !== -1) {\n if (options.suppressUnpairedNode) xmlStr += tagStart + \">\";\n else xmlStr += tagStart + \"/>\";\n } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {\n xmlStr += tagStart + \"/>\";\n } else if (tagValue && tagValue.endsWith(\">\")) {\n xmlStr += tagStart + `>${tagValue}${indentation}`;\n } else {\n xmlStr += tagStart + \">\";\n if (tagValue && indentation !== \"\" && (tagValue.includes(\"/>\") || tagValue.includes(\"`;\n }\n isPreviousElementTag = true;\n\n // Pop tag from matcher\n matcher.pop();\n }\n\n return xmlStr;\n}\n\n/**\n * Extract attribute values from the \":@\" object and return as plain object\n * for passing to matcher.push()\n */\nfunction extractAttributeValues(attrMap, options) {\n if (!attrMap || options.ignoreAttributes) return null;\n\n const attrValues = {};\n let hasAttrs = false;\n\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // Remove the attribute prefix to get clean attribute name\n const cleanAttrName = attr.startsWith(options.attributeNamePrefix)\n ? attr.substr(options.attributeNamePrefix.length)\n : attr;\n attrValues[cleanAttrName] = escapeAttribute(attrMap[attr]);\n hasAttrs = true;\n }\n\n return hasAttrs ? attrValues : null;\n}\n\n/**\n * Extract raw content from a stopNode without any processing\n * This preserves the content exactly as-is, including special characters\n */\nfunction getRawContent(arr, options) {\n if (!Array.isArray(arr)) {\n // Non-array values return as-is\n if (arr !== undefined && arr !== null) {\n return arr.toString();\n }\n return \"\";\n }\n\n let content = \"\";\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n const tagName = propName(item);\n\n if (tagName === options.textNodeName) {\n // Raw text content - NO processing, NO entity replacement\n content += item[tagName];\n } else if (tagName === options.cdataPropName) {\n // CDATA content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName === options.commentPropName) {\n // Comment content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName && tagName[0] === \"?\") {\n // Processing instruction - skip for stopNodes\n continue;\n } else if (tagName) {\n // Nested tags within stopNode — no sanitizeName, content is raw\n const attStr = attr_to_str_raw(item[\":@\"], options);\n const nestedContent = getRawContent(item[tagName], options);\n\n if (!nestedContent || nestedContent.length === 0) {\n content += `<${tagName}${attStr}/>`;\n } else {\n content += `<${tagName}${attStr}>${nestedContent}`;\n }\n }\n }\n return content;\n}\n\n/**\n * Build attribute string for stopNodes - NO entity replacement\n */\nfunction attr_to_str_raw(attrMap, options) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // For stopNodes, use raw value without processing\n let attrVal = attrMap[attr];\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${escapeAttribute(attrVal)}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n if (key !== \":@\") return key;\n }\n}\n\n/**\n * Build attribute string, resolving attribute names through sanitizeName when configured.\n * Accepts matcher so the callback has path context.\n */\nfunction attr_to_str(attrMap, options, isStopNode, matcher, xmlVersion) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n\n // Strip prefix to get the clean XML attribute name, then optionally sanitize it\n const cleanAttrName = attr.substr(options.attributeNamePrefix.length);\n const resolvedAttrName = isStopNode\n ? cleanAttrName // stopNodes are raw — skip sanitizeName for attr names too\n : resolveTagName(cleanAttrName, true, options, matcher, xmlVersion);\n\n let attrVal;\n if (isStopNode) {\n // For stopNodes, use raw value without any processing\n attrVal = attrMap[attr];\n } else {\n // Normal processing: apply attributeValueProcessor and entity replacement\n attrVal = options.attributeValueProcessor(attr, attrMap[attr]);\n attrVal = replaceEntitiesValue(attrVal, options);\n }\n\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${resolvedAttrName}`;\n } else {\n attrStr += ` ${resolvedAttrName}=\"${escapeAttribute(attrVal)}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction checkStopNode(matcher, stopNodeExpressions) {\n if (!stopNodeExpressions || stopNodeExpressions.length === 0) return false;\n\n for (let i = 0; i < stopNodeExpressions.length; i++) {\n if (matcher.matches(stopNodeExpressions[i])) {\n return true;\n }\n }\n return false;\n}\n\nfunction replaceEntitiesValue(textValue, options) {\n if (textValue && textValue.length > 0 && options.processEntities) {\n for (let i = 0; i < options.entities.length; i++) {\n const entity = options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}","'use strict';\n//parse Empty Node as self closing node\nimport buildFromOrderedJs from './orderedJs2Xml.js';\nimport getIgnoreAttributesFn from \"./ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\nimport { safeComment, safeCdata, escapeAttribute } from './util.js';\nimport { qName } from 'xml-naming';\n\nconst defaultOptions = {\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n cdataPropName: false,\n format: false,\n indentBy: ' ',\n suppressEmptyNode: false,\n suppressUnpairedNode: true,\n suppressBooleanAttributes: true,\n tagValueProcessor: function (key, a) {\n return a;\n },\n attributeValueProcessor: function (attrName, a) {\n return a;\n },\n preserveOrder: false,\n commentPropName: false,\n unpairedTags: [],\n entities: [\n { regex: new RegExp(\"&\", \"g\"), val: \"&\" },//it must be on top\n { regex: new RegExp(\">\", \"g\"), val: \">\" },\n { regex: new RegExp(\"<\", \"g\"), val: \"<\" },\n { regex: new RegExp(\"\\'\", \"g\"), val: \"'\" },\n { regex: new RegExp(\"\\\"\", \"g\"), val: \""\" }\n ],\n processEntities: true,\n stopNodes: [],\n // transformTagName: false,\n // transformAttributeName: false,\n oneListGroup: false,\n maxNestedTags: 100,\n jPath: true, // When true, callbacks receive string jPath; when false, receive Matcher instance\n sanitizeName: false // false = allow all names as-is (default, backward-compatible).\n // Set to a function (name, { isAttribute, matcher }) => string to\n // validate/sanitize tag and attribute names. Throw inside the function\n // to reject an invalid name.\n};\n\nexport default function Builder(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n // Convert old-style stopNodes for backward compatibility\n // Old syntax: \"*.tag\" meant \"tag anywhere in tree\"\n // New syntax: \"..tag\" means \"tag anywhere in tree\"\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n this.options.stopNodes = this.options.stopNodes.map(node => {\n if (typeof node === 'string' && node.startsWith('*.')) {\n // Convert old wildcard syntax to deep wildcard\n return '..' + node.substring(2);\n }\n return node;\n });\n }\n\n // Pre-compile stopNode expressions for pattern matching\n this.stopNodeExpressions = [];\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n for (let i = 0; i < this.options.stopNodes.length; i++) {\n const node = this.options.stopNodes[i];\n if (typeof node === 'string') {\n this.stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n this.stopNodeExpressions.push(node);\n }\n }\n }\n\n if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {\n this.isAttribute = function (/*a*/) {\n return false;\n };\n } else {\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.attrPrefixLen = this.options.attributeNamePrefix.length;\n this.isAttribute = isAttribute;\n }\n\n this.processTextOrObjNode = processTextOrObjNode\n\n if (this.options.format) {\n this.indentate = indentate;\n this.tagEndChar = '>\\n';\n this.newLine = '\\n';\n } else {\n this.indentate = function () {\n return '';\n };\n this.tagEndChar = '>';\n this.newLine = '';\n }\n}\n\n/**\n * Detect XML version from the ?xml declaration at the root of a plain-object input.\n * Checks both attributesGroupName and flat attribute forms.\n * Returns '1.0' if no declaration is found.\n */\nfunction detectXmlVersionFromObj(jObj, options) {\n const decl = jObj['?xml'];\n if (decl && typeof decl === 'object') {\n // attributesGroupName path e.g. { '$$': { '@_version': '1.1' } }\n if (options.attributesGroupName && decl[options.attributesGroupName]) {\n const v = decl[options.attributesGroupName][options.attributeNamePrefix + 'version'];\n if (v) return v;\n }\n // flat attribute path e.g. { '@_version': '1.1' }\n const v = decl[options.attributeNamePrefix + 'version'];\n if (v) return v;\n }\n return '1.0';\n}\n\n/**\n * Resolve a tag or attribute name through sanitizeName if configured.\n * Validation via xml-naming's qName is performed first; the sanitizeName\n * callback is invoked only when the name is invalid. If sanitizeName is\n * false (default), no validation occurs and the name is used as-is.\n *\n * @param {string} name - raw name from the JS object\n * @param {boolean} isAttribute - true when resolving an attribute name\n * @param {object} options\n * @param {Matcher} matcher - current matcher state (readonly from callback perspective)\n * @param {string} xmlVersion - '1.0' or '1.1', forwarded to xml-naming\n */\nfunction resolveTagName(name, isAttribute, options, matcher, xmlVersion) {\n if (!options.sanitizeName) return name;\n if (qName(name, { xmlVersion })) return name;\n return options.sanitizeName(name, { isAttribute, matcher: matcher.readOnly() });\n}\n\nBuilder.prototype.build = function (jObj) {\n if (this.options.preserveOrder) {\n return buildFromOrderedJs(jObj, this.options);\n } else {\n if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {\n jObj = {\n [this.options.arrayNodeName]: jObj\n }\n }\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n const xmlVersion = detectXmlVersionFromObj(jObj, this.options);\n return this.j2x(jObj, 0, matcher, xmlVersion).val;\n }\n};\n\nBuilder.prototype.j2x = function (jObj, level, matcher, xmlVersion) {\n let attrStr = '';\n let val = '';\n if (this.options.maxNestedTags && matcher.getDepth() >= this.options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n // Get jPath based on option: string for backward compatibility, or Matcher for new features\n const jPath = this.options.jPath ? matcher.toString() : matcher;\n\n // Check if current node is a stopNode (will be used for attribute encoding)\n const isCurrentStopNode = this.checkStopNode(matcher);\n\n for (let key in jObj) {\n if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;\n\n // Resolve the key through sanitizeName before any use.\n // Special keys (textNodeName, cdataPropName, commentPropName, attributeNamePrefix,\n // attributesGroupName, \"?\" PI tags) are exempt — they are builder-internal conventions,\n // not user-supplied XML names.\n const isSpecialKey = key === this.options.textNodeName\n || key === this.options.cdataPropName\n || key === this.options.commentPropName\n || (this.options.attributesGroupName && key === this.options.attributesGroupName)\n || this.isAttribute(key)\n || key[0] === '?';\n\n const resolvedKey = isSpecialKey\n ? key\n : resolveTagName(key, false, this.options, matcher, xmlVersion);\n\n if (typeof jObj[key] === 'undefined') {\n // supress undefined node only if it is not an attribute\n if (this.isAttribute(key)) {\n val += '';\n }\n } else if (jObj[key] === null) {\n // null attribute should be ignored by the attribute list, but should not cause the tag closing\n if (this.isAttribute(key)) {\n val += '';\n } else if (resolvedKey === this.options.cdataPropName || resolvedKey === this.options.commentPropName) {\n val += '';\n } else if (resolvedKey[0] === '?') {\n val += this.indentate(level) + '<' + resolvedKey + '?' + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + resolvedKey + '/' + this.tagEndChar;\n }\n } else if (jObj[key] instanceof Date) {\n val += this.buildTextValNode(jObj[key], resolvedKey, '', level, matcher);\n } else if (typeof jObj[key] !== 'object') {\n //premitive type\n const attr = this.isAttribute(key);\n if (attr && !this.ignoreAttributesFn(attr, jPath)) {\n // Resolve the attribute name through sanitizeName\n const resolvedAttr = resolveTagName(attr, true, this.options, matcher, xmlVersion);\n attrStr += this.buildAttrPairStr(resolvedAttr, '' + jObj[key], isCurrentStopNode);\n } else if (!attr) {\n //tag value\n if (key === this.options.textNodeName) {\n let newval = this.options.tagValueProcessor(key, '' + jObj[key]);\n val += this.replaceEntitiesValue(newval);\n } else {\n // Check if this is a stopNode before building\n matcher.push(resolvedKey);\n const isStopNode = this.checkStopNode(matcher);\n matcher.pop();\n\n if (isStopNode) {\n // Build as raw content without encoding\n const textValue = '' + jObj[key];\n if (textValue === '') {\n val += this.indentate(level) + '<' + resolvedKey + this.closeTag(resolvedKey) + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + resolvedKey + '>' + textValue + '' + textValue + '${item}`;\n } else if (typeof item === 'object' && item !== null) {\n const nestedContent = this.buildRawContent(item);\n const nestedAttrs = this.buildAttributesForStopNode(item);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n }\n }\n } else if (typeof value === 'object' && value !== null) {\n // Nested object\n const nestedContent = this.buildRawContent(value);\n const nestedAttrs = this.buildAttributesForStopNode(value);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n } else {\n // Primitive value\n content += `<${key}>${value}`;\n }\n }\n\n return content;\n};\n\n// Build attribute string for stopNode (no entity encoding)\nBuilder.prototype.buildAttributesForStopNode = function (obj) {\n if (!obj || typeof obj !== 'object') return '';\n\n let attrStr = '';\n\n // Check for attributesGroupName (when attributes are grouped)\n if (this.options.attributesGroupName && obj[this.options.attributesGroupName]) {\n const attrGroup = obj[this.options.attributesGroupName];\n for (let attrKey in attrGroup) {\n if (!Object.prototype.hasOwnProperty.call(attrGroup, attrKey)) continue;\n const cleanKey = attrKey.startsWith(this.options.attributeNamePrefix)\n ? attrKey.substring(this.options.attributeNamePrefix.length)\n : attrKey;\n const val = attrGroup[attrKey];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + cleanKey;\n } else {\n attrStr += ' ' + cleanKey + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n } else {\n // Look for individual attributes\n for (let key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n const attr = this.isAttribute(key);\n if (attr) {\n const val = obj[key];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + attr;\n } else {\n attrStr += ' ' + attr + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n }\n }\n\n return attrStr;\n};\n\nBuilder.prototype.buildObjectNode = function (val, key, attrStr, level) {\n if (val === \"\") {\n if (key[0] === \"?\") return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n else {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }\n } else if (key[0] === \"?\") {\n // PI/XML-declaration tags never have body content — treat them like empty.\n return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n } else {\n let tagEndExp = '' + val + tagEndExp);\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {\n return this.indentate(level) + `` + this.newLine;\n } else {\n return (\n this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +\n val +\n this.indentate(level) + tagEndExp);\n }\n }\n}\n\nBuilder.prototype.closeTag = function (key) {\n let closeTag = \"\";\n if (this.options.unpairedTags.indexOf(key) !== -1) { //unpaired\n if (!this.options.suppressUnpairedNode) closeTag = \"/\"\n } else if (this.options.suppressEmptyNode) { //empty\n closeTag = \"/\";\n } else {\n closeTag = `>` + this.newLine;\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {\n const safeVal = safeComment(val);\n return this.indentate(level) + `` + this.newLine;\n } else if (key[0] === \"?\") {//PI tag\n return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n } else {\n // Normal processing: apply tagValueProcessor and entity replacement\n let textValue = this.options.tagValueProcessor(key, val);\n textValue = this.replaceEntitiesValue(textValue);\n\n if (textValue === '') {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n } else {\n return this.indentate(level) + '<' + key + attrStr + '>' +\n textValue +\n ' 0 && this.options.processEntities) {\n for (let i = 0; i < this.options.entities.length; i++) {\n const entity = this.options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\n\nfunction indentate(level) {\n return this.options.indentBy.repeat(level);\n}\n\nfunction isAttribute(name /*, options*/) {\n if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {\n return name.substr(this.attrPrefixLen);\n } else {\n return false;\n }\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}","// Re-export from fast-xml-builder for backward compatibility\nimport XMLBuilder from 'fast-xml-builder';\nexport default XMLBuilder;\n\n// If there are any named exports you also want to re-export:\nexport * from 'fast-xml-builder';"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","Expression","constructor","pattern","options","data","separator","segments","_parse","_hasDeepWildcard","some","seg","type","_hasAttributeCondition","undefined","attrName","_hasPositionSelector","position","i","currentPart","length","trim","push","_parseSegment","part","segment","bracketContent","withoutBrackets","bracketMatch","match","content","slice","namespace","tag","tagAndPosition","includes","nsIndex","indexOf","substring","Error","positionMatch","colonIndex","lastIndexOf","tagPart","posPart","test","eqIndex","attrValue","nthMatch","positionValue","parseInt","hasDeepWildcard","hasAttributeCondition","hasPositionSelector","toString","MatcherView","matcher","_matcher","getCurrentTag","path","getCurrentNamespace","getAttrValue","values","hasAttr","current","getPosition","getCounter","counter","getIndex","getDepth","includeNamespace","toArray","map","n","matches","expression","matchesAny","exprSet","Matcher","siblingStacks","_pathStringCache","_view","tagName","attrValues","currentLevel","Map","siblings","siblingKey","count","set","node","pop","updateCurrent","sep","result","join","reset","_matchWithDeepWildcard","_matchSimple","_matchSegment","pathIdx","segIdx","nextSeg","found","isCurrentNode","String","snapshot","restore","readOnly","safeComment","val","replace","safeCdata","escapeAttribute","nameStartChar10","nameStartChar11","nameChar11","buildRegexes","startChar","char","flags","ncNamePat","name","RegExp","ncName","qName","nmToken","nmTokens","regexes10","regexes11","str","xmlVersion","getRegexes","resolveTagName","isAttribute","sanitizeName","toXml","jArray","indentation","format","stopNodeExpressions","stopNodes","Array","isArray","first","propName","attrs","versionKey","attributeNamePrefix","detectXmlVersionFromArray","arrToStr","arr","xmlStr","isPreviousElementTag","maxNestedTags","text","replaceEntitiesValue","tagObj","rawTagName","textNodeName","cdataPropName","commentPropName","extractAttributeValues","isStopNode","checkStopNode","tagText","tagValueProcessor","attr_to_str","newIdentation","indentBy","tagStart","tagValue","getRawContent","unpairedTags","suppressUnpairedNode","suppressEmptyNode","endsWith","attrMap","ignoreAttributes","hasAttrs","attr","startsWith","substr","item","attStr","attr_to_str_raw","nestedContent","attrStr","attrVal","suppressBooleanAttributes","keys","cleanAttrName","resolvedAttrName","attributeValueProcessor","textValue","processEntities","entities","entity","regex","defaultOptions","attributesGroupName","a","preserveOrder","oneListGroup","jPath","Builder","assign","ignoreAttributesFn","attrPrefixLen","processTextOrObjNode","indentate","tagEndChar","newLine","object","level","extractAttributes","rawContent","buildRawContent","buildAttributesForStopNode","buildObjectNode","j2x","buildTextValNode","repeat","build","jObj","buildFromOrderedJs","arrayNodeName","decl","v","detectXmlVersionFromObj","isCurrentStopNode","resolvedKey","Date","resolvedAttr","buildAttrPairStr","newval","closeTag","arrLen","listTagVal","listTagAttr","j","Ks","L","attrGroup","attrKey","nestedAttrs","cleanKey","tagEndExp","piClosingChar","safeVal"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/lib/fxp.cjs b/node_modules/fast-xml-parser/lib/fxp.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c6d744631a3e00f9f63e9a844f074681e304beee --- /dev/null +++ b/node_modules/fast-xml-parser/lib/fxp.cjs @@ -0,0 +1 @@ +(()=>{"use strict";var t={d:(e,i)=>{for(var n in i)t.o(i,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:i[n]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{XMLBuilder:()=>xe,XMLParser:()=>Jt,XMLValidator:()=>be});const i=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=new RegExp("^["+i+"]["+i+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function r(t,e){const i=[];let n=e.exec(t);for(;n;){const r=[];r.startIndex=e.lastIndex-n[0].length;const s=n.length;for(let t=0;t"!==t[s]&&" "!==t[s]&&"\t"!==t[s]&&"\n"!==t[s]&&"\r"!==t[s];s++)l+=t[s];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),s--),!E(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",y("InvalidTag",e,w(t,s))}const p=g(t,s);if(!1===p)return y("InvalidAttr","Attributes for '"+l+"' have open quote.",w(t,s));let u=p.value;if(s=p.index,"/"===u[u.length-1]){const i=s-u.length;u=u.substring(0,u.length-1);const r=x(u,e);if(!0!==r)return y(r.err.code,r.err.msg,w(t,i+r.err.line));n=!0}else if(a){if(!p.tagClosed)return y("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",w(t,s));if(u.trim().length>0)return y("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",w(t,o));if(0===i.length)return y("InvalidTag","Closing tag '"+l+"' has not been opened.",w(t,o));{const e=i.pop();if(l!==e.tagName){let i=w(t,e.tagStartPos);return y("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",w(t,o))}0==i.length&&(r=!0)}}else{const a=x(u,e);if(!0!==a)return y(a.err.code,a.err.msg,w(t,s-u.length+a.err.line));if(!0===r)return y("InvalidXml","Multiple possible root nodes found.",w(t,s));-1!==e.unpairedTags.indexOf(l)||i.push({tagName:l,tagStartPos:o}),n=!0}for(s++;s0)||y("InvalidXml","Invalid '"+JSON.stringify(i.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):y("InvalidXml","Start tag expected.",1)}function c(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function h(t,e){const i=e;for(;e5&&"xml"===n)return y("InvalidXml","XML declaration allowed only at the start of the document.",w(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function d(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let i=1;for(e+=8;e"===t[e]&&(i--,0===i))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}const u='"',f="'";function g(t,e){let i="",n="",r=!1;for(;e"===t[e]&&""===n){r=!0;break}i+=t[e]}return""===n&&{value:i,index:e,tagClosed:r}}const m=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function x(t,e){const i=r(t,m),n={};for(let t=0;to.includes(t)?"__"+t:t,A={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0,unicode:!1},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,i){return t},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:S};function T(t,e){if("string"!=typeof t)return;const i=t.toLowerCase();if(o.some(t=>i===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(a.some(t=>i===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function _(t,e){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:Math.max(1,t.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,t.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,t.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,t.maxExpandedLength??1e5),maxEntityCount:Math.max(1,t.maxEntityCount??1e3),allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null,appliesTo:t.appliesTo??"all"}:_(!0)}const C=function(t){const e=Object.assign({},A,t),i=[{value:e.attributeNamePrefix,name:"attributeNamePrefix"},{value:e.attributesGroupName,name:"attributesGroupName"},{value:e.textNodeName,name:"textNodeName"},{value:e.cdataPropName,name:"cdataPropName"},{value:e.commentPropName,name:"commentPropName"}];for(const{value:t,name:e}of i)t&&T(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=S),e.processEntities=_(e.processEntities,e.htmlEntities),e.unpairedTagsSet=new Set(e.unpairedTags),e.stopNodes&&Array.isArray(e.stopNodes)&&(e.stopNodes=e.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),e};let $;$="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class O{constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null)}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][$]={startIndex:e})}static getMetaDataSymbol(){return $}}const P=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�",j=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",I=j+"\\-\\.\\d·̀-ͯ҇‿-⁀",k=(t,e,i="")=>{const n=`[${t.replace(":","")}][${e.replace(":","")}]*`;return{name:new RegExp(`^[${t}][${e}]*$`,i),ncName:new RegExp(`^${n}$`,i),qName:new RegExp(`^${n}(?::${n})?$`,i),nmToken:new RegExp(`^[${e}]+$`,i),nmTokens:new RegExp(`^[${e}]+(?:\\s+[${e}]+)*$`,i)}},L=k(P,P+"\\-\\.\\d·̀-ͯ‿-⁀"),D=k(j,I,"u"),R=(t,{xmlVersion:e="1.0"}={})=>((t="1.0")=>"1.1"===t?D:L)(e).qName.test(t);class M{constructor(t,e){this.suppressValidationErr=!t,this.options=t,this.xmlVersion=e||1}setXmlVersion(t=1){this.xmlVersion=t}readDocType(t,e){const i=Object.create(null);let n=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let r=1,s=!1,o=!1,a="";for(;e"===t[e]){if(o?"-"===t[e-1]&&"-"===t[e-2]&&(o=!1,r--):r--,0===r)break}else"["===t[e]?s=!0:a+=t[e];else{if(s&&q(t,"!ENTITY",e)){let r,s;if(e+=7,[r,s,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===s.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&n>=this.options.maxEntityCount)throw new Error(`Entity count (${n+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);i[r]=s,n++}}else if(s&&q(t,"!ELEMENT",e)){e+=8;const{index:i}=this.readElementExp(t,e+1);e=i}else if(s&&q(t,"!ATTLIST",e))e+=8;else if(s&&q(t,"!NOTATION",e)){e+=9;const{index:i}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=i}else{if(!q(t,"!--",e))throw new Error("Invalid DOCTYPE");o=!0}r++,a=""}if(0!==r)throw new Error("Unclosed DOCTYPE")}return{entities:i,i:e}}readEntityExp(t,e){const i=e=V(t,e);for(;ethis.options.maxEntitySize)throw new Error(`Entity "${n}" size (${r.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[n,r,--e]}readNotationExp(t,e){const i=e=V(t,e);for(;e{for(;e=48&&r<=57||45===r))if(r=55296&&r<=56319){if(n+1=56320&&e<=57343){const t=65536+(r-55296<<10)+(e-56320);if(G.has(t)){i=n;break}}}}else if(255!==W[r-B]||X.has(r)){i=n;break}}if(-1===i)return t;const n=[];i>0&&n.push(t.slice(0,i));for(let r=i;r=48&&i<=57||45===i){n.push(t[r]);continue}if(i=55296&&i<=56319){if(r+1=56320&&e<=57343){const t=65536+(i-55296<<10)+(e-56320),s=G.get(t);if(void 0!==s){n.push(String.fromCharCode(s+48)),r++;continue}}}n.push(t[r]);continue}if(X.has(i)){n.push("-");continue}const s=W[i-B];n.push(255!==s?String.fromCharCode(s+48):t[r])}return n.join("")}(i),"0"===i))return 0;if(e.hex&&Y.test(i))return tt(i,16);if(e.binary&&z.test(i))return tt(i,2);if(e.octal&&H.test(i))return tt(i,8);if(isFinite(i)){if(i.includes("e")||i.includes("E"))return function(t,e,i){if(!i.eNotation)return t;const n=e.match(K);if(n){let r=n[1]||"";const s=-1===n[3].indexOf("e")?"E":"e",o=n[2],a=r?t[o.length+1]===s:t[o.length]===s;return o.length>1&&a?t:(1!==o.length||!n[3].startsWith(`.${s}`)&&n[3][0]!==s)&&o.length>0?i.leadingZeros&&!a?(e=(n[1]||"")+n[3],Number(e)):t:Number(e)}return t}(t,i,e);{const r=Q.exec(i);if(r){const s=r[1]||"",o=r[2];let a=(n=r[3])&&-1!==n.indexOf(".")?("."===(n=n.replace(/0+$/,""))?n="0":"."===n[0]?n="0"+n:"."===n[n.length-1]&&(n=n.substring(0,n.length-1)),n):n;const l=s?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const n=Number(i),r=String(n);if(0===n)return n;if(-1!==r.search(/[eE]/))return e.eNotation?n:t;if(-1!==i.indexOf("."))return"0"===r||r===a||r===`${s}${a}`?n:t;let l=o?a:i;return o?l===r||s+l===r?n:t:l===r||l===s+r?n:t}}return t}}var n;return function(t,e,i){const n=e===1/0;switch(i.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return n?"Infinity":"-Infinity";default:return t}}(t,Number(i),e)}const K=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function tt(t,e){const i=t.trim();if(2!==e&&8!==e||(t=i.substring(2)),parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}class et{constructor(t){this._matcher=t}get separator(){return this._matcher.separator}getCurrentTag(){const t=this._matcher.path;return t.length>0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const i=e[e.length-1];return void 0!==i.values&&t in i.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class it{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new et(this)}push(t,e=null,i=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const n=this.path.length;this.siblingStacks[n]||(this.siblingStacks[n]=new Map);const r=this.siblingStacks[n],s=i?`${i}:${t}`:t,o=r.get(s)||0;let a=0;for(const t of r.values())a+=t;r.set(s,o+1);const l={tag:t,position:a,counter:o};null!=i&&(l.namespace=i),null!=e&&(l.values=e),this.path.push(l)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const i=t||this.separator;if(i===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e=0&&e>=0;){const n=t[i];if("deep-wildcard"===n.type){if(i--,i<0)return!0;const n=t[i];let r=!1;for(let t=e;t>=0;t--)if(this._matchSegment(n,this.path[t],t===this.path.length-1)){e=t-1,i--,r=!0;break}if(!r)return!1}else{if(!this._matchSegment(n,this.path[e],e===this.path.length-1))return!1;e--,i--}}return i<0}_matchSegment(t,e,i){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!i)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!i)return!1;const n=e.counter??0;if("first"===t.position&&0!==n)return!1;if("odd"===t.position&&n%2!=1)return!1;if("even"===t.position&&n%2!=0)return!1;if("nth"===t.position&&n!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}class nt{constructor(t,e={},i){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=i,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let i=0,n="";for(;i",lt:"<",quot:'"'},at={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},lt=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"}),pt=new Set("!?\\\\/[]$%{}^&*()<>|+");function ct(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(pt.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function ht(...t){const e=Object.create(null);for(const i of t)if(i)for(const t of Object.keys(i)){const n=i[t];if("string"==typeof n)e[t]=n;else if(n&&"object"==typeof n&&void 0!==n.val){const i=n.val;"string"==typeof i&&(e[t]=i)}}return e}const dt="external",ut="base",ft="all",gt=Object.freeze({allow:0,leave:1,remove:2,throw:3}),mt=new Set([9,10,13]);class xt{constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??dt)&&e!==dt?e===ft?new Set([ft]):e===ut?new Set([ut]):Array.isArray(e)?new Set(e):new Set([dt]):new Set([dt]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=ht(ot,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const i=function(t){if(!t)return{xmlVersion:1,onLevel:gt.allow,nullLevel:gt.remove};const e=1.1===t.xmlVersion?1.1:1,i=gt[t.onNCR]??gt.allow,n=gt[t.nullNCR]??gt.remove;return{xmlVersion:e,onLevel:i,nullLevel:Math.max(n,gt.remove)}}(t.ncr);this._ncrXmlVersion=i.xmlVersion,this._ncrOnLevel=i.onLevel,this._ncrNullLevel=i.nullLevel,this._onExternalEntity="function"==typeof t.onExternalEntity?t.onExternalEntity:null,this._onInputEntity="function"==typeof t.onInputEntity?t.onInputEntity:null}_applyRegistrationHook(t,e,i,n){if(!t)return!0;const r=t(e,i);if(r===lt.BLOCK)return!1;if(r===lt.THROW)throw new Error(`[EntityDecoder] Registration of ${n} entity "&${e};" was rejected by hook`);return!0}setExternalEntities(t){if(t)for(const e of Object.keys(t))ct(e);if(!this._onExternalEntity)return void(this._externalMap=ht(t));const e=ht(t),i=Object.create(null);for(const[t,n]of Object.entries(e))this._applyRegistrationHook(this._onExternalEntity,t,n,"external")&&(i[t]=n);this._externalMap=i}addExternalEntity(t,e){ct(t),"string"==typeof e&&-1===e.indexOf("&")&&this._applyRegistrationHook(this._onExternalEntity,t,e,"external")&&(this._externalMap[t]=e)}addInputEntities(t){if(this._totalExpansions=0,this._expandedLength=0,!this._onInputEntity)return void(this._inputMap=ht(t));const e=ht(t),i=Object.create(null);for(const[t,n]of Object.entries(e))this._applyRegistrationHook(this._onInputEntity,t,n,"input")&&(i[t]=n);this._inputMap=i}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1}decode(t){if("string"!=typeof t||0===t.length)return t;if(-1===t.indexOf("&"))return t;const e=t,i=[],n=t.length;let r=0,s=0;const o=this._maxTotalExpansions>0,a=this._maxExpandedLength>0,l=o||a;for(;s=n||59!==t.charCodeAt(e)){s++;continue}const p=t.slice(s+1,e);if(0===p.length){s++;continue}let c,h;if(this._removeSet.has(p))c="",void 0===h&&(h=dt);else{if(this._leaveSet.has(p)){s++;continue}if(35===p.charCodeAt(0)){const t=this._resolveNCR(p);if(void 0===t){s++;continue}c=t,h=ut}else{const t=this._resolveName(p);c=t?.value,h=t?.tier}}if(void 0!==c){if(s>r&&i.push(t.slice(r,s)),i.push(c),r=e+1,s=r,l&&this._tierCounts(h)){if(o&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(a){const t=c.length-(p.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else s++}r=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!mt.has(t)?gt.remove:-1}_applyNCRAction(t,e,i){switch(t){case gt.allow:return String.fromCodePoint(i);case gt.remove:return"";case gt.leave:return;case gt.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${i.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(i)}}_resolveNCR(t){const e=t.charCodeAt(1);let i;if(i=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(i)||i<0||i>1114111)return;const n=this._classifyNCR(i);if(!this._numericAllowed&&n/]/i},{id:"html-script-close",description:"<\/script closing tag",pattern:/<\/script[\s>]/i},{id:"html-javascript-protocol",description:"javascript: URI scheme (with optional whitespace/encoding)",pattern:/j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i},{id:"html-vbscript-protocol",description:"vbscript: URI scheme",pattern:/vbscript[\t\n\r ]*:/i},{id:"html-data-html",description:"data:text/html URI — can execute scripts in browsers",pattern:/data[\t\n\r ]*:[\t\n\r ]*text\/html/i},{id:"html-data-xhtml",description:"data:application/xhtml+xml URI",pattern:/data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i},{id:"html-data-svg",description:"data:image/svg+xml URI — can execute scripts",pattern:/data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i},{id:"html-inline-event-handler",description:"Inline event handler attributes: onclick=, onerror=, onload=, etc.",pattern:/\bon\w{1,30}\s*=/i},{id:"html-entity-obfuscated-script",description:"HTML-entity-encoded ]/i,\n },\n {\n id: 'html-javascript-protocol',\n description: 'javascript: URI scheme (with optional whitespace/encoding)',\n // Handles javascript:, j\\u0061vascript:, and whitespace variants\n pattern: /j[\\t\\n\\r ]*a[\\t\\n\\r ]*v[\\t\\n\\r ]*a[\\t\\n\\r ]*s[\\t\\n\\r ]*c[\\t\\n\\r ]*r[\\t\\n\\r ]*i[\\t\\n\\r ]*p[\\t\\n\\r ]*t[\\t\\n\\r ]*:/i,\n },\n {\n id: 'html-vbscript-protocol',\n description: 'vbscript: URI scheme',\n pattern: /vbscript[\\t\\n\\r ]*:/i,\n },\n {\n id: 'html-data-html',\n description: 'data:text/html URI — can execute scripts in browsers',\n pattern: /data[\\t\\n\\r ]*:[\\t\\n\\r ]*text\\/html/i,\n },\n {\n id: 'html-data-xhtml',\n description: 'data:application/xhtml+xml URI',\n pattern: /data[\\t\\n\\r ]*:[\\t\\n\\r ]*application\\/xhtml/i,\n },\n {\n id: 'html-data-svg',\n description: 'data:image/svg+xml URI — can execute scripts',\n pattern: /data[\\t\\n\\r ]*:[\\t\\n\\r ]*image\\/svg\\+xml/i,\n },\n {\n id: 'html-inline-event-handler',\n description: 'Inline event handler attributes: onclick=, onerror=, onload=, etc.',\n // \\bon ensures we match a word boundary so \"phonetic=\" is not caught\n pattern: /\\bon\\w{1,30}\\s*=/i,\n },\n {\n id: 'html-entity-obfuscated-script',\n description: 'HTML-entity-encoded ', 'HTML') // true\n * isUnsafe('hello world', 'HTML') // false\n * isUnsafe('value', ['HTML', 'SQL']) // false\n * isUnsafe('value', /my-pattern/i) // false\n */\nfunction isUnsafe(value, context) {\n assertString(value);\n assertContext(context);\n\n // Custom RegExp — caller-supplied pattern\n if (context instanceof RegExp) {\n return context.test(value);\n }\n\n // Single named context\n if (typeof context === 'string') {\n return matchContext(value, context) !== null;\n }\n\n // Array of named contexts — unsafe if ANY context matches\n for (const c of context) {\n if (matchContext(value, c) !== null) return true;\n }\n return false;\n}\n\n/**\n * Like `isUnsafe`, but instead of a boolean returns the first `MatchResult`\n * describing **why** the value was flagged, or `null` if it is safe.\n *\n * Useful for logging, error messages, or policy reporting.\n *\n * @param {string} value\n * @param {ContextName|ContextName[]|RegExp} context\n * @returns {MatchResult|null}\n *\n * @example\n * whyUnsafe('', 'HTML')\n * // { context: 'HTML', id: 'html-script-open', description: '...', pattern: /.../ }\n */\nfunction whyUnsafe(value, context) {\n assertString(value);\n assertContext(context);\n\n if (context instanceof RegExp) {\n return context.test(value)\n ? { context: 'CUSTOM', id: 'custom-regex', description: 'Matched caller-supplied pattern', pattern: context }\n : null;\n }\n\n if (typeof context === 'string') {\n return matchContext(value, context);\n }\n\n for (const c of context) {\n const result = matchContext(value, c);\n if (result !== null) return result;\n }\n return null;\n}\n\n/**\n * Returns all matching rules across the given context(s), or an empty array\n * if the value is safe. Useful for comprehensive auditing.\n *\n * @param {string} value\n * @param {ContextName|ContextName[]|RegExp} context\n * @returns {MatchResult[]}\n */\nfunction allUnsafe(value, context) {\n assertString(value);\n assertContext(context);\n\n const results = [];\n\n if (context instanceof RegExp) {\n if (context.test(value)) {\n results.push({ context: 'CUSTOM', id: 'custom-regex', description: 'Matched caller-supplied pattern', pattern: context });\n }\n return results;\n }\n\n const contexts = typeof context === 'string' ? [context] : context;\n\n for (const c of contexts) {\n const patterns = CONTEXT_REGISTRY[c];\n for (const rule of patterns) {\n if (rule.pattern.test(value)) {\n results.push({ context: c, id: rule.id, description: rule.description, pattern: rule.pattern });\n }\n }\n }\n\n return results;\n}\n\nexport { isUnsafe, whyUnsafe, allUnsafe, VALID_CONTEXTS };\nexport default isUnsafe;","'use strict';\n///@ts-check\n\nimport { getAllMatches, isExist, DANGEROUS_PROPERTY_NAMES, criticalProperties } from '../util.js';\nimport xmlNode from './xmlNode.js';\nimport DocTypeReader from './DocTypeReader.js';\nimport toNumber from \"strnum\";\nimport getIgnoreAttributesFn from \"../ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\nimport { ExpressionSet } from 'path-expression-matcher';\nimport { EntityDecoder, XML, CURRENCY, COMMON_HTML, ENTITY_ACTION } from '@nodable/entities';\nimport { isUnsafe, VALID_CONTEXTS } from \"is-unsafe\"\n\n\n// const regx =\n// '<((!\\\\[CDATA\\\\[([\\\\s\\\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\\\/)(NAME)\\\\s*>))([^<]*)'\n// .replace(/NAME/g, util.nameRegexp);\n\n//const tagsRegx = new RegExp(\"<(\\\\/?[\\\\w:\\\\-\\._]+)([^>]*)>(\\\\s*\"+cdataRegx+\")*([^<]+)?\",\"g\");\n//const tagsRegx = new RegExp(\"<(\\\\/?)((\\\\w*:)?([\\\\w:\\\\-\\._]+))([^>]*)>([^<]*)(\"+cdataRegx+\"([^<]*))*([^<]+)?\",\"g\");\n\n// Helper functions for attribute and namespace handling\n\n/**\n * Extract raw attributes (without prefix) from prefixed attribute map\n * @param {object} prefixedAttrs - Attributes with prefix from buildAttributesMap\n * @param {object} options - Parser options containing attributeNamePrefix\n * @returns {object} Raw attributes for matcher\n */\nfunction extractRawAttributes(prefixedAttrs, options) {\n if (!prefixedAttrs) return {};\n\n // Handle attributesGroupName option\n const attrs = options.attributesGroupName\n ? prefixedAttrs[options.attributesGroupName]\n : prefixedAttrs;\n\n if (!attrs) return {};\n\n const rawAttrs = {};\n for (const key in attrs) {\n // Remove the attribute prefix to get raw name\n if (key.startsWith(options.attributeNamePrefix)) {\n const rawName = key.substring(options.attributeNamePrefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * Extract namespace from raw tag name\n * @param {string} rawTagName - Tag name possibly with namespace (e.g., \"soap:Envelope\")\n * @returns {string|undefined} Namespace or undefined\n */\nfunction extractNamespace(rawTagName) {\n if (!rawTagName || typeof rawTagName !== 'string') return undefined;\n\n const colonIndex = rawTagName.indexOf(':');\n if (colonIndex !== -1 && colonIndex > 0) {\n const ns = rawTagName.substring(0, colonIndex);\n // Don't treat xmlns as a namespace\n if (ns !== 'xmlns') {\n return ns;\n }\n }\n return undefined;\n}\n\nexport default class OrderedObjParser {\n constructor(options, externalEntities) {\n this.options = options;\n this.currentNode = null;\n this.tagsNodeStack = [];\n this.parseXml = parseXml;\n this.parseTextData = parseTextData;\n this.resolveNameSpace = resolveNameSpace;\n this.buildAttributesMap = buildAttributesMap;\n this.isItStopNode = isItStopNode;\n this.replaceEntitiesValue = replaceEntitiesValue;\n this.readStopNodeData = readStopNodeData;\n this.saveTextToParentTag = saveTextToParentTag;\n this.addChild = addChild;\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n let namedEntities = { ...XML };\n if (this.options.entityDecoder) {\n this.entityDecoder = this.options.entityDecoder\n } else {\n if (typeof this.options.htmlEntities === \"object\") namedEntities = this.options.htmlEntities;\n else if (this.options.htmlEntities === true) namedEntities = { ...COMMON_HTML, ...CURRENCY };\n this.entityDecoder = new EntityDecoder({\n namedEntities: { ...namedEntities, ...externalEntities },\n numericAllowed: this.options.htmlEntities,\n limit: {\n maxTotalExpansions: this.options.processEntities.maxTotalExpansions,\n maxExpandedLength: this.options.processEntities.maxExpandedLength,\n applyLimitsTo: this.options.processEntities.appliesTo,\n },\n // onExternalEntity: (name, value) => isUnsafe(value) ? 'block' : 'allow',\n onInputEntity: (name, value) =>\n //TODO: VALID_CONTEXTS.HTML should be set only if this.options.htmlEntities\n isUnsafe(value, [VALID_CONTEXTS.HTML, VALID_CONTEXTS.XML])\n ? ENTITY_ACTION.BLOCK : ENTITY_ACTION.ALLOW,\n\n //postCheck: resolved => resolved\n });\n }\n\n // Initialize path matcher for path-expression-matcher\n this.matcher = new Matcher();\n this.readonlyMatcher = this.matcher.readOnly();\n\n // Flag to track if current node is a stop node (optimization)\n this.isCurrentNodeStopNode = false;\n\n // Pre-compile stopNodes expressions\n this.stopNodeExpressionsSet = new ExpressionSet();\n const stopNodesOpts = this.options.stopNodes;\n if (stopNodesOpts && stopNodesOpts.length > 0) {\n for (let i = 0; i < stopNodesOpts.length; i++) {\n const stopNodeExp = stopNodesOpts[i];\n if (typeof stopNodeExp === 'string') {\n // Convert string to Expression object\n this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));\n } else if (stopNodeExp instanceof Expression) {\n // Already an Expression object\n this.stopNodeExpressionsSet.add(stopNodeExp);\n }\n }\n this.stopNodeExpressionsSet.seal();\n }\n }\n\n}\n\n\n/**\n * @param {string} val\n * @param {string} tagName\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n * @param {boolean} dontTrim\n * @param {boolean} hasAttributes\n * @param {boolean} isLeafNode\n * @param {boolean} escapeEntities\n */\nfunction parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {\n const options = this.options;\n if (val !== undefined) {\n if (options.trimValues && !dontTrim) {\n val = val.trim();\n }\n if (val.length > 0) {\n if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath);\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;\n const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);\n if (newval === null || newval === undefined) {\n //don't parse\n return val;\n } else if (typeof newval !== typeof val || newval !== val) {\n //overwrite\n return newval;\n } else if (options.trimValues) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n const trimmedVal = val.trim();\n if (trimmedVal === val) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n return val;\n }\n }\n }\n }\n}\n\nfunction resolveNameSpace(tagname) {\n if (this.options.removeNSPrefix) {\n const tags = tagname.split(':');\n const prefix = tagname.charAt(0) === '/' ? '/' : '';\n if (tags[0] === 'xmlns') {\n return '';\n }\n if (tags.length === 2) {\n tagname = prefix + tags[1];\n }\n }\n return tagname;\n}\n\n//TODO: change regex to capture NS\n//const attrsRegx = new RegExp(\"([\\\\w\\\\-\\\\.\\\\:]+)\\\\s*=\\\\s*(['\\\"])((.|\\n)*?)\\\\2\",\"gm\");\nconst attrsRegx = new RegExp('([^\\\\s=]+)\\\\s*(=\\\\s*([\\'\"])([\\\\s\\\\S]*?)\\\\3)?', 'gm');\n\nfunction buildAttributesMap(attrStr, jPath, tagName, force = false) {\n const options = this.options;\n if (force === true || (options.ignoreAttributes !== true && typeof attrStr === 'string')) {\n // attrStr = attrStr.replace(/\\r?\\n/g, ' ');\n //attrStr = attrStr || attrStr.trim();\n\n const matches = getAllMatches(attrStr, attrsRegx);\n const len = matches.length; //don't make it inline\n const attrs = {};\n\n // Pre-process values once: trim + entity replacement\n // Reused in both matcher update and second pass\n const processedVals = new Array(len);\n let hasRawAttrs = false;\n const rawAttrsForMatcher = {};\n\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n const oldVal = matches[i][4];\n\n if (attrName.length && oldVal !== undefined) {\n let val = oldVal;\n if (options.trimValues) val = val.trim();\n val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);\n processedVals[i] = val;\n\n rawAttrsForMatcher[attrName] = val;\n hasRawAttrs = true;\n }\n }\n\n // Update matcher ONCE before second pass, if applicable\n if (hasRawAttrs && typeof jPath === 'object' && jPath.updateCurrent) {\n jPath.updateCurrent(rawAttrsForMatcher);\n }\n\n // Hoist toString() once — path doesn't change during attribute processing\n const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;\n\n // Second pass: apply processors, build final attrs\n let hasAttrs = false;\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n\n if (this.ignoreAttributesFn(attrName, jPathStr)) continue;\n\n let aName = options.attributeNamePrefix + attrName;\n\n if (attrName.length) {\n if (options.transformAttributeName) {\n aName = options.transformAttributeName(aName);\n }\n aName = sanitizeName(aName, options);\n\n if (matches[i][4] !== undefined) {\n // Reuse already-processed value — no double entity replacement\n const oldVal = processedVals[i];\n\n const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);\n if (newVal === null || newVal === undefined) {\n attrs[aName] = oldVal;\n } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {\n attrs[aName] = newVal;\n } else {\n attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);\n }\n hasAttrs = true;\n } else if (options.allowBooleanAttributes) {\n attrs[aName] = true;\n hasAttrs = true;\n }\n }\n }\n\n if (!hasAttrs) return;\n\n if (options.attributesGroupName && !options.preserveOrder) {\n const attrCollection = {};\n attrCollection[options.attributesGroupName] = attrs;\n return attrCollection;\n }\n return attrs;\n }\n}\nconst parseXml = function (xmlData) {\n xmlData = xmlData.replace(/\\r\\n?/g, \"\\n\"); //TODO: remove this line\n const xmlObj = new xmlNode('!xml');\n let currentNode = xmlObj;\n let textData = \"\";\n\n // Reset matcher for new document\n this.matcher.reset();\n this.entityDecoder.reset();\n\n // Reset entity expansion counters for this document\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n const options = this.options;\n const docTypeReader = new DocTypeReader(options.processEntities);\n const xmlLen = xmlData.length;\n for (let i = 0; i < xmlLen; i++) {//for each char in XML data\n const ch = xmlData[i];\n if (ch === '<') {\n // const nextIndex = i+1;\n // const _2ndChar = xmlData[nextIndex];\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//Closing Tag '/'\n const closeIndex = findClosingIndex(xmlData, \">\", i, \"Closing Tag is not closed.\")\n let tagName = xmlData.substring(i + 2, closeIndex).trim();\n\n if (options.removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n }\n }\n\n tagName = transformTagName(options.transformTagName, tagName, \"\", options).tagName;\n\n if (currentNode) {\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n }\n\n //check if last tag of nested tag was unpaired tag\n const lastTagName = this.matcher.getCurrentTag();\n if (tagName && options.unpairedTagsSet.has(tagName)) {\n throw new Error(`Unpaired tag can not be used as closing tag: `);\n }\n if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {\n // Pop the unpaired tag\n this.matcher.pop();\n this.tagsNodeStack.pop();\n }\n // Pop the closing tag\n this.matcher.pop();\n this.isCurrentNodeStopNode = false; // Reset flag when closing tag\n\n currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope\n textData = \"\";\n i = closeIndex;\n } else if (c1 === 63) { //'?'\n\n let tagData = readTagExp(xmlData, i, false, \"?>\");\n if (!tagData) throw new Error(\"Pi Tag is not closed.\");\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true);\n if (attsMap) {\n const ver = attsMap[this.options.attributeNamePrefix + \"version\"];\n this.entityDecoder.setXmlVersion(Number(ver) || 1.0);\n docTypeReader.setXmlVersion(Number(ver) || 1.0);\n }\n if ((options.ignoreDeclaration && tagData.tagName === \"?xml\") || options.ignorePiTags) {\n //do nothing\n } else {\n\n const childNode = new xmlNode(tagData.tagName);\n childNode.add(options.textNodeName, \"\");\n\n if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) {\n childNode[\":@\"] = attsMap\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, i);\n }\n\n\n i = tagData.closeIndex + 1;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { //'!--'\n const endIndex = findClosingIndex(xmlData, \"-->\", i + 4, \"Comment is not closed.\")\n if (options.commentPropName) {\n const comment = xmlData.substring(i + 4, endIndex - 2);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);\n }\n i = endIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 68) { //'!D'\n const result = docTypeReader.readDocType(xmlData, i);\n this.entityDecoder.addInputEntities(result.entities);\n i = result.i;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"CDATA is not closed.\") - 2;\n const tagExp = xmlData.substring(i + 9, closeIndex);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);\n if (val == undefined) val = \"\";\n\n //cdata should be set even if it is 0 length string\n if (options.cdataPropName) {\n currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);\n } else {\n currentNode.add(options.textNodeName, val);\n }\n\n i = closeIndex + 2;\n } else {//Opening tag\n let result = readTagExp(xmlData, i, options.removeNSPrefix);\n\n // Safety check: readTagExp can return undefined\n if (!result) {\n // Log context for debugging\n const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));\n throw new Error(`readTagExp returned undefined at position ${i}. Context: \"${context}\"`);\n }\n\n let tagName = result.tagName;\n const rawTagName = result.rawTagName;\n let tagExp = result.tagExp;\n let attrExpPresent = result.attrExpPresent;\n let closeIndex = result.closeIndex;\n\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n if (options.strictReservedNames &&\n (tagName === options.commentPropName\n || tagName === options.cdataPropName\n || tagName === options.textNodeName\n || tagName === options.attributesGroupName\n )) {\n throw new Error(`Invalid tag name: ${tagName}`);\n }\n\n //save text as child node\n if (currentNode && textData) {\n if (currentNode.tagname !== '!xml') {\n //when nested tag is found\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);\n }\n }\n\n //check if last tag was unpaired tag\n const lastTag = currentNode;\n if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {\n currentNode = this.tagsNodeStack.pop();\n this.matcher.pop();\n }\n\n // Clean up self-closing syntax BEFORE processing attributes\n // This is where tagExp gets the trailing / removed\n let isSelfClosing = false;\n if (tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1) {\n isSelfClosing = true;\n if (tagName[tagName.length - 1] === \"/\") {\n tagName = tagName.substr(0, tagName.length - 1);\n tagExp = tagName;\n } else {\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n\n // Re-check attrExpPresent after cleaning\n attrExpPresent = (tagName !== tagExp);\n }\n\n // Now process attributes with CLEAN tagExp (no trailing /)\n let prefixedAttrs = null;\n let rawAttrs = {};\n let namespace = undefined;\n\n // Extract namespace from rawTagName\n namespace = extractNamespace(rawTagName);\n\n // Push tag to matcher FIRST (with empty attrs for now) so callbacks see correct path\n if (tagName !== xmlObj.tagname) {\n this.matcher.push(tagName, {}, namespace);\n }\n\n // Now build attributes - callbacks will see correct matcher state\n if (tagName !== tagExp && attrExpPresent) {\n // Build attributes (returns prefixed attributes for the tree)\n // Note: buildAttributesMap now internally updates the matcher with raw attributes\n prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName);\n\n if (prefixedAttrs) {\n // Extract raw attributes (without prefix) for our use\n //TODO: seems a performance overhead\n rawAttrs = extractRawAttributes(prefixedAttrs, options);\n }\n }\n\n // Now check if this is a stop node (after attributes are set)\n if (tagName !== xmlObj.tagname) {\n this.isCurrentNodeStopNode = this.isItStopNode();\n }\n\n const startIndex = i;\n if (this.isCurrentNodeStopNode) {\n let tagContent = \"\";\n\n // For self-closing tags, content is empty\n if (isSelfClosing) {\n i = result.closeIndex;\n }\n //unpaired tag\n else if (options.unpairedTagsSet.has(tagName)) {\n i = result.closeIndex;\n }\n //normal tag\n else {\n //read until closing tag is found\n const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);\n if (!result) throw new Error(`Unexpected end of ${rawTagName}`);\n i = result.i;\n tagContent = result.tagContent;\n }\n\n const childNode = new xmlNode(tagName);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n\n // For stop nodes, store raw content as-is without any processing\n childNode.add(options.textNodeName, tagContent);\n\n this.matcher.pop(); // Pop the stop node tag\n this.isCurrentNodeStopNode = false; // Reset flag\n\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n } else {\n //selfClosing tag\n if (isSelfClosing) {\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop self-closing tag\n this.isCurrentNodeStopNode = false; // Reset flag\n }\n else if (options.unpairedTagsSet.has(tagName)) {//unpaired tag\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop unpaired tag\n this.isCurrentNodeStopNode = false; // Reset flag\n i = result.closeIndex;\n // Continue to next iteration without changing currentNode\n continue;\n }\n //opening tag\n else {\n const childNode = new xmlNode(tagName);\n if (this.tagsNodeStack.length > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n this.tagsNodeStack.push(currentNode);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n currentNode = childNode;\n }\n textData = \"\";\n i = closeIndex;\n }\n }\n } else {\n textData += xmlData[i];\n }\n }\n return xmlObj.child;\n}\n\nfunction addChild(currentNode, childNode, matcher, startIndex) {\n // unset startIndex if not requested\n if (!this.options.captureMetaData) startIndex = undefined;\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher;\n const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[\":@\"])\n if (result === false) {\n //do nothing\n } else if (typeof result === \"string\") {\n childNode.tagname = result\n currentNode.addChild(childNode, startIndex);\n } else {\n currentNode.addChild(childNode, startIndex);\n }\n}\n\n/**\n * @param {object} val - Entity object with regex and val properties\n * @param {string} tagName - Tag name\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n */\nfunction replaceEntitiesValue(val, tagName, jPath) {\n const entityConfig = this.options.processEntities;\n\n if (!entityConfig || !entityConfig.enabled) {\n return val;\n }\n\n // Check if tag is allowed to contain entities\n if (entityConfig.allowedTags) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n const allowed = Array.isArray(entityConfig.allowedTags)\n ? entityConfig.allowedTags.includes(tagName)\n : entityConfig.allowedTags(tagName, jPathOrMatcher);\n\n if (!allowed) {\n return val;\n }\n }\n\n // Apply custom tag filter if provided\n if (entityConfig.tagFilter) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) {\n return val; // Skip based on custom filter\n }\n }\n\n return this.entityDecoder.decode(val);\n}\n\n\nfunction saveTextToParentTag(textData, parentNode, matcher, isLeafNode) {\n if (textData) { //store previously collected data as textNode\n if (isLeafNode === undefined) isLeafNode = parentNode.child.length === 0\n\n textData = this.parseTextData(textData,\n parentNode.tagname,\n matcher,\n false,\n parentNode[\":@\"] ? Object.keys(parentNode[\":@\"]).length !== 0 : false,\n isLeafNode);\n\n if (textData !== undefined && textData !== \"\")\n parentNode.add(this.options.textNodeName, textData);\n textData = \"\";\n }\n return textData;\n}\n\n/**\n * @param {Array} stopNodeExpressions - Array of compiled Expression objects\n * @param {Matcher} matcher - Current path matcher\n */\nfunction isItStopNode() {\n if (this.stopNodeExpressionsSet.size === 0) return false;\n\n return this.matcher.matchesAny(this.stopNodeExpressionsSet);\n}\n\n/**\n * Returns the tag Expression and where it is ending handling single-double quotes situation\n * @param {string} xmlData \n * @param {number} i starting index\n * @returns \n */\nfunction tagExpWithClosingIndex(xmlData, i, closingChar = \">\") {\n //TODO: ignore boolean attributes in tag expression\n //TODO: if ignore attributes, dont read full attribute expression but the end. But read for xml declaration\n let attrBoundary = 0;\n const len = xmlData.length;\n const closeCode0 = closingChar.charCodeAt(0);\n const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;\n\n let result = '';\n let segmentStart = i;\n\n for (let index = i; index < len; index++) {\n const code = xmlData.charCodeAt(index);\n\n if (attrBoundary) {\n if (code === attrBoundary) attrBoundary = 0;\n } else if (code === 34 || code === 39) { // \" or '\n attrBoundary = code;\n } else if (code === closeCode0) {\n if (closeCode1 !== -1) {\n if (xmlData.charCodeAt(index + 1) === closeCode1) {\n result += xmlData.substring(segmentStart, index);\n return { data: result, index };\n }\n } else {\n result += xmlData.substring(segmentStart, index);\n return { data: result, index };\n }\n } else if (code === 9 && !attrBoundary) { // \\t - only replace with space outside attribute values\n // Flush accumulated segment, add space, start new segment\n result += xmlData.substring(segmentStart, index) + ' ';\n segmentStart = index + 1;\n }\n }\n}\n\nfunction findClosingIndex(xmlData, str, i, errMsg) {\n const closingIndex = xmlData.indexOf(str, i);\n if (closingIndex === -1) {\n throw new Error(errMsg)\n } else {\n return closingIndex + str.length - 1;\n }\n}\n\nfunction findClosingChar(xmlData, char, i, errMsg) {\n const closingIndex = xmlData.indexOf(char, i);\n if (closingIndex === -1) throw new Error(errMsg);\n return closingIndex; // no offset needed\n}\n\nfunction readTagExp(xmlData, i, removeNSPrefix, closingChar = \">\") {\n const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);\n if (!result) return;\n let tagExp = result.data;\n const closeIndex = result.index;\n const separatorIndex = tagExp.search(/\\s/);\n let tagName = tagExp;\n let attrExpPresent = true;\n if (separatorIndex !== -1) {//separate tag name and attributes expression\n tagName = tagExp.substring(0, separatorIndex);\n tagExp = tagExp.substring(separatorIndex + 1).trimStart();\n }\n\n const rawTagName = tagName;\n if (removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n attrExpPresent = tagName !== result.data.substr(colonIndex + 1);\n }\n }\n\n return {\n tagName: tagName,\n tagExp: tagExp,\n closeIndex: closeIndex,\n attrExpPresent: attrExpPresent,\n rawTagName: rawTagName,\n }\n}\n/**\n * find paired tag for a stop node\n * @param {string} xmlData \n * @param {string} tagName \n * @param {number} i \n */\nfunction readStopNodeData(xmlData, tagName, i) {\n const startIndex = i;\n // Starting at 1 since we already have an open tag\n let openTagCount = 1;\n\n const xmllen = xmlData.length;\n for (; i < xmllen; i++) {\n if (xmlData[i] === \"<\") {\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//close tag '/'\n const closeIndex = findClosingChar(xmlData, \">\", i, `${tagName} is not closed`);\n let closeTagName = xmlData.substring(i + 2, closeIndex).trim();\n if (closeTagName === tagName) {\n openTagCount--;\n if (openTagCount === 0) {\n return {\n tagContent: xmlData.substring(startIndex, i),\n i: closeIndex\n }\n }\n }\n i = closeIndex;\n } else if (c1 === 63) { //?\n const closeIndex = findClosingIndex(xmlData, \"?>\", i + 1, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { // '!--'\n const closeIndex = findClosingIndex(xmlData, \"-->\", i + 3, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"StopNode is not closed.\") - 2;\n i = closeIndex;\n } else {\n const tagData = readTagExp(xmlData, i, false)\n\n if (tagData) {\n const openTagName = tagData && tagData.tagName;\n if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== \"/\") {\n openTagCount++;\n }\n i = tagData.closeIndex;\n }\n }\n }\n }//end for loop\n}\n\nfunction parseValue(val, shouldParse, options) {\n if (shouldParse && typeof val === 'string') {\n //console.log(options)\n const newval = val.trim();\n if (newval === 'true') return true;\n else if (newval === 'false') return false;\n else return toNumber(val, options);\n } else {\n if (isExist(val)) {\n return val;\n } else {\n return '';\n }\n }\n}\n\nfunction fromCodePoint(str, base, prefix) {\n const codePoint = Number.parseInt(str, base);\n\n if (codePoint >= 0 && codePoint <= 0x10FFFF) {\n return String.fromCodePoint(codePoint);\n } else {\n return prefix + str + \";\";\n }\n}\n\nfunction transformTagName(fn, tagName, tagExp, options) {\n if (fn) {\n const newTagName = fn(tagName);\n if (tagExp === tagName) {\n tagExp = newTagName\n }\n tagName = newTagName;\n }\n tagName = sanitizeName(tagName, options);\n return { tagName, tagExp };\n}\n\n\n\nfunction sanitizeName(name, options) {\n if (criticalProperties.includes(name)) {\n throw new Error(`[SECURITY] Invalid name: \"${name}\" is a reserved JavaScript keyword that could cause prototype pollution`);\n } else if (DANGEROUS_PROPERTY_NAMES.includes(name)) {\n return options.onDangerousProperty(name);\n }\n return name;\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}","'use strict';\n\nimport XmlNode from './xmlNode.js';\nimport { Matcher } from 'path-expression-matcher';\n\nconst METADATA_SYMBOL = XmlNode.getMetaDataSymbol();\n\n/**\n * Helper function to strip attribute prefix from attribute map\n * @param {object} attrs - Attributes with prefix (e.g., {\"@_class\": \"code\"})\n * @param {string} prefix - Attribute prefix to remove (e.g., \"@_\")\n * @returns {object} Attributes without prefix (e.g., {\"class\": \"code\"})\n */\nfunction stripAttributePrefix(attrs, prefix) {\n if (!attrs || typeof attrs !== 'object') return {};\n if (!prefix) return attrs;\n\n const rawAttrs = {};\n for (const key in attrs) {\n if (key.startsWith(prefix)) {\n const rawName = key.substring(prefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * \n * @param {array} node \n * @param {any} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns \n */\nexport default function prettify(node, options, matcher, readonlyMatcher) {\n return compress(node, options, matcher, readonlyMatcher);\n}\n\n/**\n * @param {array} arr \n * @param {object} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns object\n */\nfunction compress(arr, options, matcher, readonlyMatcher) {\n let text;\n const compressedObj = {}; //This is intended to be a plain object\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const property = propName(tagObj);\n\n // Push current property to matcher WITH RAW ATTRIBUTES (no prefix)\n if (property !== undefined && property !== options.textNodeName) {\n const rawAttrs = stripAttributePrefix(\n tagObj[\":@\"] || {},\n options.attributeNamePrefix\n );\n matcher.push(property, rawAttrs);\n }\n\n if (property === options.textNodeName) {\n if (text === undefined) text = tagObj[property];\n else text += \"\" + tagObj[property];\n } else if (property === undefined) {\n continue;\n } else if (tagObj[property]) {\n\n let val = compress(tagObj[property], options, matcher, readonlyMatcher);\n const isLeaf = isLeafTag(val, options);\n\n if (Object.keys(val).length === 0 && options.alwaysCreateTextNode) {\n val[options.textNodeName] = \"\";\n }\n\n if (tagObj[\":@\"]) {\n assignAttributes(val, tagObj[\":@\"], readonlyMatcher, options);\n } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) {\n val = val[options.textNodeName];\n } else if (Object.keys(val).length === 0) {\n if (options.alwaysCreateTextNode) val[options.textNodeName] = \"\";\n else val = \"\";\n }\n\n if (tagObj[METADATA_SYMBOL] !== undefined && typeof val === \"object\" && val !== null) {\n val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL]; // copy over metadata\n }\n\n\n if (compressedObj[property] !== undefined && Object.prototype.hasOwnProperty.call(compressedObj, property)) {\n if (!Array.isArray(compressedObj[property])) {\n compressedObj[property] = [compressedObj[property]];\n }\n compressedObj[property].push(val);\n } else {\n //TODO: if a node is not an array, then check if it should be an array\n //also determine if it is a leaf node\n\n // Pass jPath string or readonlyMatcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;\n if (options.isArray(property, jPathOrMatcher, isLeaf)) {\n compressedObj[property] = [val];\n } else {\n compressedObj[property] = val;\n }\n }\n\n // Pop property from matcher after processing\n if (property !== undefined && property !== options.textNodeName) {\n matcher.pop();\n }\n }\n\n }\n // if(text && text.length > 0) compressedObj[options.textNodeName] = text;\n if (typeof text === \"string\") {\n if (text.length > 0) compressedObj[options.textNodeName] = text;\n } else if (text !== undefined) compressedObj[options.textNodeName] = text;\n\n\n return compressedObj;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (key !== \":@\") return key;\n }\n}\n\nfunction assignAttributes(obj, attrMap, readonlyMatcher, options) {\n if (attrMap) {\n const keys = Object.keys(attrMap);\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n const atrrName = keys[i]; // This is the PREFIXED name (e.g., \"@_class\")\n\n // Strip prefix for matcher path (for isArray callback)\n const rawAttrName = atrrName.startsWith(options.attributeNamePrefix)\n ? atrrName.substring(options.attributeNamePrefix.length)\n : atrrName;\n\n // For attributes, we need to create a temporary path\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath\n ? readonlyMatcher.toString() + \".\" + rawAttrName\n : readonlyMatcher;\n\n if (options.isArray(atrrName, jPathOrMatcher, true, true)) {\n obj[atrrName] = [attrMap[atrrName]];\n } else {\n obj[atrrName] = attrMap[atrrName];\n }\n }\n }\n}\n\nfunction isLeafTag(obj, options) {\n const { textNodeName } = options;\n const propCount = Object.keys(obj).length;\n\n if (propCount === 0) {\n return true;\n }\n\n if (\n propCount === 1 &&\n (obj[textNodeName] || typeof obj[textNodeName] === \"boolean\" || obj[textNodeName] === 0)\n ) {\n return true;\n }\n\n return false;\n}","import { buildOptions } from './OptionsBuilder.js';\nimport OrderedObjParser from './OrderedObjParser.js';\nimport prettify from './node2json.js';\nimport { validate } from \"../validator.js\";\nimport XmlNode from './xmlNode.js';\n\nexport default class XMLParser {\n\n constructor(options) {\n this.externalEntities = {};\n this.options = buildOptions(options);\n\n }\n /**\n * Parse XML dats to JS object \n * @param {string|Uint8Array} xmlData \n * @param {boolean|Object} validationOption \n */\n parse(xmlData, validationOption) {\n if (typeof xmlData !== \"string\" && xmlData.toString) {\n xmlData = xmlData.toString();\n } else if (typeof xmlData !== \"string\") {\n throw new Error(\"XML data is accepted in String or Bytes[] form.\")\n }\n\n if (validationOption) {\n if (validationOption === true) validationOption = {}; //validate with default options\n\n const result = validate(xmlData, validationOption);\n if (result !== true) {\n throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`)\n }\n }\n const orderedObjParser = new OrderedObjParser(this.options, this.externalEntities);\n // orderedObjParser.entityDecoder.setExternalEntities(this.externalEntities);\n const orderedResult = orderedObjParser.parseXml(xmlData);\n if (this.options.preserveOrder || orderedResult === undefined) return orderedResult;\n else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);\n }\n\n /**\n * Add Entity which is not by default supported by this library\n * @param {string} key \n * @param {string} value \n */\n addEntity(key, value) {\n if (value.indexOf(\"&\") !== -1) {\n throw new Error(\"Entity value can't have '&'\")\n } else if (key.indexOf(\"&\") !== -1 || key.indexOf(\";\") !== -1) {\n throw new Error(\"An entity must be set without '&' and ';'. Eg. use '#xD' for ' '\")\n } else if (value === \"&\") {\n throw new Error(\"An entity with value '&' is not permitted\");\n } else {\n this.externalEntities[key] = value;\n }\n }\n\n /**\n * Returns a Symbol that can be used to access the metadata\n * property on a node.\n * \n * If Symbol is not available in the environment, an ordinary property is used\n * and the name of the property is here returned.\n * \n * The XMLMetaData property is only present when `captureMetaData`\n * is true in the options.\n */\n static getMetaDataSymbol() {\n return XmlNode.getMetaDataSymbol();\n }\n}","\n\nexport function safeComment(val) {\n return String(val)\n .replace(/--/g, '- -') // -- is illegal anywhere in comment content\n .replace(/--/g, '- -') // handle the scenario when 2 consiucative dashes appears \n .replace(/-$/, '- '); // trailing - would form -- with the closing -->\n}\n\nexport function safeCdata(val) {\n return String(val).replace(/\\]\\]>/g, ']]]]>')\n}\n\nexport function escapeAttribute(val) {\n return String(val).replace(/\"/g, '"').replace(/'/g, ''')\n}","import { Expression, Matcher } from 'path-expression-matcher';\nimport { safeComment, safeCdata, escapeAttribute } from \"./util.js\";\nimport { qName } from 'xml-naming';\n\nconst EOL = \"\\n\";\n\n/**\n * Detect XML version from the first element of the ordered array input.\n * The first element must be a ?xml processing instruction with a version attribute.\n * Returns '1.0' if not found.\n *\n * @param {array} jArray\n * @param {object} options\n */\nfunction detectXmlVersionFromArray(jArray, options) {\n if (!Array.isArray(jArray) || jArray.length === 0) return '1.0';\n const first = jArray[0];\n const firstKey = propName(first);\n if (firstKey === '?xml') {\n const attrs = first[':@'];\n if (attrs) {\n const versionKey = options.attributeNamePrefix + 'version';\n if (attrs[versionKey]) return attrs[versionKey];\n }\n }\n return '1.0';\n}\n\n/**\n * Resolve a tag or attribute name through sanitizeName if configured.\n * Validation via xml-naming's qName is performed first; the sanitizeName\n * callback is invoked only when the name is invalid. If sanitizeName is\n * false (default), no validation occurs and the name is used as-is.\n *\n * @param {string} name - raw name from the JS object\n * @param {boolean} isAttribute - true when resolving an attribute name\n * @param {object} options\n * @param {Matcher} matcher - current matcher state (readonly from callback perspective)\n * @param {string} xmlVersion - '1.0' or '1.1', forwarded to xml-naming\n */\nfunction resolveTagName(name, isAttribute, options, matcher, xmlVersion) {\n if (!options.sanitizeName) return name;\n if (qName(name, { xmlVersion })) return name;\n return options.sanitizeName(name, { isAttribute, matcher: matcher.readOnly() });\n}\n\n/**\n * @param {array} jArray\n * @param {any} options\n * @returns\n */\nexport default function toXml(jArray, options) {\n let indentation = \"\";\n if (options.format) {\n indentation = EOL;\n }\n\n // Pre-compile stopNode expressions for pattern matching\n const stopNodeExpressions = [];\n if (options.stopNodes && Array.isArray(options.stopNodes)) {\n for (let i = 0; i < options.stopNodes.length; i++) {\n const node = options.stopNodes[i];\n if (typeof node === 'string') {\n stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n stopNodeExpressions.push(node);\n }\n }\n }\n\n // Detect XML version for use in name validation\n const xmlVersion = detectXmlVersionFromArray(jArray, options);\n\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n\n return arrToStr(jArray, options, indentation, matcher, stopNodeExpressions, xmlVersion);\n}\n\nfunction arrToStr(arr, options, indentation, matcher, stopNodeExpressions, xmlVersion) {\n let xmlStr = \"\";\n let isPreviousElementTag = false;\n\n if (options.maxNestedTags && matcher.getDepth() > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n\n if (!Array.isArray(arr)) {\n // Non-array values (e.g. string tag values) should be treated as text content\n if (arr !== undefined && arr !== null) {\n let text = arr.toString();\n text = replaceEntitiesValue(text, options);\n return text;\n }\n return \"\";\n }\n\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const rawTagName = propName(tagObj);\n if (rawTagName === undefined) continue;\n\n // Special names are exempt from sanitizeName: internal conventions and PI tags\n // are not user-supplied XML element names.\n const isSpecialName = rawTagName === options.textNodeName\n || rawTagName === options.cdataPropName\n || rawTagName === options.commentPropName\n || rawTagName[0] === '?';\n\n // Resolve tag name (may transform it; may throw for invalid names)\n const tagName = isSpecialName\n ? rawTagName\n : resolveTagName(rawTagName, false, options, matcher, xmlVersion);\n\n // Extract attributes from \":@\" property\n const attrValues = extractAttributeValues(tagObj[\":@\"], options);\n\n // Push resolved tag to matcher WITH attributes\n matcher.push(tagName, attrValues);\n\n // Check if this is a stop node using Expression matching\n const isStopNode = checkStopNode(matcher, stopNodeExpressions);\n\n if (tagName === options.textNodeName) {\n let tagText = tagObj[rawTagName];\n if (!isStopNode) {\n tagText = options.tagValueProcessor(tagName, tagText);\n tagText = replaceEntitiesValue(tagText, options);\n }\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += tagText;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.cdataPropName) {\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n const val = tagObj[rawTagName][0][options.textNodeName];\n const safeVal = safeCdata(val);\n xmlStr += ``;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.commentPropName) {\n const val = tagObj[rawTagName][0][options.textNodeName];\n const safeVal = safeComment(val);\n xmlStr += indentation + ``;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n } else if (tagName[0] === \"?\") {\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode, matcher, xmlVersion);\n const tempInd = tagName === \"?xml\" ? \"\" : indentation;\n // Text node content on PI/XML declaration tags is intentionally ignored.\n // Only attributes are valid on these tags per the XML spec.\n xmlStr += tempInd + `<${tagName}${attStr}?>`;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n }\n\n let newIdentation = indentation;\n if (newIdentation !== \"\") {\n newIdentation += options.indentBy;\n }\n\n // Pass isStopNode to attr_to_str so attributes are also not processed for stopNodes\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode, matcher, xmlVersion);\n const tagStart = indentation + `<${tagName}${attStr}`;\n\n // If this is a stopNode, get raw content without processing\n let tagValue;\n if (isStopNode) {\n tagValue = getRawContent(tagObj[rawTagName], options);\n } else {\n tagValue = arrToStr(tagObj[rawTagName], options, newIdentation, matcher, stopNodeExpressions, xmlVersion);\n }\n\n if (options.unpairedTags.indexOf(tagName) !== -1) {\n if (options.suppressUnpairedNode) xmlStr += tagStart + \">\";\n else xmlStr += tagStart + \"/>\";\n } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {\n xmlStr += tagStart + \"/>\";\n } else if (tagValue && tagValue.endsWith(\">\")) {\n xmlStr += tagStart + `>${tagValue}${indentation}`;\n } else {\n xmlStr += tagStart + \">\";\n if (tagValue && indentation !== \"\" && (tagValue.includes(\"/>\") || tagValue.includes(\"`;\n }\n isPreviousElementTag = true;\n\n // Pop tag from matcher\n matcher.pop();\n }\n\n return xmlStr;\n}\n\n/**\n * Extract attribute values from the \":@\" object and return as plain object\n * for passing to matcher.push()\n */\nfunction extractAttributeValues(attrMap, options) {\n if (!attrMap || options.ignoreAttributes) return null;\n\n const attrValues = {};\n let hasAttrs = false;\n\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // Remove the attribute prefix to get clean attribute name\n const cleanAttrName = attr.startsWith(options.attributeNamePrefix)\n ? attr.substr(options.attributeNamePrefix.length)\n : attr;\n attrValues[cleanAttrName] = escapeAttribute(attrMap[attr]);\n hasAttrs = true;\n }\n\n return hasAttrs ? attrValues : null;\n}\n\n/**\n * Extract raw content from a stopNode without any processing\n * This preserves the content exactly as-is, including special characters\n */\nfunction getRawContent(arr, options) {\n if (!Array.isArray(arr)) {\n // Non-array values return as-is\n if (arr !== undefined && arr !== null) {\n return arr.toString();\n }\n return \"\";\n }\n\n let content = \"\";\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n const tagName = propName(item);\n\n if (tagName === options.textNodeName) {\n // Raw text content - NO processing, NO entity replacement\n content += item[tagName];\n } else if (tagName === options.cdataPropName) {\n // CDATA content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName === options.commentPropName) {\n // Comment content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName && tagName[0] === \"?\") {\n // Processing instruction - skip for stopNodes\n continue;\n } else if (tagName) {\n // Nested tags within stopNode — no sanitizeName, content is raw\n const attStr = attr_to_str_raw(item[\":@\"], options);\n const nestedContent = getRawContent(item[tagName], options);\n\n if (!nestedContent || nestedContent.length === 0) {\n content += `<${tagName}${attStr}/>`;\n } else {\n content += `<${tagName}${attStr}>${nestedContent}`;\n }\n }\n }\n return content;\n}\n\n/**\n * Build attribute string for stopNodes - NO entity replacement\n */\nfunction attr_to_str_raw(attrMap, options) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // For stopNodes, use raw value without processing\n let attrVal = attrMap[attr];\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${escapeAttribute(attrVal)}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n if (key !== \":@\") return key;\n }\n}\n\n/**\n * Build attribute string, resolving attribute names through sanitizeName when configured.\n * Accepts matcher so the callback has path context.\n */\nfunction attr_to_str(attrMap, options, isStopNode, matcher, xmlVersion) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n\n // Strip prefix to get the clean XML attribute name, then optionally sanitize it\n const cleanAttrName = attr.substr(options.attributeNamePrefix.length);\n const resolvedAttrName = isStopNode\n ? cleanAttrName // stopNodes are raw — skip sanitizeName for attr names too\n : resolveTagName(cleanAttrName, true, options, matcher, xmlVersion);\n\n let attrVal;\n if (isStopNode) {\n // For stopNodes, use raw value without any processing\n attrVal = attrMap[attr];\n } else {\n // Normal processing: apply attributeValueProcessor and entity replacement\n attrVal = options.attributeValueProcessor(attr, attrMap[attr]);\n attrVal = replaceEntitiesValue(attrVal, options);\n }\n\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${resolvedAttrName}`;\n } else {\n attrStr += ` ${resolvedAttrName}=\"${escapeAttribute(attrVal)}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction checkStopNode(matcher, stopNodeExpressions) {\n if (!stopNodeExpressions || stopNodeExpressions.length === 0) return false;\n\n for (let i = 0; i < stopNodeExpressions.length; i++) {\n if (matcher.matches(stopNodeExpressions[i])) {\n return true;\n }\n }\n return false;\n}\n\nfunction replaceEntitiesValue(textValue, options) {\n if (textValue && textValue.length > 0 && options.processEntities) {\n for (let i = 0; i < options.entities.length; i++) {\n const entity = options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}","'use strict';\n//parse Empty Node as self closing node\nimport buildFromOrderedJs from './orderedJs2Xml.js';\nimport getIgnoreAttributesFn from \"./ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\nimport { safeComment, safeCdata, escapeAttribute } from './util.js';\nimport { qName } from 'xml-naming';\n\nconst defaultOptions = {\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n cdataPropName: false,\n format: false,\n indentBy: ' ',\n suppressEmptyNode: false,\n suppressUnpairedNode: true,\n suppressBooleanAttributes: true,\n tagValueProcessor: function (key, a) {\n return a;\n },\n attributeValueProcessor: function (attrName, a) {\n return a;\n },\n preserveOrder: false,\n commentPropName: false,\n unpairedTags: [],\n entities: [\n { regex: new RegExp(\"&\", \"g\"), val: \"&\" },//it must be on top\n { regex: new RegExp(\">\", \"g\"), val: \">\" },\n { regex: new RegExp(\"<\", \"g\"), val: \"<\" },\n { regex: new RegExp(\"\\'\", \"g\"), val: \"'\" },\n { regex: new RegExp(\"\\\"\", \"g\"), val: \""\" }\n ],\n processEntities: true,\n stopNodes: [],\n // transformTagName: false,\n // transformAttributeName: false,\n oneListGroup: false,\n maxNestedTags: 100,\n jPath: true, // When true, callbacks receive string jPath; when false, receive Matcher instance\n sanitizeName: false // false = allow all names as-is (default, backward-compatible).\n // Set to a function (name, { isAttribute, matcher }) => string to\n // validate/sanitize tag and attribute names. Throw inside the function\n // to reject an invalid name.\n};\n\nexport default function Builder(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n // Convert old-style stopNodes for backward compatibility\n // Old syntax: \"*.tag\" meant \"tag anywhere in tree\"\n // New syntax: \"..tag\" means \"tag anywhere in tree\"\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n this.options.stopNodes = this.options.stopNodes.map(node => {\n if (typeof node === 'string' && node.startsWith('*.')) {\n // Convert old wildcard syntax to deep wildcard\n return '..' + node.substring(2);\n }\n return node;\n });\n }\n\n // Pre-compile stopNode expressions for pattern matching\n this.stopNodeExpressions = [];\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n for (let i = 0; i < this.options.stopNodes.length; i++) {\n const node = this.options.stopNodes[i];\n if (typeof node === 'string') {\n this.stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n this.stopNodeExpressions.push(node);\n }\n }\n }\n\n if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {\n this.isAttribute = function (/*a*/) {\n return false;\n };\n } else {\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.attrPrefixLen = this.options.attributeNamePrefix.length;\n this.isAttribute = isAttribute;\n }\n\n this.processTextOrObjNode = processTextOrObjNode\n\n if (this.options.format) {\n this.indentate = indentate;\n this.tagEndChar = '>\\n';\n this.newLine = '\\n';\n } else {\n this.indentate = function () {\n return '';\n };\n this.tagEndChar = '>';\n this.newLine = '';\n }\n}\n\n/**\n * Detect XML version from the ?xml declaration at the root of a plain-object input.\n * Checks both attributesGroupName and flat attribute forms.\n * Returns '1.0' if no declaration is found.\n */\nfunction detectXmlVersionFromObj(jObj, options) {\n const decl = jObj['?xml'];\n if (decl && typeof decl === 'object') {\n // attributesGroupName path e.g. { '$$': { '@_version': '1.1' } }\n if (options.attributesGroupName && decl[options.attributesGroupName]) {\n const v = decl[options.attributesGroupName][options.attributeNamePrefix + 'version'];\n if (v) return v;\n }\n // flat attribute path e.g. { '@_version': '1.1' }\n const v = decl[options.attributeNamePrefix + 'version'];\n if (v) return v;\n }\n return '1.0';\n}\n\n/**\n * Resolve a tag or attribute name through sanitizeName if configured.\n * Validation via xml-naming's qName is performed first; the sanitizeName\n * callback is invoked only when the name is invalid. If sanitizeName is\n * false (default), no validation occurs and the name is used as-is.\n *\n * @param {string} name - raw name from the JS object\n * @param {boolean} isAttribute - true when resolving an attribute name\n * @param {object} options\n * @param {Matcher} matcher - current matcher state (readonly from callback perspective)\n * @param {string} xmlVersion - '1.0' or '1.1', forwarded to xml-naming\n */\nfunction resolveTagName(name, isAttribute, options, matcher, xmlVersion) {\n if (!options.sanitizeName) return name;\n if (qName(name, { xmlVersion })) return name;\n return options.sanitizeName(name, { isAttribute, matcher: matcher.readOnly() });\n}\n\nBuilder.prototype.build = function (jObj) {\n if (this.options.preserveOrder) {\n return buildFromOrderedJs(jObj, this.options);\n } else {\n if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {\n jObj = {\n [this.options.arrayNodeName]: jObj\n }\n }\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n const xmlVersion = detectXmlVersionFromObj(jObj, this.options);\n return this.j2x(jObj, 0, matcher, xmlVersion).val;\n }\n};\n\nBuilder.prototype.j2x = function (jObj, level, matcher, xmlVersion) {\n let attrStr = '';\n let val = '';\n if (this.options.maxNestedTags && matcher.getDepth() >= this.options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n // Get jPath based on option: string for backward compatibility, or Matcher for new features\n const jPath = this.options.jPath ? matcher.toString() : matcher;\n\n // Check if current node is a stopNode (will be used for attribute encoding)\n const isCurrentStopNode = this.checkStopNode(matcher);\n\n for (let key in jObj) {\n if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;\n\n // Resolve the key through sanitizeName before any use.\n // Special keys (textNodeName, cdataPropName, commentPropName, attributeNamePrefix,\n // attributesGroupName, \"?\" PI tags) are exempt — they are builder-internal conventions,\n // not user-supplied XML names.\n const isSpecialKey = key === this.options.textNodeName\n || key === this.options.cdataPropName\n || key === this.options.commentPropName\n || (this.options.attributesGroupName && key === this.options.attributesGroupName)\n || this.isAttribute(key)\n || key[0] === '?';\n\n const resolvedKey = isSpecialKey\n ? key\n : resolveTagName(key, false, this.options, matcher, xmlVersion);\n\n if (typeof jObj[key] === 'undefined') {\n // supress undefined node only if it is not an attribute\n if (this.isAttribute(key)) {\n val += '';\n }\n } else if (jObj[key] === null) {\n // null attribute should be ignored by the attribute list, but should not cause the tag closing\n if (this.isAttribute(key)) {\n val += '';\n } else if (resolvedKey === this.options.cdataPropName || resolvedKey === this.options.commentPropName) {\n val += '';\n } else if (resolvedKey[0] === '?') {\n val += this.indentate(level) + '<' + resolvedKey + '?' + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + resolvedKey + '/' + this.tagEndChar;\n }\n } else if (jObj[key] instanceof Date) {\n val += this.buildTextValNode(jObj[key], resolvedKey, '', level, matcher);\n } else if (typeof jObj[key] !== 'object') {\n //premitive type\n const attr = this.isAttribute(key);\n if (attr && !this.ignoreAttributesFn(attr, jPath)) {\n // Resolve the attribute name through sanitizeName\n const resolvedAttr = resolveTagName(attr, true, this.options, matcher, xmlVersion);\n attrStr += this.buildAttrPairStr(resolvedAttr, '' + jObj[key], isCurrentStopNode);\n } else if (!attr) {\n //tag value\n if (key === this.options.textNodeName) {\n let newval = this.options.tagValueProcessor(key, '' + jObj[key]);\n val += this.replaceEntitiesValue(newval);\n } else {\n // Check if this is a stopNode before building\n matcher.push(resolvedKey);\n const isStopNode = this.checkStopNode(matcher);\n matcher.pop();\n\n if (isStopNode) {\n // Build as raw content without encoding\n const textValue = '' + jObj[key];\n if (textValue === '') {\n val += this.indentate(level) + '<' + resolvedKey + this.closeTag(resolvedKey) + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + resolvedKey + '>' + textValue + '' + textValue + '${item}`;\n } else if (typeof item === 'object' && item !== null) {\n const nestedContent = this.buildRawContent(item);\n const nestedAttrs = this.buildAttributesForStopNode(item);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n }\n }\n } else if (typeof value === 'object' && value !== null) {\n // Nested object\n const nestedContent = this.buildRawContent(value);\n const nestedAttrs = this.buildAttributesForStopNode(value);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n } else {\n // Primitive value\n content += `<${key}>${value}`;\n }\n }\n\n return content;\n};\n\n// Build attribute string for stopNode (no entity encoding)\nBuilder.prototype.buildAttributesForStopNode = function (obj) {\n if (!obj || typeof obj !== 'object') return '';\n\n let attrStr = '';\n\n // Check for attributesGroupName (when attributes are grouped)\n if (this.options.attributesGroupName && obj[this.options.attributesGroupName]) {\n const attrGroup = obj[this.options.attributesGroupName];\n for (let attrKey in attrGroup) {\n if (!Object.prototype.hasOwnProperty.call(attrGroup, attrKey)) continue;\n const cleanKey = attrKey.startsWith(this.options.attributeNamePrefix)\n ? attrKey.substring(this.options.attributeNamePrefix.length)\n : attrKey;\n const val = attrGroup[attrKey];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + cleanKey;\n } else {\n attrStr += ' ' + cleanKey + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n } else {\n // Look for individual attributes\n for (let key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n const attr = this.isAttribute(key);\n if (attr) {\n const val = obj[key];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + attr;\n } else {\n attrStr += ' ' + attr + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n }\n }\n\n return attrStr;\n};\n\nBuilder.prototype.buildObjectNode = function (val, key, attrStr, level) {\n if (val === \"\") {\n if (key[0] === \"?\") return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n else {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }\n } else if (key[0] === \"?\") {\n // PI/XML-declaration tags never have body content — treat them like empty.\n return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n } else {\n let tagEndExp = '' + val + tagEndExp);\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {\n return this.indentate(level) + `` + this.newLine;\n } else {\n return (\n this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +\n val +\n this.indentate(level) + tagEndExp);\n }\n }\n}\n\nBuilder.prototype.closeTag = function (key) {\n let closeTag = \"\";\n if (this.options.unpairedTags.indexOf(key) !== -1) { //unpaired\n if (!this.options.suppressUnpairedNode) closeTag = \"/\"\n } else if (this.options.suppressEmptyNode) { //empty\n closeTag = \"/\";\n } else {\n closeTag = `>` + this.newLine;\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {\n const safeVal = safeComment(val);\n return this.indentate(level) + `` + this.newLine;\n } else if (key[0] === \"?\") {//PI tag\n return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n } else {\n // Normal processing: apply tagValueProcessor and entity replacement\n let textValue = this.options.tagValueProcessor(key, val);\n textValue = this.replaceEntitiesValue(textValue);\n\n if (textValue === '') {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n } else {\n return this.indentate(level) + '<' + key + attrStr + '>' +\n textValue +\n ' 0 && this.options.processEntities) {\n for (let i = 0; i < this.options.entities.length; i++) {\n const entity = this.options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\n\nfunction indentate(level) {\n return this.options.indentBy.repeat(level);\n}\n\nfunction isAttribute(name /*, options*/) {\n if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {\n return name.substr(this.attrPrefixLen);\n } else {\n return false;\n }\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}","// Re-export from fast-xml-builder for backward compatibility\nimport XMLBuilder from 'fast-xml-builder';\nexport default XMLBuilder;\n\n// If there are any named exports you also want to re-export:\nexport * from 'fast-xml-builder';","'use strict';\n\nimport { validate } from './validator.js';\nimport XMLParser from './xmlparser/XMLParser.js';\nimport XMLBuilder from './xmlbuilder/json2xml.js';\n\nconst XMLValidator = {\n validate: validate\n}\nexport {\n XMLParser,\n XMLValidator,\n XMLBuilder\n};"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","nameStartChar","regexName","RegExp","getAllMatches","string","regex","matches","match","exec","allmatches","startIndex","lastIndex","length","len","index","push","isName","DANGEROUS_PROPERTY_NAMES","criticalProperties","defaultOptions","allowBooleanAttributes","unpairedTags","validate","xmlData","options","assign","tags","tagFound","reachedRoot","substr","i","readPI","err","isWhiteSpace","getErrorObject","getLineNumberForPosition","tagStartPos","readCommentAndCDATA","closingTag","tagName","trim","substring","validateTagName","result","readAttributeStr","attrStr","attrStrStart","isValid","validateAttributeString","code","msg","line","tagClosed","otg","pop","openPos","col","indexOf","afterAmp","validateAmpersand","JSON","stringify","map","t","replace","char","start","tagname","angleBracketsCount","doubleQuote","singleQuote","startChar","validAttrStrRegxp","attrNames","getPositionFromMatch","undefined","attrName","validateAttrName","re","validateNumberAmpersand","count","message","lineNumber","lines","split","defaultOnDangerousProperty","name","includes","preserveOrder","attributeNamePrefix","attributesGroupName","textNodeName","ignoreAttributes","removeNSPrefix","parseTagValue","parseAttributeValue","trimValues","cdataPropName","numberParseOptions","hex","leadingZeros","eNotation","unicode","tagValueProcessor","val","attributeValueProcessor","stopNodes","alwaysCreateTextNode","isArray","commentPropName","processEntities","htmlEntities","entityDecoder","ignoreDeclaration","ignorePiTags","transformTagName","transformAttributeName","updateTag","jPath","attrs","captureMetaData","maxNestedTags","strictReservedNames","onDangerousProperty","validatePropertyName","propertyName","optionName","normalized","toLowerCase","some","dangerous","Error","normalizeProcessEntities","enabled","maxEntitySize","maxExpansionDepth","maxTotalExpansions","Infinity","maxExpandedLength","maxEntityCount","allowedTags","tagFilter","appliesTo","Math","max","_value$maxEntitySize","_value$maxExpansionDe","_value$maxTotalExpans","_value$maxExpandedLen","_value$maxEntityCount","_value$allowedTags","_value$tagFilter","_value$appliesTo","METADATA_SYMBOL","buildOptions","built","_i","_propertyNameOptions","_propertyNameOptions$","unpairedTagsSet","Set","Array","node","startsWith","XmlNode","child","create","_proto","add","_this$child$push","addChild","_this$child$push2","_this$child$push3","keys","getMetaDataSymbol","nameStartChar10","nameStartChar11","nameChar11","buildRegexes","flags","ncNamePat","ncName","qName","nmToken","nmTokens","regexes10","regexes11","str","xmlVersion","getRegexes","test","DocTypeReader","suppressValidationErr","setXmlVersion","readDocType","entities","entityCount","hasBody","comment","hasSeq","entityName","_this$readEntityExp","readEntityExp","readElementExp","readNotationExp","skipWhitespace","validateEntityName","toUpperCase","entityValue","_this$readIdentifierV","readIdentifierVal","notationName","identifierType","publicIdentifier","systemIdentifier","_this$readIdentifierV2","_this$readIdentifierV3","_this$readIdentifierV4","type","identifierVal","elementName","contentModel","readAttlistExp","attributeName","attributeType","allowedNotations","notation","join","defaultValue","_this$readIdentifierV5","data","seq","j","SCRIPT_ZEROS","HIGH_MAP","Map","TABLE_OFFSET","TABLE","Uint8Array","LOW_MAX","fill","zero","d","cp","set","MINUS_SET","hexRegex","binRegex","octRegex","numRegex","consider","binary","octal","decimalPoint","infinity","toNumber","trimmedStr","skipLike","firstHit","cc","charCodeAt","has","low","chars","slice","String","fromCharCode","anynum","parse_int","isFinite","eNotationRegx","sign","eChar","eAdjacentToLeadingZeros","Number","resolveEnotation","numTrimmedByZeros","numStr","decimalAdjacentToLeadingZeros","num","parsedStr","search","n","isPositive","handleInfinity","base","parseInt","window","MatcherView","constructor","matcher","_matcher","separator","getCurrentTag","path","tag","getCurrentNamespace","namespace","getAttrValue","values","hasAttr","current","getPosition","position","getCounter","counter","getIndex","getDepth","toString","includeNamespace","toArray","expression","matchesAny","exprSet","Matcher","siblingStacks","_pathStringCache","_view","attrValues","currentLevel","siblings","siblingKey","updateCurrent","sep","reset","segments","hasDeepWildcard","_matchWithDeepWildcard","_matchSimple","_matchSegment","pathIdx","segIdx","segment","nextSeg","found","isCurrentNode","attrValue","positionValue","snapshot","restore","readOnly","Expression","pattern","_parse","_hasDeepWildcard","seg","_hasAttributeCondition","_hasPositionSelector","currentPart","_parseSegment","part","bracketContent","withoutBrackets","bracketMatch","content","tagAndPosition","nsIndex","positionMatch","colonIndex","lastIndexOf","tagPart","posPart","eqIndex","nthMatch","hasAttributeCondition","hasPositionSelector","ExpressionSet","_byDepthAndTag","_wildcardByDepth","_deepWildcards","_patterns","_sealed","TypeError","depth","lastSeg","addAll","expressions","expr","size","seal","isSealed","findMatch","exactKey","exactBucket","wildcardBucket","CURRENCY","cent","pound","curren","yen","euro","dollar","fnof","inr","af","birr","peso","rub","won","yuan","cedil","XML","amp","apos","gt","lt","quot","COMMON_HTML","nbsp","copy","reg","trade","mdash","ndash","hellip","laquo","raquo","lsquo","rsquo","ldquo","rdquo","bull","para","sect","deg","frac12","frac14","frac34","ENTITY_ACTION","freeze","ALLOW","BLOCK","THROW","SPECIAL_CHARS","ch","mergeEntityMaps","maps","out","raw","LIMIT_TIER_EXTERNAL","LIMIT_TIER_BASE","LIMIT_TIER_ALL","NCR_LEVEL","allow","leave","remove","throw","XML10_ALLOWED_C0","EntityDecoder","_limit","limit","_maxTotalExpansions","_maxExpandedLength","_postCheck","postCheck","r","_limitTiers","applyLimitsTo","_numericAllowed","numericAllowed","_baseMap","DEFAULT_XML_ENTITIES","namedEntities","_externalMap","_inputMap","_totalExpansions","_expandedLength","_removeSet","_leaveSet","ncrCfg","ncr","onLevel","nullLevel","onNCR","nullNCR","parseNCRConfig","_ncrXmlVersion","_ncrOnLevel","_ncrNullLevel","_onExternalEntity","onExternalEntity","_onInputEntity","onInputEntity","_applyRegistrationHook","hook","context","action","setExternalEntities","flat","filtered","entries","addExternalEntity","addInputEntities","version","decode","original","chunks","last","limitExpansions","limitLength","checkLimits","token","replacement","tier","ncrResult","_resolveNCR","resolved","_resolveName","_tierCounts","delta","_classifyNCR","_applyNCRAction","fromCodePoint","padStart","second","isNaN","minimum","effective","id","description","CONTEXT_REGISTRY","HTML","SVG","SQL","SQL_PATTERNS","SHELL","REDOS","NOSQL","LOG","VALID_CONTEXTS","fromEntries","k","matchContext","contextName","patterns","rule","isUnsafe","assertString","c","assertContext","_extends","bind","e","arguments","apply","extractRawAttributes","prefixedAttrs","rawAttrs","extractNamespace","rawTagName","ns","OrderedObjParser","externalEntities","currentNode","tagsNodeStack","parseXml","parseTextData","resolveNameSpace","buildAttributesMap","isItStopNode","replaceEntitiesValue","readStopNodeData","saveTextToParentTag","ignoreAttributesFn","_step","_iterator","_createForOfIteratorHelperLoose","done","entityExpansionCount","currentExpandedLength","readonlyMatcher","isCurrentNodeStopNode","stopNodeExpressionsSet","stopNodesOpts","stopNodeExp","dontTrim","hasAttributes","isLeafNode","escapeEntities","jPathOrMatcher","newval","parseValue","prefix","charAt","attrsRegx","force","processedVals","hasRawAttrs","rawAttrsForMatcher","oldVal","jPathStr","hasAttrs","aName","sanitizeName","newVal","attrCollection","xmlObj","xmlNode","textData","docTypeReader","xmlLen","c1","closeIndex","findClosingIndex","lastTagName","tagData","readTagExp","attsMap","tagExp","ver","childNode","attrExpPresent","endIndex","_ref","_ref2","min","_transformTagName","lastTag","isSelfClosing","tagContent","_transformTagName2","entityConfig","parentNode","errMsg","closingIndex","findClosingChar","closingChar","attrBoundary","closeCode0","closeCode1","segmentStart","tagExpWithClosingIndex","separatorIndex","trimStart","openTagCount","xmllen","shouldParse","fn","newTagName","stripAttributePrefix","prettify","compress","arr","text","compressedObj","tagObj","property","propName","isLeaf","isLeafTag","assignAttributes","attrMap","atrrName","rawAttrName","propCount","XMLParser","parse","validationOption","orderedObjParser","orderedResult","addEntity","safeComment","safeCdata","escapeAttribute","resolveTagName","isAttribute","toXml","jArray","indentation","format","stopNodeExpressions","first","versionKey","detectXmlVersionFromArray","arrToStr","xmlStr","isPreviousElementTag","extractAttributeValues","isStopNode","checkStopNode","tagText","attr_to_str","newIdentation","indentBy","tagStart","tagValue","getRawContent","suppressUnpairedNode","suppressEmptyNode","endsWith","attr","item","attStr","attr_to_str_raw","nestedContent","attrVal","suppressBooleanAttributes","cleanAttrName","resolvedAttrName","textValue","entity","a","oneListGroup","Builder","attrPrefixLen","processTextOrObjNode","indentate","tagEndChar","newLine","object","level","extractAttributes","rawContent","buildRawContent","buildAttributesForStopNode","buildObjectNode","j2x","buildTextValNode","repeat","build","jObj","buildFromOrderedJs","arrayNodeName","decl","v","detectXmlVersionFromObj","isCurrentStopNode","resolvedKey","Date","resolvedAttr","buildAttrPairStr","closeTag","arrLen","listTagVal","listTagAttr","Ks","L","attrGroup","attrKey","nestedAttrs","cleanKey","tagEndExp","piClosingChar","safeVal","XMLValidator"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/lib/fxparser.min.js b/node_modules/fast-xml-parser/lib/fxparser.min.js new file mode 100644 index 0000000000000000000000000000000000000000..e98edd53751befeec29b4b05c79291bc1c89b43a --- /dev/null +++ b/node_modules/fast-xml-parser/lib/fxparser.min.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.XMLParser=e():t.XMLParser=e()}(this,()=>(()=>{"use strict";var t={d:(e,r)=>{for(var i in r)t.o(r,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:r[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{default:()=>Qt});var r=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",i=new RegExp("^["+r+"]["+r+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function n(t,e){for(var r=[],i=e.exec(t);i;){var n=[];n.startIndex=e.lastIndex-i[0].length;for(var a=i.length,s=0;s0?this.child.push(((r={})[t.tagname]=t.child,r[":@"]=t[":@"],r)):this.child.push(((i={})[t.tagname]=t.child,i)),void 0!==e&&(this.child[this.child.length-1][h]={startIndex:e})},t.getMetaDataSymbol=function(){return h},t}();const g=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�",m=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",v=m+"\\-\\.\\d·̀-ͯ҇‿-⁀",x=(t,e,r="")=>{const i=`[${t.replace(":","")}][${e.replace(":","")}]*`;return{name:new RegExp(`^[${t}][${e}]*$`,r),ncName:new RegExp(`^${i}$`,r),qName:new RegExp(`^${i}(?::${i})?$`,r),nmToken:new RegExp(`^[${e}]+$`,r),nmTokens:new RegExp(`^[${e}]+(?:\\s+[${e}]+)*$`,r)}},b=x(g,g+"\\-\\.\\d·̀-ͯ‿-⁀"),y=x(m,v,"u"),E=(t,{xmlVersion:e="1.0"}={})=>((t="1.0")=>"1.1"===t?y:b)(e).qName.test(t);var w=function(){function t(t,e){this.suppressValidationErr=!t,this.options=t,this.xmlVersion=e||1}var e=t.prototype;return e.setXmlVersion=function(t){void 0===t&&(t=1),this.xmlVersion=t},e.readDocType=function(t,e){var r=Object.create(null),i=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");e+=9;for(var n=1,a=!1,s=!1;e"===t[e]){if(s?"-"===t[e-1]&&"-"===t[e-2]&&(s=!1,n--):n--,0===n)break}else"["===t[e]?a=!0:t[e];else{if(a&&N(t,"!ENTITY",e)){e+=7;var o,l=void 0,c=this.readEntityExp(t,e+1,this.suppressValidationErr);if(o=c[0],l=c[1],e=c[2],-1===l.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&i>=this.options.maxEntityCount)throw new Error("Entity count ("+(i+1)+") exceeds maximum allowed ("+this.options.maxEntityCount+")");r[o]=l,i++}}else if(a&&N(t,"!ELEMENT",e))e+=8,e=this.readElementExp(t,e+1).index;else if(a&&N(t,"!ATTLIST",e))e+=8;else if(a&&N(t,"!NOTATION",e))e+=9,e=this.readNotationExp(t,e+1,this.suppressValidationErr).index;else{if(!N(t,"!--",e))throw new Error("Invalid DOCTYPE");s=!0}n++}if(0!==n)throw new Error("Unclosed DOCTYPE");return{entities:r,i:e}},e.readEntityExp=function(t,e){for(var r=e=S(t,e);ethis.options.maxEntitySize)throw new Error('Entity "'+i+'" size ('+n.length+") exceeds maximum allowed size ("+this.options.maxEntitySize+")");return[i,n,--e]},e.readNotationExp=function(t,e){for(var r=e=S(t,e);e=48&&n<=57||45===n))if(n=55296&&n<=56319){if(i+1=56320&&e<=57343){const t=65536+(n-55296<<10)+(e-56320);if(A.has(t)){r=i;break}}}}else if(255!==I[n-C]||j.has(n)){r=i;break}}if(-1===r)return t;const i=[];r>0&&i.push(t.slice(0,r));for(let n=r;n=48&&r<=57||45===r){i.push(t[n]);continue}if(r=55296&&r<=56319){if(n+1=56320&&e<=57343){const t=65536+(r-55296<<10)+(e-56320),a=A.get(t);if(void 0!==a){i.push(String.fromCharCode(a+48)),n++;continue}}}i.push(t[n]);continue}if(j.has(r)){i.push("-");continue}const a=I[r-C];i.push(255!==a?String.fromCharCode(a+48):t[n])}return i.join("")}(r),"0"===r))return 0;if(e.hex&&O.test(r))return R(r,16);if(e.binary&&k.test(r))return R(r,2);if(e.octal&&D.test(r))return R(r,8);if(isFinite(r)){if(r.includes("e")||r.includes("E"))return function(t,e,r){if(!r.eNotation)return t;const i=e.match(M);if(i){let n=i[1]||"";const a=-1===i[3].indexOf("e")?"E":"e",s=i[2],o=n?t[s.length+1]===a:t[s.length]===a;return s.length>1&&o?t:(1!==s.length||!i[3].startsWith(`.${a}`)&&i[3][0]!==a)&&s.length>0?r.leadingZeros&&!o?(e=(i[1]||"")+i[3],Number(e)):t:Number(e)}return t}(t,r,e);{const n=L.exec(r);if(n){const a=n[1]||"",s=n[2];let o=(i=n[3])&&-1!==i.indexOf(".")?("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1)),i):i;const l=a?"."===t[s.length+1]:"."===t[s.length];if(!e.leadingZeros&&(s.length>1||1===s.length&&!l))return t;{const i=Number(r),n=String(i);if(0===i)return i;if(-1!==n.search(/[eE]/))return e.eNotation?i:t;if(-1!==r.indexOf("."))return"0"===n||n===o||n===`${a}${o}`?i:t;let l=s?o:r;return s?l===n||a+l===n?i:t:l===n||l===a+n?i:t}}return t}}var i;return function(t,e,r){const i=e===1/0;switch(r.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return i?"Infinity":"-Infinity";default:return t}}(t,Number(r),e)}const M=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function R(t,e){const r=t.trim();if(2!==e&&8!==e||(t=r.substring(2)),parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function V(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,i=Array(e);r0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const r=e[e.length-1];return void 0!==r.values&&t in r.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class U{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new q(this)}push(t,e=null,r=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const i=this.path.length;this.siblingStacks[i]||(this.siblingStacks[i]=new Map);const n=this.siblingStacks[i],a=r?`${r}:${t}`:t,s=n.get(a)||0;let o=0;for(const t of n.values())o+=t;n.set(a,s+1);const l={tag:t,position:o,counter:s};null!=r&&(l.namespace=r),null!=e&&(l.values=e),this.path.push(l)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const r=t||this.separator;if(r===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(r);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(r)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e=0&&e>=0;){const i=t[r];if("deep-wildcard"===i.type){if(r--,r<0)return!0;const i=t[r];let n=!1;for(let t=e;t>=0;t--)if(this._matchSegment(i,this.path[t],t===this.path.length-1)){e=t-1,r--,n=!0;break}if(!n)return!1}else{if(!this._matchSegment(i,this.path[e],e===this.path.length-1))return!1;e--,r--}}return r<0}_matchSegment(t,e,r){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!r)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!r)return!1;const i=e.counter??0;if("first"===t.position&&0!==i)return!1;if("odd"===t.position&&i%2!=1)return!1;if("even"===t.position&&i%2!=0)return!1;if("nth"===t.position&&i!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}class F{constructor(t,e={},r){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=r,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let r=0,i="";for(;r",lt:"<",quot:'"'},Y={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},G=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"}),H=new Set("!?\\\\/[]$%{}^&*()<>|+");function z(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(H.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function Q(...t){const e=Object.create(null);for(const r of t)if(r)for(const t of Object.keys(r)){const i=r[t];if("string"==typeof i)e[t]=i;else if(i&&"object"==typeof i&&void 0!==i.val){const r=i.val;"string"==typeof r&&(e[t]=r)}}return e}const J="external",Z="base",K="all",tt=Object.freeze({allow:0,leave:1,remove:2,throw:3}),et=new Set([9,10,13]);class rt{constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??J)&&e!==J?e===K?new Set([K]):e===Z?new Set([Z]):Array.isArray(e)?new Set(e):new Set([J]):new Set([J]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=Q(W,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const r=function(t){if(!t)return{xmlVersion:1,onLevel:tt.allow,nullLevel:tt.remove};const e=1.1===t.xmlVersion?1.1:1,r=tt[t.onNCR]??tt.allow,i=tt[t.nullNCR]??tt.remove;return{xmlVersion:e,onLevel:r,nullLevel:Math.max(i,tt.remove)}}(t.ncr);this._ncrXmlVersion=r.xmlVersion,this._ncrOnLevel=r.onLevel,this._ncrNullLevel=r.nullLevel,this._onExternalEntity="function"==typeof t.onExternalEntity?t.onExternalEntity:null,this._onInputEntity="function"==typeof t.onInputEntity?t.onInputEntity:null}_applyRegistrationHook(t,e,r,i){if(!t)return!0;const n=t(e,r);if(n===G.BLOCK)return!1;if(n===G.THROW)throw new Error(`[EntityDecoder] Registration of ${i} entity "&${e};" was rejected by hook`);return!0}setExternalEntities(t){if(t)for(const e of Object.keys(t))z(e);if(!this._onExternalEntity)return void(this._externalMap=Q(t));const e=Q(t),r=Object.create(null);for(const[t,i]of Object.entries(e))this._applyRegistrationHook(this._onExternalEntity,t,i,"external")&&(r[t]=i);this._externalMap=r}addExternalEntity(t,e){z(t),"string"==typeof e&&-1===e.indexOf("&")&&this._applyRegistrationHook(this._onExternalEntity,t,e,"external")&&(this._externalMap[t]=e)}addInputEntities(t){if(this._totalExpansions=0,this._expandedLength=0,!this._onInputEntity)return void(this._inputMap=Q(t));const e=Q(t),r=Object.create(null);for(const[t,i]of Object.entries(e))this._applyRegistrationHook(this._onInputEntity,t,i,"input")&&(r[t]=i);this._inputMap=r}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1}decode(t){if("string"!=typeof t||0===t.length)return t;if(-1===t.indexOf("&"))return t;const e=t,r=[],i=t.length;let n=0,a=0;const s=this._maxTotalExpansions>0,o=this._maxExpandedLength>0,l=s||o;for(;a=i||59!==t.charCodeAt(e)){a++;continue}const c=t.slice(a+1,e);if(0===c.length){a++;continue}let p,d;if(this._removeSet.has(c))p="",void 0===d&&(d=J);else{if(this._leaveSet.has(c)){a++;continue}if(35===c.charCodeAt(0)){const t=this._resolveNCR(c);if(void 0===t){a++;continue}p=t,d=Z}else{const t=this._resolveName(c);p=t?.value,d=t?.tier}}if(void 0!==p){if(a>n&&r.push(t.slice(n,a)),r.push(p),n=e+1,a=n,l&&this._tierCounts(d)){if(s&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(o){const t=p.length-(c.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else a++}n=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!et.has(t)?tt.remove:-1}_applyNCRAction(t,e,r){switch(t){case tt.allow:return String.fromCodePoint(r);case tt.remove:return"";case tt.leave:return;case tt.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${r.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(r)}}_resolveNCR(t){const e=t.charCodeAt(1);let r;if(r=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(r)||r<0||r>1114111)return;const i=this._classifyNCR(r);if(!this._numericAllowed&&i/]/i},{id:"html-script-close",description:"<\/script closing tag",pattern:/<\/script[\s>]/i},{id:"html-javascript-protocol",description:"javascript: URI scheme (with optional whitespace/encoding)",pattern:/j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i},{id:"html-vbscript-protocol",description:"vbscript: URI scheme",pattern:/vbscript[\t\n\r ]*:/i},{id:"html-data-html",description:"data:text/html URI — can execute scripts in browsers",pattern:/data[\t\n\r ]*:[\t\n\r ]*text\/html/i},{id:"html-data-xhtml",description:"data:application/xhtml+xml URI",pattern:/data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i},{id:"html-data-svg",description:"data:image/svg+xml URI — can execute scripts",pattern:/data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i},{id:"html-inline-event-handler",description:"Inline event handler attributes: onclick=, onerror=, onload=, etc.",pattern:/\bon\w{1,30}\s*=/i},{id:"html-entity-obfuscated-script",description:"HTML-entity-encoded ]/i,\n },\n {\n id: 'html-javascript-protocol',\n description: 'javascript: URI scheme (with optional whitespace/encoding)',\n // Handles javascript:, j\\u0061vascript:, and whitespace variants\n pattern: /j[\\t\\n\\r ]*a[\\t\\n\\r ]*v[\\t\\n\\r ]*a[\\t\\n\\r ]*s[\\t\\n\\r ]*c[\\t\\n\\r ]*r[\\t\\n\\r ]*i[\\t\\n\\r ]*p[\\t\\n\\r ]*t[\\t\\n\\r ]*:/i,\n },\n {\n id: 'html-vbscript-protocol',\n description: 'vbscript: URI scheme',\n pattern: /vbscript[\\t\\n\\r ]*:/i,\n },\n {\n id: 'html-data-html',\n description: 'data:text/html URI — can execute scripts in browsers',\n pattern: /data[\\t\\n\\r ]*:[\\t\\n\\r ]*text\\/html/i,\n },\n {\n id: 'html-data-xhtml',\n description: 'data:application/xhtml+xml URI',\n pattern: /data[\\t\\n\\r ]*:[\\t\\n\\r ]*application\\/xhtml/i,\n },\n {\n id: 'html-data-svg',\n description: 'data:image/svg+xml URI — can execute scripts',\n pattern: /data[\\t\\n\\r ]*:[\\t\\n\\r ]*image\\/svg\\+xml/i,\n },\n {\n id: 'html-inline-event-handler',\n description: 'Inline event handler attributes: onclick=, onerror=, onload=, etc.',\n // \\bon ensures we match a word boundary so \"phonetic=\" is not caught\n pattern: /\\bon\\w{1,30}\\s*=/i,\n },\n {\n id: 'html-entity-obfuscated-script',\n description: 'HTML-entity-encoded ', 'HTML') // true\n * isUnsafe('hello world', 'HTML') // false\n * isUnsafe('value', ['HTML', 'SQL']) // false\n * isUnsafe('value', /my-pattern/i) // false\n */\nfunction isUnsafe(value, context) {\n assertString(value);\n assertContext(context);\n\n // Custom RegExp — caller-supplied pattern\n if (context instanceof RegExp) {\n return context.test(value);\n }\n\n // Single named context\n if (typeof context === 'string') {\n return matchContext(value, context) !== null;\n }\n\n // Array of named contexts — unsafe if ANY context matches\n for (const c of context) {\n if (matchContext(value, c) !== null) return true;\n }\n return false;\n}\n\n/**\n * Like `isUnsafe`, but instead of a boolean returns the first `MatchResult`\n * describing **why** the value was flagged, or `null` if it is safe.\n *\n * Useful for logging, error messages, or policy reporting.\n *\n * @param {string} value\n * @param {ContextName|ContextName[]|RegExp} context\n * @returns {MatchResult|null}\n *\n * @example\n * whyUnsafe('', 'HTML')\n * // { context: 'HTML', id: 'html-script-open', description: '...', pattern: /.../ }\n */\nfunction whyUnsafe(value, context) {\n assertString(value);\n assertContext(context);\n\n if (context instanceof RegExp) {\n return context.test(value)\n ? { context: 'CUSTOM', id: 'custom-regex', description: 'Matched caller-supplied pattern', pattern: context }\n : null;\n }\n\n if (typeof context === 'string') {\n return matchContext(value, context);\n }\n\n for (const c of context) {\n const result = matchContext(value, c);\n if (result !== null) return result;\n }\n return null;\n}\n\n/**\n * Returns all matching rules across the given context(s), or an empty array\n * if the value is safe. Useful for comprehensive auditing.\n *\n * @param {string} value\n * @param {ContextName|ContextName[]|RegExp} context\n * @returns {MatchResult[]}\n */\nfunction allUnsafe(value, context) {\n assertString(value);\n assertContext(context);\n\n const results = [];\n\n if (context instanceof RegExp) {\n if (context.test(value)) {\n results.push({ context: 'CUSTOM', id: 'custom-regex', description: 'Matched caller-supplied pattern', pattern: context });\n }\n return results;\n }\n\n const contexts = typeof context === 'string' ? [context] : context;\n\n for (const c of contexts) {\n const patterns = CONTEXT_REGISTRY[c];\n for (const rule of patterns) {\n if (rule.pattern.test(value)) {\n results.push({ context: c, id: rule.id, description: rule.description, pattern: rule.pattern });\n }\n }\n }\n\n return results;\n}\n\nexport { isUnsafe, whyUnsafe, allUnsafe, VALID_CONTEXTS };\nexport default isUnsafe;","'use strict';\n///@ts-check\n\nimport { getAllMatches, isExist, DANGEROUS_PROPERTY_NAMES, criticalProperties } from '../util.js';\nimport xmlNode from './xmlNode.js';\nimport DocTypeReader from './DocTypeReader.js';\nimport toNumber from \"strnum\";\nimport getIgnoreAttributesFn from \"../ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\nimport { ExpressionSet } from 'path-expression-matcher';\nimport { EntityDecoder, XML, CURRENCY, COMMON_HTML, ENTITY_ACTION } from '@nodable/entities';\nimport { isUnsafe, VALID_CONTEXTS } from \"is-unsafe\"\n\n\n// const regx =\n// '<((!\\\\[CDATA\\\\[([\\\\s\\\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\\\/)(NAME)\\\\s*>))([^<]*)'\n// .replace(/NAME/g, util.nameRegexp);\n\n//const tagsRegx = new RegExp(\"<(\\\\/?[\\\\w:\\\\-\\._]+)([^>]*)>(\\\\s*\"+cdataRegx+\")*([^<]+)?\",\"g\");\n//const tagsRegx = new RegExp(\"<(\\\\/?)((\\\\w*:)?([\\\\w:\\\\-\\._]+))([^>]*)>([^<]*)(\"+cdataRegx+\"([^<]*))*([^<]+)?\",\"g\");\n\n// Helper functions for attribute and namespace handling\n\n/**\n * Extract raw attributes (without prefix) from prefixed attribute map\n * @param {object} prefixedAttrs - Attributes with prefix from buildAttributesMap\n * @param {object} options - Parser options containing attributeNamePrefix\n * @returns {object} Raw attributes for matcher\n */\nfunction extractRawAttributes(prefixedAttrs, options) {\n if (!prefixedAttrs) return {};\n\n // Handle attributesGroupName option\n const attrs = options.attributesGroupName\n ? prefixedAttrs[options.attributesGroupName]\n : prefixedAttrs;\n\n if (!attrs) return {};\n\n const rawAttrs = {};\n for (const key in attrs) {\n // Remove the attribute prefix to get raw name\n if (key.startsWith(options.attributeNamePrefix)) {\n const rawName = key.substring(options.attributeNamePrefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * Extract namespace from raw tag name\n * @param {string} rawTagName - Tag name possibly with namespace (e.g., \"soap:Envelope\")\n * @returns {string|undefined} Namespace or undefined\n */\nfunction extractNamespace(rawTagName) {\n if (!rawTagName || typeof rawTagName !== 'string') return undefined;\n\n const colonIndex = rawTagName.indexOf(':');\n if (colonIndex !== -1 && colonIndex > 0) {\n const ns = rawTagName.substring(0, colonIndex);\n // Don't treat xmlns as a namespace\n if (ns !== 'xmlns') {\n return ns;\n }\n }\n return undefined;\n}\n\nexport default class OrderedObjParser {\n constructor(options, externalEntities) {\n this.options = options;\n this.currentNode = null;\n this.tagsNodeStack = [];\n this.parseXml = parseXml;\n this.parseTextData = parseTextData;\n this.resolveNameSpace = resolveNameSpace;\n this.buildAttributesMap = buildAttributesMap;\n this.isItStopNode = isItStopNode;\n this.replaceEntitiesValue = replaceEntitiesValue;\n this.readStopNodeData = readStopNodeData;\n this.saveTextToParentTag = saveTextToParentTag;\n this.addChild = addChild;\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n let namedEntities = { ...XML };\n if (this.options.entityDecoder) {\n this.entityDecoder = this.options.entityDecoder\n } else {\n if (typeof this.options.htmlEntities === \"object\") namedEntities = this.options.htmlEntities;\n else if (this.options.htmlEntities === true) namedEntities = { ...COMMON_HTML, ...CURRENCY };\n this.entityDecoder = new EntityDecoder({\n namedEntities: { ...namedEntities, ...externalEntities },\n numericAllowed: this.options.htmlEntities,\n limit: {\n maxTotalExpansions: this.options.processEntities.maxTotalExpansions,\n maxExpandedLength: this.options.processEntities.maxExpandedLength,\n applyLimitsTo: this.options.processEntities.appliesTo,\n },\n // onExternalEntity: (name, value) => isUnsafe(value) ? 'block' : 'allow',\n onInputEntity: (name, value) =>\n //TODO: VALID_CONTEXTS.HTML should be set only if this.options.htmlEntities\n isUnsafe(value, [VALID_CONTEXTS.HTML, VALID_CONTEXTS.XML])\n ? ENTITY_ACTION.BLOCK : ENTITY_ACTION.ALLOW,\n\n //postCheck: resolved => resolved\n });\n }\n\n // Initialize path matcher for path-expression-matcher\n this.matcher = new Matcher();\n this.readonlyMatcher = this.matcher.readOnly();\n\n // Flag to track if current node is a stop node (optimization)\n this.isCurrentNodeStopNode = false;\n\n // Pre-compile stopNodes expressions\n this.stopNodeExpressionsSet = new ExpressionSet();\n const stopNodesOpts = this.options.stopNodes;\n if (stopNodesOpts && stopNodesOpts.length > 0) {\n for (let i = 0; i < stopNodesOpts.length; i++) {\n const stopNodeExp = stopNodesOpts[i];\n if (typeof stopNodeExp === 'string') {\n // Convert string to Expression object\n this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));\n } else if (stopNodeExp instanceof Expression) {\n // Already an Expression object\n this.stopNodeExpressionsSet.add(stopNodeExp);\n }\n }\n this.stopNodeExpressionsSet.seal();\n }\n }\n\n}\n\n\n/**\n * @param {string} val\n * @param {string} tagName\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n * @param {boolean} dontTrim\n * @param {boolean} hasAttributes\n * @param {boolean} isLeafNode\n * @param {boolean} escapeEntities\n */\nfunction parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {\n const options = this.options;\n if (val !== undefined) {\n if (options.trimValues && !dontTrim) {\n val = val.trim();\n }\n if (val.length > 0) {\n if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath);\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;\n const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);\n if (newval === null || newval === undefined) {\n //don't parse\n return val;\n } else if (typeof newval !== typeof val || newval !== val) {\n //overwrite\n return newval;\n } else if (options.trimValues) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n const trimmedVal = val.trim();\n if (trimmedVal === val) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n return val;\n }\n }\n }\n }\n}\n\nfunction resolveNameSpace(tagname) {\n if (this.options.removeNSPrefix) {\n const tags = tagname.split(':');\n const prefix = tagname.charAt(0) === '/' ? '/' : '';\n if (tags[0] === 'xmlns') {\n return '';\n }\n if (tags.length === 2) {\n tagname = prefix + tags[1];\n }\n }\n return tagname;\n}\n\n//TODO: change regex to capture NS\n//const attrsRegx = new RegExp(\"([\\\\w\\\\-\\\\.\\\\:]+)\\\\s*=\\\\s*(['\\\"])((.|\\n)*?)\\\\2\",\"gm\");\nconst attrsRegx = new RegExp('([^\\\\s=]+)\\\\s*(=\\\\s*([\\'\"])([\\\\s\\\\S]*?)\\\\3)?', 'gm');\n\nfunction buildAttributesMap(attrStr, jPath, tagName, force = false) {\n const options = this.options;\n if (force === true || (options.ignoreAttributes !== true && typeof attrStr === 'string')) {\n // attrStr = attrStr.replace(/\\r?\\n/g, ' ');\n //attrStr = attrStr || attrStr.trim();\n\n const matches = getAllMatches(attrStr, attrsRegx);\n const len = matches.length; //don't make it inline\n const attrs = {};\n\n // Pre-process values once: trim + entity replacement\n // Reused in both matcher update and second pass\n const processedVals = new Array(len);\n let hasRawAttrs = false;\n const rawAttrsForMatcher = {};\n\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n const oldVal = matches[i][4];\n\n if (attrName.length && oldVal !== undefined) {\n let val = oldVal;\n if (options.trimValues) val = val.trim();\n val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);\n processedVals[i] = val;\n\n rawAttrsForMatcher[attrName] = val;\n hasRawAttrs = true;\n }\n }\n\n // Update matcher ONCE before second pass, if applicable\n if (hasRawAttrs && typeof jPath === 'object' && jPath.updateCurrent) {\n jPath.updateCurrent(rawAttrsForMatcher);\n }\n\n // Hoist toString() once — path doesn't change during attribute processing\n const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;\n\n // Second pass: apply processors, build final attrs\n let hasAttrs = false;\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n\n if (this.ignoreAttributesFn(attrName, jPathStr)) continue;\n\n let aName = options.attributeNamePrefix + attrName;\n\n if (attrName.length) {\n if (options.transformAttributeName) {\n aName = options.transformAttributeName(aName);\n }\n aName = sanitizeName(aName, options);\n\n if (matches[i][4] !== undefined) {\n // Reuse already-processed value — no double entity replacement\n const oldVal = processedVals[i];\n\n const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);\n if (newVal === null || newVal === undefined) {\n attrs[aName] = oldVal;\n } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {\n attrs[aName] = newVal;\n } else {\n attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);\n }\n hasAttrs = true;\n } else if (options.allowBooleanAttributes) {\n attrs[aName] = true;\n hasAttrs = true;\n }\n }\n }\n\n if (!hasAttrs) return;\n\n if (options.attributesGroupName && !options.preserveOrder) {\n const attrCollection = {};\n attrCollection[options.attributesGroupName] = attrs;\n return attrCollection;\n }\n return attrs;\n }\n}\nconst parseXml = function (xmlData) {\n xmlData = xmlData.replace(/\\r\\n?/g, \"\\n\"); //TODO: remove this line\n const xmlObj = new xmlNode('!xml');\n let currentNode = xmlObj;\n let textData = \"\";\n\n // Reset matcher for new document\n this.matcher.reset();\n this.entityDecoder.reset();\n\n // Reset entity expansion counters for this document\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n const options = this.options;\n const docTypeReader = new DocTypeReader(options.processEntities);\n const xmlLen = xmlData.length;\n for (let i = 0; i < xmlLen; i++) {//for each char in XML data\n const ch = xmlData[i];\n if (ch === '<') {\n // const nextIndex = i+1;\n // const _2ndChar = xmlData[nextIndex];\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//Closing Tag '/'\n const closeIndex = findClosingIndex(xmlData, \">\", i, \"Closing Tag is not closed.\")\n let tagName = xmlData.substring(i + 2, closeIndex).trim();\n\n if (options.removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n }\n }\n\n tagName = transformTagName(options.transformTagName, tagName, \"\", options).tagName;\n\n if (currentNode) {\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n }\n\n //check if last tag of nested tag was unpaired tag\n const lastTagName = this.matcher.getCurrentTag();\n if (tagName && options.unpairedTagsSet.has(tagName)) {\n throw new Error(`Unpaired tag can not be used as closing tag: `);\n }\n if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {\n // Pop the unpaired tag\n this.matcher.pop();\n this.tagsNodeStack.pop();\n }\n // Pop the closing tag\n this.matcher.pop();\n this.isCurrentNodeStopNode = false; // Reset flag when closing tag\n\n currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope\n textData = \"\";\n i = closeIndex;\n } else if (c1 === 63) { //'?'\n\n let tagData = readTagExp(xmlData, i, false, \"?>\");\n if (!tagData) throw new Error(\"Pi Tag is not closed.\");\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true);\n if (attsMap) {\n const ver = attsMap[this.options.attributeNamePrefix + \"version\"];\n this.entityDecoder.setXmlVersion(Number(ver) || 1.0);\n docTypeReader.setXmlVersion(Number(ver) || 1.0);\n }\n if ((options.ignoreDeclaration && tagData.tagName === \"?xml\") || options.ignorePiTags) {\n //do nothing\n } else {\n\n const childNode = new xmlNode(tagData.tagName);\n childNode.add(options.textNodeName, \"\");\n\n if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) {\n childNode[\":@\"] = attsMap\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, i);\n }\n\n\n i = tagData.closeIndex + 1;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { //'!--'\n const endIndex = findClosingIndex(xmlData, \"-->\", i + 4, \"Comment is not closed.\")\n if (options.commentPropName) {\n const comment = xmlData.substring(i + 4, endIndex - 2);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);\n }\n i = endIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 68) { //'!D'\n const result = docTypeReader.readDocType(xmlData, i);\n this.entityDecoder.addInputEntities(result.entities);\n i = result.i;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"CDATA is not closed.\") - 2;\n const tagExp = xmlData.substring(i + 9, closeIndex);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);\n if (val == undefined) val = \"\";\n\n //cdata should be set even if it is 0 length string\n if (options.cdataPropName) {\n currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);\n } else {\n currentNode.add(options.textNodeName, val);\n }\n\n i = closeIndex + 2;\n } else {//Opening tag\n let result = readTagExp(xmlData, i, options.removeNSPrefix);\n\n // Safety check: readTagExp can return undefined\n if (!result) {\n // Log context for debugging\n const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));\n throw new Error(`readTagExp returned undefined at position ${i}. Context: \"${context}\"`);\n }\n\n let tagName = result.tagName;\n const rawTagName = result.rawTagName;\n let tagExp = result.tagExp;\n let attrExpPresent = result.attrExpPresent;\n let closeIndex = result.closeIndex;\n\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n if (options.strictReservedNames &&\n (tagName === options.commentPropName\n || tagName === options.cdataPropName\n || tagName === options.textNodeName\n || tagName === options.attributesGroupName\n )) {\n throw new Error(`Invalid tag name: ${tagName}`);\n }\n\n //save text as child node\n if (currentNode && textData) {\n if (currentNode.tagname !== '!xml') {\n //when nested tag is found\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);\n }\n }\n\n //check if last tag was unpaired tag\n const lastTag = currentNode;\n if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {\n currentNode = this.tagsNodeStack.pop();\n this.matcher.pop();\n }\n\n // Clean up self-closing syntax BEFORE processing attributes\n // This is where tagExp gets the trailing / removed\n let isSelfClosing = false;\n if (tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1) {\n isSelfClosing = true;\n if (tagName[tagName.length - 1] === \"/\") {\n tagName = tagName.substr(0, tagName.length - 1);\n tagExp = tagName;\n } else {\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n\n // Re-check attrExpPresent after cleaning\n attrExpPresent = (tagName !== tagExp);\n }\n\n // Now process attributes with CLEAN tagExp (no trailing /)\n let prefixedAttrs = null;\n let rawAttrs = {};\n let namespace = undefined;\n\n // Extract namespace from rawTagName\n namespace = extractNamespace(rawTagName);\n\n // Push tag to matcher FIRST (with empty attrs for now) so callbacks see correct path\n if (tagName !== xmlObj.tagname) {\n this.matcher.push(tagName, {}, namespace);\n }\n\n // Now build attributes - callbacks will see correct matcher state\n if (tagName !== tagExp && attrExpPresent) {\n // Build attributes (returns prefixed attributes for the tree)\n // Note: buildAttributesMap now internally updates the matcher with raw attributes\n prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName);\n\n if (prefixedAttrs) {\n // Extract raw attributes (without prefix) for our use\n //TODO: seems a performance overhead\n rawAttrs = extractRawAttributes(prefixedAttrs, options);\n }\n }\n\n // Now check if this is a stop node (after attributes are set)\n if (tagName !== xmlObj.tagname) {\n this.isCurrentNodeStopNode = this.isItStopNode();\n }\n\n const startIndex = i;\n if (this.isCurrentNodeStopNode) {\n let tagContent = \"\";\n\n // For self-closing tags, content is empty\n if (isSelfClosing) {\n i = result.closeIndex;\n }\n //unpaired tag\n else if (options.unpairedTagsSet.has(tagName)) {\n i = result.closeIndex;\n }\n //normal tag\n else {\n //read until closing tag is found\n const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);\n if (!result) throw new Error(`Unexpected end of ${rawTagName}`);\n i = result.i;\n tagContent = result.tagContent;\n }\n\n const childNode = new xmlNode(tagName);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n\n // For stop nodes, store raw content as-is without any processing\n childNode.add(options.textNodeName, tagContent);\n\n this.matcher.pop(); // Pop the stop node tag\n this.isCurrentNodeStopNode = false; // Reset flag\n\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n } else {\n //selfClosing tag\n if (isSelfClosing) {\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop self-closing tag\n this.isCurrentNodeStopNode = false; // Reset flag\n }\n else if (options.unpairedTagsSet.has(tagName)) {//unpaired tag\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop unpaired tag\n this.isCurrentNodeStopNode = false; // Reset flag\n i = result.closeIndex;\n // Continue to next iteration without changing currentNode\n continue;\n }\n //opening tag\n else {\n const childNode = new xmlNode(tagName);\n if (this.tagsNodeStack.length > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n this.tagsNodeStack.push(currentNode);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n currentNode = childNode;\n }\n textData = \"\";\n i = closeIndex;\n }\n }\n } else {\n textData += xmlData[i];\n }\n }\n return xmlObj.child;\n}\n\nfunction addChild(currentNode, childNode, matcher, startIndex) {\n // unset startIndex if not requested\n if (!this.options.captureMetaData) startIndex = undefined;\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher;\n const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[\":@\"])\n if (result === false) {\n //do nothing\n } else if (typeof result === \"string\") {\n childNode.tagname = result\n currentNode.addChild(childNode, startIndex);\n } else {\n currentNode.addChild(childNode, startIndex);\n }\n}\n\n/**\n * @param {object} val - Entity object with regex and val properties\n * @param {string} tagName - Tag name\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n */\nfunction replaceEntitiesValue(val, tagName, jPath) {\n const entityConfig = this.options.processEntities;\n\n if (!entityConfig || !entityConfig.enabled) {\n return val;\n }\n\n // Check if tag is allowed to contain entities\n if (entityConfig.allowedTags) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n const allowed = Array.isArray(entityConfig.allowedTags)\n ? entityConfig.allowedTags.includes(tagName)\n : entityConfig.allowedTags(tagName, jPathOrMatcher);\n\n if (!allowed) {\n return val;\n }\n }\n\n // Apply custom tag filter if provided\n if (entityConfig.tagFilter) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) {\n return val; // Skip based on custom filter\n }\n }\n\n return this.entityDecoder.decode(val);\n}\n\n\nfunction saveTextToParentTag(textData, parentNode, matcher, isLeafNode) {\n if (textData) { //store previously collected data as textNode\n if (isLeafNode === undefined) isLeafNode = parentNode.child.length === 0\n\n textData = this.parseTextData(textData,\n parentNode.tagname,\n matcher,\n false,\n parentNode[\":@\"] ? Object.keys(parentNode[\":@\"]).length !== 0 : false,\n isLeafNode);\n\n if (textData !== undefined && textData !== \"\")\n parentNode.add(this.options.textNodeName, textData);\n textData = \"\";\n }\n return textData;\n}\n\n/**\n * @param {Array} stopNodeExpressions - Array of compiled Expression objects\n * @param {Matcher} matcher - Current path matcher\n */\nfunction isItStopNode() {\n if (this.stopNodeExpressionsSet.size === 0) return false;\n\n return this.matcher.matchesAny(this.stopNodeExpressionsSet);\n}\n\n/**\n * Returns the tag Expression and where it is ending handling single-double quotes situation\n * @param {string} xmlData \n * @param {number} i starting index\n * @returns \n */\nfunction tagExpWithClosingIndex(xmlData, i, closingChar = \">\") {\n //TODO: ignore boolean attributes in tag expression\n //TODO: if ignore attributes, dont read full attribute expression but the end. But read for xml declaration\n let attrBoundary = 0;\n const len = xmlData.length;\n const closeCode0 = closingChar.charCodeAt(0);\n const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;\n\n let result = '';\n let segmentStart = i;\n\n for (let index = i; index < len; index++) {\n const code = xmlData.charCodeAt(index);\n\n if (attrBoundary) {\n if (code === attrBoundary) attrBoundary = 0;\n } else if (code === 34 || code === 39) { // \" or '\n attrBoundary = code;\n } else if (code === closeCode0) {\n if (closeCode1 !== -1) {\n if (xmlData.charCodeAt(index + 1) === closeCode1) {\n result += xmlData.substring(segmentStart, index);\n return { data: result, index };\n }\n } else {\n result += xmlData.substring(segmentStart, index);\n return { data: result, index };\n }\n } else if (code === 9 && !attrBoundary) { // \\t - only replace with space outside attribute values\n // Flush accumulated segment, add space, start new segment\n result += xmlData.substring(segmentStart, index) + ' ';\n segmentStart = index + 1;\n }\n }\n}\n\nfunction findClosingIndex(xmlData, str, i, errMsg) {\n const closingIndex = xmlData.indexOf(str, i);\n if (closingIndex === -1) {\n throw new Error(errMsg)\n } else {\n return closingIndex + str.length - 1;\n }\n}\n\nfunction findClosingChar(xmlData, char, i, errMsg) {\n const closingIndex = xmlData.indexOf(char, i);\n if (closingIndex === -1) throw new Error(errMsg);\n return closingIndex; // no offset needed\n}\n\nfunction readTagExp(xmlData, i, removeNSPrefix, closingChar = \">\") {\n const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);\n if (!result) return;\n let tagExp = result.data;\n const closeIndex = result.index;\n const separatorIndex = tagExp.search(/\\s/);\n let tagName = tagExp;\n let attrExpPresent = true;\n if (separatorIndex !== -1) {//separate tag name and attributes expression\n tagName = tagExp.substring(0, separatorIndex);\n tagExp = tagExp.substring(separatorIndex + 1).trimStart();\n }\n\n const rawTagName = tagName;\n if (removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n attrExpPresent = tagName !== result.data.substr(colonIndex + 1);\n }\n }\n\n return {\n tagName: tagName,\n tagExp: tagExp,\n closeIndex: closeIndex,\n attrExpPresent: attrExpPresent,\n rawTagName: rawTagName,\n }\n}\n/**\n * find paired tag for a stop node\n * @param {string} xmlData \n * @param {string} tagName \n * @param {number} i \n */\nfunction readStopNodeData(xmlData, tagName, i) {\n const startIndex = i;\n // Starting at 1 since we already have an open tag\n let openTagCount = 1;\n\n const xmllen = xmlData.length;\n for (; i < xmllen; i++) {\n if (xmlData[i] === \"<\") {\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//close tag '/'\n const closeIndex = findClosingChar(xmlData, \">\", i, `${tagName} is not closed`);\n let closeTagName = xmlData.substring(i + 2, closeIndex).trim();\n if (closeTagName === tagName) {\n openTagCount--;\n if (openTagCount === 0) {\n return {\n tagContent: xmlData.substring(startIndex, i),\n i: closeIndex\n }\n }\n }\n i = closeIndex;\n } else if (c1 === 63) { //?\n const closeIndex = findClosingIndex(xmlData, \"?>\", i + 1, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { // '!--'\n const closeIndex = findClosingIndex(xmlData, \"-->\", i + 3, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"StopNode is not closed.\") - 2;\n i = closeIndex;\n } else {\n const tagData = readTagExp(xmlData, i, false)\n\n if (tagData) {\n const openTagName = tagData && tagData.tagName;\n if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== \"/\") {\n openTagCount++;\n }\n i = tagData.closeIndex;\n }\n }\n }\n }//end for loop\n}\n\nfunction parseValue(val, shouldParse, options) {\n if (shouldParse && typeof val === 'string') {\n //console.log(options)\n const newval = val.trim();\n if (newval === 'true') return true;\n else if (newval === 'false') return false;\n else return toNumber(val, options);\n } else {\n if (isExist(val)) {\n return val;\n } else {\n return '';\n }\n }\n}\n\nfunction fromCodePoint(str, base, prefix) {\n const codePoint = Number.parseInt(str, base);\n\n if (codePoint >= 0 && codePoint <= 0x10FFFF) {\n return String.fromCodePoint(codePoint);\n } else {\n return prefix + str + \";\";\n }\n}\n\nfunction transformTagName(fn, tagName, tagExp, options) {\n if (fn) {\n const newTagName = fn(tagName);\n if (tagExp === tagName) {\n tagExp = newTagName\n }\n tagName = newTagName;\n }\n tagName = sanitizeName(tagName, options);\n return { tagName, tagExp };\n}\n\n\n\nfunction sanitizeName(name, options) {\n if (criticalProperties.includes(name)) {\n throw new Error(`[SECURITY] Invalid name: \"${name}\" is a reserved JavaScript keyword that could cause prototype pollution`);\n } else if (DANGEROUS_PROPERTY_NAMES.includes(name)) {\n return options.onDangerousProperty(name);\n }\n return name;\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}","'use strict';\n\nimport XmlNode from './xmlNode.js';\nimport { Matcher } from 'path-expression-matcher';\n\nconst METADATA_SYMBOL = XmlNode.getMetaDataSymbol();\n\n/**\n * Helper function to strip attribute prefix from attribute map\n * @param {object} attrs - Attributes with prefix (e.g., {\"@_class\": \"code\"})\n * @param {string} prefix - Attribute prefix to remove (e.g., \"@_\")\n * @returns {object} Attributes without prefix (e.g., {\"class\": \"code\"})\n */\nfunction stripAttributePrefix(attrs, prefix) {\n if (!attrs || typeof attrs !== 'object') return {};\n if (!prefix) return attrs;\n\n const rawAttrs = {};\n for (const key in attrs) {\n if (key.startsWith(prefix)) {\n const rawName = key.substring(prefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * \n * @param {array} node \n * @param {any} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns \n */\nexport default function prettify(node, options, matcher, readonlyMatcher) {\n return compress(node, options, matcher, readonlyMatcher);\n}\n\n/**\n * @param {array} arr \n * @param {object} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns object\n */\nfunction compress(arr, options, matcher, readonlyMatcher) {\n let text;\n const compressedObj = {}; //This is intended to be a plain object\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const property = propName(tagObj);\n\n // Push current property to matcher WITH RAW ATTRIBUTES (no prefix)\n if (property !== undefined && property !== options.textNodeName) {\n const rawAttrs = stripAttributePrefix(\n tagObj[\":@\"] || {},\n options.attributeNamePrefix\n );\n matcher.push(property, rawAttrs);\n }\n\n if (property === options.textNodeName) {\n if (text === undefined) text = tagObj[property];\n else text += \"\" + tagObj[property];\n } else if (property === undefined) {\n continue;\n } else if (tagObj[property]) {\n\n let val = compress(tagObj[property], options, matcher, readonlyMatcher);\n const isLeaf = isLeafTag(val, options);\n\n if (Object.keys(val).length === 0 && options.alwaysCreateTextNode) {\n val[options.textNodeName] = \"\";\n }\n\n if (tagObj[\":@\"]) {\n assignAttributes(val, tagObj[\":@\"], readonlyMatcher, options);\n } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) {\n val = val[options.textNodeName];\n } else if (Object.keys(val).length === 0) {\n if (options.alwaysCreateTextNode) val[options.textNodeName] = \"\";\n else val = \"\";\n }\n\n if (tagObj[METADATA_SYMBOL] !== undefined && typeof val === \"object\" && val !== null) {\n val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL]; // copy over metadata\n }\n\n\n if (compressedObj[property] !== undefined && Object.prototype.hasOwnProperty.call(compressedObj, property)) {\n if (!Array.isArray(compressedObj[property])) {\n compressedObj[property] = [compressedObj[property]];\n }\n compressedObj[property].push(val);\n } else {\n //TODO: if a node is not an array, then check if it should be an array\n //also determine if it is a leaf node\n\n // Pass jPath string or readonlyMatcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;\n if (options.isArray(property, jPathOrMatcher, isLeaf)) {\n compressedObj[property] = [val];\n } else {\n compressedObj[property] = val;\n }\n }\n\n // Pop property from matcher after processing\n if (property !== undefined && property !== options.textNodeName) {\n matcher.pop();\n }\n }\n\n }\n // if(text && text.length > 0) compressedObj[options.textNodeName] = text;\n if (typeof text === \"string\") {\n if (text.length > 0) compressedObj[options.textNodeName] = text;\n } else if (text !== undefined) compressedObj[options.textNodeName] = text;\n\n\n return compressedObj;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (key !== \":@\") return key;\n }\n}\n\nfunction assignAttributes(obj, attrMap, readonlyMatcher, options) {\n if (attrMap) {\n const keys = Object.keys(attrMap);\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n const atrrName = keys[i]; // This is the PREFIXED name (e.g., \"@_class\")\n\n // Strip prefix for matcher path (for isArray callback)\n const rawAttrName = atrrName.startsWith(options.attributeNamePrefix)\n ? atrrName.substring(options.attributeNamePrefix.length)\n : atrrName;\n\n // For attributes, we need to create a temporary path\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath\n ? readonlyMatcher.toString() + \".\" + rawAttrName\n : readonlyMatcher;\n\n if (options.isArray(atrrName, jPathOrMatcher, true, true)) {\n obj[atrrName] = [attrMap[atrrName]];\n } else {\n obj[atrrName] = attrMap[atrrName];\n }\n }\n }\n}\n\nfunction isLeafTag(obj, options) {\n const { textNodeName } = options;\n const propCount = Object.keys(obj).length;\n\n if (propCount === 0) {\n return true;\n }\n\n if (\n propCount === 1 &&\n (obj[textNodeName] || typeof obj[textNodeName] === \"boolean\" || obj[textNodeName] === 0)\n ) {\n return true;\n }\n\n return false;\n}","'use strict';\n\nimport { getAllMatches, isName } from './util.js';\n\nconst defaultOptions = {\n allowBooleanAttributes: false, //A tag can have attributes without any value\n unpairedTags: []\n};\n\n//const tagsPattern = new RegExp(\"<\\\\/?([\\\\w:\\\\-_\\.]+)\\\\s*\\/?>\",\"g\");\nexport function validate(xmlData, options) {\n options = Object.assign({}, defaultOptions, options);\n\n //xmlData = xmlData.replace(/(\\r\\n|\\n|\\r)/gm,\"\");//make it single line\n //xmlData = xmlData.replace(/(^\\s*<\\?xml.*?\\?>)/g,\"\");//Remove XML starting tag\n //xmlData = xmlData.replace(/()/g,\"\");//Remove DOCTYPE\n const tags = [];\n let tagFound = false;\n\n //indicates that the root tag has been closed (aka. depth 0 has been reached)\n let reachedRoot = false;\n\n if (xmlData[0] === '\\ufeff') {\n // check for byte order mark (BOM)\n xmlData = xmlData.substr(1);\n }\n\n for (let i = 0; i < xmlData.length; i++) {\n\n if (xmlData[i] === '<' && xmlData[i + 1] === '?') {\n i += 2;\n i = readPI(xmlData, i);\n if (i.err) return i;\n } else if (xmlData[i] === '<') {\n //starting of tag\n //read until you reach to '>' avoiding any '>' in attribute value\n let tagStartPos = i;\n i++;\n\n if (xmlData[i] === '!') {\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else {\n let closingTag = false;\n if (xmlData[i] === '/') {\n //closing tag\n closingTag = true;\n i++;\n }\n //read tagname\n let tagName = '';\n for (; i < xmlData.length &&\n xmlData[i] !== '>' &&\n xmlData[i] !== ' ' &&\n xmlData[i] !== '\\t' &&\n xmlData[i] !== '\\n' &&\n xmlData[i] !== '\\r'; i++\n ) {\n tagName += xmlData[i];\n }\n tagName = tagName.trim();\n //console.log(tagName);\n\n if (tagName[tagName.length - 1] === '/') {\n //self closing tag without attributes\n tagName = tagName.substring(0, tagName.length - 1);\n //continue;\n i--;\n }\n if (!validateTagName(tagName)) {\n let msg;\n if (tagName.trim().length === 0) {\n msg = \"Invalid space after '<'.\";\n } else {\n msg = \"Tag '\" + tagName + \"' is an invalid name.\";\n }\n return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));\n }\n\n const result = readAttributeStr(xmlData, i);\n if (result === false) {\n return getErrorObject('InvalidAttr', \"Attributes for '\" + tagName + \"' have open quote.\", getLineNumberForPosition(xmlData, i));\n }\n let attrStr = result.value;\n i = result.index;\n\n if (attrStr[attrStr.length - 1] === '/') {\n //self closing tag\n const attrStrStart = i - attrStr.length;\n attrStr = attrStr.substring(0, attrStr.length - 1);\n const isValid = validateAttributeString(attrStr, options);\n if (isValid === true) {\n tagFound = true;\n //continue; //text may presents after self closing tag\n } else {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));\n }\n } else if (closingTag) {\n if (!result.tagClosed) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' doesn't have proper closing.\", getLineNumberForPosition(xmlData, i));\n } else if (attrStr.trim().length > 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' can't have attributes or invalid starting.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else if (tags.length === 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' has not been opened.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else {\n const otg = tags.pop();\n if (tagName !== otg.tagName) {\n let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);\n return getErrorObject('InvalidTag',\n \"Expected closing tag '\" + otg.tagName + \"' (opened in line \" + openPos.line + \", col \" + openPos.col + \") instead of closing tag '\" + tagName + \"'.\",\n getLineNumberForPosition(xmlData, tagStartPos));\n }\n\n //when there are no more tags, we reached the root level.\n if (tags.length == 0) {\n reachedRoot = true;\n }\n }\n } else {\n const isValid = validateAttributeString(attrStr, options);\n if (isValid !== true) {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));\n }\n\n //if the root level has been reached before ...\n if (reachedRoot === true) {\n return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));\n } else if (options.unpairedTags.indexOf(tagName) !== -1) {\n //don't push into stack\n } else {\n tags.push({ tagName, tagStartPos });\n }\n tagFound = true;\n }\n\n //skip tag text value\n //It may include comments and CDATA value\n for (i++; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n if (xmlData[i + 1] === '!') {\n //comment or CADATA\n i++;\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else if (xmlData[i + 1] === '?') {\n i = readPI(xmlData, ++i);\n if (i.err) return i;\n } else {\n break;\n }\n } else if (xmlData[i] === '&') {\n const afterAmp = validateAmpersand(xmlData, i);\n if (afterAmp == -1)\n return getErrorObject('InvalidChar', \"char '&' is not expected.\", getLineNumberForPosition(xmlData, i));\n i = afterAmp;\n } else {\n if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {\n return getErrorObject('InvalidXml', \"Extra text at the end\", getLineNumberForPosition(xmlData, i));\n }\n }\n } //end of reading tag text value\n if (xmlData[i] === '<') {\n i--;\n }\n }\n } else {\n if (isWhiteSpace(xmlData[i])) {\n continue;\n }\n return getErrorObject('InvalidChar', \"char '\" + xmlData[i] + \"' is not expected.\", getLineNumberForPosition(xmlData, i));\n }\n }\n\n if (!tagFound) {\n return getErrorObject('InvalidXml', 'Start tag expected.', 1);\n } else if (tags.length == 1) {\n return getErrorObject('InvalidTag', \"Unclosed tag '\" + tags[0].tagName + \"'.\", getLineNumberForPosition(xmlData, tags[0].tagStartPos));\n } else if (tags.length > 0) {\n return getErrorObject('InvalidXml', \"Invalid '\" +\n JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\\r?\\n/g, '') +\n \"' found.\", { line: 1, col: 1 });\n }\n\n return true;\n};\n\nfunction isWhiteSpace(char) {\n return char === ' ' || char === '\\t' || char === '\\n' || char === '\\r';\n}\n/**\n * Read Processing insstructions and skip\n * @param {*} xmlData\n * @param {*} i\n */\nfunction readPI(xmlData, i) {\n const start = i;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] == '?' || xmlData[i] == ' ') {\n //tagname\n const tagname = xmlData.substr(start, i - start);\n if (i > 5 && tagname === 'xml') {\n return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));\n } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {\n //check if valid attribut string\n i++;\n break;\n } else {\n continue;\n }\n }\n }\n return i;\n}\n\nfunction readCommentAndCDATA(xmlData, i) {\n if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {\n //comment\n for (i += 3; i < xmlData.length; i++) {\n if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n } else if (\n xmlData.length > i + 8 &&\n xmlData[i + 1] === 'D' &&\n xmlData[i + 2] === 'O' &&\n xmlData[i + 3] === 'C' &&\n xmlData[i + 4] === 'T' &&\n xmlData[i + 5] === 'Y' &&\n xmlData[i + 6] === 'P' &&\n xmlData[i + 7] === 'E'\n ) {\n let angleBracketsCount = 1;\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n angleBracketsCount++;\n } else if (xmlData[i] === '>') {\n angleBracketsCount--;\n if (angleBracketsCount === 0) {\n break;\n }\n }\n }\n } else if (\n xmlData.length > i + 9 &&\n xmlData[i + 1] === '[' &&\n xmlData[i + 2] === 'C' &&\n xmlData[i + 3] === 'D' &&\n xmlData[i + 4] === 'A' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'A' &&\n xmlData[i + 7] === '['\n ) {\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n }\n\n return i;\n}\n\nconst doubleQuote = '\"';\nconst singleQuote = \"'\";\n\n/**\n * Keep reading xmlData until '<' is found outside the attribute value.\n * @param {string} xmlData\n * @param {number} i\n */\nfunction readAttributeStr(xmlData, i) {\n let attrStr = '';\n let startChar = '';\n let tagClosed = false;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {\n if (startChar === '') {\n startChar = xmlData[i];\n } else if (startChar !== xmlData[i]) {\n //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa\n } else {\n startChar = '';\n }\n } else if (xmlData[i] === '>') {\n if (startChar === '') {\n tagClosed = true;\n break;\n }\n }\n attrStr += xmlData[i];\n }\n if (startChar !== '') {\n return false;\n }\n\n return {\n value: attrStr,\n index: i,\n tagClosed: tagClosed\n };\n}\n\n/**\n * Select all the attributes whether valid or invalid.\n */\nconst validAttrStrRegxp = new RegExp('(\\\\s*)([^\\\\s=]+)(\\\\s*=)?(\\\\s*([\\'\"])(([\\\\s\\\\S])*?)\\\\5)?', 'g');\n\n//attr, =\"sd\", a=\"amit's\", a=\"sd\"b=\"saf\", ab cd=\"\"\n\nfunction validateAttributeString(attrStr, options) {\n //console.log(\"start:\"+attrStr+\":end\");\n\n //if(attrStr.trim().length === 0) return true; //empty string\n\n const matches = getAllMatches(attrStr, validAttrStrRegxp);\n const attrNames = {};\n\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][1].length === 0) {\n //nospace before attribute name: a=\"sd\"b=\"saf\"\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' has no space in starting.\", getPositionFromMatch(matches[i]))\n } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' is without value.\", getPositionFromMatch(matches[i]));\n } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {\n //independent attribute: ab\n return getErrorObject('InvalidAttr', \"boolean attribute '\" + matches[i][2] + \"' is not allowed.\", getPositionFromMatch(matches[i]));\n }\n /* else if(matches[i][6] === undefined){//attribute without value: ab=\n return { err: { code:\"InvalidAttr\",msg:\"attribute \" + matches[i][2] + \" has no value assigned.\"}};\n } */\n const attrName = matches[i][2];\n if (!validateAttrName(attrName)) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is an invalid name.\", getPositionFromMatch(matches[i]));\n }\n if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {\n //check for duplicate attribute.\n attrNames[attrName] = 1;\n } else {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is repeated.\", getPositionFromMatch(matches[i]));\n }\n }\n\n return true;\n}\n\nfunction validateNumberAmpersand(xmlData, i) {\n let re = /\\d/;\n if (xmlData[i] === 'x') {\n i++;\n re = /[\\da-fA-F]/;\n }\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === ';')\n return i;\n if (!xmlData[i].match(re))\n break;\n }\n return -1;\n}\n\nfunction validateAmpersand(xmlData, i) {\n // https://www.w3.org/TR/xml/#dt-charref\n i++;\n if (xmlData[i] === ';')\n return -1;\n if (xmlData[i] === '#') {\n i++;\n return validateNumberAmpersand(xmlData, i);\n }\n let count = 0;\n for (; i < xmlData.length; i++, count++) {\n if (xmlData[i].match(/\\w/) && count < 20)\n continue;\n if (xmlData[i] === ';')\n break;\n return -1;\n }\n return i;\n}\n\nfunction getErrorObject(code, message, lineNumber) {\n return {\n err: {\n code: code,\n msg: message,\n line: lineNumber.line || lineNumber,\n col: lineNumber.col,\n },\n };\n}\n\nfunction validateAttrName(attrName) {\n return isName(attrName);\n}\n\n// const startsWithXML = /^xml/i;\n\nfunction validateTagName(tagname) {\n return isName(tagname) /* && !tagname.match(startsWithXML) */;\n}\n\n//this function returns the line number for the character at the given index\nfunction getLineNumberForPosition(xmlData, index) {\n const lines = xmlData.substring(0, index).split(/\\r?\\n/);\n return {\n line: lines.length,\n\n // column number is last line's length + 1, because column numbering starts at 1:\n col: lines[lines.length - 1].length + 1\n };\n}\n\n//this function returns the position of the first character of match within attrStr\nfunction getPositionFromMatch(match) {\n return match.startIndex + match[1].length;\n}\n","import { buildOptions } from './OptionsBuilder.js';\nimport OrderedObjParser from './OrderedObjParser.js';\nimport prettify from './node2json.js';\nimport { validate } from \"../validator.js\";\nimport XmlNode from './xmlNode.js';\n\nexport default class XMLParser {\n\n constructor(options) {\n this.externalEntities = {};\n this.options = buildOptions(options);\n\n }\n /**\n * Parse XML dats to JS object \n * @param {string|Uint8Array} xmlData \n * @param {boolean|Object} validationOption \n */\n parse(xmlData, validationOption) {\n if (typeof xmlData !== \"string\" && xmlData.toString) {\n xmlData = xmlData.toString();\n } else if (typeof xmlData !== \"string\") {\n throw new Error(\"XML data is accepted in String or Bytes[] form.\")\n }\n\n if (validationOption) {\n if (validationOption === true) validationOption = {}; //validate with default options\n\n const result = validate(xmlData, validationOption);\n if (result !== true) {\n throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`)\n }\n }\n const orderedObjParser = new OrderedObjParser(this.options, this.externalEntities);\n // orderedObjParser.entityDecoder.setExternalEntities(this.externalEntities);\n const orderedResult = orderedObjParser.parseXml(xmlData);\n if (this.options.preserveOrder || orderedResult === undefined) return orderedResult;\n else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);\n }\n\n /**\n * Add Entity which is not by default supported by this library\n * @param {string} key \n * @param {string} value \n */\n addEntity(key, value) {\n if (value.indexOf(\"&\") !== -1) {\n throw new Error(\"Entity value can't have '&'\")\n } else if (key.indexOf(\"&\") !== -1 || key.indexOf(\";\") !== -1) {\n throw new Error(\"An entity must be set without '&' and ';'. Eg. use '#xD' for ' '\")\n } else if (value === \"&\") {\n throw new Error(\"An entity with value '&' is not permitted\");\n } else {\n this.externalEntities[key] = value;\n }\n }\n\n /**\n * Returns a Symbol that can be used to access the metadata\n * property on a node.\n * \n * If Symbol is not available in the environment, an ordinary property is used\n * and the name of the property is here returned.\n * \n * The XMLMetaData property is only present when `captureMetaData`\n * is true in the options.\n */\n static getMetaDataSymbol() {\n return XmlNode.getMetaDataSymbol();\n }\n}"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","nameStartChar","regexName","RegExp","getAllMatches","string","regex","matches","match","exec","allmatches","startIndex","lastIndex","length","len","index","push","isName","DANGEROUS_PROPERTY_NAMES","criticalProperties","defaultOnDangerousProperty","name","includes","defaultOptions","preserveOrder","attributeNamePrefix","attributesGroupName","textNodeName","ignoreAttributes","removeNSPrefix","allowBooleanAttributes","parseTagValue","parseAttributeValue","trimValues","cdataPropName","numberParseOptions","hex","leadingZeros","eNotation","unicode","tagValueProcessor","tagName","val","attributeValueProcessor","attrName","stopNodes","alwaysCreateTextNode","isArray","commentPropName","unpairedTags","processEntities","htmlEntities","entityDecoder","ignoreDeclaration","ignorePiTags","transformTagName","transformAttributeName","updateTag","jPath","attrs","captureMetaData","maxNestedTags","strictReservedNames","onDangerousProperty","validatePropertyName","propertyName","optionName","normalized","toLowerCase","some","dangerous","Error","normalizeProcessEntities","enabled","maxEntitySize","maxExpansionDepth","maxTotalExpansions","Infinity","maxExpandedLength","maxEntityCount","allowedTags","tagFilter","appliesTo","Math","max","_value$maxEntitySize","_value$maxExpansionDe","_value$maxTotalExpans","_value$maxExpandedLen","_value$maxEntityCount","_value$allowedTags","_value$tagFilter","_value$appliesTo","METADATA_SYMBOL","buildOptions","options","built","assign","_i","_propertyNameOptions","_propertyNameOptions$","unpairedTagsSet","Set","Array","map","node","startsWith","substring","XmlNode","tagname","child","create","_proto","add","_this$child$push","addChild","_this$child$push2","_this$child$push3","keys","undefined","getMetaDataSymbol","nameStartChar10","nameStartChar11","nameChar11","buildRegexes","startChar","char","flags","ncNamePat","replace","ncName","qName","nmToken","nmTokens","regexes10","regexes11","str","xmlVersion","getRegexes","test","DocTypeReader","suppressValidationErr","setXmlVersion","readDocType","xmlData","i","entities","entityCount","angleBracketsCount","hasBody","comment","hasSeq","entityName","_this$readEntityExp","readEntityExp","indexOf","readElementExp","readNotationExp","skipWhitespace","validateEntityName","toUpperCase","entityValue","_this$readIdentifierV","readIdentifierVal","notationName","identifierType","publicIdentifier","systemIdentifier","_this$readIdentifierV2","_this$readIdentifierV3","_this$readIdentifierV4","type","identifierVal","elementName","contentModel","trim","readAttlistExp","attributeName","attributeType","allowedNotations","notation","join","defaultValue","_this$readIdentifierV5","data","seq","j","SCRIPT_ZEROS","HIGH_MAP","Map","TABLE_OFFSET","TABLE","Uint8Array","LOW_MAX","fill","zero","d","cp","set","MINUS_SET","hexRegex","binRegex","octRegex","numRegex","consider","binary","octal","decimalPoint","infinity","toNumber","trimmedStr","skipLike","firstHit","cc","charCodeAt","has","low","chars","slice","String","fromCharCode","anynum","parse_int","isFinite","eNotationRegx","sign","eChar","eAdjacentToLeadingZeros","Number","resolveEnotation","numTrimmedByZeros","numStr","decimalAdjacentToLeadingZeros","num","parsedStr","search","n","isPositive","handleInfinity","base","parseInt","window","MatcherView","constructor","matcher","_matcher","separator","getCurrentTag","path","tag","getCurrentNamespace","namespace","getAttrValue","values","hasAttr","current","getPosition","position","getCounter","counter","getIndex","getDepth","toString","includeNamespace","toArray","expression","matchesAny","exprSet","Matcher","siblingStacks","_pathStringCache","_view","attrValues","currentLevel","siblings","siblingKey","count","pop","updateCurrent","sep","result","reset","segments","hasDeepWildcard","_matchWithDeepWildcard","_matchSimple","_matchSegment","pathIdx","segIdx","segment","nextSeg","found","isCurrentNode","attrValue","positionValue","snapshot","restore","readOnly","Expression","pattern","_parse","_hasDeepWildcard","seg","_hasAttributeCondition","_hasPositionSelector","currentPart","_parseSegment","part","bracketContent","withoutBrackets","bracketMatch","content","tagAndPosition","nsIndex","positionMatch","colonIndex","lastIndexOf","tagPart","posPart","eqIndex","nthMatch","hasAttributeCondition","hasPositionSelector","ExpressionSet","_byDepthAndTag","_wildcardByDepth","_deepWildcards","_patterns","_sealed","TypeError","depth","lastSeg","addAll","expressions","expr","size","seal","isSealed","findMatch","exactKey","exactBucket","wildcardBucket","CURRENCY","cent","pound","curren","yen","euro","dollar","fnof","inr","af","birr","peso","rub","won","yuan","cedil","XML","amp","apos","gt","lt","quot","COMMON_HTML","nbsp","copy","reg","trade","mdash","ndash","hellip","laquo","raquo","lsquo","rsquo","ldquo","rdquo","bull","para","sect","deg","frac12","frac14","frac34","ENTITY_ACTION","freeze","ALLOW","BLOCK","THROW","SPECIAL_CHARS","ch","mergeEntityMaps","maps","out","raw","LIMIT_TIER_EXTERNAL","LIMIT_TIER_BASE","LIMIT_TIER_ALL","NCR_LEVEL","allow","leave","remove","throw","XML10_ALLOWED_C0","EntityDecoder","_limit","limit","_maxTotalExpansions","_maxExpandedLength","_postCheck","postCheck","r","_limitTiers","applyLimitsTo","_numericAllowed","numericAllowed","_baseMap","DEFAULT_XML_ENTITIES","namedEntities","_externalMap","_inputMap","_totalExpansions","_expandedLength","_removeSet","_leaveSet","ncrCfg","ncr","onLevel","nullLevel","onNCR","nullNCR","parseNCRConfig","_ncrXmlVersion","_ncrOnLevel","_ncrNullLevel","_onExternalEntity","onExternalEntity","_onInputEntity","onInputEntity","_applyRegistrationHook","hook","context","action","setExternalEntities","flat","filtered","entries","addExternalEntity","addInputEntities","version","decode","original","chunks","last","limitExpansions","limitLength","checkLimits","token","replacement","tier","ncrResult","_resolveNCR","resolved","_resolveName","_tierCounts","delta","_classifyNCR","_applyNCRAction","fromCodePoint","padStart","second","isNaN","minimum","effective","id","description","CONTEXT_REGISTRY","HTML","SVG","SQL","SQL_PATTERNS","SHELL","REDOS","NOSQL","LOG","VALID_CONTEXTS","fromEntries","k","matchContext","contextName","patterns","rule","isUnsafe","assertString","c","assertContext","_extends","bind","e","arguments","t","apply","extractRawAttributes","prefixedAttrs","rawAttrs","extractNamespace","rawTagName","ns","OrderedObjParser","externalEntities","currentNode","tagsNodeStack","parseXml","parseTextData","resolveNameSpace","buildAttributesMap","isItStopNode","replaceEntitiesValue","readStopNodeData","saveTextToParentTag","ignoreAttributesFn","_step","_iterator","_createForOfIteratorHelperLoose","done","entityExpansionCount","currentExpandedLength","readonlyMatcher","isCurrentNodeStopNode","stopNodeExpressionsSet","stopNodesOpts","stopNodeExp","dontTrim","hasAttributes","isLeafNode","escapeEntities","jPathOrMatcher","newval","parseValue","tags","split","prefix","charAt","attrsRegx","attrStr","force","processedVals","hasRawAttrs","rawAttrsForMatcher","oldVal","jPathStr","hasAttrs","aName","sanitizeName","newVal","attrCollection","xmlObj","xmlNode","textData","docTypeReader","xmlLen","c1","closeIndex","findClosingIndex","substr","lastTagName","tagData","readTagExp","attsMap","tagExp","ver","childNode","attrExpPresent","endIndex","_ref","_ref2","min","_transformTagName","lastTag","isSelfClosing","tagContent","_transformTagName2","entityConfig","parentNode","errMsg","closingIndex","findClosingChar","closingChar","attrBoundary","closeCode0","closeCode1","segmentStart","code","tagExpWithClosingIndex","separatorIndex","trimStart","openTagCount","xmllen","shouldParse","fn","newTagName","stripAttributePrefix","prettify","compress","arr","text","compressedObj","tagObj","property","propName","isLeaf","isLeafTag","assignAttributes","attrMap","atrrName","rawAttrName","propCount","isWhiteSpace","readPI","start","getErrorObject","getLineNumberForPosition","readCommentAndCDATA","readAttributeStr","tagClosed","validAttrStrRegxp","validateAttributeString","attrNames","getPositionFromMatch","validateAttrName","validateAmpersand","re","validateNumberAmpersand","message","lineNumber","err","msg","line","col","validateTagName","lines","XMLParser","parse","validationOption","tagFound","reachedRoot","tagStartPos","closingTag","attrStrStart","isValid","otg","openPos","afterAmp","JSON","stringify","validate","orderedObjParser","orderedResult","addEntity"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/lib/fxvalidator.min.js b/node_modules/fast-xml-parser/lib/fxvalidator.min.js new file mode 100644 index 0000000000000000000000000000000000000000..5d0215b7663e453785cd21f0b0ef46429419915d --- /dev/null +++ b/node_modules/fast-xml-parser/lib/fxvalidator.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.XMLValidator=t():e.XMLValidator=t()}(this,()=>(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{validate:()=>l});var r=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=new RegExp("^["+r+"]["+r+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),i=function(e){return!(null==n.exec(e))},a={allowBooleanAttributes:!1,unpairedTags:[]};function l(e,t){t=Object.assign({},a,t);var r=[],n=!1,i=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(var l=0;l"!==e[l]&&" "!==e[l]&&"\t"!==e[l]&&"\n"!==e[l]&&"\r"!==e[l];l++)v+=e[l];if("/"===(v=v.trim())[v.length-1]&&(v=v.substring(0,v.length-1),l--),!m(v))return p("InvalidTag",0===v.trim().length?"Invalid space after '<'.":"Tag '"+v+"' is an invalid name.",F(e,l));var b=d(e,l);if(!1===b)return p("InvalidAttr","Attributes for '"+v+"' have open quote.",F(e,l));var I=b.value;if(l=b.index,"/"===I[I.length-1]){var x=l-I.length,y=c(I=I.substring(0,I.length-1),t);if(!0!==y)return p(y.err.code,y.err.msg,F(e,x+y.err.line));n=!0}else if(g){if(!b.tagClosed)return p("InvalidTag","Closing tag '"+v+"' doesn't have proper closing.",F(e,l));if(I.trim().length>0)return p("InvalidTag","Closing tag '"+v+"' can't have attributes or invalid starting.",F(e,s));if(0===r.length)return p("InvalidTag","Closing tag '"+v+"' has not been opened.",F(e,s));var A=r.pop();if(v!==A.tagName){var C=F(e,A.tagStartPos);return p("InvalidTag","Expected closing tag '"+A.tagName+"' (opened in line "+C.line+", col "+C.col+") instead of closing tag '"+v+"'.",F(e,s))}0==r.length&&(i=!0)}else{var T=c(I,t);if(!0!==T)return p(T.err.code,T.err.msg,F(e,l-I.length+T.err.line));if(!0===i)return p("InvalidXml","Multiple possible root nodes found.",F(e,l));-1!==t.unpairedTags.indexOf(v)||r.push({tagName:v,tagStartPos:s}),n=!0}for(l++;l0)||p("InvalidXml","Invalid '"+JSON.stringify(r.map(function(e){return e.tagName}),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):p("InvalidXml","Start tag expected.",1)}function o(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function u(e,t){for(var r=t;t5&&"xml"===n)return p("InvalidXml","XML declaration allowed only at the start of the document.",F(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}}return t}function f(e,t){if(e.length>t+5&&"-"===e[t+1]&&"-"===e[t+2]){for(t+=3;t"===e[t+2]){t+=2;break}}else if(e.length>t+8&&"D"===e[t+1]&&"O"===e[t+2]&&"C"===e[t+3]&&"T"===e[t+4]&&"Y"===e[t+5]&&"P"===e[t+6]&&"E"===e[t+7]){var r=1;for(t+=8;t"===e[t]&&0===--r)break}else if(e.length>t+9&&"["===e[t+1]&&"C"===e[t+2]&&"D"===e[t+3]&&"A"===e[t+4]&&"T"===e[t+5]&&"A"===e[t+6]&&"["===e[t+7])for(t+=8;t"===e[t+2]){t+=2;break}return t}var s='"',g="'";function d(e,t){for(var r="",n="",i=!1;t"===e[t]&&""===n){i=!0;break}r+=e[t]}return""===n&&{value:r,index:t,tagClosed:i}}var v=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function c(e,t){for(var r=function(e,t){for(var r=[],n=t.exec(e);n;){var i=[];i.startIndex=t.lastIndex-n[0].length;for(var a=n.length,l=0;l {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","'use strict';\n\nconst nameStartChar = ':A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD';\nconst nameChar = nameStartChar + '\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040';\nexport const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*';\nconst regexName = new RegExp('^' + nameRegexp + '$');\n\nexport function getAllMatches(string, regex) {\n const matches = [];\n let match = regex.exec(string);\n while (match) {\n const allmatches = [];\n allmatches.startIndex = regex.lastIndex - match[0].length;\n const len = match.length;\n for (let index = 0; index < len; index++) {\n allmatches.push(match[index]);\n }\n matches.push(allmatches);\n match = regex.exec(string);\n }\n return matches;\n}\n\nexport const isName = function (string) {\n const match = regexName.exec(string);\n return !(match === null || typeof match === 'undefined');\n}\n\nexport function isExist(v) {\n return typeof v !== 'undefined';\n}\n\nexport function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\nexport function getValue(v) {\n if (exports.isExist(v)) {\n return v;\n } else {\n return '';\n }\n}\n\n/**\n * Dangerous property names that could lead to prototype pollution or security issues\n */\nexport const DANGEROUS_PROPERTY_NAMES = [\n // '__proto__',\n // 'constructor',\n // 'prototype',\n 'hasOwnProperty',\n 'toString',\n 'valueOf',\n '__defineGetter__',\n '__defineSetter__',\n '__lookupGetter__',\n '__lookupSetter__'\n];\n\nexport const criticalProperties = [\"__proto__\", \"constructor\", \"prototype\"];","'use strict';\n\nimport { getAllMatches, isName } from './util.js';\n\nconst defaultOptions = {\n allowBooleanAttributes: false, //A tag can have attributes without any value\n unpairedTags: []\n};\n\n//const tagsPattern = new RegExp(\"<\\\\/?([\\\\w:\\\\-_\\.]+)\\\\s*\\/?>\",\"g\");\nexport function validate(xmlData, options) {\n options = Object.assign({}, defaultOptions, options);\n\n //xmlData = xmlData.replace(/(\\r\\n|\\n|\\r)/gm,\"\");//make it single line\n //xmlData = xmlData.replace(/(^\\s*<\\?xml.*?\\?>)/g,\"\");//Remove XML starting tag\n //xmlData = xmlData.replace(/()/g,\"\");//Remove DOCTYPE\n const tags = [];\n let tagFound = false;\n\n //indicates that the root tag has been closed (aka. depth 0 has been reached)\n let reachedRoot = false;\n\n if (xmlData[0] === '\\ufeff') {\n // check for byte order mark (BOM)\n xmlData = xmlData.substr(1);\n }\n\n for (let i = 0; i < xmlData.length; i++) {\n\n if (xmlData[i] === '<' && xmlData[i + 1] === '?') {\n i += 2;\n i = readPI(xmlData, i);\n if (i.err) return i;\n } else if (xmlData[i] === '<') {\n //starting of tag\n //read until you reach to '>' avoiding any '>' in attribute value\n let tagStartPos = i;\n i++;\n\n if (xmlData[i] === '!') {\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else {\n let closingTag = false;\n if (xmlData[i] === '/') {\n //closing tag\n closingTag = true;\n i++;\n }\n //read tagname\n let tagName = '';\n for (; i < xmlData.length &&\n xmlData[i] !== '>' &&\n xmlData[i] !== ' ' &&\n xmlData[i] !== '\\t' &&\n xmlData[i] !== '\\n' &&\n xmlData[i] !== '\\r'; i++\n ) {\n tagName += xmlData[i];\n }\n tagName = tagName.trim();\n //console.log(tagName);\n\n if (tagName[tagName.length - 1] === '/') {\n //self closing tag without attributes\n tagName = tagName.substring(0, tagName.length - 1);\n //continue;\n i--;\n }\n if (!validateTagName(tagName)) {\n let msg;\n if (tagName.trim().length === 0) {\n msg = \"Invalid space after '<'.\";\n } else {\n msg = \"Tag '\" + tagName + \"' is an invalid name.\";\n }\n return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));\n }\n\n const result = readAttributeStr(xmlData, i);\n if (result === false) {\n return getErrorObject('InvalidAttr', \"Attributes for '\" + tagName + \"' have open quote.\", getLineNumberForPosition(xmlData, i));\n }\n let attrStr = result.value;\n i = result.index;\n\n if (attrStr[attrStr.length - 1] === '/') {\n //self closing tag\n const attrStrStart = i - attrStr.length;\n attrStr = attrStr.substring(0, attrStr.length - 1);\n const isValid = validateAttributeString(attrStr, options);\n if (isValid === true) {\n tagFound = true;\n //continue; //text may presents after self closing tag\n } else {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));\n }\n } else if (closingTag) {\n if (!result.tagClosed) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' doesn't have proper closing.\", getLineNumberForPosition(xmlData, i));\n } else if (attrStr.trim().length > 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' can't have attributes or invalid starting.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else if (tags.length === 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' has not been opened.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else {\n const otg = tags.pop();\n if (tagName !== otg.tagName) {\n let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);\n return getErrorObject('InvalidTag',\n \"Expected closing tag '\" + otg.tagName + \"' (opened in line \" + openPos.line + \", col \" + openPos.col + \") instead of closing tag '\" + tagName + \"'.\",\n getLineNumberForPosition(xmlData, tagStartPos));\n }\n\n //when there are no more tags, we reached the root level.\n if (tags.length == 0) {\n reachedRoot = true;\n }\n }\n } else {\n const isValid = validateAttributeString(attrStr, options);\n if (isValid !== true) {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));\n }\n\n //if the root level has been reached before ...\n if (reachedRoot === true) {\n return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));\n } else if (options.unpairedTags.indexOf(tagName) !== -1) {\n //don't push into stack\n } else {\n tags.push({ tagName, tagStartPos });\n }\n tagFound = true;\n }\n\n //skip tag text value\n //It may include comments and CDATA value\n for (i++; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n if (xmlData[i + 1] === '!') {\n //comment or CADATA\n i++;\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else if (xmlData[i + 1] === '?') {\n i = readPI(xmlData, ++i);\n if (i.err) return i;\n } else {\n break;\n }\n } else if (xmlData[i] === '&') {\n const afterAmp = validateAmpersand(xmlData, i);\n if (afterAmp == -1)\n return getErrorObject('InvalidChar', \"char '&' is not expected.\", getLineNumberForPosition(xmlData, i));\n i = afterAmp;\n } else {\n if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {\n return getErrorObject('InvalidXml', \"Extra text at the end\", getLineNumberForPosition(xmlData, i));\n }\n }\n } //end of reading tag text value\n if (xmlData[i] === '<') {\n i--;\n }\n }\n } else {\n if (isWhiteSpace(xmlData[i])) {\n continue;\n }\n return getErrorObject('InvalidChar', \"char '\" + xmlData[i] + \"' is not expected.\", getLineNumberForPosition(xmlData, i));\n }\n }\n\n if (!tagFound) {\n return getErrorObject('InvalidXml', 'Start tag expected.', 1);\n } else if (tags.length == 1) {\n return getErrorObject('InvalidTag', \"Unclosed tag '\" + tags[0].tagName + \"'.\", getLineNumberForPosition(xmlData, tags[0].tagStartPos));\n } else if (tags.length > 0) {\n return getErrorObject('InvalidXml', \"Invalid '\" +\n JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\\r?\\n/g, '') +\n \"' found.\", { line: 1, col: 1 });\n }\n\n return true;\n};\n\nfunction isWhiteSpace(char) {\n return char === ' ' || char === '\\t' || char === '\\n' || char === '\\r';\n}\n/**\n * Read Processing insstructions and skip\n * @param {*} xmlData\n * @param {*} i\n */\nfunction readPI(xmlData, i) {\n const start = i;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] == '?' || xmlData[i] == ' ') {\n //tagname\n const tagname = xmlData.substr(start, i - start);\n if (i > 5 && tagname === 'xml') {\n return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));\n } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {\n //check if valid attribut string\n i++;\n break;\n } else {\n continue;\n }\n }\n }\n return i;\n}\n\nfunction readCommentAndCDATA(xmlData, i) {\n if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {\n //comment\n for (i += 3; i < xmlData.length; i++) {\n if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n } else if (\n xmlData.length > i + 8 &&\n xmlData[i + 1] === 'D' &&\n xmlData[i + 2] === 'O' &&\n xmlData[i + 3] === 'C' &&\n xmlData[i + 4] === 'T' &&\n xmlData[i + 5] === 'Y' &&\n xmlData[i + 6] === 'P' &&\n xmlData[i + 7] === 'E'\n ) {\n let angleBracketsCount = 1;\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n angleBracketsCount++;\n } else if (xmlData[i] === '>') {\n angleBracketsCount--;\n if (angleBracketsCount === 0) {\n break;\n }\n }\n }\n } else if (\n xmlData.length > i + 9 &&\n xmlData[i + 1] === '[' &&\n xmlData[i + 2] === 'C' &&\n xmlData[i + 3] === 'D' &&\n xmlData[i + 4] === 'A' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'A' &&\n xmlData[i + 7] === '['\n ) {\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n }\n\n return i;\n}\n\nconst doubleQuote = '\"';\nconst singleQuote = \"'\";\n\n/**\n * Keep reading xmlData until '<' is found outside the attribute value.\n * @param {string} xmlData\n * @param {number} i\n */\nfunction readAttributeStr(xmlData, i) {\n let attrStr = '';\n let startChar = '';\n let tagClosed = false;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {\n if (startChar === '') {\n startChar = xmlData[i];\n } else if (startChar !== xmlData[i]) {\n //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa\n } else {\n startChar = '';\n }\n } else if (xmlData[i] === '>') {\n if (startChar === '') {\n tagClosed = true;\n break;\n }\n }\n attrStr += xmlData[i];\n }\n if (startChar !== '') {\n return false;\n }\n\n return {\n value: attrStr,\n index: i,\n tagClosed: tagClosed\n };\n}\n\n/**\n * Select all the attributes whether valid or invalid.\n */\nconst validAttrStrRegxp = new RegExp('(\\\\s*)([^\\\\s=]+)(\\\\s*=)?(\\\\s*([\\'\"])(([\\\\s\\\\S])*?)\\\\5)?', 'g');\n\n//attr, =\"sd\", a=\"amit's\", a=\"sd\"b=\"saf\", ab cd=\"\"\n\nfunction validateAttributeString(attrStr, options) {\n //console.log(\"start:\"+attrStr+\":end\");\n\n //if(attrStr.trim().length === 0) return true; //empty string\n\n const matches = getAllMatches(attrStr, validAttrStrRegxp);\n const attrNames = {};\n\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][1].length === 0) {\n //nospace before attribute name: a=\"sd\"b=\"saf\"\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' has no space in starting.\", getPositionFromMatch(matches[i]))\n } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' is without value.\", getPositionFromMatch(matches[i]));\n } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {\n //independent attribute: ab\n return getErrorObject('InvalidAttr', \"boolean attribute '\" + matches[i][2] + \"' is not allowed.\", getPositionFromMatch(matches[i]));\n }\n /* else if(matches[i][6] === undefined){//attribute without value: ab=\n return { err: { code:\"InvalidAttr\",msg:\"attribute \" + matches[i][2] + \" has no value assigned.\"}};\n } */\n const attrName = matches[i][2];\n if (!validateAttrName(attrName)) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is an invalid name.\", getPositionFromMatch(matches[i]));\n }\n if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {\n //check for duplicate attribute.\n attrNames[attrName] = 1;\n } else {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is repeated.\", getPositionFromMatch(matches[i]));\n }\n }\n\n return true;\n}\n\nfunction validateNumberAmpersand(xmlData, i) {\n let re = /\\d/;\n if (xmlData[i] === 'x') {\n i++;\n re = /[\\da-fA-F]/;\n }\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === ';')\n return i;\n if (!xmlData[i].match(re))\n break;\n }\n return -1;\n}\n\nfunction validateAmpersand(xmlData, i) {\n // https://www.w3.org/TR/xml/#dt-charref\n i++;\n if (xmlData[i] === ';')\n return -1;\n if (xmlData[i] === '#') {\n i++;\n return validateNumberAmpersand(xmlData, i);\n }\n let count = 0;\n for (; i < xmlData.length; i++, count++) {\n if (xmlData[i].match(/\\w/) && count < 20)\n continue;\n if (xmlData[i] === ';')\n break;\n return -1;\n }\n return i;\n}\n\nfunction getErrorObject(code, message, lineNumber) {\n return {\n err: {\n code: code,\n msg: message,\n line: lineNumber.line || lineNumber,\n col: lineNumber.col,\n },\n };\n}\n\nfunction validateAttrName(attrName) {\n return isName(attrName);\n}\n\n// const startsWithXML = /^xml/i;\n\nfunction validateTagName(tagname) {\n return isName(tagname) /* && !tagname.match(startsWithXML) */;\n}\n\n//this function returns the line number for the character at the given index\nfunction getLineNumberForPosition(xmlData, index) {\n const lines = xmlData.substring(0, index).split(/\\r?\\n/);\n return {\n line: lines.length,\n\n // column number is last line's length + 1, because column numbering starts at 1:\n col: lines[lines.length - 1].length + 1\n };\n}\n\n//this function returns the position of the first character of match within attrStr\nfunction getPositionFromMatch(match) {\n return match.startIndex + match[1].length;\n}\n"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","nameStartChar","regexName","RegExp","isName","string","exec","defaultOptions","allowBooleanAttributes","unpairedTags","validate","xmlData","options","assign","tags","tagFound","reachedRoot","substr","i","length","readPI","err","isWhiteSpace","getErrorObject","getLineNumberForPosition","tagStartPos","readCommentAndCDATA","closingTag","tagName","trim","substring","validateTagName","result","readAttributeStr","attrStr","index","attrStrStart","isValid","validateAttributeString","code","msg","line","tagClosed","otg","pop","openPos","col","indexOf","push","afterAmp","validateAmpersand","JSON","stringify","map","t","replace","char","start","tagname","angleBracketsCount","doubleQuote","singleQuote","startChar","validAttrStrRegxp","matches","regex","match","allmatches","startIndex","lastIndex","len","getAllMatches","attrNames","getPositionFromMatch","undefined","attrName","validateAttrName","re","validateNumberAmpersand","count","message","lineNumber","lines","split"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/package.json b/node_modules/fast-xml-parser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..576337fa777807e9ab0cca9f892799a764049650 --- /dev/null +++ b/node_modules/fast-xml-parser/package.json @@ -0,0 +1,96 @@ +{ + "name": "fast-xml-parser", + "version": "5.9.0", + "description": "Validate XML, Parse XML, Build XML without C/C++ based libraries", + "main": "./lib/fxp.cjs", + "type": "module", + "sideEffects": false, + "module": "./src/fxp.js", + "types": "./src/fxp.d.ts", + "exports": { + ".": { + "import": { + "types": "./src/fxp.d.ts", + "default": "./src/fxp.js" + }, + "require": { + "types": "./lib/fxp.d.cts", + "default": "./lib/fxp.cjs" + } + } + }, + "scripts": { + "test": "c8 --reporter=lcov --reporter=text jasmine spec/*spec.js", + "test-types": "tsc --noEmit spec/typings/typings-test.ts", + "unit": "jasmine", + "perf": "node ./benchmark/perfTest3.js", + "lint": "eslint src/**/*.js spec/**/*.js benchmark/**/*.js", + "bundle": "webpack --config webpack.cjs.config.js", + "prettier": "prettier --write src/**/*.js", + "checkReadiness": "publish-please --dry-run", + "publish-please": "publish-please", + "prepublishOnly": "publish-please guard" + }, + "bin": { + "fxparser": "src/cli/cli.js" + }, + "files": [ + "lib", + "src", + "CHANGELOG.md" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/NaturalIntelligence/fast-xml-parser.git" + }, + "keywords": [ + "fast", + "xml", + "json", + "parser", + "xml2js", + "x2js", + "xml2json", + "js", + "validator", + "validate", + "transformer", + "assert", + "js2xml", + "json2xml", + "html" + ], + "author": "Amit Gupta (https://solothought.com)", + "license": "MIT", + "devDependencies": { + "@babel/core": "^7.13.10", + "@babel/plugin-transform-runtime": "^7.13.10", + "@babel/preset-env": "^7.13.10", + "@babel/register": "^7.13.8", + "@byspec/xml": "^0.1.0", + "@types/node": "20", + "babel-loader": "^8.2.2", + "c8": "^10.1.3", + "eslint": "^8.3.0", + "jasmine": "^5.6.0", + "prettier": "^3.5.1", + "publish-please": "^5.5.2", + "typescript": "5", + "webpack": "^5.64.4", + "webpack-cli": "^4.9.1" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "dependencies": { + "@nodable/entities": "^2.2.0", + "fast-xml-builder": "^1.2.0", + "is-unsafe": "^1.0.1", + "path-expression-matcher": "^1.5.0", + "strnum": "^2.4.0", + "xml-naming": "^0.1.0" + } +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/cli/cli.js b/node_modules/fast-xml-parser/src/cli/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..b4773e40362211ccd6b227bcfa836b4a4f5ba8e3 --- /dev/null +++ b/node_modules/fast-xml-parser/src/cli/cli.js @@ -0,0 +1,97 @@ +#!/usr/bin/env node +'use strict'; +/*eslint-disable no-console*/ +import fs from 'fs'; +import { resolve } from 'path'; +import {XMLParser, XMLValidator} from "../fxp.js"; +import ReadToEnd from './read.js'; +import cmdDetail from "./man.js" + +console.warn("\x1b[33m%s\x1b[0m", "⚠️ Warning: The built-in CLI interface is now deprecated."); +console.warn("Please install the dedicated CLI package instead:"); +console.warn(" npm install -g fxp-cli"); + +if (process.argv[2] === '--help' || process.argv[2] === '-h') { + console.log(cmdDetail); +} else if (process.argv[2] === '--version') { + const packageJsonPath = resolve(process.cwd(), 'package.json'); + const version = JSON.parse(fs.readFileSync(packageJsonPath).toString()).version; + console.log(version); +} else { + const options = { + removeNSPrefix: true, + ignoreAttributes: false, + parseTagValue: true, + parseAttributeValue: true, + }; + let fileName = ''; + let outputFileName; + let validate = false; + let validateOnly = false; + for (let i = 2; i < process.argv.length; i++) { + if (process.argv[i] === '-ns') { + options.removeNSPrefix = false; + } else if (process.argv[i] === '-a') { + options.ignoreAttributes = true; + } else if (process.argv[i] === '-c') { + options.parseTagValue = false; + options.parseAttributeValue = false; + } else if (process.argv[i] === '-o') { + outputFileName = process.argv[++i]; + } else if (process.argv[i] === '-v') { + validate = true; + } else if (process.argv[i] === '-V') { + validateOnly = true; + } else { + //filename + fileName = process.argv[i]; + } + } + + const callback = function(xmlData) { + let output = ''; + if (validateOnly) { + output = XMLValidator.validate(xmlData); + process.exitCode = output === true ? 0 : 1; + } else { + const parser = new XMLParser(options); + output = JSON.stringify(parser.parse(xmlData,validate), null, 4); + } + if (outputFileName) { + writeToFile(outputFileName, output); + } else { + console.log(output); + } + }; + + + try { + + if (!fileName) { + ReadToEnd.readToEnd(process.stdin, function(err, data) { + if (err) { + throw err; + } + callback(data.toString()); + }); + } else { + fs.readFile(fileName, function(err, data) { + if (err) { + throw err; + } + callback(data.toString()); + }); + } + } catch (e) { + console.log('Seems an invalid file or stream.' + e); + } +} + +function writeToFile(fileName, data) { + fs.writeFile(fileName, data, function(err) { + if (err) { + throw err; + } + console.log('JSON output has been written to ' + fileName); + }); +} diff --git a/node_modules/fast-xml-parser/src/cli/man.js b/node_modules/fast-xml-parser/src/cli/man.js new file mode 100644 index 0000000000000000000000000000000000000000..418ea3d68497d3acf1fc57bafd9b5d6019fb4824 --- /dev/null +++ b/node_modules/fast-xml-parser/src/cli/man.js @@ -0,0 +1,17 @@ +import fs from 'fs'; +import { resolve } from 'path'; +const packageJsonPath = resolve(process.cwd(), 'package.json'); +const version = JSON.parse(fs.readFileSync(packageJsonPath).toString()).version; + +export default `Fast XML Parser ${version} +---------------- +$ fxparser [-ns|-a|-c|-v|-V] [-o outputfile.json] +$ cat xmlfile.xml | fxparser [-ns|-a|-c|-v|-V] [-o outputfile.json] + +Options +---------------- +-ns: remove namespace from tag and atrribute name. +-a: don't parse attributes. +-c: parse values to premitive type. +-v: validate before parsing. +-V: validate only.` \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/cli/read.js b/node_modules/fast-xml-parser/src/cli/read.js new file mode 100644 index 0000000000000000000000000000000000000000..99a20669cc74835f50abc473413de4559d6466d5 --- /dev/null +++ b/node_modules/fast-xml-parser/src/cli/read.js @@ -0,0 +1,43 @@ +'use strict'; + +import { Transform } from 'stream'; + +export default class ReadToEnd extends Transform { + constructor(options = {}) { + super(options); + this._encoding = options.encoding || 'utf8'; + this._buffer = ''; + } + + _transform(chunk, encoding, done) { + this._buffer += chunk.toString(this._encoding); + this.push(chunk); + done(); + } + + _flush(done) { + this.emit('complete', null, this._buffer); + done(); + } + + static readToEnd(stream, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + const dest = new ReadToEnd(options); + + stream.pipe(dest); + + stream.on('error', (err) => { + stream.unpipe(dest); + callback(err); + }); + + dest.on('complete', callback); + dest.resume(); + + return dest; + } +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/fxp.d.ts b/node_modules/fast-xml-parser/src/fxp.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..167ff4a178610a76bcf797a05796ab9279c38720 --- /dev/null +++ b/node_modules/fast-xml-parser/src/fxp.d.ts @@ -0,0 +1,752 @@ +/** + * Types copied from path-expression-matcher + * @version + * @updated + * + * Update this file when path-expression-matcher releases a new version. + * Source: https://github.com/NaturalIntelligence/path-expression-matcher + */ + +/** + * Options for creating an Expression + */ +export interface ExpressionOptions { + /** + * Path separator character + * @default '.' + */ + separator?: string; +} + +/** + * Parsed segment from an expression pattern + */ +export interface Segment { + type: 'tag' | 'deep-wildcard'; + tag?: string; + namespace?: string; + attrName?: string; + attrValue?: string; + position?: 'first' | 'last' | 'odd' | 'even' | 'nth'; + positionValue?: number; +} + +/** + * Expression - Parses and stores a tag pattern expression. + * Patterns are parsed once and stored in an optimized structure for fast matching. + * + * @example + * ```typescript + * const expr = new Expression("root.users.user"); + * const expr2 = new Expression("..user[id]:first"); + * const expr3 = new Expression("root/users/user", { separator: '/' }); + * ``` + * + * Pattern Syntax: + * - `root.users.user` — Match exact path + * - `..user` — Match "user" at any depth (deep wildcard) + * - `user[id]` — Match user tag with "id" attribute + * - `user[id=123]` — Match user tag where id="123" + * - `user:first` — Match first occurrence of user tag + * - `ns::user` — Match user tag with namespace "ns" + * - `ns::user[id]:first` — Combine namespace, attribute, and position + */ +export class Expression { + readonly pattern: string; + readonly separator: string; + readonly segments: Segment[]; + + constructor(pattern: string, options?: ExpressionOptions); + + get length(): number; + hasDeepWildcard(): boolean; + hasAttributeCondition(): boolean; + hasPositionSelector(): boolean; + toString(): string; +} + +// --------------------------------------------------------------------------- +// MatcherView +// --------------------------------------------------------------------------- + +/** + * A lightweight, live read-only view of a Matcher instance. + * + * Returned by `Matcher.readOnly()`. The same instance is reused across every + * callback invocation — no allocation overhead per call. Reads directly from + * the parent Matcher's internal state so it always reflects the current parser + * position with no copying or freezing. + * + * Mutation methods (`push`, `pop`, `reset`, `updateCurrent`, `restore`) are + * simply absent — misuse is caught at compile time by TypeScript. + * + * This is the type received by all FXP user callbacks when `jPath: false`. + */ +export class MatcherView { + readonly separator: string; + + /** Check if current path matches an Expression. */ + matches(expression: Expression): boolean; + + /** Get current tag name, or `undefined` if path is empty. */ + getCurrentTag(): string | undefined; + + /** Get current namespace, or `undefined` if not present. */ + getCurrentNamespace(): string | undefined; + + /** Get attribute value of the current node. */ + getAttrValue(attrName: string): any; + + /** Check if the current node has a given attribute. */ + hasAttr(attrName: string): boolean; + + /** Sibling position of the current node (child index in parent). */ + getPosition(): number; + + /** Occurrence counter of the current tag name at this level. */ + getCounter(): number; + + /** Number of nodes in the current path. */ + getDepth(): number; + + /** Current path as a string (e.g. `"root.users.user"`). */ + toString(separator?: string, includeNamespace?: boolean): string; + + /** Current path as an array of tag names. */ + toArray(): string[]; +} + +/** + * @deprecated Use {@link MatcherView} instead. + * Alias kept for backward compatibility. + */ +export type ReadonlyMatcher = MatcherView; + +/** Internal node structure — exposed via snapshot only. */ +export interface PathNode { + tag: string; + namespace?: string; + position: number; + counter: number; + values?: Record; +} + +/** Snapshot of matcher state returned by `snapshot()` and `readOnly().snapshot()`. */ +export interface MatcherSnapshot { + path: PathNode[]; + siblingStacks: Map[]; +} + +/********************************************************************** + * + * END of path-expression-matcher relevant typings + * + **********************************************************************/ + +// jPath: true → string +// jPath: false → MatcherView +type JPathOrMatcher = string | MatcherView; +type JPathOrExpression = string | Expression; + +export type ProcessEntitiesOptions = { + /** + * Whether to enable entity processing + * + * Defaults to `true` + */ + enabled?: boolean; + + /** + * Maximum size in characters for a single entity definition + * + * Defaults to `10000` + */ + maxEntitySize?: number; + + /** + * Maximum depth for nested entity references (reserved for future use) + * + * Defaults to `10` + */ + maxExpansionDepth?: number; + + /** + * Maximum total number of entity expansions allowed + * + * Defaults to `1000` + */ + maxTotalExpansions?: number; + + /** + * Maximum total expanded content length in characters + * + * Defaults to `100000` + */ + maxExpandedLength?: number; + + /** + * Maximum number of entities allowed in the XML + * + * Defaults to `100` + */ + maxEntityCount?: number; + + /** + * Array of tag names where entity replacement is allowed. + * If null, entities are replaced in all tags. + * + * Defaults to `null` + */ + allowedTags?: string[] | null; + + /** + * Custom filter function to determine if entities should be replaced in a tag + * + * @param tagName - The name of the current tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @returns `true` to allow entity replacement, `false` to skip + * + * Defaults to `null` + */ + tagFilter?: ((tagName: string, jPathOrMatcher: JPathOrMatcher) => boolean) | null; +}; + +export type EntityDecoderOptions = { + setExternalEntities: (entities: Record) => void; + addInputEntities: (entities: Record) => void; + reset: () => void; + decode: (text: string) => string; + setXmlVersion: (version: string) => void; +} + +export type X2jOptions = { + /** + * Preserve the order of tags in resulting JS object + * + * Defaults to `false` + */ + preserveOrder?: boolean; + + /** + * Give a prefix to the attribute name in the resulting JS object + * + * Defaults to '@_' + */ + attributeNamePrefix?: string; + + /** + * A name to group all attributes of a tag under, or `false` to disable + * + * Defaults to `false` + */ + attributesGroupName?: false | string; + + /** + * The name of the next node in the resulting JS + * + * Defaults to `#text` + */ + textNodeName?: string; + + /** + * Whether to ignore attributes when parsing + * + * When `true` - ignores all the attributes + * + * When `false` - parses all the attributes + * + * When `Array` - filters out attributes that match provided patterns + * + * When `Function` - calls the function for each attribute and filters out those for which the function returned `true` + * + * Defaults to `true` + */ + ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPathOrMatcher: JPathOrMatcher) => boolean); + + /** + * Whether to remove namespace string from tag and attribute names + * + * Defaults to `false` + */ + removeNSPrefix?: boolean; + + /** + * Whether to allow attributes without value + * + * Defaults to `false` + */ + allowBooleanAttributes?: boolean; + + /** + * Whether to parse tag value with `strnum` package + * + * Defaults to `true` + */ + parseTagValue?: boolean; + + /** + * Whether to parse attribute value with `strnum` package + * + * Defaults to `false` + */ + parseAttributeValue?: boolean; + + /** + * Whether to remove surrounding whitespace from tag or attribute value + * + * Defaults to `true` + */ + trimValues?: boolean; + + /** + * Give a property name to set CDATA values to instead of merging to tag's text value + * + * Defaults to `false` + */ + cdataPropName?: false | string; + + /** + * If set, parse comments and set as this property + * + * Defaults to `false` + */ + commentPropName?: false | string; + + /** + * Control how tag value should be parsed. Called only if tag value is not empty + * + * @param tagName - The name of the tag + * @param tagValue - The value of the tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @param hasAttributes - Whether the tag has attributes + * @param isLeafNode - Whether the tag is a leaf node + * @returns {undefined|null} `undefined` or `null` to set original value. + * @returns {unknown} + * + * 1. Different value or value with different data type to set new value. + * 2. Same value to set parsed value if `parseTagValue: true`. + * + * Defaults to `(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode) => val` + */ + tagValueProcessor?: (tagName: string, tagValue: string, jPathOrMatcher: JPathOrMatcher, hasAttributes: boolean, isLeafNode: boolean) => unknown; + + /** + * Control how attribute value should be parsed + * + * @param attrName - The name of the attribute + * @param attrValue - The value of the attribute + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @returns {undefined|null} `undefined` or `null` to set original value + * @returns {unknown} + * + * Defaults to `(attrName, val, jPathOrMatcher) => val` + */ + attributeValueProcessor?: (attrName: string, attrValue: string, jPathOrMatcher: JPathOrMatcher) => unknown; + + /** + * Options to pass to `strnum` for parsing numbers + * + * Defaults to `{ hex: true, leadingZeros: true, eNotation: true }` + */ + numberParseOptions?: strnumOptions; + + /** + * Nodes to stop parsing at + * + * Accepts string patterns or Expression objects from path-expression-matcher + * + * String patterns starting with "*." are automatically converted to ".." for backward compatibility + * + * Defaults to `[]` + */ + stopNodes?: JPathOrExpression[]; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; + + /** + * Whether to always create a text node + * + * Defaults to `false` + */ + alwaysCreateTextNode?: boolean; + + /** + * Determine whether a tag should be parsed as an array + * + * @param tagName - The name of the tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @param isLeafNode - Whether the tag is a leaf node + * @param isAttribute - Whether this is an attribute + * @returns {boolean} + * + * Defaults to `() => false` + */ + isArray?: (tagName: string, jPathOrMatcher: JPathOrMatcher, isLeafNode: boolean, isAttribute: boolean) => boolean; + + /** + * Whether to process default and DOCTYPE entities + * + * When `true` - enables entity processing with default limits + * + * When `false` - disables all entity processing + * + * When `ProcessEntitiesOptions` - enables entity processing with custom configuration + * + * Defaults to `true` + */ + processEntities?: boolean | ProcessEntitiesOptions; + + /** + * Whether to process HTML entities + * + * Defaults to `false` + * @deprecated Use `entityDecoder` instead + */ + htmlEntities?: boolean; + + /** + * Custom entity decoder + */ + entityDecoder?: EntityDecoderOptions; + /** + * Whether to ignore the declaration tag from output + * + * Defaults to `false` + */ + ignoreDeclaration?: boolean; + + /** + * Whether to ignore Pi tags + * + * Defaults to `false` + */ + ignorePiTags?: boolean; + + /** + * Transform tag names + * + * Defaults to `false` + */ + transformTagName?: ((tagName: string) => string) | false; + + /** + * Transform attribute names + * + * Defaults to `false` + */ + transformAttributeName?: ((attributeName: string) => string) | false; + + /** + * Change the tag name when a different name is returned. Skip the tag from parsed result when false is returned. + * Modify `attrs` object to control attributes for the given tag. + * + * @param tagName - The name of the tag + * @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false) + * @param attrs - The attributes object + * @returns {string} new tag name. + * @returns false to skip the tag + * + * Defaults to `(tagName, jPathOrMatcher, attrs) => tagName` + */ + updateTag?: (tagName: string, jPathOrMatcher: JPathOrMatcher, attrs: { [k: string]: string }) => string | boolean; + + /** + * If true, adds a Symbol to all object nodes, accessible by {@link XMLParser.getMetaDataSymbol} with + * metadata about each the node in the XML file. + */ + captureMetaData?: boolean; + + /** + * Maximum number of nested tags + * + * Defaults to `100` + */ + maxNestedTags?: number; + + /** + * Whether to strictly validate tag names + * + * Defaults to `true` + */ + strictReservedNames?: boolean; + + /** + * Controls whether callbacks receive jPath as string or Matcher instance + * + * When `true` - callbacks receive jPath as string (backward compatible) + * + * When `false` - callbacks receive Matcher instance for advanced pattern matching + * + * Defaults to `true` + */ + jPath?: boolean; + + /** + * Function to sanitize dangerous property names + * + * @param name - The name of the property + * @returns {string} The sanitized name + * + * Defaults to `(name) => __name` + */ + onDangerousProperty?: (name: string) => string; +}; + + + +export type strnumOptions = { + hex: boolean; + leadingZeros: boolean, + skipLike?: RegExp, + eNotation?: boolean, + infinity?: string, + unicode?: boolean +} + +export type validationOptions = { + /** + * Whether to allow attributes without value + * + * Defaults to `false` + */ + allowBooleanAttributes?: boolean; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; +}; + +export type XmlBuilderOptions = { + /** + * Give a prefix to the attribute name in the resulting JS object + * + * Defaults to '@_' + */ + attributeNamePrefix?: string; + + /** + * A name to group all attributes of a tag under, or `false` to disable + * + * Defaults to `false` + */ + attributesGroupName?: false | string; + + /** + * The name of the next node in the resulting JS + * + * Defaults to `#text` + */ + textNodeName?: string; + + /** + * Whether to ignore attributes when building + * + * When `true` - ignores all the attributes + * + * When `false` - builds all the attributes + * + * When `Array` - filters out attributes that match provided patterns + * + * When `Function` - calls the function for each attribute and filters out those for which the function returned `true` + * + * Defaults to `true` + */ + ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean); + + /** + * Give a property name to set CDATA values to instead of merging to tag's text value + * + * Defaults to `false` + */ + cdataPropName?: false | string; + + /** + * If set, parse comments and set as this property + * + * Defaults to `false` + */ + commentPropName?: false | string; + + /** + * Whether to make output pretty instead of single line + * + * Defaults to `false` + */ + format?: boolean; + + + /** + * If `format` is set to `true`, sets the indent string + * + * Defaults to ` ` + */ + indentBy?: string; + + /** + * Give a name to a top-level array + * + * Defaults to `undefined` + */ + arrayNodeName?: string; + + /** + * Create empty tags for tags with no text value + * + * Defaults to `false` + */ + suppressEmptyNode?: boolean; + + /** + * Suppress an unpaired tag + * + * Defaults to `true` + */ + suppressUnpairedNode?: boolean; + + /** + * Don't put a value for boolean attributes + * + * Defaults to `true` + */ + suppressBooleanAttributes?: boolean; + + /** + * Preserve the order of tags in resulting JS object + * + * Defaults to `false` + */ + preserveOrder?: boolean; + + /** + * List of tags without closing tags + * + * Defaults to `[]` + */ + unpairedTags?: string[]; + + /** + * Nodes to stop parsing at + * + * Accepts string patterns or Expression objects from path-expression-matcher + * + * Defaults to `[]` + */ + stopNodes?: JPathOrExpression[]; + + /** + * Control how tag value should be parsed. Called only if tag value is not empty + * + * @returns {undefined|null} `undefined` or `null` to set original value. + * @returns {unknown} + * + * 1. Different value or value with different data type to set new value. + * 2. Same value to set parsed value if `parseTagValue: true`. + * + * Defaults to `(tagName, val, jPath, hasAttributes, isLeafNode) => val` + */ + tagValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Control how attribute value should be parsed + * + * @param attrName + * @param attrValue + * @param jPath + * @returns {undefined|null} `undefined` or `null` to set original value + * @returns {unknown} + * + * Defaults to `(attrName, val, jPath) => val` + */ + attributeValueProcessor?: (name: string, value: unknown) => unknown; + + /** + * Whether to process default and DOCTYPE entities + * + * Defaults to `true` + */ + processEntities?: boolean; + + + oneListGroup?: boolean; + + /** + * Maximum number of nested tags + * + * Defaults to `100` + */ + maxNestedTags?: number; +}; + +type ESchema = string | object | Array; + +export type ValidationError = { + err: { + code: string; + msg: string, + line: number, + col: number + }; +}; + +export class XMLParser { + constructor(options?: X2jOptions); + + parse(xmlData: string | Uint8Array): any; + /** + * @deprecated The `validationOptions` parameter is deprecated. + * Use the `fast-xml-validator` package instead for XML validation. + * @see https://www.npmjs.com/package/fast-xml-validator + */ + parse(xmlData: string | Uint8Array, validationOptions: validationOptions | boolean): any; + /** + * Add Entity which is not by default supported by this library + * @param entityIdentifier {string} Eg: 'ent' for &ent; + * @param entityValue {string} Eg: '\r' + * @deprecated Use `entityDecoder` instead + */ + addEntity(entityIdentifier: string, entityValue: string): void; + + /** + * Returns a Symbol that can be used to access the {@link XMLMetaData} + * property on a node. + * + * If Symbol is not available in the environment, an ordinary property is used + * and the name of the property is here returned. + * + * The XMLMetaData property is only present when {@link X2jOptions.captureMetaData} + * is true in the options. + */ + static getMetaDataSymbol(): Symbol; +} + +/** + * @deprecated Use fast-xml-validator instead + * @see https://www.npmjs.com/package/fast-xml-validator + */ +export class XMLValidator { + static validate(xmlData: string, options?: validationOptions): true | ValidationError; +} +/** + * @deprecated Use npm package 'fast-xml-builder' instead + */ +export class XMLBuilder { + constructor(options?: XmlBuilderOptions); + build(jObj: any): string; +} + +/** + * This object is available on nodes via the symbol {@link XMLParser.getMetaDataSymbol} + * when {@link X2jOptions.captureMetaData} is true. + */ +export interface XMLMetaData { + /** The index, if available, of the character where the XML node began in the input stream. */ + startIndex?: number; +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/fxp.js b/node_modules/fast-xml-parser/src/fxp.js new file mode 100644 index 0000000000000000000000000000000000000000..470ed56d01490e1758fa2dd30dfb48d796fb2a75 --- /dev/null +++ b/node_modules/fast-xml-parser/src/fxp.js @@ -0,0 +1,14 @@ +'use strict'; + +import { validate } from './validator.js'; +import XMLParser from './xmlparser/XMLParser.js'; +import XMLBuilder from './xmlbuilder/json2xml.js'; + +const XMLValidator = { + validate: validate +} +export { + XMLParser, + XMLValidator, + XMLBuilder +}; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/ignoreAttributes.js b/node_modules/fast-xml-parser/src/ignoreAttributes.js new file mode 100644 index 0000000000000000000000000000000000000000..bdec0a6117eb75fb367bf89236d6817b26fc1078 --- /dev/null +++ b/node_modules/fast-xml-parser/src/ignoreAttributes.js @@ -0,0 +1,18 @@ +export default function getIgnoreAttributesFn(ignoreAttributes) { + if (typeof ignoreAttributes === 'function') { + return ignoreAttributes + } + if (Array.isArray(ignoreAttributes)) { + return (attrName) => { + for (const pattern of ignoreAttributes) { + if (typeof pattern === 'string' && attrName === pattern) { + return true + } + if (pattern instanceof RegExp && pattern.test(attrName)) { + return true + } + } + } + } + return () => false +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/util.js b/node_modules/fast-xml-parser/src/util.js new file mode 100644 index 0000000000000000000000000000000000000000..c2c809d1ae4c81ca6427ffc29529063907ff0eba --- /dev/null +++ b/node_modules/fast-xml-parser/src/util.js @@ -0,0 +1,61 @@ +'use strict'; + +const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; +const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; +export const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*'; +const regexName = new RegExp('^' + nameRegexp + '$'); + +export function getAllMatches(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); + } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; +} + +export const isName = function (string) { + const match = regexName.exec(string); + return !(match === null || typeof match === 'undefined'); +} + +export function isExist(v) { + return typeof v !== 'undefined'; +} + +export function isEmptyObject(obj) { + return Object.keys(obj).length === 0; +} + +export function getValue(v) { + if (exports.isExist(v)) { + return v; + } else { + return ''; + } +} + +/** + * Dangerous property names that could lead to prototype pollution or security issues + */ +export const DANGEROUS_PROPERTY_NAMES = [ + // '__proto__', + // 'constructor', + // 'prototype', + 'hasOwnProperty', + 'toString', + 'valueOf', + '__defineGetter__', + '__defineSetter__', + '__lookupGetter__', + '__lookupSetter__' +]; + +export const criticalProperties = ["__proto__", "constructor", "prototype"]; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/CharsSymbol.js b/node_modules/fast-xml-parser/src/v6/CharsSymbol.js new file mode 100644 index 0000000000000000000000000000000000000000..6ac2de4cfda8f8a2a26243f4e6c4f1cc3e0ec24c --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/CharsSymbol.js @@ -0,0 +1,16 @@ +export default { + "<" : "<", //tag start + ">" : ">", //tag end + "/" : "/", //close tag + "!" : "!", //comment or docttype + "!--" : "!--", //comment + "-->" : "-->", //comment end + "?" : "?", //pi + "?>" : "?>", //pi end + "?xml" : "?xml", //pi end + "![" : "![", //cdata + "]]>" : "]]>", //cdata end + "[" : "[", + "-" : "-", + "D" : "D", +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/EntitiesParser.js b/node_modules/fast-xml-parser/src/v6/EntitiesParser.js new file mode 100644 index 0000000000000000000000000000000000000000..576e069d69d1bf3d48c6a3f78daeceae9b60a3e4 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/EntitiesParser.js @@ -0,0 +1,106 @@ +const ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }; +const htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent": { regex: /&(cent|#162);/g, val: "¢" }, + "pound": { regex: /&(pound|#163);/g, val: "£" }, + "yen": { regex: /&(yen|#165);/g, val: "¥" }, + "euro": { regex: /&(euro|#8364);/g, val: "€" }, + "copyright": { regex: /&(copy|#169);/g, val: "©" }, + "reg": { regex: /&(reg|#174);/g, val: "®" }, + "inr": { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 16)) }, +}; +export default class EntitiesParser { + constructor(replaceHtmlEntities) { + this.replaceHtmlEntities = replaceHtmlEntities; + this.docTypeEntities = {}; + this.lastEntities = { + "apos": { regex: /&(apos|#39|#x27);/g, val: "'" }, + "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" }, + "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" }, + "quot": { regex: /&(quot|#34|#x22);/g, val: "\"" }, + }; + } + + addExternalEntities(externalEntities) { + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.addExternalEntity(ent, externalEntities[ent]) + } + } + addExternalEntity(key, val) { + validateEntityName(key); + const escaped = key.replace(/[.\-+*:]/g, '\\.'); + if (val.indexOf("&") !== -1) { + reportWarning(`Entity ${key} is not added as '&' is found in value;`) + return; + } else { + this.lastEntities[key] = { + regex: new RegExp("&" + escaped + ";", "g"), + val: val + } + } + } + + addDocTypeEntities(entities) { + const entKeys = Object.keys(entities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + const escaped = ent.replace(/[.\-+*:]/g, '\\.'); + this.docTypeEntities[ent] = { + regex: new RegExp("&" + escaped + ";", "g"), + val: entities[ent] + } + } + } + + parse(val) { + return this.replaceEntitiesValue(val) + } + + /** + * 1. Replace DOCTYPE entities + * 2. Replace external entities + * 3. Replace HTML entities if asked + * @param {string} val + */ + replaceEntitiesValue(val) { + if (typeof val === "string" && val.length > 0) { + for (let entityName in this.docTypeEntities) { + const entity = this.docTypeEntities[entityName]; + val = val.replace(entity.regx, entity.val); + } + for (let entityName in this.lastEntities) { + const entity = this.lastEntities[entityName]; + val = val.replace(entity.regex, entity.val); + } + if (this.replaceHtmlEntities) { + for (let entityName in htmlEntities) { + const entity = htmlEntities[entityName]; + val = val.replace(entity.regex, entity.val); + } + } + val = val.replace(ampEntity.regex, ampEntity.val); + } + return val; + } +} + +//an entity name should not contains special characters that may be used in regex +//Eg !?\\\/[]$%{}^&*()<> +const specialChar = "!?\\/[]$%{}^&*()<>|+"; + +function validateEntityName(name) { + for (let i = 0; i < specialChar.length; i++) { + const ch = specialChar[i]; + if (name.indexOf(ch) !== -1) throw new Error(`Invalid character ${ch} in entity name`); + } + return name; +} diff --git a/node_modules/fast-xml-parser/src/v6/OptionsBuilder.js b/node_modules/fast-xml-parser/src/v6/OptionsBuilder.js new file mode 100644 index 0000000000000000000000000000000000000000..6e3391954ebe678281f5605de4e2dad9df4f945a --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OptionsBuilder.js @@ -0,0 +1,61 @@ + +import { JsObjOutputBuilder } from './OutputBuilders/JsObjBuilder.js'; + +export const defaultOptions = { + preserveOrder: false, + removeNSPrefix: false, // remove NS from tag name or attribute name if true + //ignoreRootElement : false, + stopNodes: [], //nested tags will not be parsed even for errors + // isArray: () => false, //User will set it + htmlEntities: false, + // skipEmptyListItem: false + tags: { + unpaired: [], + nameFor: { + cdata: false, + comment: false, + text: '#text' + }, + separateTextProperty: false, + }, + attributes: { + ignore: false, + booleanType: true, + entities: true, + }, + + // select: ["img[src]"], + // stop: ["anim", "[ads]"] + only: [], // rest tags will be skipped. It will result in flat array + hierarchy: false, //will be used when a particular tag is set to be parsed. + skip: [], // will be skipped from parse result. on('skip') will be triggered + + select: [], // on('select', tag => tag ) will be called if match + stop: [], //given tagPath will not be parsed. innerXML will be set as string value + OutputBuilder: new JsObjOutputBuilder(), +}; + +export const buildOptions = function (options) { + const finalOptions = { ...defaultOptions }; + copyProperties(finalOptions, options) + return finalOptions; +}; + +function copyProperties(target, source) { + for (let key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + if (key === 'OutputBuilder') { + target[key] = source[key]; + } else if (typeof source[key] === 'object' && !Array.isArray(source[key])) { + // Recursively copy nested properties + if (typeof target[key] === 'undefined') { + target[key] = {}; + } + copyProperties(target[key], source[key]); + } else { + // Copy non-nested properties + target[key] = source[key]; + } + } + } +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/BaseOutputBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/BaseOutputBuilder.js new file mode 100644 index 0000000000000000000000000000000000000000..aee73658d1a382315c40150f52aa9fd0b9b5cc52 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/BaseOutputBuilder.js @@ -0,0 +1,69 @@ +export default class BaseOutputBuilder { + constructor() { + // this.attributes = {}; + } + + addAttribute(name, value) { + if (this.options.onAttribute) { + //TODO: better to pass tag path + const v = this.options.onAttribute(name, value, this.tagName); + if (v) this.attributes[v.name] = v.value; + } else { + name = this.options.attributes.prefix + name + this.options.attributes.suffix; + this.attributes[name] = this.parseValue(value, this.options.attributes.valueParsers); + } + } + + /** + * parse value by chain of parsers + * @param {string} val + * @returns {any} parsed value if matching parser found + */ + parseValue = function (val, valParsers) { + for (let i = 0; i < valParsers.length; i++) { + let valParser = valParsers[i]; + if (typeof valParser === "string") { + valParser = this.registeredParsers[valParser]; + } + if (valParser) { + val = valParser.parse(val); + } + } + return val; + } + + /** + * To add a nested empty tag. + * @param {string} key + * @param {any} val + */ + _addChild(key, val) { } + + /** + * skip the comment if property is not set + */ + addComment(text) { + if (this.options.nameFor.comment) + this._addChild(this.options.nameFor.comment, text); + } + + //store CDATA separately if property is set + //otherwise add to tag's value + addCdata(text) { + if (this.options.nameFor.cdata) { + this._addChild(this.options.nameFor.cdata, text); + } else { + this.addRawValue(text || ""); + } + } + + addRawValue = text => this.addValue(text); + + addDeclaration() { + if (!this.options.declaration) { + } else { + this.addPi("?xml"); + } + this.attributes = {} + } +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsArrBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsArrBuilder.js new file mode 100644 index 0000000000000000000000000000000000000000..04205e583edfadd5d6560336cadbdf12b5ed7402 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsArrBuilder.js @@ -0,0 +1,103 @@ +import { buildOptions, registerCommonValueParsers } from './ParserOptionsBuilder.js'; + +export default class OutputBuilder { + constructor(options) { + this.options = buildOptions(options); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name, parserInstance) {//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions) { + return new JsArrBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +const rootName = '!js_arr'; +import BaseOutputBuilder from './BaseOutputBuilder.js'; + +class JsArrBuilder extends BaseOutputBuilder { + + constructor(parserOptions, options, registeredParsers) { + super(); + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = options; + this.registeredParsers = registeredParsers; + + this.root = new Node(rootName); + this.currentNode = this.root; + this.attributes = {}; + } + + addTag(tag) { + //when a new tag is added, it should be added as child of current node + //TODO: shift this check to the parser + if (tag.name === "__proto__") tag.name = "#__proto__"; + + this.tagsStack.push(this.currentNode); + this.currentNode = new Node(tag.name, this.attributes); + this.attributes = {}; + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag() { + const node = this.currentNode; + this.currentNode = this.tagsStack.pop(); //set parent node in scope + if (this.options.onClose !== undefined) { + //TODO TagPathMatcher + const resultTag = this.options.onClose(node, + new TagPathMatcher(this.tagsStack, node)); + + if (resultTag) return; + } + this.currentNode.child.push(node); //to parent node + } + + //Called by parent class methods + _addChild(key, val) { + // if(key === "__proto__") tagName = "#__proto__"; + this.currentNode.child.push({ [key]: val }); + // this.currentNode.leafType = false; + } + + /** + * Add text value child node + * @param {string} text + */ + addValue(text) { + this.currentNode.child.push({ [this.options.nameFor.text]: this.parseValue(text, this.options.tags.valueParsers) }); + } + + addPi(name) { + //TODO: set pi flag + if (!this.options.ignorePiTags) { + const node = new Node(name, this.attributes); + this.currentNode[":@"] = this.attributes; + this.currentNode.child.push(node); + } + this.attributes = {}; + } + getOutput() { + return this.root.child[0]; + } +} + + + +class Node { + constructor(tagname, attributes) { + this.tagname = tagname; + this.child = []; //nested tags, text, cdata, comments + if (attributes && Object.keys(attributes).length > 0) + this[":@"] = attributes; + } +} + +module.exports = OutputBuilder; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsMinArrBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsMinArrBuilder.js new file mode 100644 index 0000000000000000000000000000000000000000..f0eee0cfdea1d6eee8d7a2f750cdffc6980c181e --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsMinArrBuilder.js @@ -0,0 +1,100 @@ +import {buildOptions,registerCommonValueParsers} from"./ParserOptionsBuilder.js"; + +export default class OutputBuilder{ + constructor(options){ + this.options = buildOptions(options); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name,parserInstance){//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions){ + return new JsMinArrBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +import BaseOutputBuilder from "./BaseOutputBuilder.js"; +const rootName = '^'; + +class JsMinArrBuilder extends BaseOutputBuilder{ + + constructor(parserOptions, options,registeredParsers) { + super(); + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = options; + this.registeredParsers = registeredParsers; + + this.root = {[rootName]: []}; + this.currentNode = this.root; + this.currentNodeTagName = rootName; + this.attributes = {}; + } + + addTag(tag){ + //when a new tag is added, it should be added as child of current node + //TODO: shift this check to the parser + if(tag.name === "__proto__") tag.name = "#__proto__"; + + this.tagsStack.push([this.currentNodeTagName,this.currentNode]); //this.currentNode is parent node here + this.currentNodeTagName = tag.name; + this.currentNode = { [tag.name]:[]} + if(Object.keys(this.attributes).length > 0){ + this.currentNode[":@"] = this.attributes; + this.attributes = {}; + } + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag(){ + const node = this.currentNode; + const nodeName = this.currentNodeTagName; + const arr = this.tagsStack.pop(); //set parent node in scope + this.currentNodeTagName = arr[0]; + this.currentNode = arr[1]; + + if(this.options.onClose !== undefined){ + //TODO TagPathMatcher + const resultTag = this.options.onClose(node, + new TagPathMatcher(this.tagsStack,node)); + + if(resultTag) return; + } + this.currentNode[this.currentNodeTagName].push(node); //to parent node + } + + //Called by parent class methods + _addChild(key, val){ + // if(key === "__proto__") tagName = "#__proto__"; + this.currentNode.push( {[key]: val }); + // this.currentNode.leafType = false; + } + + /** + * Add text value child node + * @param {string} text + */ + addValue(text){ + this.currentNode[this.currentNodeTagName].push( {[this.options.nameFor.text]: this.parseValue(text, this.options.tags.valueParsers) }); + } + + addPi(name){ + if(!this.options.ignorePiTags){ + const node = { [name]:[]} + if(this.attributes){ + node[":@"] = this.attributes; + } + this.currentNode.push(node); + } + this.attributes = {}; + } + getOutput(){ + return this.root[rootName]; + } +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsObjBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsObjBuilder.js new file mode 100644 index 0000000000000000000000000000000000000000..9e19de9e644b952864feca659f621b70adf0f6ea --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/JsObjBuilder.js @@ -0,0 +1,154 @@ + + +import { buildOptions, registerCommonValueParsers } from './ParserOptionsBuilder.js'; + +export default class OutputBuilder { + constructor(builderOptions) { + this.options = buildOptions(builderOptions); + this.registeredParsers = registerCommonValueParsers(this.options); + } + + registerValueParser(name, parserInstance) {//existing name will override the parser without warning + this.registeredParsers[name] = parserInstance; + } + + getInstance(parserOptions) { + return new JsObjBuilder(parserOptions, this.options, this.registeredParsers); + } +} + +import BaseOutputBuilder from './BaseOutputBuilder.js'; +const rootName = '^'; + +class JsObjBuilder extends BaseOutputBuilder { + + constructor(parserOptions, builderOptions, registeredParsers) { + super(); + //hold the raw detail of a tag and sequence with reference to the output + this.tagsStack = []; + this.parserOptions = parserOptions; + this.options = builderOptions; + this.registeredParsers = registeredParsers; + + this.root = {}; + this.parent = this.root; + this.tagName = rootName; + this.value = {}; + this.textValue = ""; + this.attributes = {}; + } + + addTag(tag) { + + let value = ""; + if (!isEmpty(this.attributes)) { + value = {}; + if (this.options.attributes.groupBy) { + value[this.options.attributes.groupBy] = this.attributes; + } else { + value = this.attributes; + } + } + + this.tagsStack.push([this.tagName, this.textValue, this.value]); //parent tag, parent text value, parent tag value (jsobj) + this.tagName = tag.name; + this.value = value; + this.textValue = ""; + this.attributes = {}; + } + + /** + * Check if the node should be added by checking user's preference + * @param {Node} node + * @returns boolean: true if the node should not be added + */ + closeTag() { + const tagName = this.tagName; + let value = this.value; + let textValue = this.textValue; + + //update tag text value + if (typeof value !== "object" && !Array.isArray(value)) { + value = this.parseValue(textValue.trim(), this.options.tags.valueParsers); + } else if (textValue.length > 0) { + value[this.options.nameFor.text] = this.parseValue(textValue.trim(), this.options.tags.valueParsers); + } + + + let resultTag = { + tagName: tagName, + value: value + }; + + if (this.options.onTagClose !== undefined) { + //TODO TagPathMatcher + resultTag = this.options.onClose(tagName, value, this.textValue, new TagPathMatcher(this.tagsStack, node)); + + if (!resultTag) return; + } + + //set parent node in scope + let arr = this.tagsStack.pop(); + let parentTag = arr[2]; + parentTag = this._addChildTo(resultTag.tagName, resultTag.value, parentTag); + + this.tagName = arr[0]; + this.textValue = arr[1]; + this.value = parentTag; + } + + _addChild(key, val) { + if (typeof this.value === "string") { + this.value = { [this.options.nameFor.text]: this.value }; + } + + this._addChildTo(key, val, this.value); + // this.currentNode.leafType = false; + this.attributes = {}; + } + + _addChildTo(key, val, node) { + if (typeof node === 'string') node = {}; + if (!node[key]) { + node[key] = val; + } else { //Repeated + if (!Array.isArray(node[key])) { //but not stored as array + node[key] = [node[key]]; + } + node[key].push(val); + } + return node; + } + + + /** + * Add text value child node + * @param {string} text + */ + addValue(text) { + //TODO: use bytes join + if (this.textValue.length > 0) this.textValue += " " + text; + else this.textValue = text; + } + + addPi(name) { + let value = ""; + if (!isEmpty(this.attributes)) { + value = {}; + if (this.options.attributes.groupBy) { + value[this.options.attributes.groupBy] = this.attributes; + } else { + value = this.attributes; + } + } + this._addChild(name, value); + + } + getOutput() { + return this.value; + } +} + +function isEmpty(obj) { + return Object.keys(obj).length === 0; +} diff --git a/node_modules/fast-xml-parser/src/v6/OutputBuilders/ParserOptionsBuilder.js b/node_modules/fast-xml-parser/src/v6/OutputBuilders/ParserOptionsBuilder.js new file mode 100644 index 0000000000000000000000000000000000000000..0e206834bdad5623dceaa1b37fe9a6f567274b00 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/OutputBuilders/ParserOptionsBuilder.js @@ -0,0 +1,94 @@ +import trimParser from "../valueParsers/trim.js"; +import booleanParser from "../valueParsers/booleanParser.js"; +import currencyParser from "../valueParsers/currency.js"; +import numberParser from "../valueParsers/number.js"; + +const defaultOptions = { + nameFor: { + text: "#text", + comment: "", + cdata: "", + }, + // onTagClose: () => {}, + // onAttribute: () => {}, + piTag: false, + declaration: false, //"?xml" + tags: { + valueParsers: [ + // "trim", + // "boolean", + // "number", + // "currency", + // "date", + ] + }, + attributes: { + prefix: "@_", + suffix: "", + groupBy: "", + + valueParsers: [ + // "trim", + // "boolean", + // "number", + // "currency", + // "date", + ] + }, + dataType: { + + } +} + +//TODO +const withJoin = ["trim", "join", /*"entities",*/"number", "boolean", "currency"/*, "date"*/] +const withoutJoin = ["trim", /*"entities",*/"number", "boolean", "currency"/*, "date"*/] + +export function buildOptions(options) { + //clone + const finalOptions = { ...defaultOptions }; + + //add config missed in cloning + finalOptions.tags.valueParsers.push(...withJoin) + if (!this.preserveOrder) + finalOptions.tags.valueParsers.push(...withoutJoin); + + //add config missed in cloning + finalOptions.attributes.valueParsers.push(...withJoin) + + //override configuration + copyProperties(finalOptions, options); + return finalOptions; +} + +function copyProperties(target, source) { + for (let key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + if (typeof source[key] === 'object' && !Array.isArray(source[key])) { + // Recursively copy nested properties + if (typeof target[key] === 'undefined') { + target[key] = {}; + } + copyProperties(target[key], source[key]); + } else { + // Copy non-nested properties + target[key] = source[key]; + } + } + } +} + +export function registerCommonValueParsers(options) { + return { + "trim": new trimParser(), + // "join": this.entityParser.parse, + "boolean": new booleanParser(), + "number": new numberParser({ + hex: true, + leadingZeros: true, + eNotation: true + }), + "currency": new currencyParser(), + // "date": this.entityParser.parse, + } +} diff --git a/node_modules/fast-xml-parser/src/v6/Report.js b/node_modules/fast-xml-parser/src/v6/Report.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/fast-xml-parser/src/v6/TagPath.js b/node_modules/fast-xml-parser/src/v6/TagPath.js new file mode 100644 index 0000000000000000000000000000000000000000..98148c78cfc42da20da6db753ca2accfa31dcc45 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/TagPath.js @@ -0,0 +1,81 @@ +export default class TagPath{ + constructor(pathStr){ + let text = ""; + let tName = ""; + let pos; + let aName = ""; + let aVal = ""; + this.stack = [] + + for (let i = 0; i < pathStr.length; i++) { + let ch = pathStr[i]; + if(ch === " ") { + if(text.length === 0) continue; + tName = text; text = ""; + }else if(ch === "["){ + if(tName.length === 0){ + tName = text; text = ""; + } + i++; + for (; i < pathStr.length; i++) { + ch = pathStr[i]; + if(ch=== "=") continue; + else if(ch=== "]") {aName = text.trim(); text=""; break; i--;} + else if(ch === "'" || ch === '"'){ + let attrEnd = pathStr.indexOf(ch,i+1); + aVal = pathStr.substring(i+1, attrEnd); + i = attrEnd; + }else{ + text +=ch; + } + } + }else if(ch !== " " && text.length === 0 && tName.length > 0){//reading tagName + //save previous tag + this.stack.push(new TagPathNode(tName,pos,aName,aVal)); + text = ch; tName = ""; aName = ""; aVal = ""; + }else{ + text+=ch; + } + } + + //last tag in the path + if(tName.length >0 || text.length>0){ + this.stack.push(new TagPathNode(text||tName,pos,aName,aVal)); + } + } + + match(tagStack,node){ + if(this.stack[0].name !== "*"){ + if(this.stack.length !== tagStack.length +1) return false; + + //loop through tagPath and tagStack and match + for (let i = 0; i < this.tagStack.length; i++) { + if(!this.stack[i].match(tagStack[i])) return false; + } + } + if(!this.stack[this.stack.length - 1].match(node)) return false; + return true; + } +} + +class TagPathNode{ + constructor(name,position,attrName,attrVal){ + this.name = name; + this.position = position; + this.attrName = attrName, + this.attrVal = attrVal; + } + + match(node){ + let matching = true; + matching = node.name === this.name; + if(this.position) matching = node.position === this.position; + if(this.attrName) matching = node.attrs[this.attrName !== undefined]; + if(this.attrVal) matching = node.attrs[this.attrName !== this.attrVal]; + return matching; + } +} + +// console.log((new TagPath("* b[b]")).stack); +// console.log((new TagPath("a[a] b[b] c")).stack); +// console.log((new TagPath(" b [ b= 'cf sdadwa' ] a ")).stack); \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/TagPathMatcher.js b/node_modules/fast-xml-parser/src/v6/TagPathMatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..8110447661fa827f97ef59cf9bb472c60eea7dc7 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/TagPathMatcher.js @@ -0,0 +1,13 @@ +import {TagPath} from './TagPath.js'; + +export default class TagPathMatcher{ + constructor(stack,node){ + this.stack = stack; + this.node= node; + } + + match(path){ + const tagPath = new TagPath(path); + return tagPath.match(this.stack, this.node); + } +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/v6/XMLParser.js b/node_modules/fast-xml-parser/src/v6/XMLParser.js new file mode 100644 index 0000000000000000000000000000000000000000..44c70dc47452960696cde345185288148fdfc4d5 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/XMLParser.js @@ -0,0 +1,83 @@ +import { buildOptions } from './OptionsBuilder.js'; +import Xml2JsParser from './Xml2JsParser.js'; + +export default class XMLParser { + + constructor(options) { + this.externalEntities = {}; + this.options = buildOptions(options); + // console.log(this.options) + } + /** + * Parse XML data string to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parse(xmlData) { + if (Array.isArray(xmlData) && xmlData.byteLength !== undefined) { + return this.parse(xmlData); + } else if (xmlData.toString) { + xmlData = xmlData.toString(); + } else { + throw new Error("XML data is accepted in String or Bytes[] form.") + } + // if( validationOption){ + // if(validationOption === true) validationOption = {}; //validate with default options + + // const result = validator.validate(xmlData, validationOption); + // if (result !== true) { + // throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) + // } + // } + const parser = new Xml2JsParser(this.options); + parser.entityParser.addExternalEntities(this.externalEntities); + return parser.parse(xmlData); + } + /** + * Parse XML data buffer to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parseBytesArr(xmlData) { + if (Array.isArray(xmlData) && xmlData.byteLength !== undefined) { + } else { + throw new Error("XML data is accepted in Bytes[] form.") + } + const parser = new Xml2JsParser(this.options); + parser.entityParser.addExternalEntities(this.externalEntities); + return parser.parseBytesArr(xmlData); + } + /** + * Parse XML data stream to JS object + * @param {fs.ReadableStream} xmlDataStream + */ + parseStream(xmlDataStream) { + if (!isStream(xmlDataStream)) throw new Error("FXP: Invalid stream input"); + + const orderedObjParser = new Xml2JsParser(this.options); + orderedObjParser.entityParser.addExternalEntities(this.externalEntities); + return orderedObjParser.parseStream(xmlDataStream); + } + + /** + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value + */ + addEntity(key, value) { + if (value.indexOf("&") !== -1) { + throw new Error("Entity value can't have '&'") + } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) { + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") + } else if (value === "&") { + throw new Error("An entity with value '&' is not permitted"); + } else { + this.externalEntities[key] = value; + } + } +} + +function isStream(stream) { + if (stream && typeof stream.read === "function" && typeof stream.on === "function" && typeof stream.readableEnded === "boolean") return true; + return false; +} diff --git a/node_modules/fast-xml-parser/src/v6/Xml2JsParser.js b/node_modules/fast-xml-parser/src/v6/Xml2JsParser.js new file mode 100644 index 0000000000000000000000000000000000000000..bd6226537e53d7d225e6fc8fa05eec493abd9109 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/Xml2JsParser.js @@ -0,0 +1,235 @@ +import StringSource from './inputSource/StringSource.js'; +import BufferSource from './inputSource/BufferSource.js'; +import {readTagExp,readClosingTagName} from './XmlPartReader.js'; +import {readComment, readCdata,readDocType,readPiTag} from './XmlSpecialTagsReader.js'; +import TagPath from './TagPath.js'; +import TagPathMatcher from './TagPathMatcher.js'; +import EntitiesParser from './EntitiesParser.js'; + +//To hold the data of current tag +//This is usually used to compare jpath expression against current tag +class TagDetail{ + constructor(name){ + this.name = name; + this.position = 0; + // this.attributes = {}; + } +} + +export default class Xml2JsParser { + constructor(options) { + this.options = options; + + this.currentTagDetail = null; + this.tagTextData = ""; + this.tagsStack = []; + this.entityParser = new EntitiesParser(options.htmlEntities); + this.stopNodes = []; + for (let i = 0; i < this.options.stopNodes.length; i++) { + this.stopNodes.push(new TagPath(this.options.stopNodes[i])); + } + } + + parse(strData) { + this.source = new StringSource(strData); + this.parseXml(); + return this.outputBuilder.getOutput(); + } + parseBytesArr(data) { + this.source = new BufferSource(data ); + this.parseXml(); + return this.outputBuilder.getOutput(); + } + + parseXml() { + //TODO: Separate TagValueParser as separate class. So no scope issue in node builder class + + //OutputBuilder should be set in XML Parser + this.outputBuilder = this.options.OutputBuilder.getInstance(this.options); + this.root = { root: true}; + this.currentTagDetail = this.root; + + while(this.source.canRead()){ + let ch = this.source.readCh(); + if (ch === "") break; + + if(ch === "<"){//tagStart + let nextChar = this.source.readChAt(0); + if (nextChar === "" ) throw new Error("Unexpected end of source"); + + + if(nextChar === "!" || nextChar === "?"){ + this.source.updateBufferBoundary(); + //previously collected text should be added to current node + this.addTextNode(); + + this.readSpecialTag(nextChar);// Read DOCTYPE, comment, CDATA, PI tag + }else if(nextChar === "/"){ + this.source.updateBufferBoundary(); + this.readClosingTag(); + // console.log(this.source.buffer.length, this.source.readable); + // console.log(this.tagsStack.length); + }else{//opening tag + this.readOpeningTag(); + } + }else{ + this.tagTextData += ch; + } + }//End While loop + if(this.tagsStack.length > 0 || ( this.tagTextData !== "undefined" && this.tagTextData.trimEnd().length > 0) ) throw new Error("Unexpected data in the end of document"); + } + + /** + * read closing paired tag. Set parent tag in scope. + * skip a node on user's choice + */ + readClosingTag(){ + const tagName = this.processTagName(readClosingTagName(this.source)); + // console.log(tagName, this.tagsStack.length); + this.validateClosingTag(tagName); + // All the text data collected, belongs to current tag. + if(!this.currentTagDetail.root) this.addTextNode(); + this.outputBuilder.closeTag(); + // Since the tag is closed now, parent tag comes in scope + this.currentTagDetail = this.tagsStack.pop(); + } + + validateClosingTag(tagName){ + // This can't be unpaired tag, or a stop tag. + if(this.isUnpaired(tagName) || this.isStopNode(tagName)) throw new Error(`Unexpected closing tag '${tagName}'`); + // This must match with last opening tag + else if(tagName !== this.currentTagDetail.name) + throw new Error(`Unexpected closing tag '${tagName}' expecting '${this.currentTagDetail.name}'`) + } + + /** + * Read paired, unpaired, self-closing, stop and special tags. + * Create a new node + * Push paired tag in stack. + */ + readOpeningTag(){ + //save previously collected text data to current node + this.addTextNode(); + + //create new tag + let tagExp = readTagExp(this, ">" ); + + // process and skip from tagsStack For unpaired tag, self closing tag, and stop node + const tagDetail = new TagDetail(tagExp.tagName); + if(this.isUnpaired(tagExp.tagName)) { + //TODO: this will lead 2 extra stack operation + this.outputBuilder.addTag(tagDetail); + this.outputBuilder.closeTag(); + } else if(tagExp.selfClosing){ + this.outputBuilder.addTag(tagDetail); + this.outputBuilder.closeTag(); + } else if(this.isStopNode(this.currentTagDetail)){ + // TODO: let's user set a stop node boundary detector for complex contents like script tag + //TODO: pass tag name only to avoid string operations + const content = source.readUptoCloseTag(` 0){ + //TODO: shift parsing to output builder + + this.outputBuilder.addValue(this.replaceEntities(this.tagTextData)); + } + this.tagTextData = ""; + } + // } + } + + processAttrName(name){ + if(name === "__proto__") name = "#__proto__"; + name = resolveNameSpace(name, this.removeNSPrefix); + return name; + } + + processTagName(name){ + if(name === "__proto__") name = "#__proto__"; + name = resolveNameSpace(name, this.removeNSPrefix); + return name; + } + + /** + * Generate tags path from tagsStack + */ + tagsPath(tagName){ + //TODO: return TagPath Object. User can call match method with path + return ""; + } + + isUnpaired(tagName){ + return this.options.tags.unpaired.indexOf(tagName) !== -1; + } + + /** + * valid expressions are + * tag nested + * * nested + * tag nested[attribute] + * tag nested[attribute=""] + * tag nested[attribute!=""] + * tag nested:0 //for future + * @param {string} tagName + * @returns + */ + isStopNode(node){ + for (let i = 0; i < this.stopNodes.length; i++) { + const givenPath = this.stopNodes[i]; + if(givenPath.match(this.tagsStack, node)) return true; + } + return false + } + + replaceEntities(text){ + //TODO: if option is set then replace entities + return this.entityParser.parse(text) + } +} + +function resolveNameSpace(name, removeNSPrefix) { + if (removeNSPrefix) { + const parts = name.split(':'); + if(parts.length === 2){ + if (parts[0] === 'xmlns') return ''; + else return parts[1]; + }else reportError(`Multiple namespaces ${name}`) + } + return name; +} diff --git a/node_modules/fast-xml-parser/src/v6/XmlPartReader.js b/node_modules/fast-xml-parser/src/v6/XmlPartReader.js new file mode 100644 index 0000000000000000000000000000000000000000..61c57ec8d2e132e4d8555db956e3c741e66e811b --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/XmlPartReader.js @@ -0,0 +1,210 @@ +'use strict'; + +/** + * find paired tag for a stop node + * @param {string} xmlDoc + * @param {string} tagName + * @param {number} i : start index + */ +export function readStopNode(xmlDoc, tagName, i){ + const startIndex = i; + // Starting at 1 since we already have an open tag + let openTagCount = 1; + + for (; i < xmlDoc.length; i++) { + if( xmlDoc[i] === "<"){ + if (xmlDoc[i+1] === "/") {//close tag + const closeIndex = findSubStrIndex(xmlDoc, ">", i, `${tagName} is not closed`); + let closeTagName = xmlDoc.substring(i+2,closeIndex).trim(); + if(closeTagName === tagName){ + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlDoc.substring(startIndex, i), + i : closeIndex + } + } + } + i=closeIndex; + } else if(xmlDoc[i+1] === '?') { + const closeIndex = findSubStrIndex(xmlDoc, "?>", i+1, "StopNode is not closed.") + i=closeIndex; + } else if(xmlDoc.substr(i + 1, 3) === '!--') { + const closeIndex = findSubStrIndex(xmlDoc, "-->", i+3, "StopNode is not closed.") + i=closeIndex; + } else if(xmlDoc.substr(i + 1, 2) === '![') { + const closeIndex = findSubStrIndex(xmlDoc, "]]>", i, "StopNode is not closed.") - 2; + i=closeIndex; + } else { + const tagData = readTagExp(xmlDoc, i, '>') + + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { + openTagCount++; + } + i=tagData.closeIndex; + } + } + } + }//end for loop +} + +/** + * Read closing tag name + * @param {Source} source + * @returns tag name + */ +export function readClosingTagName(source){ + let text = ""; //temporary data + while(source.canRead()){ + let ch = source.readCh(); + // if (ch === null || ch === undefined) break; + // source.updateBuffer(); + + if (ch === ">") return text.trimEnd(); + else text += ch; + } + throw new Error(`Unexpected end of source. Reading '${substr}'`); +} + +/** + * Read XML tag and build attributes map + * This function can be used to read normal tag, pi tag. + * This function can't be used to read comment, CDATA, DOCTYPE. + * Eg + * @param {string} xmlDoc + * @param {number} startIndex starting index + * @returns tag expression includes tag name & attribute string + */ +export function readTagExp(parser) { + let inSingleQuotes = false; + let inDoubleQuotes = false; + let i; + let EOE = false; + + for (i = 0; parser.source.canRead(i); i++) { + const char = parser.source.readChAt(i); + + if (char === "'" && !inDoubleQuotes) { + inSingleQuotes = !inSingleQuotes; + } else if (char === '"' && !inSingleQuotes) { + inDoubleQuotes = !inDoubleQuotes; + } else if (char === '>' && !inSingleQuotes && !inDoubleQuotes) { + // If not inside quotes, stop reading at '>' + EOE = true; + break; + } + + } + if(inSingleQuotes || inDoubleQuotes){ + throw new Error("Invalid attribute expression. Quote is not properly closed"); + }else if(!EOE) throw new Error("Unexpected closing of source. Waiting for '>'"); + + + const exp = parser.source.readStr(i); + parser.source.updateBufferBoundary(i + 1); + return buildTagExpObj(exp, parser) +} + +export function readPiExp(parser) { + let inSingleQuotes = false; + let inDoubleQuotes = false; + let i; + let EOE = false; + + for (i = 0; parser.source.canRead(i) ; i++) { + const currentChar = parser.source.readChAt(i); + const nextChar = parser.source.readChAt(i+1); + + if (currentChar === "'" && !inDoubleQuotes) { + inSingleQuotes = !inSingleQuotes; + } else if (currentChar === '"' && !inSingleQuotes) { + inDoubleQuotes = !inDoubleQuotes; + } + + if (!inSingleQuotes && !inDoubleQuotes) { + if (currentChar === '?' && nextChar === '>') { + EOE = true; + break; // Exit the loop when '?>' is found + } + } + } + if(inSingleQuotes || inDoubleQuotes){ + throw new Error("Invalid attribute expression. Quote is not properly closed in PI tag expression"); + }else if(!EOE) throw new Error("Unexpected closing of source. Waiting for '?>'"); + + if(!parser.options.attributes.ignore){ + //TODO: use regex to verify attributes if not set to ignore + } + + const exp = parser.source.readStr(i); + parser.source.updateBufferBoundary(i + 1); + return buildTagExpObj(exp, parser) +} + +function buildTagExpObj(exp, parser){ + const tagExp = { + tagName: "", + selfClosing: false + }; + let attrsExp = ""; + + // Check for self-closing tag before setting the name + if(exp[exp.length -1] === "/") { + tagExp.selfClosing = true; + exp = exp.slice(0, -1); // Remove the trailing slash + } + + //separate tag name + let i = 0; + for (; i < exp.length; i++) { + const char = exp[i]; + if(char === " "){ + tagExp.tagName = exp.substring(0, i); + attrsExp = exp.substring(i + 1); + break; + } + } + //only tag + if(tagExp.tagName.length === 0 && i === exp.length)tagExp.tagName = exp; + + tagExp.tagName = tagExp.tagName.trimEnd(); + + if(!parser.options.attributes.ignore && attrsExp.length > 0){ + parseAttributesExp(attrsExp,parser) + } + + return tagExp; +} + +const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); + +function parseAttributesExp(attrStr, parser) { + const matches = getAllMatches(attrStr, attrsRegx); + const len = matches.length; //don't make it inline + for (let i = 0; i < len; i++) { + let attrName = parser.processAttrName(matches[i][1]); + let attrVal = parser.replaceEntities(matches[i][4] || true); + + parser.outputBuilder.addAttribute(attrName, attrVal); + } +} + + +const getAllMatches = function(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); + } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; +}; + diff --git a/node_modules/fast-xml-parser/src/v6/XmlSpecialTagsReader.js b/node_modules/fast-xml-parser/src/v6/XmlSpecialTagsReader.js new file mode 100644 index 0000000000000000000000000000000000000000..330e0a46da7d54b01c1c4290363fe393cad27c68 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/XmlSpecialTagsReader.js @@ -0,0 +1,111 @@ +import {readPiExp} from './XmlPartReader.js'; + +export function readCdata(parser){ + //"); + parser.outputBuilder.addCdata(text); +} +export function readPiTag(parser){ + //"); + if(!tagExp) throw new Error("Invalid Pi Tag expression."); + + if (tagExp.tagName === "?xml") {//TODO: test if tagName is just xml + parser.outputBuilder.addDeclaration(); + } else { + parser.outputBuilder.addPi("?"+tagExp.tagName); + } +} + +export function readComment(parser){ + //"); + parser.outputBuilder.addComment(text); +} + +const DOCTYPE_tags = { + "EL":/^EMENT\s+([^\s>]+)\s+(ANY|EMPTY|\(.+\)\s*$)/m, + "AT":/^TLIST\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+$/m, + "NO":/^TATION.+$/m +} +export function readDocType(parser){ + //"); + const regx = DOCTYPE_tags[str]; + if(regx){ + const match = dTagExp.match(regx); + if(!match) throw new Error("Invalid DOCTYPE"); + }else throw new Error("Invalid DOCTYPE"); + } + }else if( ch === '>' && lastch === "]"){//end of doctype + return; + } + }else if( ch === '>'){//end of doctype + return; + }else if( ch === '['){ + hasBody = true; + }else{ + lastch = ch; + } + }//End While loop + +} + +function registerEntity(parser){ + //read Entity + let attrBoundary=""; + let name ="", val =""; + while(source.canRead()){ + let ch = source.readCh(); + + if(attrBoundary){ + if (ch === attrBoundary){ + val = text; + text = "" + } + }else if(ch === " " || ch === "\t"){ + if(!name){ + name = text.trimStart(); + text = ""; + } + }else if (ch === '"' || ch === "'") {//start of attrBoundary + attrBoundary = ch; + }else if(ch === ">"){ + parser.entityParser.addExternalEntity(name,val); + return; + }else{ + text+=ch; + } + } +} diff --git a/node_modules/fast-xml-parser/src/v6/inputSource/BufferSource.js b/node_modules/fast-xml-parser/src/v6/inputSource/BufferSource.js new file mode 100644 index 0000000000000000000000000000000000000000..2c5d8b59c6b6587222dda290b426bc25c8c7c1d8 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/inputSource/BufferSource.js @@ -0,0 +1,116 @@ +const Constants = { + space: 32, + tab: 9 +} +export default class BufferSource{ + constructor(bytesArr){ + this.line = 1; + this.cols = 0; + this.buffer = bytesArr; + this.startIndex = 0; + } + + + + readCh() { + return String.fromCharCode(this.buffer[this.startIndex++]); + } + + readChAt(index) { + return String.fromCharCode(this.buffer[this.startIndex+index]); + } + + readStr(n,from){ + if(typeof from === "undefined") from = this.startIndex; + return this.buffer.slice(from, from + n).toString(); + } + + readUpto(stopStr) { + const inputLength = this.buffer.length; + const stopLength = stopStr.length; + const stopBuffer = Buffer.from(stopStr); + + for (let i = this.startIndex; i < inputLength; i++) { + let match = true; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopBuffer[j]) { + match = false; + break; + } + } + + if (match) { + const result = this.buffer.slice(this.startIndex, i).toString(); + this.startIndex = i + stopLength; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); +} + +readUptoCloseTag(stopStr) { //stopStr: "'){ //TODO: if it should be equivalent ASCII + match = 2; + //tag boundary found + // this.startIndex + } + }else{ + match = 1; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopBuffer[j]) { + match = 0; + break; + } + } + } + if (match === 2) {//matched closing part + const result = this.buffer.slice(this.startIndex, stopIndex - 1 ).toString(); + this.startIndex = i + 1; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); +} + + readFromBuffer(n, shouldUpdate) { + let ch; + if (n === 1) { + ch = this.buffer[this.startIndex]; + if (ch === 10) { + this.line++; + this.cols = 1; + } else { + this.cols++; + } + ch = String.fromCharCode(ch); + } else { + this.cols += n; + ch = this.buffer.slice(this.startIndex, this.startIndex + n).toString(); + } + if (shouldUpdate) this.updateBuffer(n); + return ch; + } + + updateBufferBoundary(n = 1) { //n: number of characters read + this.startIndex += n; + } + + canRead(n){ + n = n || this.startIndex; + return this.buffer.length - n + 1 > 0; + } + +} diff --git a/node_modules/fast-xml-parser/src/v6/inputSource/StringSource.js b/node_modules/fast-xml-parser/src/v6/inputSource/StringSource.js new file mode 100644 index 0000000000000000000000000000000000000000..275889a39b2ca73cb2dfc758590b1be21c253955 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/inputSource/StringSource.js @@ -0,0 +1,121 @@ +const whiteSpaces = [" ", "\n", "\t"]; + + +export default class StringSource{ + constructor(str){ + this.line = 1; + this.cols = 0; + this.buffer = str; + //a boundary pointer to indicate where from the buffer dat should be read + // data before this pointer can be deleted to free the memory + this.startIndex = 0; + } + + readCh() { + return this.buffer[this.startIndex++]; + } + + readChAt(index) { + return this.buffer[this.startIndex+index]; + } + + readStr(n,from){ + if(typeof from === "undefined") from = this.startIndex; + return this.buffer.substring(from, from + n); + } + + readUpto(stopStr) { + const inputLength = this.buffer.length; + const stopLength = stopStr.length; + + for (let i = this.startIndex; i < inputLength; i++) { + let match = true; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopStr[j]) { + match = false; + break; + } + } + + if (match) { + const result = this.buffer.substring(this.startIndex, i); + this.startIndex = i + stopLength; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); + } + + readUptoCloseTag(stopStr) { //stopStr: "'){ + match = 2; + //tag boundary found + // this.startIndex + } + }else{ + match = 1; + for (let j = 0; j < stopLength; j++) { + if (this.buffer[i + j] !== stopStr[j]) { + match = 0; + break; + } + } + } + if (match === 2) {//matched closing part + const result = this.buffer.substring(this.startIndex, stopIndex - 1 ); + this.startIndex = i + 1; + return result; + } + } + + throw new Error(`Unexpected end of source. Reading '${stopStr}'`); + } + + readFromBuffer(n, updateIndex){ + let ch; + if(n===1){ + ch = this.buffer[this.startIndex]; + // if(ch === "\n") { + // this.line++; + // this.cols = 1; + // }else{ + // this.cols++; + // } + }else{ + ch = this.buffer.substring(this.startIndex, this.startIndex + n); + // if("".indexOf("\n") !== -1){ + // //TODO: handle the scenario when there are multiple lines + // //TODO: col should be set to number of chars after last '\n' + // // this.cols = 1; + // }else{ + // this.cols += n; + + // } + } + if(updateIndex) this.updateBufferBoundary(n); + return ch; + } + + //TODO: rename to updateBufferReadIndex + + updateBufferBoundary(n = 1) { //n: number of characters read + this.startIndex += n; + } + + canRead(n){ + n = n || this.startIndex; + return this.buffer.length - n + 1 > 0; + } + +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/EntitiesParser.js b/node_modules/fast-xml-parser/src/v6/valueParsers/EntitiesParser.js new file mode 100644 index 0000000000000000000000000000000000000000..b7f7ba8f5532c54f927330caceb7e58301d44ef8 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/EntitiesParser.js @@ -0,0 +1,105 @@ +const ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }; +const htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent": { regex: /&(cent|#162);/g, val: "¢" }, + "pound": { regex: /&(pound|#163);/g, val: "£" }, + "yen": { regex: /&(yen|#165);/g, val: "¥" }, + "euro": { regex: /&(euro|#8364);/g, val: "€" }, + "copyright": { regex: /&(copy|#169);/g, val: "©" }, + "reg": { regex: /&(reg|#174);/g, val: "®" }, + "inr": { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 16)) }, +}; + +export default class EntitiesParser { + constructor(replaceHtmlEntities) { + this.replaceHtmlEntities = replaceHtmlEntities; + this.docTypeEntities = {}; + this.lastEntities = { + "apos": { regex: /&(apos|#39|#x27);/g, val: "'" }, + "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" }, + "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" }, + "quot": { regex: /&(quot|#34|#x22);/g, val: "\"" }, + }; + } + + addExternalEntities(externalEntities) { + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.addExternalEntity(ent, externalEntities[ent]) + } + } + addExternalEntity(key, val) { + validateEntityName(key); + if (val.indexOf("&") !== -1) { + reportWarning(`Entity ${key} is not added as '&' is found in value;`) + return; + } else { + this.lastEntities[ent] = { + regex: new RegExp("&" + key + ";", "g"), + val: val + } + } + } + + addDocTypeEntities(entities) { + const entKeys = Object.keys(entities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.docTypeEntities[ent] = { + regex: new RegExp("&" + ent + ";", "g"), + val: entities[ent] + } + } + } + + parse(val) { + return this.replaceEntitiesValue(val) + } + + /** + * 1. Replace DOCTYPE entities + * 2. Replace external entities + * 3. Replace HTML entities if asked + * @param {string} val + */ + replaceEntitiesValue(val) { + if (typeof val === "string" && val.length > 0) { + for (let entityName in this.docTypeEntities) { + const entity = this.docTypeEntities[entityName]; + val = val.replace(entity.regx, entity.val); + } + for (let entityName in this.lastEntities) { + const entity = this.lastEntities[entityName]; + val = val.replace(entity.regex, entity.val); + } + if (this.replaceHtmlEntities) { + for (let entityName in htmlEntities) { + const entity = htmlEntities[entityName]; + val = val.replace(entity.regex, entity.val); + } + } + val = val.replace(ampEntity.regex, ampEntity.val); + } + return val; + } +}; + +//an entity name should not contains special characters that may be used in regex +//Eg !?\\\/[]$%{}^&*()<> +const specialChar = "!?\\\/[]$%{}^&*()<>|+"; + +function validateEntityName(name) { + for (let i = 0; i < specialChar.length; i++) { + const ch = specialChar[i]; + if (name.indexOf(ch) !== -1) throw new Error(`Invalid character ${ch} in entity name`); + } + return name; +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParser.js b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParser.js new file mode 100644 index 0000000000000000000000000000000000000000..bc8f8064281b5e9a30c1077c7fcb9f600edce809 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParser.js @@ -0,0 +1,22 @@ +export default class boolParser{ + constructor(trueList, falseList){ + if(trueList) + this.trueList = trueList; + else + this.trueList = ["true"]; + + if(falseList) + this.falseList = falseList; + else + this.falseList = ["false"]; + } + parse(val){ + if (typeof val === 'string') { + //TODO: performance: don't convert + const temp = val.toLowerCase(); + if(this.trueList.indexOf(temp) !== -1) return true; + else if(this.falseList.indexOf(temp) !== -1 ) return false; + } + return val; + } +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParserExt.js b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParserExt.js new file mode 100644 index 0000000000000000000000000000000000000000..ec3ba427f56fec9dc4fdc8e56364a133e4df2c30 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/booleanParserExt.js @@ -0,0 +1,19 @@ +export default function boolParserExt(val){ + if(isArray(val)){ + for (let i = 0; i < val.length; i++) { + val[i] = parse(val[i]) + } + }else{ + val = parse(val) + } + return val; +} + +function parse(val){ + if (typeof val === 'string') { + const temp = val.toLowerCase(); + if(temp === 'true' || temp ==="yes" || temp==="1") return true; + else if(temp === 'false' || temp ==="no" || temp==="0") return false; + } + return val; +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/currency.js b/node_modules/fast-xml-parser/src/v6/valueParsers/currency.js new file mode 100644 index 0000000000000000000000000000000000000000..3772817678bc48756460ad8f8f5e1f5460158f8a --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/currency.js @@ -0,0 +1,38 @@ +const defaultOptions = { + maxLength: 200, + // locale: "en-IN" +} +const localeMap = { + "$":"en-US", + "€":"de-DE", + "£":"en-GB", + "¥":"ja-JP", + "₹":"en-IN", +} +const sign = "(?:-|\+)?"; +const digitsAndSeparator = "(?:\d+|\d{1,3}(?:,\d{3})+)"; +const decimalPart = "(?:\.\d{1,2})?"; +const symbol = "(?:\$|€|¥|₹)?"; + +const currencyCheckRegex = /^\s*(?:-|\+)?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d{1,2})?\s*(?:\$|€|¥|₹)?\s*$/u; + +export default class CurrencyParser{ + constructor(options){ + this.options = options || defaultOptions; + } + parse(val){ + if (typeof val === 'string' && val.length <= this.options.maxLength) { + if(val.indexOf(",,") !== -1 && val.indexOf(".." !== -1)){ + const match = val.match(currencyCheckRegex); + if(match){ + const locale = this.options.locale || localeMap[match[2]||match[5]||"₹"]; + const formatter = new Intl.NumberFormat(locale) + val = val.replace(/[^0-9,.]/g, '').trim(); + val = Number(val.replace(formatter.format(1000)[1], '')); + } + } + } + return val; + } +} +CurrencyParser.defaultOptions = defaultOptions; diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/join.js b/node_modules/fast-xml-parser/src/v6/valueParsers/join.js new file mode 100644 index 0000000000000000000000000000000000000000..f597d99af09033cb045d81a631be977bdc209999 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/join.js @@ -0,0 +1,13 @@ +/** + * + * @param {array} val + * @param {string} by + * @returns + */ +export default function join(val, by=" "){ + if(isArray(val)){ + val.join(by) + } + return val; +} + diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/number.js b/node_modules/fast-xml-parser/src/v6/valueParsers/number.js new file mode 100644 index 0000000000000000000000000000000000000000..8397fb616e3261a683b42c77854be5c41957c474 --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/number.js @@ -0,0 +1,14 @@ +import toNumber from "strnum"; + + +export default class numParser{ + constructor(options){ + this.options = options; + } + parse(val){ + if (typeof val === 'string') { + val = toNumber(val,this.options); + } + return val; + } +} diff --git a/node_modules/fast-xml-parser/src/v6/valueParsers/trim.js b/node_modules/fast-xml-parser/src/v6/valueParsers/trim.js new file mode 100644 index 0000000000000000000000000000000000000000..50eed7f9bba23ded3d63bddc77cd11a2dae324ec --- /dev/null +++ b/node_modules/fast-xml-parser/src/v6/valueParsers/trim.js @@ -0,0 +1,6 @@ +export default class trimmer{ + parse(val){ + if(typeof val === "string") return val.trim(); + else return val; + } +} diff --git a/node_modules/fast-xml-parser/src/validator.js b/node_modules/fast-xml-parser/src/validator.js new file mode 100644 index 0000000000000000000000000000000000000000..277225c256a8c0fece78c4ece523e0e07441d13f --- /dev/null +++ b/node_modules/fast-xml-parser/src/validator.js @@ -0,0 +1,425 @@ +'use strict'; + +import { getAllMatches, isName } from './util.js'; + +const defaultOptions = { + allowBooleanAttributes: false, //A tag can have attributes without any value + unpairedTags: [] +}; + +//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g"); +export function validate(xmlData, options) { + options = Object.assign({}, defaultOptions, options); + + //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line + //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag + //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE + const tags = []; + let tagFound = false; + + //indicates that the root tag has been closed (aka. depth 0 has been reached) + let reachedRoot = false; + + if (xmlData[0] === '\ufeff') { + // check for byte order mark (BOM) + xmlData = xmlData.substr(1); + } + + for (let i = 0; i < xmlData.length; i++) { + + if (xmlData[i] === '<' && xmlData[i + 1] === '?') { + i += 2; + i = readPI(xmlData, i); + if (i.err) return i; + } else if (xmlData[i] === '<') { + //starting of tag + //read until you reach to '>' avoiding any '>' in attribute value + let tagStartPos = i; + i++; + + if (xmlData[i] === '!') { + i = readCommentAndCDATA(xmlData, i); + continue; + } else { + let closingTag = false; + if (xmlData[i] === '/') { + //closing tag + closingTag = true; + i++; + } + //read tagname + let tagName = ''; + for (; i < xmlData.length && + xmlData[i] !== '>' && + xmlData[i] !== ' ' && + xmlData[i] !== '\t' && + xmlData[i] !== '\n' && + xmlData[i] !== '\r'; i++ + ) { + tagName += xmlData[i]; + } + tagName = tagName.trim(); + //console.log(tagName); + + if (tagName[tagName.length - 1] === '/') { + //self closing tag without attributes + tagName = tagName.substring(0, tagName.length - 1); + //continue; + i--; + } + if (!validateTagName(tagName)) { + let msg; + if (tagName.trim().length === 0) { + msg = "Invalid space after '<'."; + } else { + msg = "Tag '" + tagName + "' is an invalid name."; + } + return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i)); + } + + const result = readAttributeStr(xmlData, i); + if (result === false) { + return getErrorObject('InvalidAttr', "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i)); + } + let attrStr = result.value; + i = result.index; + + if (attrStr[attrStr.length - 1] === '/') { + //self closing tag + const attrStrStart = i - attrStr.length; + attrStr = attrStr.substring(0, attrStr.length - 1); + const isValid = validateAttributeString(attrStr, options); + if (isValid === true) { + tagFound = true; + //continue; //text may presents after self closing tag + } else { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); + } + } else if (closingTag) { + if (!result.tagClosed) { + return getErrorObject('InvalidTag', "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); + } else if (attrStr.trim().length > 0) { + return getErrorObject('InvalidTag', "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); + } else if (tags.length === 0) { + return getErrorObject('InvalidTag', "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); + } else { + const otg = tags.pop(); + if (tagName !== otg.tagName) { + let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); + return getErrorObject('InvalidTag', + "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", + getLineNumberForPosition(xmlData, tagStartPos)); + } + + //when there are no more tags, we reached the root level. + if (tags.length == 0) { + reachedRoot = true; + } + } + } else { + const isValid = validateAttributeString(attrStr, options); + if (isValid !== true) { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); + } + + //if the root level has been reached before ... + if (reachedRoot === true) { + return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i)); + } else if (options.unpairedTags.indexOf(tagName) !== -1) { + //don't push into stack + } else { + tags.push({ tagName, tagStartPos }); + } + tagFound = true; + } + + //skip tag text value + //It may include comments and CDATA value + for (i++; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + if (xmlData[i + 1] === '!') { + //comment or CADATA + i++; + i = readCommentAndCDATA(xmlData, i); + continue; + } else if (xmlData[i + 1] === '?') { + i = readPI(xmlData, ++i); + if (i.err) return i; + } else { + break; + } + } else if (xmlData[i] === '&') { + const afterAmp = validateAmpersand(xmlData, i); + if (afterAmp == -1) + return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); + i = afterAmp; + } else { + if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { + return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i)); + } + } + } //end of reading tag text value + if (xmlData[i] === '<') { + i--; + } + } + } else { + if (isWhiteSpace(xmlData[i])) { + continue; + } + return getErrorObject('InvalidChar', "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i)); + } + } + + if (!tagFound) { + return getErrorObject('InvalidXml', 'Start tag expected.', 1); + } else if (tags.length == 1) { + return getErrorObject('InvalidTag', "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); + } else if (tags.length > 0) { + return getErrorObject('InvalidXml', "Invalid '" + + JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '') + + "' found.", { line: 1, col: 1 }); + } + + return true; +}; + +function isWhiteSpace(char) { + return char === ' ' || char === '\t' || char === '\n' || char === '\r'; +} +/** + * Read Processing insstructions and skip + * @param {*} xmlData + * @param {*} i + */ +function readPI(xmlData, i) { + const start = i; + for (; i < xmlData.length; i++) { + if (xmlData[i] == '?' || xmlData[i] == ' ') { + //tagname + const tagname = xmlData.substr(start, i - start); + if (i > 5 && tagname === 'xml') { + return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i)); + } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') { + //check if valid attribut string + i++; + break; + } else { + continue; + } + } + } + return i; +} + +function readCommentAndCDATA(xmlData, i) { + if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') { + //comment + for (i += 3; i < xmlData.length; i++) { + if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } else if ( + xmlData.length > i + 8 && + xmlData[i + 1] === 'D' && + xmlData[i + 2] === 'O' && + xmlData[i + 3] === 'C' && + xmlData[i + 4] === 'T' && + xmlData[i + 5] === 'Y' && + xmlData[i + 6] === 'P' && + xmlData[i + 7] === 'E' + ) { + let angleBracketsCount = 1; + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + angleBracketsCount++; + } else if (xmlData[i] === '>') { + angleBracketsCount--; + if (angleBracketsCount === 0) { + break; + } + } + } + } else if ( + xmlData.length > i + 9 && + xmlData[i + 1] === '[' && + xmlData[i + 2] === 'C' && + xmlData[i + 3] === 'D' && + xmlData[i + 4] === 'A' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'A' && + xmlData[i + 7] === '[' + ) { + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } + + return i; +} + +const doubleQuote = '"'; +const singleQuote = "'"; + +/** + * Keep reading xmlData until '<' is found outside the attribute value. + * @param {string} xmlData + * @param {number} i + */ +function readAttributeStr(xmlData, i) { + let attrStr = ''; + let startChar = ''; + let tagClosed = false; + for (; i < xmlData.length; i++) { + if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { + if (startChar === '') { + startChar = xmlData[i]; + } else if (startChar !== xmlData[i]) { + //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa + } else { + startChar = ''; + } + } else if (xmlData[i] === '>') { + if (startChar === '') { + tagClosed = true; + break; + } + } + attrStr += xmlData[i]; + } + if (startChar !== '') { + return false; + } + + return { + value: attrStr, + index: i, + tagClosed: tagClosed + }; +} + +/** + * Select all the attributes whether valid or invalid. + */ +const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g'); + +//attr, ="sd", a="amit's", a="sd"b="saf", ab cd="" + +function validateAttributeString(attrStr, options) { + //console.log("start:"+attrStr+":end"); + + //if(attrStr.trim().length === 0) return true; //empty string + + const matches = getAllMatches(attrStr, validAttrStrRegxp); + const attrNames = {}; + + for (let i = 0; i < matches.length; i++) { + if (matches[i][1].length === 0) { + //nospace before attribute name: a="sd"b="saf" + return getErrorObject('InvalidAttr', "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i])) + } else if (matches[i][3] !== undefined && matches[i][4] === undefined) { + return getErrorObject('InvalidAttr', "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) { + //independent attribute: ab + return getErrorObject('InvalidAttr', "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i])); + } + /* else if(matches[i][6] === undefined){//attribute without value: ab= + return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}}; + } */ + const attrName = matches[i][2]; + if (!validateAttrName(attrName)) { + return getErrorObject('InvalidAttr', "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i])); + } + if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) { + //check for duplicate attribute. + attrNames[attrName] = 1; + } else { + return getErrorObject('InvalidAttr', "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i])); + } + } + + return true; +} + +function validateNumberAmpersand(xmlData, i) { + let re = /\d/; + if (xmlData[i] === 'x') { + i++; + re = /[\da-fA-F]/; + } + for (; i < xmlData.length; i++) { + if (xmlData[i] === ';') + return i; + if (!xmlData[i].match(re)) + break; + } + return -1; +} + +function validateAmpersand(xmlData, i) { + // https://www.w3.org/TR/xml/#dt-charref + i++; + if (xmlData[i] === ';') + return -1; + if (xmlData[i] === '#') { + i++; + return validateNumberAmpersand(xmlData, i); + } + let count = 0; + for (; i < xmlData.length; i++, count++) { + if (xmlData[i].match(/\w/) && count < 20) + continue; + if (xmlData[i] === ';') + break; + return -1; + } + return i; +} + +function getErrorObject(code, message, lineNumber) { + return { + err: { + code: code, + msg: message, + line: lineNumber.line || lineNumber, + col: lineNumber.col, + }, + }; +} + +function validateAttrName(attrName) { + return isName(attrName); +} + +// const startsWithXML = /^xml/i; + +function validateTagName(tagname) { + return isName(tagname) /* && !tagname.match(startsWithXML) */; +} + +//this function returns the line number for the character at the given index +function getLineNumberForPosition(xmlData, index) { + const lines = xmlData.substring(0, index).split(/\r?\n/); + return { + line: lines.length, + + // column number is last line's length + 1, because column numbering starts at 1: + col: lines[lines.length - 1].length + 1 + }; +} + +//this function returns the position of the first character of match within attrStr +function getPositionFromMatch(match) { + return match.startIndex + match[1].length; +} diff --git a/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js b/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js new file mode 100644 index 0000000000000000000000000000000000000000..30cfaa174a4e9256b6033e7cf355af080eae09a6 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js @@ -0,0 +1,6 @@ +// Re-export from fast-xml-builder for backward compatibility +import XMLBuilder from 'fast-xml-builder'; +export default XMLBuilder; + +// If there are any named exports you also want to re-export: +export * from 'fast-xml-builder'; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js b/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js new file mode 100644 index 0000000000000000000000000000000000000000..f60094451fadc2dffde1d7d39cdac7326c6dbe62 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js @@ -0,0 +1,411 @@ +import { qName as isName } from 'xml-naming'; + +export default class DocTypeReader { + constructor(options, xmlVersion) { + this.suppressValidationErr = !options; + this.options = options; + this.xmlVersion = xmlVersion || 1.0; + } + + setXmlVersion(xmlVersion = 1.0) { + this.xmlVersion = xmlVersion; + } + readDocType(xmlData, i) { + const entities = Object.create(null); + let entityCount = 0; + + if (xmlData[i + 3] === 'O' && + xmlData[i + 4] === 'C' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'Y' && + xmlData[i + 7] === 'P' && + xmlData[i + 8] === 'E') { + i = i + 9; + let angleBracketsCount = 1; + let hasBody = false, comment = false; + let exp = ""; + for (; i < xmlData.length; i++) { + if (xmlData[i] === '<' && !comment) { //Determine the tag type + if (hasBody && hasSeq(xmlData, "!ENTITY", i)) { + i += 7; + let entityName, val; + [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr); + if (val.indexOf("&") === -1) { //Parameter entities are not supported + if (this.options.enabled !== false && + this.options.maxEntityCount != null && + entityCount >= this.options.maxEntityCount) { + throw new Error( + `Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})` + ); + } + //const escaped = entityName.replace(/[.\-+*:]/g, '\\.'); + //const escaped = entityName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + entities[entityName] = val; + entityCount++; + } + } + else if (hasBody && hasSeq(xmlData, "!ELEMENT", i)) { + i += 8;//Not supported + const { index } = this.readElementExp(xmlData, i + 1); + i = index; + } else if (hasBody && hasSeq(xmlData, "!ATTLIST", i)) { + i += 8;//Not supported + // const {index} = this.readAttlistExp(xmlData,i+1); + // i = index; + } else if (hasBody && hasSeq(xmlData, "!NOTATION", i)) { + i += 9;//Not supported + const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr); + i = index; + } else if (hasSeq(xmlData, "!--", i)) comment = true; + else throw new Error(`Invalid DOCTYPE`); + + angleBracketsCount++; + exp = ""; + } else if (xmlData[i] === '>') { //Read tag content + if (comment) { + if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") { + comment = false; + angleBracketsCount--; + } + } else { + angleBracketsCount--; + } + if (angleBracketsCount === 0) { + break; + } + } else if (xmlData[i] === '[') { + hasBody = true; + } else { + exp += xmlData[i]; + } + } + if (angleBracketsCount !== 0) { + throw new Error(`Unclosed DOCTYPE`); + } + } else { + throw new Error(`Invalid Tag instead of DOCTYPE`); + } + return { entities, i }; + } + readEntityExp(xmlData, i) { + //External entities are not supported + // + + //Parameter entities are not supported + // + + //Internal entities are supported + // + + // Skip leading whitespace after this.options.maxEntitySize) { + throw new Error( + `Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})` + ); + } + + i--; + return [entityName, entityValue, i]; + } + + readNotationExp(xmlData, i) { + // Skip leading whitespace after + // + // + // + // + + // Skip leading whitespace after { + while (index < data.length && /\s/.test(data[index])) { + index++; + } + return index; +}; + + + +function hasSeq(data, seq, i) { + for (let j = 0; j < seq.length; j++) { + if (seq[j] !== data[i + j + 1]) return false; + } + return true; +} + +function validateEntityName(name, xmlVersion) { + if (isName(name, { xmlVersion: xmlVersion })) + return name; + else + throw new Error(`Invalid entity name ${name}`); +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js b/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js new file mode 100644 index 0000000000000000000000000000000000000000..0822b996829367f984af70d206b2ba24c7817114 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js @@ -0,0 +1,164 @@ +import { DANGEROUS_PROPERTY_NAMES, criticalProperties } from "../util.js"; +import { COMMON_HTML, CURRENCY } from '@nodable/entities'; + +const defaultOnDangerousProperty = (name) => { + if (DANGEROUS_PROPERTY_NAMES.includes(name)) { + return "__" + name; + } + return name; +}; + + +export const defaultOptions = { + preserveOrder: false, + attributeNamePrefix: '@_', + attributesGroupName: false, + textNodeName: '#text', + ignoreAttributes: true, + removeNSPrefix: false, // remove NS from tag name or attribute name if true + allowBooleanAttributes: false, //a tag can have attributes without any value + //ignoreRootElement : false, + parseTagValue: true, + parseAttributeValue: false, + trimValues: true, //Trim string values of tag and attributes + cdataPropName: false, + numberParseOptions: { + hex: true, + leadingZeros: true, + eNotation: true, + unicode: false + }, + tagValueProcessor: function (tagName, val) { + return val; + }, + attributeValueProcessor: function (attrName, val) { + return val; + }, + stopNodes: [], //nested tags will not be parsed even for errors + alwaysCreateTextNode: false, + isArray: () => false, + commentPropName: false, + unpairedTags: [], + processEntities: true, + htmlEntities: false, + entityDecoder: null, + ignoreDeclaration: false, + ignorePiTags: false, + transformTagName: false, + transformAttributeName: false, + updateTag: function (tagName, jPath, attrs) { + return tagName + }, + // skipEmptyListItem: false + captureMetaData: false, + maxNestedTags: 100, + strictReservedNames: true, + jPath: true, // if true, pass jPath string to callbacks; if false, pass matcher instance + onDangerousProperty: defaultOnDangerousProperty +}; + + +/** + * Validates that a property name is safe to use + * @param {string} propertyName - The property name to validate + * @param {string} optionName - The option field name (for error message) + * @throws {Error} If property name is dangerous + */ +function validatePropertyName(propertyName, optionName) { + if (typeof propertyName !== 'string') { + return; // Only validate string property names + } + + const normalized = propertyName.toLowerCase(); + if (DANGEROUS_PROPERTY_NAMES.some(dangerous => normalized === dangerous.toLowerCase())) { + throw new Error( + `[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution` + ); + } + + if (criticalProperties.some(dangerous => normalized === dangerous.toLowerCase())) { + throw new Error( + `[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution` + ); + } +} + +/** + * Normalizes processEntities option for backward compatibility + * @param {boolean|object} value + * @returns {object} Always returns normalized object + */ +function normalizeProcessEntities(value, htmlEntities) { + // Boolean backward compatibility + if (typeof value === 'boolean') { + return { + enabled: value, // true or false + maxEntitySize: 10000, + maxExpansionDepth: 10000, + maxTotalExpansions: Infinity, + maxExpandedLength: 100000, + maxEntityCount: 1000, + allowedTags: null, + tagFilter: null, + appliesTo: "all", + }; + } + + // Object config - merge with defaults + if (typeof value === 'object' && value !== null) { + return { + enabled: value.enabled !== false, + maxEntitySize: Math.max(1, value.maxEntitySize ?? 10000), + maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 10000), + maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity), + maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 100000), + maxEntityCount: Math.max(1, value.maxEntityCount ?? 1000), + allowedTags: value.allowedTags ?? null, + tagFilter: value.tagFilter ?? null, + appliesTo: value.appliesTo ?? "all", + }; + } + + // Default to enabled with limits + return normalizeProcessEntities(true); +} + +export const buildOptions = function (options) { + const built = Object.assign({}, defaultOptions, options); + + // Validate property names to prevent prototype pollution + const propertyNameOptions = [ + { value: built.attributeNamePrefix, name: 'attributeNamePrefix' }, + { value: built.attributesGroupName, name: 'attributesGroupName' }, + { value: built.textNodeName, name: 'textNodeName' }, + { value: built.cdataPropName, name: 'cdataPropName' }, + { value: built.commentPropName, name: 'commentPropName' } + ]; + + for (const { value, name } of propertyNameOptions) { + if (value) { + validatePropertyName(value, name); + } + } + + if (built.onDangerousProperty === null) { + built.onDangerousProperty = defaultOnDangerousProperty; + } + + // Always normalize processEntities for backward compatibility and validation + built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities); + built.unpairedTagsSet = new Set(built.unpairedTags); + // Convert old-style stopNodes for backward compatibility + if (built.stopNodes && Array.isArray(built.stopNodes)) { + built.stopNodes = built.stopNodes.map(node => { + if (typeof node === 'string' && node.startsWith('*.')) { + // Old syntax: *.tagname meant "tagname anywhere" + // Convert to new syntax: ..tagname + return '..' + node.substring(2); + } + return node; + }); + } + //console.debug(built.processEntities) + return built; +}; \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js b/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js new file mode 100644 index 0000000000000000000000000000000000000000..e51f3750f3e7c4814be728dcf88d7ba0c8fe8bcd --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js @@ -0,0 +1,846 @@ +'use strict'; +///@ts-check + +import { getAllMatches, isExist, DANGEROUS_PROPERTY_NAMES, criticalProperties } from '../util.js'; +import xmlNode from './xmlNode.js'; +import DocTypeReader from './DocTypeReader.js'; +import toNumber from "strnum"; +import getIgnoreAttributesFn from "../ignoreAttributes.js"; +import { Expression, Matcher } from 'path-expression-matcher'; +import { ExpressionSet } from 'path-expression-matcher'; +import { EntityDecoder, XML, CURRENCY, COMMON_HTML, ENTITY_ACTION } from '@nodable/entities'; +import { isUnsafe, VALID_CONTEXTS } from "is-unsafe" + + +// const regx = +// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' +// .replace(/NAME/g, util.nameRegexp); + +//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g"); +//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g"); + +// Helper functions for attribute and namespace handling + +/** + * Extract raw attributes (without prefix) from prefixed attribute map + * @param {object} prefixedAttrs - Attributes with prefix from buildAttributesMap + * @param {object} options - Parser options containing attributeNamePrefix + * @returns {object} Raw attributes for matcher + */ +function extractRawAttributes(prefixedAttrs, options) { + if (!prefixedAttrs) return {}; + + // Handle attributesGroupName option + const attrs = options.attributesGroupName + ? prefixedAttrs[options.attributesGroupName] + : prefixedAttrs; + + if (!attrs) return {}; + + const rawAttrs = {}; + for (const key in attrs) { + // Remove the attribute prefix to get raw name + if (key.startsWith(options.attributeNamePrefix)) { + const rawName = key.substring(options.attributeNamePrefix.length); + rawAttrs[rawName] = attrs[key]; + } else { + // Attribute without prefix (shouldn't normally happen, but be safe) + rawAttrs[key] = attrs[key]; + } + } + return rawAttrs; +} + +/** + * Extract namespace from raw tag name + * @param {string} rawTagName - Tag name possibly with namespace (e.g., "soap:Envelope") + * @returns {string|undefined} Namespace or undefined + */ +function extractNamespace(rawTagName) { + if (!rawTagName || typeof rawTagName !== 'string') return undefined; + + const colonIndex = rawTagName.indexOf(':'); + if (colonIndex !== -1 && colonIndex > 0) { + const ns = rawTagName.substring(0, colonIndex); + // Don't treat xmlns as a namespace + if (ns !== 'xmlns') { + return ns; + } + } + return undefined; +} + +export default class OrderedObjParser { + constructor(options, externalEntities) { + this.options = options; + this.currentNode = null; + this.tagsNodeStack = []; + this.parseXml = parseXml; + this.parseTextData = parseTextData; + this.resolveNameSpace = resolveNameSpace; + this.buildAttributesMap = buildAttributesMap; + this.isItStopNode = isItStopNode; + this.replaceEntitiesValue = replaceEntitiesValue; + this.readStopNodeData = readStopNodeData; + this.saveTextToParentTag = saveTextToParentTag; + this.addChild = addChild; + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes) + this.entityExpansionCount = 0; + this.currentExpandedLength = 0; + let namedEntities = { ...XML }; + if (this.options.entityDecoder) { + this.entityDecoder = this.options.entityDecoder + } else { + if (typeof this.options.htmlEntities === "object") namedEntities = this.options.htmlEntities; + else if (this.options.htmlEntities === true) namedEntities = { ...COMMON_HTML, ...CURRENCY }; + this.entityDecoder = new EntityDecoder({ + namedEntities: { ...namedEntities, ...externalEntities }, + numericAllowed: this.options.htmlEntities, + limit: { + maxTotalExpansions: this.options.processEntities.maxTotalExpansions, + maxExpandedLength: this.options.processEntities.maxExpandedLength, + applyLimitsTo: this.options.processEntities.appliesTo, + }, + // onExternalEntity: (name, value) => isUnsafe(value) ? 'block' : 'allow', + onInputEntity: (name, value) => + //TODO: VALID_CONTEXTS.HTML should be set only if this.options.htmlEntities + isUnsafe(value, [VALID_CONTEXTS.HTML, VALID_CONTEXTS.XML]) + ? ENTITY_ACTION.BLOCK : ENTITY_ACTION.ALLOW, + + //postCheck: resolved => resolved + }); + } + + // Initialize path matcher for path-expression-matcher + this.matcher = new Matcher(); + this.readonlyMatcher = this.matcher.readOnly(); + + // Flag to track if current node is a stop node (optimization) + this.isCurrentNodeStopNode = false; + + // Pre-compile stopNodes expressions + this.stopNodeExpressionsSet = new ExpressionSet(); + const stopNodesOpts = this.options.stopNodes; + if (stopNodesOpts && stopNodesOpts.length > 0) { + for (let i = 0; i < stopNodesOpts.length; i++) { + const stopNodeExp = stopNodesOpts[i]; + if (typeof stopNodeExp === 'string') { + // Convert string to Expression object + this.stopNodeExpressionsSet.add(new Expression(stopNodeExp)); + } else if (stopNodeExp instanceof Expression) { + // Already an Expression object + this.stopNodeExpressionsSet.add(stopNodeExp); + } + } + this.stopNodeExpressionsSet.seal(); + } + } + +} + + +/** + * @param {string} val + * @param {string} tagName + * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath + * @param {boolean} dontTrim + * @param {boolean} hasAttributes + * @param {boolean} isLeafNode + * @param {boolean} escapeEntities + */ +function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { + const options = this.options; + if (val !== undefined) { + if (options.trimValues && !dontTrim) { + val = val.trim(); + } + if (val.length > 0) { + if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath); + + // Pass jPath string or matcher based on options.jPath setting + const jPathOrMatcher = options.jPath ? jPath.toString() : jPath; + const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode); + if (newval === null || newval === undefined) { + //don't parse + return val; + } else if (typeof newval !== typeof val || newval !== val) { + //overwrite + return newval; + } else if (options.trimValues) { + return parseValue(val, options.parseTagValue, options.numberParseOptions); + } else { + const trimmedVal = val.trim(); + if (trimmedVal === val) { + return parseValue(val, options.parseTagValue, options.numberParseOptions); + } else { + return val; + } + } + } + } +} + +function resolveNameSpace(tagname) { + if (this.options.removeNSPrefix) { + const tags = tagname.split(':'); + const prefix = tagname.charAt(0) === '/' ? '/' : ''; + if (tags[0] === 'xmlns') { + return ''; + } + if (tags.length === 2) { + tagname = prefix + tags[1]; + } + } + return tagname; +} + +//TODO: change regex to capture NS +//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm"); +const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); + +function buildAttributesMap(attrStr, jPath, tagName, force = false) { + const options = this.options; + if (force === true || (options.ignoreAttributes !== true && typeof attrStr === 'string')) { + // attrStr = attrStr.replace(/\r?\n/g, ' '); + //attrStr = attrStr || attrStr.trim(); + + const matches = getAllMatches(attrStr, attrsRegx); + const len = matches.length; //don't make it inline + const attrs = {}; + + // Pre-process values once: trim + entity replacement + // Reused in both matcher update and second pass + const processedVals = new Array(len); + let hasRawAttrs = false; + const rawAttrsForMatcher = {}; + + for (let i = 0; i < len; i++) { + const attrName = this.resolveNameSpace(matches[i][1]); + const oldVal = matches[i][4]; + + if (attrName.length && oldVal !== undefined) { + let val = oldVal; + if (options.trimValues) val = val.trim(); + val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher); + processedVals[i] = val; + + rawAttrsForMatcher[attrName] = val; + hasRawAttrs = true; + } + } + + // Update matcher ONCE before second pass, if applicable + if (hasRawAttrs && typeof jPath === 'object' && jPath.updateCurrent) { + jPath.updateCurrent(rawAttrsForMatcher); + } + + // Hoist toString() once — path doesn't change during attribute processing + const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher; + + // Second pass: apply processors, build final attrs + let hasAttrs = false; + for (let i = 0; i < len; i++) { + const attrName = this.resolveNameSpace(matches[i][1]); + + if (this.ignoreAttributesFn(attrName, jPathStr)) continue; + + let aName = options.attributeNamePrefix + attrName; + + if (attrName.length) { + if (options.transformAttributeName) { + aName = options.transformAttributeName(aName); + } + aName = sanitizeName(aName, options); + + if (matches[i][4] !== undefined) { + // Reuse already-processed value — no double entity replacement + const oldVal = processedVals[i]; + + const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr); + if (newVal === null || newVal === undefined) { + attrs[aName] = oldVal; + } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) { + attrs[aName] = newVal; + } else { + attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions); + } + hasAttrs = true; + } else if (options.allowBooleanAttributes) { + attrs[aName] = true; + hasAttrs = true; + } + } + } + + if (!hasAttrs) return; + + if (options.attributesGroupName && !options.preserveOrder) { + const attrCollection = {}; + attrCollection[options.attributesGroupName] = attrs; + return attrCollection; + } + return attrs; + } +} +const parseXml = function (xmlData) { + xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line + const xmlObj = new xmlNode('!xml'); + let currentNode = xmlObj; + let textData = ""; + + // Reset matcher for new document + this.matcher.reset(); + this.entityDecoder.reset(); + + // Reset entity expansion counters for this document + this.entityExpansionCount = 0; + this.currentExpandedLength = 0; + const options = this.options; + const docTypeReader = new DocTypeReader(options.processEntities); + const xmlLen = xmlData.length; + for (let i = 0; i < xmlLen; i++) {//for each char in XML data + const ch = xmlData[i]; + if (ch === '<') { + // const nextIndex = i+1; + // const _2ndChar = xmlData[nextIndex]; + const c1 = xmlData.charCodeAt(i + 1); + if (c1 === 47) {//Closing Tag '/' + const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.") + let tagName = xmlData.substring(i + 2, closeIndex).trim(); + + if (options.removeNSPrefix) { + const colonIndex = tagName.indexOf(":"); + if (colonIndex !== -1) { + tagName = tagName.substr(colonIndex + 1); + } + } + + tagName = transformTagName(options.transformTagName, tagName, "", options).tagName; + + if (currentNode) { + textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher); + } + + //check if last tag of nested tag was unpaired tag + const lastTagName = this.matcher.getCurrentTag(); + if (tagName && options.unpairedTagsSet.has(tagName)) { + throw new Error(`Unpaired tag can not be used as closing tag: `); + } + if (lastTagName && options.unpairedTagsSet.has(lastTagName)) { + // Pop the unpaired tag + this.matcher.pop(); + this.tagsNodeStack.pop(); + } + // Pop the closing tag + this.matcher.pop(); + this.isCurrentNodeStopNode = false; // Reset flag when closing tag + + currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope + textData = ""; + i = closeIndex; + } else if (c1 === 63) { //'?' + + let tagData = readTagExp(xmlData, i, false, "?>"); + if (!tagData) throw new Error("Pi Tag is not closed."); + + textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher); + const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true); + if (attsMap) { + const ver = attsMap[this.options.attributeNamePrefix + "version"]; + this.entityDecoder.setXmlVersion(Number(ver) || 1.0); + docTypeReader.setXmlVersion(Number(ver) || 1.0); + } + if ((options.ignoreDeclaration && tagData.tagName === "?xml") || options.ignorePiTags) { + //do nothing + } else { + + const childNode = new xmlNode(tagData.tagName); + childNode.add(options.textNodeName, ""); + + if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) { + childNode[":@"] = attsMap + } + this.addChild(currentNode, childNode, this.readonlyMatcher, i); + } + + + i = tagData.closeIndex + 1; + } else if (c1 === 33 + && xmlData.charCodeAt(i + 2) === 45 + && xmlData.charCodeAt(i + 3) === 45) { //'!--' + const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed.") + if (options.commentPropName) { + const comment = xmlData.substring(i + 4, endIndex - 2); + + textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher); + + currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]); + } + i = endIndex; + } else if (c1 === 33 + && xmlData.charCodeAt(i + 2) === 68) { //'!D' + const result = docTypeReader.readDocType(xmlData, i); + this.entityDecoder.addInputEntities(result.entities); + i = result.i; + } else if (c1 === 33 + && xmlData.charCodeAt(i + 2) === 91) { // '![' + const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; + const tagExp = xmlData.substring(i + 9, closeIndex); + + textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher); + + let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true); + if (val == undefined) val = ""; + + //cdata should be set even if it is 0 length string + if (options.cdataPropName) { + currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]); + } else { + currentNode.add(options.textNodeName, val); + } + + i = closeIndex + 2; + } else {//Opening tag + let result = readTagExp(xmlData, i, options.removeNSPrefix); + + // Safety check: readTagExp can return undefined + if (!result) { + // Log context for debugging + const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50)); + throw new Error(`readTagExp returned undefined at position ${i}. Context: "${context}"`); + } + + let tagName = result.tagName; + const rawTagName = result.rawTagName; + let tagExp = result.tagExp; + let attrExpPresent = result.attrExpPresent; + let closeIndex = result.closeIndex; + + ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options)); + + if (options.strictReservedNames && + (tagName === options.commentPropName + || tagName === options.cdataPropName + || tagName === options.textNodeName + || tagName === options.attributesGroupName + )) { + throw new Error(`Invalid tag name: ${tagName}`); + } + + //save text as child node + if (currentNode && textData) { + if (currentNode.tagname !== '!xml') { + //when nested tag is found + textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false); + } + } + + //check if last tag was unpaired tag + const lastTag = currentNode; + if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) { + currentNode = this.tagsNodeStack.pop(); + this.matcher.pop(); + } + + // Clean up self-closing syntax BEFORE processing attributes + // This is where tagExp gets the trailing / removed + let isSelfClosing = false; + if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { + isSelfClosing = true; + if (tagName[tagName.length - 1] === "/") { + tagName = tagName.substr(0, tagName.length - 1); + tagExp = tagName; + } else { + tagExp = tagExp.substr(0, tagExp.length - 1); + } + + // Re-check attrExpPresent after cleaning + attrExpPresent = (tagName !== tagExp); + } + + // Now process attributes with CLEAN tagExp (no trailing /) + let prefixedAttrs = null; + let rawAttrs = {}; + let namespace = undefined; + + // Extract namespace from rawTagName + namespace = extractNamespace(rawTagName); + + // Push tag to matcher FIRST (with empty attrs for now) so callbacks see correct path + if (tagName !== xmlObj.tagname) { + this.matcher.push(tagName, {}, namespace); + } + + // Now build attributes - callbacks will see correct matcher state + if (tagName !== tagExp && attrExpPresent) { + // Build attributes (returns prefixed attributes for the tree) + // Note: buildAttributesMap now internally updates the matcher with raw attributes + prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName); + + if (prefixedAttrs) { + // Extract raw attributes (without prefix) for our use + //TODO: seems a performance overhead + rawAttrs = extractRawAttributes(prefixedAttrs, options); + } + } + + // Now check if this is a stop node (after attributes are set) + if (tagName !== xmlObj.tagname) { + this.isCurrentNodeStopNode = this.isItStopNode(); + } + + const startIndex = i; + if (this.isCurrentNodeStopNode) { + let tagContent = ""; + + // For self-closing tags, content is empty + if (isSelfClosing) { + i = result.closeIndex; + } + //unpaired tag + else if (options.unpairedTagsSet.has(tagName)) { + i = result.closeIndex; + } + //normal tag + else { + //read until closing tag is found + const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); + if (!result) throw new Error(`Unexpected end of ${rawTagName}`); + i = result.i; + tagContent = result.tagContent; + } + + const childNode = new xmlNode(tagName); + + if (prefixedAttrs) { + childNode[":@"] = prefixedAttrs; + } + + // For stop nodes, store raw content as-is without any processing + childNode.add(options.textNodeName, tagContent); + + this.matcher.pop(); // Pop the stop node tag + this.isCurrentNodeStopNode = false; // Reset flag + + this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex); + } else { + //selfClosing tag + if (isSelfClosing) { + ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options)); + + const childNode = new xmlNode(tagName); + if (prefixedAttrs) { + childNode[":@"] = prefixedAttrs; + } + this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex); + this.matcher.pop(); // Pop self-closing tag + this.isCurrentNodeStopNode = false; // Reset flag + } + else if (options.unpairedTagsSet.has(tagName)) {//unpaired tag + const childNode = new xmlNode(tagName); + if (prefixedAttrs) { + childNode[":@"] = prefixedAttrs; + } + this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex); + this.matcher.pop(); // Pop unpaired tag + this.isCurrentNodeStopNode = false; // Reset flag + i = result.closeIndex; + // Continue to next iteration without changing currentNode + continue; + } + //opening tag + else { + const childNode = new xmlNode(tagName); + if (this.tagsNodeStack.length > options.maxNestedTags) { + throw new Error("Maximum nested tags exceeded"); + } + this.tagsNodeStack.push(currentNode); + + if (prefixedAttrs) { + childNode[":@"] = prefixedAttrs; + } + this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex); + currentNode = childNode; + } + textData = ""; + i = closeIndex; + } + } + } else { + textData += xmlData[i]; + } + } + return xmlObj.child; +} + +function addChild(currentNode, childNode, matcher, startIndex) { + // unset startIndex if not requested + if (!this.options.captureMetaData) startIndex = undefined; + + // Pass jPath string or matcher based on options.jPath setting + const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher; + const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[":@"]) + if (result === false) { + //do nothing + } else if (typeof result === "string") { + childNode.tagname = result + currentNode.addChild(childNode, startIndex); + } else { + currentNode.addChild(childNode, startIndex); + } +} + +/** + * @param {object} val - Entity object with regex and val properties + * @param {string} tagName - Tag name + * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath + */ +function replaceEntitiesValue(val, tagName, jPath) { + const entityConfig = this.options.processEntities; + + if (!entityConfig || !entityConfig.enabled) { + return val; + } + + // Check if tag is allowed to contain entities + if (entityConfig.allowedTags) { + const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath; + const allowed = Array.isArray(entityConfig.allowedTags) + ? entityConfig.allowedTags.includes(tagName) + : entityConfig.allowedTags(tagName, jPathOrMatcher); + + if (!allowed) { + return val; + } + } + + // Apply custom tag filter if provided + if (entityConfig.tagFilter) { + const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath; + if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) { + return val; // Skip based on custom filter + } + } + + return this.entityDecoder.decode(val); +} + + +function saveTextToParentTag(textData, parentNode, matcher, isLeafNode) { + if (textData) { //store previously collected data as textNode + if (isLeafNode === undefined) isLeafNode = parentNode.child.length === 0 + + textData = this.parseTextData(textData, + parentNode.tagname, + matcher, + false, + parentNode[":@"] ? Object.keys(parentNode[":@"]).length !== 0 : false, + isLeafNode); + + if (textData !== undefined && textData !== "") + parentNode.add(this.options.textNodeName, textData); + textData = ""; + } + return textData; +} + +/** + * @param {Array} stopNodeExpressions - Array of compiled Expression objects + * @param {Matcher} matcher - Current path matcher + */ +function isItStopNode() { + if (this.stopNodeExpressionsSet.size === 0) return false; + + return this.matcher.matchesAny(this.stopNodeExpressionsSet); +} + +/** + * Returns the tag Expression and where it is ending handling single-double quotes situation + * @param {string} xmlData + * @param {number} i starting index + * @returns + */ +function tagExpWithClosingIndex(xmlData, i, closingChar = ">") { + //TODO: ignore boolean attributes in tag expression + //TODO: if ignore attributes, dont read full attribute expression but the end. But read for xml declaration + let attrBoundary = 0; + const len = xmlData.length; + const closeCode0 = closingChar.charCodeAt(0); + const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1; + + let result = ''; + let segmentStart = i; + + for (let index = i; index < len; index++) { + const code = xmlData.charCodeAt(index); + + if (attrBoundary) { + if (code === attrBoundary) attrBoundary = 0; + } else if (code === 34 || code === 39) { // " or ' + attrBoundary = code; + } else if (code === closeCode0) { + if (closeCode1 !== -1) { + if (xmlData.charCodeAt(index + 1) === closeCode1) { + result += xmlData.substring(segmentStart, index); + return { data: result, index }; + } + } else { + result += xmlData.substring(segmentStart, index); + return { data: result, index }; + } + } else if (code === 9 && !attrBoundary) { // \t - only replace with space outside attribute values + // Flush accumulated segment, add space, start new segment + result += xmlData.substring(segmentStart, index) + ' '; + segmentStart = index + 1; + } + } +} + +function findClosingIndex(xmlData, str, i, errMsg) { + const closingIndex = xmlData.indexOf(str, i); + if (closingIndex === -1) { + throw new Error(errMsg) + } else { + return closingIndex + str.length - 1; + } +} + +function findClosingChar(xmlData, char, i, errMsg) { + const closingIndex = xmlData.indexOf(char, i); + if (closingIndex === -1) throw new Error(errMsg); + return closingIndex; // no offset needed +} + +function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") { + const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar); + if (!result) return; + let tagExp = result.data; + const closeIndex = result.index; + const separatorIndex = tagExp.search(/\s/); + let tagName = tagExp; + let attrExpPresent = true; + if (separatorIndex !== -1) {//separate tag name and attributes expression + tagName = tagExp.substring(0, separatorIndex); + tagExp = tagExp.substring(separatorIndex + 1).trimStart(); + } + + const rawTagName = tagName; + if (removeNSPrefix) { + const colonIndex = tagName.indexOf(":"); + if (colonIndex !== -1) { + tagName = tagName.substr(colonIndex + 1); + attrExpPresent = tagName !== result.data.substr(colonIndex + 1); + } + } + + return { + tagName: tagName, + tagExp: tagExp, + closeIndex: closeIndex, + attrExpPresent: attrExpPresent, + rawTagName: rawTagName, + } +} +/** + * find paired tag for a stop node + * @param {string} xmlData + * @param {string} tagName + * @param {number} i + */ +function readStopNodeData(xmlData, tagName, i) { + const startIndex = i; + // Starting at 1 since we already have an open tag + let openTagCount = 1; + + const xmllen = xmlData.length; + for (; i < xmllen; i++) { + if (xmlData[i] === "<") { + const c1 = xmlData.charCodeAt(i + 1); + if (c1 === 47) {//close tag '/' + const closeIndex = findClosingChar(xmlData, ">", i, `${tagName} is not closed`); + let closeTagName = xmlData.substring(i + 2, closeIndex).trim(); + if (closeTagName === tagName) { + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlData.substring(startIndex, i), + i: closeIndex + } + } + } + i = closeIndex; + } else if (c1 === 63) { //? + const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed.") + i = closeIndex; + } else if (c1 === 33 + && xmlData.charCodeAt(i + 2) === 45 + && xmlData.charCodeAt(i + 3) === 45) { // '!--' + const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed.") + i = closeIndex; + } else if (c1 === 33 + && xmlData.charCodeAt(i + 2) === 91) { // '![' + const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; + i = closeIndex; + } else { + const tagData = readTagExp(xmlData, i, false) + + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") { + openTagCount++; + } + i = tagData.closeIndex; + } + } + } + }//end for loop +} + +function parseValue(val, shouldParse, options) { + if (shouldParse && typeof val === 'string') { + //console.log(options) + const newval = val.trim(); + if (newval === 'true') return true; + else if (newval === 'false') return false; + else return toNumber(val, options); + } else { + if (isExist(val)) { + return val; + } else { + return ''; + } + } +} + +function fromCodePoint(str, base, prefix) { + const codePoint = Number.parseInt(str, base); + + if (codePoint >= 0 && codePoint <= 0x10FFFF) { + return String.fromCodePoint(codePoint); + } else { + return prefix + str + ";"; + } +} + +function transformTagName(fn, tagName, tagExp, options) { + if (fn) { + const newTagName = fn(tagName); + if (tagExp === tagName) { + tagExp = newTagName + } + tagName = newTagName; + } + tagName = sanitizeName(tagName, options); + return { tagName, tagExp }; +} + + + +function sanitizeName(name, options) { + if (criticalProperties.includes(name)) { + throw new Error(`[SECURITY] Invalid name: "${name}" is a reserved JavaScript keyword that could cause prototype pollution`); + } else if (DANGEROUS_PROPERTY_NAMES.includes(name)) { + return options.onDangerousProperty(name); + } + return name; +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js b/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js new file mode 100644 index 0000000000000000000000000000000000000000..f82536773144be0b6e531141e183d87d15718d4c --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js @@ -0,0 +1,71 @@ +import { buildOptions } from './OptionsBuilder.js'; +import OrderedObjParser from './OrderedObjParser.js'; +import prettify from './node2json.js'; +import { validate } from "../validator.js"; +import XmlNode from './xmlNode.js'; + +export default class XMLParser { + + constructor(options) { + this.externalEntities = {}; + this.options = buildOptions(options); + + } + /** + * Parse XML dats to JS object + * @param {string|Uint8Array} xmlData + * @param {boolean|Object} validationOption + */ + parse(xmlData, validationOption) { + if (typeof xmlData !== "string" && xmlData.toString) { + xmlData = xmlData.toString(); + } else if (typeof xmlData !== "string") { + throw new Error("XML data is accepted in String or Bytes[] form.") + } + + if (validationOption) { + if (validationOption === true) validationOption = {}; //validate with default options + + const result = validate(xmlData, validationOption); + if (result !== true) { + throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`) + } + } + const orderedObjParser = new OrderedObjParser(this.options, this.externalEntities); + // orderedObjParser.entityDecoder.setExternalEntities(this.externalEntities); + const orderedResult = orderedObjParser.parseXml(xmlData); + if (this.options.preserveOrder || orderedResult === undefined) return orderedResult; + else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher); + } + + /** + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value + */ + addEntity(key, value) { + if (value.indexOf("&") !== -1) { + throw new Error("Entity value can't have '&'") + } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) { + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") + } else if (value === "&") { + throw new Error("An entity with value '&' is not permitted"); + } else { + this.externalEntities[key] = value; + } + } + + /** + * Returns a Symbol that can be used to access the metadata + * property on a node. + * + * If Symbol is not available in the environment, an ordinary property is used + * and the name of the property is here returned. + * + * The XMLMetaData property is only present when `captureMetaData` + * is true in the options. + */ + static getMetaDataSymbol() { + return XmlNode.getMetaDataSymbol(); + } +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/node2json.js b/node_modules/fast-xml-parser/src/xmlparser/node2json.js new file mode 100644 index 0000000000000000000000000000000000000000..ce2e9518e84e3896d115dd375171a7c311d6d8e6 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/node2json.js @@ -0,0 +1,177 @@ +'use strict'; + +import XmlNode from './xmlNode.js'; +import { Matcher } from 'path-expression-matcher'; + +const METADATA_SYMBOL = XmlNode.getMetaDataSymbol(); + +/** + * Helper function to strip attribute prefix from attribute map + * @param {object} attrs - Attributes with prefix (e.g., {"@_class": "code"}) + * @param {string} prefix - Attribute prefix to remove (e.g., "@_") + * @returns {object} Attributes without prefix (e.g., {"class": "code"}) + */ +function stripAttributePrefix(attrs, prefix) { + if (!attrs || typeof attrs !== 'object') return {}; + if (!prefix) return attrs; + + const rawAttrs = {}; + for (const key in attrs) { + if (key.startsWith(prefix)) { + const rawName = key.substring(prefix.length); + rawAttrs[rawName] = attrs[key]; + } else { + // Attribute without prefix (shouldn't normally happen, but be safe) + rawAttrs[key] = attrs[key]; + } + } + return rawAttrs; +} + +/** + * + * @param {array} node + * @param {any} options + * @param {Matcher} matcher - Path matcher instance + * @returns + */ +export default function prettify(node, options, matcher, readonlyMatcher) { + return compress(node, options, matcher, readonlyMatcher); +} + +/** + * @param {array} arr + * @param {object} options + * @param {Matcher} matcher - Path matcher instance + * @returns object + */ +function compress(arr, options, matcher, readonlyMatcher) { + let text; + const compressedObj = {}; //This is intended to be a plain object + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const property = propName(tagObj); + + // Push current property to matcher WITH RAW ATTRIBUTES (no prefix) + if (property !== undefined && property !== options.textNodeName) { + const rawAttrs = stripAttributePrefix( + tagObj[":@"] || {}, + options.attributeNamePrefix + ); + matcher.push(property, rawAttrs); + } + + if (property === options.textNodeName) { + if (text === undefined) text = tagObj[property]; + else text += "" + tagObj[property]; + } else if (property === undefined) { + continue; + } else if (tagObj[property]) { + + let val = compress(tagObj[property], options, matcher, readonlyMatcher); + const isLeaf = isLeafTag(val, options); + + if (Object.keys(val).length === 0 && options.alwaysCreateTextNode) { + val[options.textNodeName] = ""; + } + + if (tagObj[":@"]) { + assignAttributes(val, tagObj[":@"], readonlyMatcher, options); + } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) { + val = val[options.textNodeName]; + } else if (Object.keys(val).length === 0) { + if (options.alwaysCreateTextNode) val[options.textNodeName] = ""; + else val = ""; + } + + if (tagObj[METADATA_SYMBOL] !== undefined && typeof val === "object" && val !== null) { + val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL]; // copy over metadata + } + + + if (compressedObj[property] !== undefined && Object.prototype.hasOwnProperty.call(compressedObj, property)) { + if (!Array.isArray(compressedObj[property])) { + compressedObj[property] = [compressedObj[property]]; + } + compressedObj[property].push(val); + } else { + //TODO: if a node is not an array, then check if it should be an array + //also determine if it is a leaf node + + // Pass jPath string or readonlyMatcher based on options.jPath setting + const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher; + if (options.isArray(property, jPathOrMatcher, isLeaf)) { + compressedObj[property] = [val]; + } else { + compressedObj[property] = val; + } + } + + // Pop property from matcher after processing + if (property !== undefined && property !== options.textNodeName) { + matcher.pop(); + } + } + + } + // if(text && text.length > 0) compressedObj[options.textNodeName] = text; + if (typeof text === "string") { + if (text.length > 0) compressedObj[options.textNodeName] = text; + } else if (text !== undefined) compressedObj[options.textNodeName] = text; + + + return compressedObj; +} + +function propName(obj) { + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (key !== ":@") return key; + } +} + +function assignAttributes(obj, attrMap, readonlyMatcher, options) { + if (attrMap) { + const keys = Object.keys(attrMap); + const len = keys.length; //don't make it inline + for (let i = 0; i < len; i++) { + const atrrName = keys[i]; // This is the PREFIXED name (e.g., "@_class") + + // Strip prefix for matcher path (for isArray callback) + const rawAttrName = atrrName.startsWith(options.attributeNamePrefix) + ? atrrName.substring(options.attributeNamePrefix.length) + : atrrName; + + // For attributes, we need to create a temporary path + // Pass jPath string or matcher based on options.jPath setting + const jPathOrMatcher = options.jPath + ? readonlyMatcher.toString() + "." + rawAttrName + : readonlyMatcher; + + if (options.isArray(atrrName, jPathOrMatcher, true, true)) { + obj[atrrName] = [attrMap[atrrName]]; + } else { + obj[atrrName] = attrMap[atrrName]; + } + } + } +} + +function isLeafTag(obj, options) { + const { textNodeName } = options; + const propCount = Object.keys(obj).length; + + if (propCount === 0) { + return true; + } + + if ( + propCount === 1 && + (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0) + ) { + return true; + } + + return false; +} \ No newline at end of file diff --git a/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js b/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js new file mode 100644 index 0000000000000000000000000000000000000000..4223a8d313e22154b572c6df25850e4a9418ce25 --- /dev/null +++ b/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js @@ -0,0 +1,40 @@ +'use strict'; + +let METADATA_SYMBOL; + +if (typeof Symbol !== "function") { + METADATA_SYMBOL = "@@xmlMetadata"; +} else { + METADATA_SYMBOL = Symbol("XML Node Metadata"); +} + +export default class XmlNode { + constructor(tagname) { + this.tagname = tagname; + this.child = []; //nested tags, text, cdata, comments in order + this[":@"] = Object.create(null); //attributes map + } + add(key, val) { + // this.child.push( {name : key, val: val, isCdata: isCdata }); + if (key === "__proto__") key = "#__proto__"; + this.child.push({ [key]: val }); + } + addChild(node, startIndex) { + if (node.tagname === "__proto__") node.tagname = "#__proto__"; + if (node[":@"] && Object.keys(node[":@"]).length > 0) { + this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] }); + } else { + this.child.push({ [node.tagname]: node.child }); + } + // if requested, add the startIndex + if (startIndex !== undefined) { + // Note: for now we just overwrite the metadata. If we had more complex metadata, + // we might need to do an object append here: metadata = { ...metadata, startIndex } + this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex }; + } + } + /** symbol used for metadata */ + static getMetaDataSymbol() { + return METADATA_SYMBOL; + } +} diff --git a/node_modules/fastq/LICENSE b/node_modules/fastq/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..27c7bb46236e43d5217e02c1b1af452d860ff1e6 --- /dev/null +++ b/node_modules/fastq/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015-2020, Matteo Collina + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/fastq/README.md b/node_modules/fastq/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b44cce36ef1e06da8b5987fd9c6dc508afdff166 --- /dev/null +++ b/node_modules/fastq/README.md @@ -0,0 +1,310 @@ +# fastq + +![ci][ci-url] +[![npm version][npm-badge]][npm-url] + +Fast, in memory work queue. + +Benchmarks (1 million tasks): + +* setImmediate: 812ms +* fastq: 854ms +* async.queue: 1298ms +* neoAsync.queue: 1249ms + +Obtained on node 12.16.1, on a dedicated server. + +If you need zero-overhead series function call, check out +[fastseries](http://npm.im/fastseries). For zero-overhead parallel +function call, check out [fastparallel](http://npm.im/fastparallel). + + * Installation + * Usage + * API + * Licence & copyright + +## Install + +`npm i fastq --save` + +## Usage (callback API) + +```js +'use strict' + +const queue = require('fastq')(worker, 1) + +queue.push(42, function (err, result) { + if (err) { throw err } + console.log('the result is', result) +}) + +function worker (arg, cb) { + cb(null, arg * 2) +} +``` + +## Usage (promise API) + +```js +const queue = require('fastq').promise(worker, 1) + +async function worker (arg) { + return arg * 2 +} + +async function run () { + const result = await queue.push(42) + console.log('the result is', result) +} + +run() +``` + +### Setting "this" + +```js +'use strict' + +const that = { hello: 'world' } +const queue = require('fastq')(that, worker, 1) + +queue.push(42, function (err, result) { + if (err) { throw err } + console.log(this) + console.log('the result is', result) +}) + +function worker (arg, cb) { + console.log(this) + cb(null, arg * 2) +} +``` + +### Using with TypeScript (callback API) + +```ts +'use strict' + +import * as fastq from "fastq"; +import type { queue, done } from "fastq"; + +type Task = { + id: number +} + +const q: queue = fastq(worker, 1) + +q.push({ id: 42}) + +function worker (arg: Task, cb: done) { + console.log(arg.id) + cb(null) +} +``` + +### Using with TypeScript (promise API) + +```ts +'use strict' + +import * as fastq from "fastq"; +import type { queueAsPromised } from "fastq"; + +type Task = { + id: number +} + +const q: queueAsPromised = fastq.promise(asyncWorker, 1) + +q.push({ id: 42}).catch((err) => console.error(err)) + +async function asyncWorker (arg: Task): Promise { + // No need for a try-catch block, fastq handles errors automatically + console.log(arg.id) +} +``` + +## API + +* fastqueue() +* queue#push() +* queue#unshift() +* queue#pause() +* queue#resume() +* queue#idle() +* queue#length() +* queue#getQueue() +* queue#kill() +* queue#killAndDrain() +* queue#error() +* queue#concurrency +* queue#drain +* queue#empty +* queue#saturated +* fastqueue.promise() + +------------------------------------------------------- + +### fastqueue([that], worker, concurrency) + +Creates a new queue. + +Arguments: + +* `that`, optional context of the `worker` function. +* `worker`, worker function, it would be called with `that` as `this`, + if that is specified. +* `concurrency`, number of concurrent tasks that could be executed in + parallel. + +------------------------------------------------------- + +### queue.push(task, done) + +Add a task at the end of the queue. `done(err, result)` will be called +when the task was processed. + +------------------------------------------------------- + +### queue.unshift(task, done) + +Add a task at the beginning of the queue. `done(err, result)` will be called +when the task was processed. + +------------------------------------------------------- + +### queue.pause() + +Pause the processing of tasks. Currently worked tasks are not +stopped. + +------------------------------------------------------- + +### queue.resume() + +Resume the processing of tasks. + +------------------------------------------------------- + +### queue.idle() + +Returns `false` if there are tasks being processed or waiting to be processed. +`true` otherwise. + +------------------------------------------------------- + +### queue.length() + +Returns the number of tasks waiting to be processed (in the queue). + +------------------------------------------------------- + +### queue.getQueue() + +Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks + +------------------------------------------------------- + +### queue.kill() + +Removes all tasks waiting to be processed, and reset `drain` to an empty +function. + +------------------------------------------------------- + +### queue.killAndDrain() + +Same than `kill` but the `drain` function will be called before reset to empty. + +------------------------------------------------------- + +### queue.error(handler) + +Set a global error handler. `handler(err, task)` will be called +each time a task is completed, `err` will be not null if the task has thrown an error. + +------------------------------------------------------- + +### queue.concurrency + +Property that returns the number of concurrent tasks that could be executed in +parallel. It can be altered at runtime. + +------------------------------------------------------- + +### queue.paused + +Property (Read-Only) that returns `true` when the queue is in a paused state. + +------------------------------------------------------- + +### queue.drain + +Function that will be called when the last +item from the queue has been processed by a worker. +It can be altered at runtime. + +------------------------------------------------------- + +### queue.empty + +Function that will be called when the last +item from the queue has been assigned to a worker. +It can be altered at runtime. + +------------------------------------------------------- + +### queue.saturated + +Function that will be called when the queue hits the concurrency +limit. +It can be altered at runtime. + +------------------------------------------------------- + +### fastqueue.promise([that], worker(arg), concurrency) + +Creates a new queue with `Promise` apis. It also offers all the methods +and properties of the object returned by [`fastqueue`](#fastqueue) with the modified +[`push`](#pushPromise) and [`unshift`](#unshiftPromise) methods. + +Node v10+ is required to use the promisified version. + +Arguments: +* `that`, optional context of the `worker` function. +* `worker`, worker function, it would be called with `that` as `this`, + if that is specified. It MUST return a `Promise`. +* `concurrency`, number of concurrent tasks that could be executed in + parallel. + + +#### queue.push(task) => Promise + +Add a task at the end of the queue. The returned `Promise` will be fulfilled (rejected) +when the task is completed successfully (unsuccessfully). + +This promise could be ignored as it will not lead to a `'unhandledRejection'`. + + +#### queue.unshift(task) => Promise + +Add a task at the beginning of the queue. The returned `Promise` will be fulfilled (rejected) +when the task is completed successfully (unsuccessfully). + +This promise could be ignored as it will not lead to a `'unhandledRejection'`. + + +#### queue.drained() => Promise + +Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker. + +This promise could be ignored as it will not lead to a `'unhandledRejection'`. + +## License + +ISC + +[ci-url]: https://github.com/mcollina/fastq/workflows/ci/badge.svg +[npm-badge]: https://badge.fury.io/js/fastq.svg +[npm-url]: https://badge.fury.io/js/fastq diff --git a/node_modules/fastq/SECURITY.md b/node_modules/fastq/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..dd9f1d510216450b9311a3b30815fdf381baa787 --- /dev/null +++ b/node_modules/fastq/SECURITY.md @@ -0,0 +1,15 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 1.x | :white_check_mark: | +| < 1.0 | :x: | + +## Reporting a Vulnerability + +Please report all vulnerabilities at [https://github.com/mcollina/fastq/security](https://github.com/mcollina/fastq/security). diff --git a/node_modules/fastq/bench.js b/node_modules/fastq/bench.js new file mode 100644 index 0000000000000000000000000000000000000000..4eaa829f329690fa6cfafa0641a34e58b4ebc832 --- /dev/null +++ b/node_modules/fastq/bench.js @@ -0,0 +1,66 @@ +'use strict' + +const max = 1000000 +const fastqueue = require('./')(worker, 1) +const { promisify } = require('util') +const immediate = promisify(setImmediate) +const qPromise = require('./').promise(immediate, 1) +const async = require('async') +const neo = require('neo-async') +const asyncqueue = async.queue(worker, 1) +const neoqueue = neo.queue(worker, 1) + +function bench (func, done) { + const key = max + '*' + func.name + let count = -1 + + console.time(key) + end() + + function end () { + if (++count < max) { + func(end) + } else { + console.timeEnd(key) + if (done) { + done() + } + } + } +} + +function benchFastQ (done) { + fastqueue.push(42, done) +} + +function benchAsyncQueue (done) { + asyncqueue.push(42, done) +} + +function benchNeoQueue (done) { + neoqueue.push(42, done) +} + +function worker (arg, cb) { + setImmediate(cb) +} + +function benchSetImmediate (cb) { + worker(42, cb) +} + +function benchFastQPromise (done) { + qPromise.push(42).then(function () { done() }, done) +} + +function runBench (done) { + async.eachSeries([ + benchSetImmediate, + benchFastQ, + benchNeoQueue, + benchAsyncQueue, + benchFastQPromise + ], bench, done) +} + +runBench(runBench) diff --git a/node_modules/fastq/eslint.config.js b/node_modules/fastq/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..57482dbb57b2d12e11db04253b91adddf6f53a1f --- /dev/null +++ b/node_modules/fastq/eslint.config.js @@ -0,0 +1,11 @@ +const neostandard = require('neostandard') + +module.exports = [ + ...neostandard(), + { + name: 'node-0.10-compatibility', + rules: { + 'object-shorthand': 'off' // Disable ES6 object shorthand for Node.js 0.10 compatibility + } + } +] diff --git a/node_modules/fastq/example.js b/node_modules/fastq/example.js new file mode 100644 index 0000000000000000000000000000000000000000..665fdc8412e53ca788fb996af7b0eb6a70da94fb --- /dev/null +++ b/node_modules/fastq/example.js @@ -0,0 +1,14 @@ +'use strict' + +/* eslint-disable no-var */ + +var queue = require('./')(worker, 1) + +queue.push(42, function (err, result) { + if (err) { throw err } + console.log('the result is', result) +}) + +function worker (arg, cb) { + cb(null, 42 * 2) +} diff --git a/node_modules/fastq/example.mjs b/node_modules/fastq/example.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f31364a514aea4b972fe6dd908edc29c184a6019 --- /dev/null +++ b/node_modules/fastq/example.mjs @@ -0,0 +1,9 @@ +import { promise as queueAsPromised } from './queue.js' + +const queue = queueAsPromised(worker, 1) + +console.log('the result is', await queue.push(42)) + +async function worker (arg) { + return 42 * 2 +} diff --git a/node_modules/fastq/index.d.ts b/node_modules/fastq/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..262dd0482b2250546479f07e3f0345486d915b36 --- /dev/null +++ b/node_modules/fastq/index.d.ts @@ -0,0 +1,59 @@ +declare function fastq(context: C, worker: fastq.worker, concurrency: number): fastq.queue +declare function fastq(worker: fastq.worker, concurrency: number): fastq.queue + +declare namespace fastq { + type worker = (this: C, task: T, cb: fastq.done) => void + type asyncWorker = (this: C, task: T) => Promise + type done = (err: Error | null, result?: R) => void + type errorHandler = (err: Error, task: T) => void + + interface queue { + /** Add a task at the end of the queue. `done(err, result)` will be called when the task was processed. */ + push(task: T, done?: done): void + /** Add a task at the beginning of the queue. `done(err, result)` will be called when the task was processed. */ + unshift(task: T, done?: done): void + /** Pause the processing of tasks. Currently worked tasks are not stopped. */ + pause(): any + /** Resume the processing of tasks. */ + resume(): any + running(): number + /** Returns `false` if there are tasks being processed or waiting to be processed. `true` otherwise. */ + idle(): boolean + /** Returns the number of tasks waiting to be processed (in the queue). */ + length(): number + /** Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks */ + getQueue(): T[] + /** Removes all tasks waiting to be processed, and reset `drain` to an empty function. */ + kill(): any + /** Same than `kill` but the `drain` function will be called before reset to empty. */ + killAndDrain(): any + /** Removes all tasks waiting to be processed, calls each task's callback with an abort error (rejects promises for promise-based queues), and resets `drain` to an empty function. */ + abort(): any + /** Set a global error handler. `handler(err, task)` will be called each time a task is completed, `err` will be not null if the task has thrown an error. */ + error(handler: errorHandler): void + /** Property that returns the number of concurrent tasks that could be executed in parallel. It can be altered at runtime. */ + concurrency: number + /** Property (Read-Only) that returns `true` when the queue is in a paused state. */ + readonly paused: boolean + /** Function that will be called when the last item from the queue has been processed by a worker. It can be altered at runtime. */ + drain(): any + /** Function that will be called when the last item from the queue has been assigned to a worker. It can be altered at runtime. */ + empty: () => void + /** Function that will be called when the queue hits the concurrency limit. It can be altered at runtime. */ + saturated: () => void + } + + interface queueAsPromised extends queue { + /** Add a task at the end of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). */ + push(task: T): Promise + /** Add a task at the beginning of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). */ + unshift(task: T): Promise + /** Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker. */ + drained(): Promise + } + + function promise(context: C, worker: fastq.asyncWorker, concurrency: number): fastq.queueAsPromised + function promise(worker: fastq.asyncWorker, concurrency: number): fastq.queueAsPromised +} + +export = fastq diff --git a/node_modules/fastq/package.json b/node_modules/fastq/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9e1d9ddec34ce0223a4521dd7108c2be17e41cf3 --- /dev/null +++ b/node_modules/fastq/package.json @@ -0,0 +1,49 @@ +{ + "name": "fastq", + "version": "1.20.1", + "description": "Fast, in memory work queue", + "main": "queue.js", + "type": "commonjs", + "scripts": { + "lint": "eslint .", + "unit": "nyc --lines 100 --branches 100 --functions 100 --check-coverage --reporter=text tape test/test.js test/promise.js", + "coverage": "nyc --reporter=html --reporter=cobertura --reporter=text tape test/test.js test/promise.js", + "test:report": "npm run lint && npm run unit:report", + "test": "npm run lint && npm run unit", + "typescript": "tsc --project ./test/tsconfig.json", + "legacy": "tape test/test.js" + }, + "pre-commit": [ + "test", + "typescript" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/mcollina/fastq.git" + }, + "keywords": [ + "fast", + "queue", + "async", + "worker" + ], + "author": "Matteo Collina ", + "license": "ISC", + "bugs": { + "url": "https://github.com/mcollina/fastq/issues" + }, + "homepage": "https://github.com/mcollina/fastq#readme", + "devDependencies": { + "async": "^3.1.0", + "eslint": "^9.36.0", + "neo-async": "^2.6.1", + "neostandard": "^0.12.2", + "nyc": "^17.0.0", + "pre-commit": "^1.2.2", + "tape": "^5.0.0", + "typescript": "^5.0.4" + }, + "dependencies": { + "reusify": "^1.0.4" + } +} diff --git a/node_modules/fastq/queue.js b/node_modules/fastq/queue.js new file mode 100644 index 0000000000000000000000000000000000000000..d0fbf20279006949feda751daf8b2360b39a2da1 --- /dev/null +++ b/node_modules/fastq/queue.js @@ -0,0 +1,346 @@ +'use strict' + +/* eslint-disable no-var */ + +var reusify = require('reusify') + +function fastqueue (context, worker, _concurrency) { + if (typeof context === 'function') { + _concurrency = worker + worker = context + context = null + } + + if (!(_concurrency >= 1)) { + throw new Error('fastqueue concurrency must be equal to or greater than 1') + } + + var cache = reusify(Task) + var queueHead = null + var queueTail = null + var _running = 0 + var errorHandler = null + + var self = { + push: push, + drain: noop, + saturated: noop, + pause: pause, + paused: false, + + get concurrency () { + return _concurrency + }, + set concurrency (value) { + if (!(value >= 1)) { + throw new Error('fastqueue concurrency must be equal to or greater than 1') + } + _concurrency = value + + if (self.paused) return + for (; queueHead && _running < _concurrency;) { + _running++ + release() + } + }, + + running: running, + resume: resume, + idle: idle, + length: length, + getQueue: getQueue, + unshift: unshift, + empty: noop, + kill: kill, + killAndDrain: killAndDrain, + error: error, + abort: abort + } + + return self + + function running () { + return _running + } + + function pause () { + self.paused = true + } + + function length () { + var current = queueHead + var counter = 0 + + while (current) { + current = current.next + counter++ + } + + return counter + } + + function getQueue () { + var current = queueHead + var tasks = [] + + while (current) { + tasks.push(current.value) + current = current.next + } + + return tasks + } + + function resume () { + if (!self.paused) return + self.paused = false + if (queueHead === null) { + _running++ + release() + return + } + for (; queueHead && _running < _concurrency;) { + _running++ + release() + } + } + + function idle () { + return _running === 0 && self.length() === 0 + } + + function push (value, done) { + var current = cache.get() + + current.context = context + current.release = release + current.value = value + current.callback = done || noop + current.errorHandler = errorHandler + + if (_running >= _concurrency || self.paused) { + if (queueTail) { + queueTail.next = current + queueTail = current + } else { + queueHead = current + queueTail = current + self.saturated() + } + } else { + _running++ + worker.call(context, current.value, current.worked) + } + } + + function unshift (value, done) { + var current = cache.get() + + current.context = context + current.release = release + current.value = value + current.callback = done || noop + current.errorHandler = errorHandler + + if (_running >= _concurrency || self.paused) { + if (queueHead) { + current.next = queueHead + queueHead = current + } else { + queueHead = current + queueTail = current + self.saturated() + } + } else { + _running++ + worker.call(context, current.value, current.worked) + } + } + + function release (holder) { + if (holder) { + cache.release(holder) + } + var next = queueHead + if (next && _running <= _concurrency) { + if (!self.paused) { + if (queueTail === queueHead) { + queueTail = null + } + queueHead = next.next + next.next = null + worker.call(context, next.value, next.worked) + if (queueTail === null) { + self.empty() + } + } else { + _running-- + } + } else if (--_running === 0) { + self.drain() + } + } + + function kill () { + queueHead = null + queueTail = null + self.drain = noop + } + + function killAndDrain () { + queueHead = null + queueTail = null + self.drain() + self.drain = noop + } + + function abort () { + var current = queueHead + queueHead = null + queueTail = null + + while (current) { + var next = current.next + var callback = current.callback + var errorHandler = current.errorHandler + var val = current.value + var context = current.context + + // Reset the task state + current.value = null + current.callback = noop + current.errorHandler = null + + // Call error handler if present + if (errorHandler) { + errorHandler(new Error('abort'), val) + } + + // Call callback with error + callback.call(context, new Error('abort')) + + // Release the task back to the pool + current.release(current) + + current = next + } + + self.drain = noop + } + + function error (handler) { + errorHandler = handler + } +} + +function noop () {} + +function Task () { + this.value = null + this.callback = noop + this.next = null + this.release = noop + this.context = null + this.errorHandler = null + + var self = this + + this.worked = function worked (err, result) { + var callback = self.callback + var errorHandler = self.errorHandler + var val = self.value + self.value = null + self.callback = noop + if (self.errorHandler) { + errorHandler(err, val) + } + callback.call(self.context, err, result) + self.release(self) + } +} + +function queueAsPromised (context, worker, _concurrency) { + if (typeof context === 'function') { + _concurrency = worker + worker = context + context = null + } + + function asyncWrapper (arg, cb) { + worker.call(this, arg) + .then(function (res) { + cb(null, res) + }, cb) + } + + var queue = fastqueue(context, asyncWrapper, _concurrency) + + var pushCb = queue.push + var unshiftCb = queue.unshift + + queue.push = push + queue.unshift = unshift + queue.drained = drained + + return queue + + function push (value) { + var p = new Promise(function (resolve, reject) { + pushCb(value, function (err, result) { + if (err) { + reject(err) + return + } + resolve(result) + }) + }) + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop) + + return p + } + + function unshift (value) { + var p = new Promise(function (resolve, reject) { + unshiftCb(value, function (err, result) { + if (err) { + reject(err) + return + } + resolve(result) + }) + }) + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop) + + return p + } + + function drained () { + var p = new Promise(function (resolve) { + process.nextTick(function () { + if (queue.idle()) { + resolve() + } else { + var previousDrain = queue.drain + queue.drain = function () { + if (typeof previousDrain === 'function') previousDrain() + resolve() + queue.drain = previousDrain + } + } + }) + }) + + return p + } +} + +module.exports = fastqueue +module.exports.promise = queueAsPromised diff --git a/node_modules/fastq/test/example.ts b/node_modules/fastq/test/example.ts new file mode 100644 index 0000000000000000000000000000000000000000..a47d4419cdc04144771c747d4c0a66da990e4eaa --- /dev/null +++ b/node_modules/fastq/test/example.ts @@ -0,0 +1,83 @@ +import * as fastq from '../' +import { promise as queueAsPromised } from '../' + +// Basic example + +const queue = fastq(worker, 1) + +queue.push('world', (err, result) => { + if (err) throw err + console.log('the result is', result) +}) + +queue.push('push without cb') + +queue.concurrency + +queue.drain() + +queue.empty = () => undefined + +console.log('the queue tasks are', queue.getQueue()) + +queue.idle() + +queue.kill() + +queue.killAndDrain() + +queue.length + +queue.pause() + +queue.resume() + +queue.running() + +queue.saturated = () => undefined + +queue.unshift('world', (err, result) => { + if (err) throw err + console.log('the result is', result) +}) + +queue.unshift('unshift without cb') + +function worker(task: any, cb: fastq.done) { + cb(null, 'hello ' + task) +} + +// Generics example + +interface GenericsContext { + base: number; +} + +const genericsQueue = fastq({ base: 6 }, genericsWorker, 1) + +genericsQueue.push(7, (err, done) => { + if (err) throw err + console.log('the result is', done) +}) + +genericsQueue.unshift(7, (err, done) => { + if (err) throw err + console.log('the result is', done) +}) + +function genericsWorker(this: GenericsContext, task: number, cb: fastq.done) { + cb(null, 'the meaning of life is ' + (this.base * task)) +} + +const queue2 = queueAsPromised(asyncWorker, 1) + +async function asyncWorker(task: any) { + return 'hello ' + task +} + +async function run () { + await queue.push(42) + await queue.unshift(42) +} + +run() diff --git a/node_modules/fastq/test/promise.js b/node_modules/fastq/test/promise.js new file mode 100644 index 0000000000000000000000000000000000000000..b425fda5e16440dc9798be5a50b85bd064c8b657 --- /dev/null +++ b/node_modules/fastq/test/promise.js @@ -0,0 +1,325 @@ +'use strict' + +const test = require('tape') +const buildQueue = require('../').promise +const { promisify } = require('util') +const sleep = promisify(setTimeout) +const immediate = promisify(setImmediate) + +test('concurrency', function (t) { + t.plan(2) + t.throws(buildQueue.bind(null, worker, 0)) + t.doesNotThrow(buildQueue.bind(null, worker, 1)) + + async function worker (arg) { + return true + } +}) + +test('worker execution', async function (t) { + const queue = buildQueue(worker, 1) + + const result = await queue.push(42) + + t.equal(result, true, 'result matches') + + async function worker (arg) { + t.equal(arg, 42) + return true + } +}) + +test('limit', async function (t) { + const queue = buildQueue(worker, 1) + + const [res1, res2] = await Promise.all([queue.push(10), queue.push(0)]) + t.equal(res1, 10, 'the result matches') + t.equal(res2, 0, 'the result matches') + + async function worker (arg) { + await sleep(arg) + return arg + } +}) + +test('multiple executions', async function (t) { + const queue = buildQueue(worker, 1) + const toExec = [1, 2, 3, 4, 5] + const expected = ['a', 'b', 'c', 'd', 'e'] + let count = 0 + + await Promise.all(toExec.map(async function (task, i) { + const result = await queue.push(task) + t.equal(result, expected[i], 'the result matches') + })) + + async function worker (arg) { + t.equal(arg, toExec[count], 'arg matches') + return expected[count++] + } +}) + +test('drained', async function (t) { + const queue = buildQueue(worker, 2) + + const toExec = new Array(10).fill(10) + let count = 0 + + async function worker (arg) { + await sleep(arg) + count++ + } + + toExec.forEach(function (i) { + queue.push(i) + }) + + await queue.drained() + + t.equal(count, toExec.length) + + toExec.forEach(function (i) { + queue.push(i) + }) + + await queue.drained() + + t.equal(count, toExec.length * 2) +}) + +test('drained with exception should not throw', async function (t) { + const queue = buildQueue(worker, 2) + + const toExec = new Array(10).fill(10) + + async function worker () { + throw new Error('foo') + } + + toExec.forEach(function (i) { + queue.push(i) + }) + + await queue.drained() +}) + +test('drained with drain function', async function (t) { + let drainCalled = false + const queue = buildQueue(worker, 2) + + queue.drain = function () { + drainCalled = true + } + + const toExec = new Array(10).fill(10) + let count = 0 + + async function worker (arg) { + await sleep(arg) + count++ + } + + toExec.forEach(function () { + queue.push() + }) + + await queue.drained() + + t.equal(count, toExec.length) + t.equal(drainCalled, true) +}) + +test('drained while idle should resolve', async function (t) { + const queue = buildQueue(worker, 2) + + async function worker (arg) { + await sleep(arg) + } + + await queue.drained() +}) + +test('drained while idle should not call the drain function', async function (t) { + let drainCalled = false + const queue = buildQueue(worker, 2) + + queue.drain = function () { + drainCalled = true + } + + async function worker (arg) { + await sleep(arg) + } + + await queue.drained() + + t.equal(drainCalled, false) +}) + +test('set this', async function (t) { + t.plan(1) + const that = {} + const queue = buildQueue(that, worker, 1) + + await queue.push(42) + + async function worker (arg) { + t.equal(this, that, 'this matches') + } +}) + +test('unshift', async function (t) { + const queue = buildQueue(worker, 1) + const expected = [1, 2, 3, 4] + + await Promise.all([ + queue.push(1), + queue.push(4), + queue.unshift(3), + queue.unshift(2) + ]) + + t.is(expected.length, 0) + + async function worker (arg) { + t.equal(expected.shift(), arg, 'tasks come in order') + } +}) + +test('push with worker throwing error', async function (t) { + t.plan(5) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + q.error(function (err, task) { + t.ok(err instanceof Error, 'global error handler should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + t.equal(task, 42, 'The task executed should be passed') + }) + try { + await q.push(42) + } catch (err) { + t.ok(err instanceof Error, 'push callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + } +}) + +test('unshift with worker throwing error', async function (t) { + t.plan(2) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + try { + await q.unshift(42) + } catch (err) { + t.ok(err instanceof Error, 'push callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + } +}) + +test('no unhandledRejection (push)', async function (t) { + function handleRejection () { + t.fail('unhandledRejection') + } + process.once('unhandledRejection', handleRejection) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + + q.push(42) + + await immediate() + process.removeListener('unhandledRejection', handleRejection) +}) + +test('no unhandledRejection (unshift)', async function (t) { + function handleRejection () { + t.fail('unhandledRejection') + } + process.once('unhandledRejection', handleRejection) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + + q.unshift(42) + + await immediate() + process.removeListener('unhandledRejection', handleRejection) +}) + +test('drained should resolve after async tasks complete', async function (t) { + const logs = [] + + async function processTask () { + await new Promise(resolve => setTimeout(resolve, 0)) + logs.push('processed') + } + + const queue = buildQueue(processTask, 1) + queue.drain = () => logs.push('called drain') + + queue.drained().then(() => logs.push('drained promise resolved')) + + await Promise.all([ + queue.push(), + queue.push(), + queue.push() + ]) + + t.deepEqual(logs, [ + 'processed', + 'processed', + 'processed', + 'called drain', + 'drained promise resolved' + ], 'events happened in correct order') +}) + +test('drained should handle undefined drain function', async function (t) { + const queue = buildQueue(worker, 1) + + async function worker (arg) { + await sleep(10) + return arg + } + + queue.drain = undefined + queue.push(1) + await queue.drained() + + t.pass('drained resolved successfully with undefined drain') +}) + +test('abort rejects all pending promises', async function (t) { + const queue = buildQueue(worker, 1) + const promises = [] + let rejectedCount = 0 + + // Pause queue to prevent tasks from starting + queue.pause() + + for (let i = 0; i < 10; i++) { + promises.push(queue.push(i)) + } + + queue.abort() + + // All promises should be rejected + for (const promise of promises) { + try { + await promise + t.fail('promise should have been rejected') + } catch (err) { + t.equal(err.message, 'abort', 'error message is abort') + rejectedCount++ + } + } + + t.equal(rejectedCount, 10, 'all promises were rejected') + t.equal(queue.length(), 0, 'queue is empty') + + async function worker (arg) { + await sleep(500) + return arg + } +}) diff --git a/node_modules/fastq/test/test.js b/node_modules/fastq/test/test.js new file mode 100644 index 0000000000000000000000000000000000000000..37e211e9f3e4c15db0537bb111c313106fda03cc --- /dev/null +++ b/node_modules/fastq/test/test.js @@ -0,0 +1,733 @@ +'use strict' + +/* eslint-disable no-var */ + +var test = require('tape') +var buildQueue = require('../') + +test('concurrency', function (t) { + t.plan(6) + t.throws(buildQueue.bind(null, worker, 0)) + t.throws(buildQueue.bind(null, worker, NaN)) + t.doesNotThrow(buildQueue.bind(null, worker, 1)) + + var queue = buildQueue(worker, 1) + t.throws(function () { + queue.concurrency = 0 + }) + t.throws(function () { + queue.concurrency = NaN + }) + t.doesNotThrow(function () { + queue.concurrency = 2 + }) + + function worker (arg, cb) { + cb(null, true) + } +}) + +test('worker execution', function (t) { + t.plan(3) + + var queue = buildQueue(worker, 1) + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + function worker (arg, cb) { + t.equal(arg, 42) + cb(null, true) + } +}) + +test('limit', function (t) { + t.plan(4) + + var expected = [10, 0] + var queue = buildQueue(worker, 1) + + queue.push(10, result) + queue.push(0, result) + + function result (err, arg) { + t.error(err, 'no error') + t.equal(arg, expected.shift(), 'the result matches') + } + + function worker (arg, cb) { + setTimeout(cb, arg, null, arg) + } +}) + +test('multiple executions', function (t) { + t.plan(15) + + var queue = buildQueue(worker, 1) + var toExec = [1, 2, 3, 4, 5] + var count = 0 + + toExec.forEach(function (task) { + queue.push(task, done) + }) + + function done (err, result) { + t.error(err, 'no error') + t.equal(result, toExec[count - 1], 'the result matches') + } + + function worker (arg, cb) { + t.equal(arg, toExec[count], 'arg matches') + count++ + setImmediate(cb, null, arg) + } +}) + +test('multiple executions, one after another', function (t) { + t.plan(15) + + var queue = buildQueue(worker, 1) + var toExec = [1, 2, 3, 4, 5] + var count = 0 + + queue.push(toExec[0], done) + + function done (err, result) { + t.error(err, 'no error') + t.equal(result, toExec[count - 1], 'the result matches') + if (count < toExec.length) { + queue.push(toExec[count], done) + } + } + + function worker (arg, cb) { + t.equal(arg, toExec[count], 'arg matches') + count++ + setImmediate(cb, null, arg) + } +}) + +test('set this', function (t) { + t.plan(3) + + var that = {} + var queue = buildQueue(that, worker, 1) + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(this, that, 'this matches') + }) + + function worker (arg, cb) { + t.equal(this, that, 'this matches') + cb(null, true) + } +}) + +test('drain', function (t) { + t.plan(4) + + var queue = buildQueue(worker, 1) + var worked = false + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + queue.drain = function () { + t.equal(true, worked, 'drained') + } + + function worker (arg, cb) { + t.equal(arg, 42) + worked = true + setImmediate(cb, null, true) + } +}) + +test('pause && resume', function (t) { + t.plan(13) + + var queue = buildQueue(worker, 1) + var worked = false + var expected = [42, 24] + + t.notOk(queue.paused, 'it should not be paused') + + queue.pause() + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + queue.push(24, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + t.notOk(worked, 'it should be paused') + t.ok(queue.paused, 'it should be paused') + + queue.resume() + queue.pause() + queue.resume() + queue.resume() // second resume is a no-op + + function worker (arg, cb) { + t.notOk(queue.paused, 'it should not be paused') + t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') + t.equal(arg, expected.shift()) + worked = true + process.nextTick(function () { cb(null, true) }) + } +}) + +test('pause in flight && resume', function (t) { + t.plan(16) + + var queue = buildQueue(worker, 1) + var expected = [42, 24, 12] + + t.notOk(queue.paused, 'it should not be paused') + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.ok(queue.paused, 'it should be paused') + process.nextTick(function () { + queue.resume() + queue.pause() + queue.resume() + }) + }) + + queue.push(24, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.notOk(queue.paused, 'it should not be paused') + }) + + queue.push(12, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.notOk(queue.paused, 'it should not be paused') + }) + + queue.pause() + + function worker (arg, cb) { + t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') + t.equal(arg, expected.shift()) + process.nextTick(function () { cb(null, true) }) + } +}) + +test('altering concurrency', function (t) { + t.plan(24) + + var queue = buildQueue(worker, 1) + + queue.push(24, workDone) + queue.push(24, workDone) + queue.push(24, workDone) + + queue.pause() + + queue.concurrency = 3 // concurrency changes are ignored while paused + queue.concurrency = 2 + + queue.resume() + + t.equal(queue.running(), 2, '2 jobs running') + + queue.concurrency = 3 + + t.equal(queue.running(), 3, '3 jobs running') + + queue.concurrency = 1 + + t.equal(queue.running(), 3, '3 jobs running') // running jobs can't be killed + + queue.push(24, workDone) + queue.push(24, workDone) + queue.push(24, workDone) + queue.push(24, workDone) + + function workDone (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + } + + function worker (arg, cb) { + t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('idle()', function (t) { + t.plan(12) + + var queue = buildQueue(worker, 1) + + t.ok(queue.idle(), 'queue is idle') + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.notOk(queue.idle(), 'queue is not idle') + }) + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + // it will go idle after executing this function + setImmediate(function () { + t.ok(queue.idle(), 'queue is now idle') + }) + }) + + t.notOk(queue.idle(), 'queue is not idle') + + function worker (arg, cb) { + t.notOk(queue.idle(), 'queue is not idle') + t.equal(arg, 42) + setImmediate(cb, null, true) + } +}) + +test('saturated', function (t) { + t.plan(9) + + var queue = buildQueue(worker, 1) + var preworked = 0 + var worked = 0 + + queue.saturated = function () { + t.pass('saturated') + t.equal(preworked, 1, 'started 1 task') + t.equal(worked, 0, 'worked zero task') + } + + queue.push(42, done) + queue.push(42, done) + + function done (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + } + + function worker (arg, cb) { + t.equal(arg, 42) + preworked++ + setImmediate(function () { + worked++ + cb(null, true) + }) + } +}) + +test('length', function (t) { + t.plan(7) + + var queue = buildQueue(worker, 1) + + t.equal(queue.length(), 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.length(), 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.length(), 1, 'one task waiting') + queue.push(42, done) + t.equal(queue.length(), 2, 'two tasks waiting') + + function done (err, result) { + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('getQueue', function (t) { + t.plan(10) + + var queue = buildQueue(worker, 1) + + t.equal(queue.getQueue().length, 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.getQueue().length, 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.getQueue().length, 1, 'one task waiting') + t.equal(queue.getQueue()[0], 42, 'should be equal') + queue.push(43, done) + t.equal(queue.getQueue().length, 2, 'two tasks waiting') + t.equal(queue.getQueue()[0], 42, 'should be equal') + t.equal(queue.getQueue()[1], 43, 'should be equal') + + function done (err, result) { + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('unshift', function (t) { + t.plan(8) + + var queue = buildQueue(worker, 1) + var expected = [1, 2, 3, 4] + + queue.push(1, done) + queue.push(4, done) + queue.unshift(3, done) + queue.unshift(2, done) + + function done (err, result) { + t.error(err, 'no error') + } + + function worker (arg, cb) { + t.equal(expected.shift(), arg, 'tasks come in order') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('unshift && empty', function (t) { + t.plan(2) + + var queue = buildQueue(worker, 1) + var completed = false + + queue.pause() + + queue.empty = function () { + t.notOk(completed, 'the task has not completed yet') + } + + queue.unshift(1, done) + + queue.resume() + + function done (err, result) { + completed = true + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('push && empty', function (t) { + t.plan(2) + + var queue = buildQueue(worker, 1) + var completed = false + + queue.pause() + + queue.empty = function () { + t.notOk(completed, 'the task has not completed yet') + } + + queue.push(1, done) + + queue.resume() + + function done (err, result) { + completed = true + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('kill', function (t) { + t.plan(5) + + var queue = buildQueue(worker, 1) + var expected = [1] + + var predrain = queue.drain + + queue.drain = function drain () { + t.fail('drain should never be called') + } + + queue.push(1, done) + queue.push(4, done) + queue.unshift(3, done) + queue.unshift(2, done) + queue.kill() + + function done (err, result) { + t.error(err, 'no error') + setImmediate(function () { + t.equal(queue.length(), 0, 'no queued tasks') + t.equal(queue.running(), 0, 'no running tasks') + t.equal(queue.drain, predrain, 'drain is back to default') + }) + } + + function worker (arg, cb) { + t.equal(expected.shift(), arg, 'tasks come in order') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('killAndDrain', function (t) { + t.plan(6) + + var queue = buildQueue(worker, 1) + var expected = [1] + + var predrain = queue.drain + + queue.drain = function drain () { + t.pass('drain has been called') + } + + queue.push(1, done) + queue.push(4, done) + queue.unshift(3, done) + queue.unshift(2, done) + queue.killAndDrain() + + function done (err, result) { + t.error(err, 'no error') + setImmediate(function () { + t.equal(queue.length(), 0, 'no queued tasks') + t.equal(queue.running(), 0, 'no running tasks') + t.equal(queue.drain, predrain, 'drain is back to default') + }) + } + + function worker (arg, cb) { + t.equal(expected.shift(), arg, 'tasks come in order') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('pause && idle', function (t) { + t.plan(11) + + var queue = buildQueue(worker, 1) + var worked = false + + t.notOk(queue.paused, 'it should not be paused') + t.ok(queue.idle(), 'should be idle') + + queue.pause() + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + t.notOk(worked, 'it should be paused') + t.ok(queue.paused, 'it should be paused') + t.notOk(queue.idle(), 'should not be idle') + + queue.resume() + + t.notOk(queue.paused, 'it should not be paused') + t.notOk(queue.idle(), 'it should not be idle') + + function worker (arg, cb) { + t.equal(arg, 42) + worked = true + process.nextTick(cb.bind(null, null, true)) + process.nextTick(function () { + t.ok(queue.idle(), 'is should be idle') + }) + } +}) + +test('push without cb', function (t) { + t.plan(1) + + var queue = buildQueue(worker, 1) + + queue.push(42) + + function worker (arg, cb) { + t.equal(arg, 42) + cb() + } +}) + +test('unshift without cb', function (t) { + t.plan(1) + + var queue = buildQueue(worker, 1) + + queue.unshift(42) + + function worker (arg, cb) { + t.equal(arg, 42) + cb() + } +}) + +test('push with worker throwing error', function (t) { + t.plan(5) + var q = buildQueue(function (task, cb) { + cb(new Error('test error'), null) + }, 1) + q.error(function (err, task) { + t.ok(err instanceof Error, 'global error handler should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + t.equal(task, 42, 'The task executed should be passed') + }) + q.push(42, function (err) { + t.ok(err instanceof Error, 'push callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + }) +}) + +test('unshift with worker throwing error', function (t) { + t.plan(5) + var q = buildQueue(function (task, cb) { + cb(new Error('test error'), null) + }, 1) + q.error(function (err, task) { + t.ok(err instanceof Error, 'global error handler should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + t.equal(task, 42, 'The task executed should be passed') + }) + q.unshift(42, function (err) { + t.ok(err instanceof Error, 'unshift callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + }) +}) + +test('pause/resume should trigger drain event', function (t) { + t.plan(1) + + var queue = buildQueue(worker, 1) + queue.pause() + queue.drain = function () { + t.pass('drain should be called') + } + + function worker (arg, cb) { + cb(null, true) + } + + queue.resume() +}) + +test('paused flag', function (t) { + t.plan(2) + + var queue = buildQueue(function (arg, cb) { + cb(null) + }, 1) + t.equal(queue.paused, false) + queue.pause() + t.equal(queue.paused, true) +}) + +test('abort', function (t) { + t.plan(11) + + var queue = buildQueue(worker, 1) + var abortedTasks = 0 + + var predrain = queue.drain + + queue.drain = function drain () { + t.fail('drain should never be called') + } + + // Pause queue to prevent tasks from starting + queue.pause() + queue.push(1, doneAborted) + queue.push(4, doneAborted) + queue.unshift(3, doneAborted) + queue.unshift(2, doneAborted) + + // Abort all queued tasks + queue.abort() + + // Verify state after abort + t.equal(queue.length(), 0, 'no queued tasks after abort') + t.equal(queue.drain, predrain, 'drain is back to default') + + setImmediate(function () { + t.equal(abortedTasks, 4, 'all queued tasks were aborted') + }) + + function doneAborted (err) { + t.ok(err, 'error is present') + t.equal(err.message, 'abort', 'error message is abort') + abortedTasks++ + } + + function worker (arg, cb) { + t.fail('worker should not be called') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('abort with error handler', function (t) { + t.plan(7) + + var queue = buildQueue(worker, 1) + var errorHandlerCalled = 0 + + queue.error(function (err, task) { + t.equal(err.message, 'abort', 'error handler receives abort error') + t.ok(task !== null, 'error handler receives task value') + errorHandlerCalled++ + }) + + // Pause queue to prevent tasks from starting + queue.pause() + queue.push(1, doneAborted) + queue.push(2, doneAborted) + + // Abort all queued tasks + queue.abort() + + setImmediate(function () { + t.equal(errorHandlerCalled, 2, 'error handler called for all aborted tasks') + }) + + function doneAborted (err) { + t.ok(err, 'callback receives error') + } + + function worker (arg, cb) { + t.fail('worker should not be called') + setImmediate(function () { + cb(null, true) + }) + } +}) diff --git a/node_modules/fastq/test/tsconfig.json b/node_modules/fastq/test/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..66e16e93052a3411133dcc8cc957ba86eb409b8e --- /dev/null +++ b/node_modules/fastq/test/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "noEmit": true, + "strict": true + }, + "files": [ + "./example.ts" + ] +} diff --git a/node_modules/fflate/CHANGELOG.md b/node_modules/fflate/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..6e288d319905f641ca19236b012210af289dbea2 --- /dev/null +++ b/node_modules/fflate/CHANGELOG.md @@ -0,0 +1,125 @@ +## 0.8.3 +- Fix buffer over-read for Zip64 extra fields +- Support sync flushes (`Z_SYNC_FLUSH` in zlib) + - Allows for immediate decompression of all pushed bytes + - Enables DEFLATE stream concatenation +- Fix `zip`/`zipSync` when using cross-realm `Uint8Array` +- Improve Zip64 support for streamed or undersized archives +- Update performance estimates in README +- Fix typings for TypeScript v5.7+ +- Reduce memory consumption after compression stream completion +## 0.8.2 +- Fixed broken UMD build +- Fixed edge-case causing skipped data during streaming compression +- Fixed bug in GZIP streaming on member boundary +- Improved streaming performance on inconsistent chunk sizes +- Improved `unzip` performance on undercompressed archives +- Added flushing support into streaming API +- Added backpressure support into async streaming API + - Use new `ondrain` handler and `queuedSize` +## 0.8.1 +- Fixed reallocating on pre-supplied buffer in `inflateSync` and `unzlibSync` +- Minor documentation fixes +## 0.8.0 +- BREAKING: synchronous decompression functions now take an options object rather than an output buffer as a second parameter + - `inflateSync(compressed, outBuf)` is now `inflateSync(compressed, { out: outBuf })` +- Support dictionaries in compression and decompression +- Support multi-member files in GZIP streaming decompression +- Dramatically improved streaming performance +- Fixed missing error on certain malformed GZIP files +## 0.7.3 +- Fix folder creation for certain operating system + - Create 0-length "files" for each directory specified with "object" syntax" + - Support empty folders + - Add options for folders +- Fix minification in SWC + - Remove instanceof, no-whitespace assumptions in async functions +## 0.7.2 +- Fixed TypeScript typing for errors when using `strictNullChecks` +- Fixed failure to compress files above 64kB with `{ level: 0 }` +- Fixed AMD module definition in UMD build +## 0.7.1 +- Removed requirement for `setTimeout` +- Added support for unzip file filters (thanks to [@manucorporat](https://github.com/manucorporat): #67) +- Fixed streaming gunzip and unzlib bug causing corruption +## 0.7.0 +- Improved errors + - Now errors are error objects instead of strings + - Check the error code to apply custom logic based on error type +- Made async operations always call callbacks asynchronously +- Fixed bug that caused errors to not appear in asynchronous operations in browsers +## 0.6.10 +- Fixed async operations on Node.js with native ESM +## 0.6.5 +- Fixed streams not recognizing final chunk +- Fixed streaming UTF-8 decoder bug +## 0.6.4 +- Made streaming inflate consume all data possible +- Optimized use of values near 32-bit boundary +## 0.6.3 +- Patch exports of async functions +- Fix streaming unzip +## 0.6.2 +- Replace Adler-32 implementation (used in Zlib compression) with one more optimized for V8 + - Advice from @SheetJSDev +- Add support for extra fields, file comments in ZIP files +- Work on Rust version +## 0.6.0 +- Revamped streaming unzip for compatibility and performance improvements +- Fixed streaming data bugs +- Fixed inflation errors +- Planned new tests +## 0.5.2 +- General bugfixes +## 0.5.0 +- Add streaming zip, unzip +- Fix import issues with certain environments + - If you had problems with `worker_threads` being included in your bundle, try updating! +## 0.4.8 +- Support strict Content Security Policy + - Remove `new Function` +## 0.4.7 +- Fix data streaming bugs +## 0.4.5 +- Zip64 support + - Still not possible to have above 4GB files +## 0.4.4 +- Files up to 4GB supported + - Hey, that's better than even Node.js `zlib`! +## 0.4.1 +- Fix ZIP failure bug +- Make ZIP options work better +- Improve docs +- Fix async inflate failure +- Work on Rust version +## 0.3.11 +- Fix docs +## 0.3.9 +- Fixed issue with unzipping +## 0.3.7 +- Patched streaming compression bugs +- Added demo page +## 0.3.6 +- Allowed true ESM imports +## 0.3.4 +- Fixed rare overflow bug causing corruption +- Added async stream termination +- Added UMD bundle +## 0.3.0 +- Added support for asynchronous and synchronous streaming +- Reduced bundle size by autogenerating worker code, even in minified environments +- Error detection rather than hanging +- Improved performance +## 0.2.3 +- Improved Zlib autodetection +## 0.2.2 +- Fixed Node Worker +## 0.2.1 +- Fixed ZIP bug +## 0.2.0 +- Added support for ZIP files (parallelized) +- Added ability to terminate running asynchronous operations +## 0.1.0 +- Rewrote API: added support for asynchronous (Worker) compression/decompression, fixed critical bug involving fixed Huffman trees +## 0.0.1 +- Created, works on basic input \ No newline at end of file diff --git a/node_modules/fflate/LICENSE b/node_modules/fflate/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..bd36874f34b9ae537f2bbc383fdf6e320dfafe98 --- /dev/null +++ b/node_modules/fflate/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Arjun Barrett + +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. \ No newline at end of file diff --git a/node_modules/fflate/README.md b/node_modules/fflate/README.md new file mode 100644 index 0000000000000000000000000000000000000000..36e0654f28dafb8a121ed8880d6cd9e890898f4c --- /dev/null +++ b/node_modules/fflate/README.md @@ -0,0 +1,558 @@ +# fflate +High performance (de)compression in an 8kB package + +## Why fflate? +`fflate` (short for fast flate) is the **fastest, smallest, and most versatile** pure JavaScript compression and decompression library in existence, handily beating [`pako`](https://npmjs.com/package/pako), [`tiny-inflate`](https://npmjs.com/package/tiny-inflate), and [`UZIP.js`](https://github.com/photopea/UZIP.js) in performance benchmarks while being multiple times more lightweight. Its compression ratios are often better than even the original Zlib C library. It includes support for DEFLATE, GZIP, and Zlib data. Data compressed by `fflate` can be decompressed by other tools, and vice versa. + +In addition to the base decompression and compression APIs, `fflate` supports high-speed ZIP file archiving for an extra 3 kB. In fact, the compressor, in synchronous mode, compresses both more quickly and with a higher compression ratio than most compression software (even Info-ZIP, a C program), and in asynchronous mode it can utilize multiple threads to achieve over 3x the performance of virtually any other utility. + +| | `pako` | `tiny-inflate` | `UZIP.js` | `fflate` | +|-----------------------------|--------|------------------------|-----------------------|--------------------------------| +| Decompression performance | 1x | Up to 40% slower | **Up to 25% faster** | **Up to 25% faster** | +| Compression performance | 1x | N/A | Up to 25% faster | **Up to 50% faster** | +| Base bundle size (minified) | 45.6kB | **3kB (inflate only)** | 14.2kB | 8kB **(3kB for inflate only)** | +| Decompression support | ✅ | ✅ | ✅ | ✅ | +| Compression support | ✅ | ❌ | ✅ | ✅ | +| ZIP support | ❌ | ❌ | ✅ | ✅ | +| Streaming support | ✅ | ❌ | ❌ | ✅ | +| GZIP support | ✅ | ❌ | ❌ | ✅ | +| Supports files up to 4GB | ✅ | ❌ | ❌ | ✅ | +| Doesn't hang on error | ✅ | ❌ | ❌ | ✅ | +| Dictionary support | ✅ | ❌ | ❌ | ✅ | +| Multi-thread/Asynchronous | ❌ | ❌ | ❌ | ✅ | +| Streaming ZIP support | ❌ | ❌ | ❌ | ✅ | +| Uses ES Modules | ❌ | ❌ | ❌ | ✅ | + +## Demo +If you'd like to try `fflate` for yourself without installing it, you can take a look at the [browser demo](https://101arrowz.github.io/fflate). Since `fflate` is a pure JavaScript library, it works in both the browser and Node.js (see [Browser support](https://github.com/101arrowz/fflate/#browser-support) for more info). + +## Usage + +Install `fflate`: +```sh +npm i fflate # or yarn add fflate, or pnpm add fflate +``` + +Import: +```js +// I will assume that you use the following for the rest of this guide +import * as fflate from 'fflate'; + +// However, you should import ONLY what you need to minimize bloat. +// So, if you just need GZIP compression support: +import { gzipSync } from 'fflate'; +// Woo! You just saved 20 kB off your bundle with one line. +``` + +If your environment doesn't support ES Modules (e.g. Node.js): +```js +// Try to avoid this when using fflate in the browser, as it will import +// all of fflate's components, even those that you aren't using. +const fflate = require('fflate'); +``` + +If you want to load from a CDN in the browser: +```html + + + + + + + +``` + +If you are using Deno: +```js +// Don't use the ?dts Skypack flag; it isn't necessary for Deno support +// The @deno-types comment adds TypeScript typings + +// @deno-types="https://cdn.skypack.dev/fflate@0.8.3/lib/index.d.ts" +import * as fflate from 'https://cdn.skypack.dev/fflate@0.8.3?min'; +``` + + +If your environment doesn't support bundling: +```js +// Again, try to import just what you need + +// For the browser: +import * as fflate from 'fflate/esm/browser.js'; +// If the standard ESM import fails on Node (i.e. older version): +import * as fflate from 'fflate/esm'; +``` + +And use: +```js +// This is an ArrayBuffer of data +const massiveFileBuf = await fetch('/aMassiveFile').then( + res => res.arrayBuffer() +); +// To use fflate, you need a Uint8Array +const massiveFile = new Uint8Array(massiveFileBuf); +// Note that Node.js Buffers work just fine as well: +// const massiveFile = require('fs').readFileSync('aMassiveFile.txt'); + +// Higher level means lower performance but better compression +// The level ranges from 0 (no compression) to 9 (max compression) +// The default level is 6 +const notSoMassive = fflate.zlibSync(massiveFile, { level: 9 }); +const massiveAgain = fflate.unzlibSync(notSoMassive); +const gzipped = fflate.gzipSync(massiveFile, { + // GZIP-specific: the filename to use when decompressed + filename: 'aMassiveFile.txt', + // GZIP-specific: the modification time. Can be a Date, date string, + // or Unix timestamp + mtime: '9/1/16 2:00 PM' +}); +``` +`fflate` can autodetect a compressed file's format as well: +```js +const compressed = new Uint8Array( + await fetch('/GZIPorZLIBorDEFLATE').then(res => res.arrayBuffer()) +); +// Above example with Node.js Buffers: +// Buffer.from('H4sIAAAAAAAAE8tIzcnJBwCGphA2BQAAAA==', 'base64'); + +const decompressed = fflate.decompressSync(compressed); +``` + +Using strings is easy with `fflate`'s string conversion API: +```js +const buf = fflate.strToU8('Hello world!'); + +// The default compression method is gzip +// Increasing mem may increase performance at the cost of memory +// The mem ranges from 0 to 12, where 4 is the default +const compressed = fflate.compressSync(buf, { level: 6, mem: 8 }); + +// When you need to decompress: +const decompressed = fflate.decompressSync(compressed); +const origText = fflate.strFromU8(decompressed); +console.log(origText); // Hello world! +``` + +If you need to use an (albeit inefficient) binary string, you can set the second argument to `true`. +```js +const buf = fflate.strToU8('Hello world!'); + +// The second argument, latin1, is a boolean that indicates that the data +// is not Unicode but rather should be encoded and decoded as Latin-1. +// This is useful for creating a string from binary data that isn't +// necessarily valid UTF-8. However, binary strings are incredibly +// inefficient and tend to double file size, so they're not recommended. +const compressedString = fflate.strFromU8( + fflate.compressSync(buf), + true +); +const decompressed = fflate.decompressSync( + fflate.strToU8(compressedString, true) +); +const origText = fflate.strFromU8(decompressed); +console.log(origText); // Hello world! +``` + +You can use streams as well to incrementally add data to be compressed or decompressed: +```js +// This example uses synchronous streams, but for the best experience +// you'll definitely want to use asynchronous streams. + +let outStr = ''; +const gzipStream = new fflate.Gzip({ level: 9 }, (chunk, isLast) => { + // accumulate in an inefficient binary string (just an example) + outStr += fflate.strFromU8(chunk, true); +}); + +// You can also attach the data handler separately if you don't want to +// do so in the constructor. +gzipStream.ondata = (chunk, final) => { ... } + +// Since this is synchronous, all errors will be thrown by stream.push() +gzipStream.push(chunk1); +gzipStream.push(chunk2); + +... + +// You should mark the last chunk by using true in the second argument +// In addition to being necessary for the stream to work properly, this +// will also set the isLast parameter in the handler to true. +gzipStream.push(lastChunk, true); + +console.log(outStr); // The compressed binary string is now available + +// The options parameter for compression streams is optional; you can +// provide one parameter (the handler) or none at all if you set +// deflateStream.ondata later. +const deflateStream = new fflate.Deflate((chunk, final) => { + console.log(chunk, final); +}); + +// If you want to create a stream from strings, use EncodeUTF8 +const utfEncode = new fflate.EncodeUTF8((data, final) => { + // Chaining streams together is done by pushing to the + // next stream in the handler for the previous stream + deflateStream.push(data, final); +}); + +utfEncode.push('Hello'.repeat(1000)); +utfEncode.push(' '.repeat(100)); +utfEncode.push('world!'.repeat(10), true); + +// The deflateStream has logged the compressed data + +const inflateStream = new fflate.Inflate(); +inflateStream.ondata = (decompressedChunk, final) => { ... }; + +let stringData = ''; + +// Streaming UTF-8 decode is available too +const utfDecode = new fflate.DecodeUTF8((data, final) => { + stringData += data; +}); + +// Decompress streams auto-detect the compression method, as the +// non-streaming decompress() method does. +const dcmpStrm = new fflate.Decompress((chunk, final) => { + console.log(chunk, 'was encoded with GZIP, Zlib, or DEFLATE'); + utfDecode.push(chunk, final); +}); + +dcmpStrm.push(zlibJSONData1); +dcmpStrm.push(zlibJSONData2, true); + +// This succeeds; the UTF-8 decoder chained with the unknown compression format +// stream to reach a string as a sink. +console.log(JSON.parse(stringData)); +``` + +You can create multi-file ZIP archives easily as well. Note that by default, compression is enabled for all files, which is not useful when ZIPping many PNGs, JPEGs, PDFs, etc. because those formats are already compressed. You should either override the level on a per-file basis or globally to avoid wasting resources. +```js +// Note that the asynchronous version (see below) runs in parallel and +// is *much* (up to 3x) faster for larger archives. +const zipped = fflate.zipSync({ + // Directories can be nested structures, as in an actual filesystem + 'dir1': { + 'nested': { + // You can use Unicode in filenames + '你好.txt': fflate.strToU8('Hey there!') + }, + // You can also manually write out a directory path + 'other/tmp.txt': new Uint8Array([97, 98, 99, 100]) + }, + + // You can also provide compression options + 'massiveImage.bmp': [aMassiveFile, { + level: 9, + mem: 12 + }], + // PNG is pre-compressed; no need to waste time + 'superTinyFile.png': [aPNGFile, { level: 0 }], + + // Directories take options too + 'exec': [{ + 'hello.sh': [fflate.strToU8('echo hello world'), { + // ZIP only: Set the operating system to Unix + os: 3, + // ZIP only: Make this file executable on Unix + attrs: 0o755 << 16 + }] + }, { + // ZIP and GZIP support mtime (defaults to current time) + mtime: new Date('10/20/2020') + }] +}, { + // These options are the defaults for all files, but file-specific + // options take precedence. + level: 1, + // Obfuscate last modified time by default + mtime: new Date('1/1/1980') +}); + +// If you write the zipped data to myzip.zip and unzip, the folder +// structure will be outputted as: + +// myzip.zip (original file) +// dir1 +// |-> nested +// | |-> 你好.txt +// |-> other +// | |-> tmp.txt +// massiveImage.bmp +// superTinyFile.png + +// When decompressing, folders are not nested; all filepaths are fully +// written out in the keys. For example, the return value may be: +// { 'nested/directory/structure.txt': Uint8Array(2) [97, 97] } +const decompressed = fflate.unzipSync(zipped, { + // You may optionally supply a filter for files. By default, all files in a + // ZIP archive are extracted, but a filter can save resources by telling + // the library not to decompress certain files + filter(file) { + // Don't decompress the massive image or any files larger than 10 MiB + return file.name != 'massiveImage.bmp' && file.originalSize <= 10_000_000; + } +}); +``` + +If you need extremely high performance or custom ZIP compression formats, you can use the highly-extensible ZIP streams. They take streams as both input and output. You can even use custom compression/decompression algorithms from other libraries, as long as they [are defined in the ZIP spec](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) (see section 4.4.5). If you'd like more info on using custom compressors, [feel free to ask](https://github.com/101arrowz/fflate/discussions). +```js +// ZIP object +// Can also specify zip.ondata outside of the constructor +const zip = new fflate.Zip((err, dat, final) => { + if (!err) { + // output of the streams + console.log(dat, final); + } +}); + +const helloTxt = new fflate.ZipDeflate('hello.txt', { + level: 9 +}); + +// Always add streams to ZIP archives before pushing to those streams +zip.add(helloTxt); + +helloTxt.push(chunk1); +// Last chunk +helloTxt.push(chunk2, true); + +// ZipPassThrough is like ZipDeflate with level 0, but allows for tree shaking +const nonStreamingFile = new fflate.ZipPassThrough('test.png'); +zip.add(nonStreamingFile); +// If you have data already loaded, just .push(data, true) +nonStreamingFile.push(pngData, true); + +// You need to call .end() after finishing +// This ensures the ZIP is valid +zip.end(); + +// Unzip object +const unzipper = new fflate.Unzip(); + +// This function will almost always have to be called. It is used to support +// compression algorithms such as BZIP2 or LZMA in ZIP files if just DEFLATE +// is not enough (though it almost always is). +// If your ZIP files are not compressed, this line is not needed. +unzipper.register(fflate.UnzipInflate); + +const neededFiles = ['file1.txt', 'example.json']; + +// Can specify handler in constructor too +unzipper.onfile = file => { + // file.name is a string, file is a stream + if (neededFiles.includes(file.name)) { + file.ondata = (err, dat, final) => { + // Stream output here + console.log(dat, final); + }; + + console.log('Reading:', file.name); + + // File sizes are sometimes not set if the ZIP file did not encode + // them, so you may want to check that file.size != undefined + console.log('Compressed size', file.size); + console.log('Decompressed size', file.originalSize); + + // You should only start the stream if you plan to use it to improve + // performance. Only after starting the stream will ondata be called. + // This method will throw if the compression method hasn't been registered + file.start(); + } +}; + +// Try to keep under 5,000 files per chunk to avoid stack limit errors +// For example, if all files are a few kB, multi-megabyte chunks are OK +// If files are mostly under 100 bytes, 64kB chunks are the limit +unzipper.push(zipChunk1); +unzipper.push(zipChunk2); +unzipper.push(zipChunk3, true); +``` + +As you may have guessed, there is an asynchronous version of every method as well. Unlike most libraries, this will cause the compression or decompression run in a separate thread entirely and automatically by using Web (or Node) Workers. This means that the processing will not block the main thread at all. + +Note that there is a significant initial overhead to using workers of about 50ms for each asynchronous function. For instance, if you call `unzip` ten times, the overhead only applies for the first call, but if you call `unzip` and `zlib`, they will each cause the 50ms delay. For small (under about 50kB) payloads, the asynchronous APIs will be much slower. However, if you're compressing larger files/multiple files at once, or if the synchronous API causes the main thread to hang for too long, the callback APIs are an order of magnitude better. +```js +import { + gzip, zlib, AsyncGzip, zip, unzip, strFromU8, + Zip, AsyncZipDeflate, Unzip, AsyncUnzipInflate +} from 'fflate'; + +// Workers will work in almost any browser (even IE11!) +// All of the async APIs use a node-style callback as so: +const terminate = gzip(aMassiveFile, (err, data) => { + if (err) { + // The compressed data was likely corrupt, so we have to handle + // the error. + return; + } + // Use data however you like + console.log(data.length); +}); + +if (needToCancel) { + // The return value of any of the asynchronous APIs is a function that, + // when called, will immediately cancel the operation. The callback + // will not be called. + terminate(); +} + +// If you wish to provide options, use the second argument. + +// The consume option will render the data inside aMassiveFile unusable, +// but can improve performance and dramatically reduce memory usage. +zlib(aMassiveFile, { consume: true, level: 9 }, (err, data) => { + // Use the data +}); + +// Asynchronous streams are similar to synchronous streams, but the +// handler has the error that occurred (if any) as the first parameter, +// and they don't block the main thread. + +// Additionally, any buffers that are pushed in will be consumed and +// rendered unusable; if you need to use a buffer you push in, you +// should clone it first. +const gzs = new AsyncGzip({ level: 9, mem: 12, filename: 'hello.txt' }); +let wasCallbackCalled = false; +gzs.ondata = (err, chunk, final) => { + // Note the new err parameter + if (err) { + // Note that after this occurs, the stream becomes corrupt and must + // be discarded. You can't continue pushing chunks and expect it to + // work. + console.error(err); + return; + } + wasCallbackCalled = true; +} +gzs.push(chunk); + +// Since the stream is asynchronous, the callback will not be called +// immediately. If such behavior is absolutely necessary (it shouldn't +// be), use synchronous streams. +console.log(wasCallbackCalled) // false + +// To terminate an asynchronous stream's internal worker, call +// stream.terminate(). +gzs.terminate(); + +// This is way faster than zipSync because the compression of multiple +// files runs in parallel. In fact, the fact that it's parallelized +// makes it faster than most standalone ZIP CLIs. The effect is most +// significant for multiple large files; less so for many small ones. +zip({ f1: aMassiveFile, 'f2.txt': anotherMassiveFile }, { + // The options object is still optional, you can still do just + // zip(archive, callback) + level: 6 +}, (err, data) => { + // Save the ZIP file +}); + +// unzip is the only async function without support for consume option +// It is parallelized, so unzip is also often much faster than unzipSync +unzip(aMassiveZIPFile, (err, unzipped) => { + // If the archive has data.xml, log it here + console.log(unzipped['data.xml']); + // Conversion to string + console.log(strFromU8(unzipped['data.xml'])) +}); + +// Streaming ZIP archives can accept asynchronous streams. This automatically +// uses multicore compression. +const zip = new Zip(); +zip.ondata = (err, chunk, final) => { ... }; +// The JSON and BMP are compressed in parallel +const exampleFile = new AsyncZipDeflate('example.json'); +zip.add(exampleFile); +exampleFile.push(JSON.stringify({ large: 'object' }), true); +const exampleFile2 = new AsyncZipDeflate('example2.bmp', { level: 9 }); +zip.add(exampleFile2); +exampleFile2.push(ec2a); +exampleFile2.push(ec2b); +exampleFile2.push(ec2c); +... +exampleFile2.push(ec2Final, true); +zip.end(); + +// Streaming Unzip should register the asynchronous inflation algorithm +// for parallel processing. +const unzip = new Unzip(stream => { + if (stream.name.endsWith('.json')) { + stream.ondata = (err, chunk, final) => { ... }; + stream.start(); + + if (needToCancel) { + // To cancel these streams, call .terminate() + stream.terminate(); + } + } +}); +unzip.register(AsyncUnzipInflate); +unzip.push(data, true); +``` + +See the [documentation](https://github.com/101arrowz/fflate/blob/master/docs/README.md) for more detailed information about the API. + +## Bundle size estimates + +The bundle size measurements for `fflate` on sites like Bundlephobia include every feature of the library and should be seen as an upper bound. As long as you are using tree shaking or dead code elimination, this table should give you a general idea of `fflate`'s bundle size for the features you need. + +The maximum bundle size that is possible with `fflate` is about 33kB (12.5kB gzipped) if you use every single feature, but feature parity with `pako` is only around 10kB (as opposed to 45kB from `pako`). If your bundle size increases dramatically after adding `fflate`, please [create an issue](https://github.com/101arrowz/fflate/issues/new). + +| Feature | Bundle size (minified) | Nearest competitor | +|-------------------------|--------------------------------|-------------------------| +| Decompression | 3kB | `tiny-inflate` | +| Compression | 5kB | `UZIP.js`, 2.84x larger | +| Async decompression | 4kB (1kB + raw decompression) | N/A | +| Async compression | 6kB (1kB + raw compression) | N/A | +| ZIP decompression | 5kB (2kB + raw decompression) | `UZIP.js`, 2.84x larger | +| ZIP compression | 7kB (2kB + raw compression) | `UZIP.js`, 2.03x larger | +| GZIP/Zlib decompression | 4kB (1kB + raw decompression) | `pako`, 11.4x larger | +| GZIP/Zlib compression | 5kB (1kB + raw compression) | `pako`, 9.12x larger | +| Streaming decompression | 4kB (1kB + raw decompression) | `pako`, 11.4x larger | +| Streaming compression | 5kB (1kB + raw compression) | `pako`, 9.12x larger | + +## What makes `fflate` so fast? +Many JavaScript compression/decompression libraries exist. However, the most popular one, [`pako`](https://npmjs.com/package/pako), is merely a clone of Zlib rewritten nearly line-for-line in JavaScript. Although it is by no means poorly made, `pako` doesn't recognize the many differences between JavaScript and C, and therefore is suboptimal for performance. Moreover, even when minified, the library is 45 kB; it may not seem like much, but for anyone concerned with optimizing bundle size (especially library authors), it's more weight than necessary. + +Note that there exist some small libraries like [`tiny-inflate`](https://npmjs.com/package/tiny-inflate) for solely decompression, and with a minified size of 3 kB, it can be appealing; however, its performance is lackluster, typically 40% worse than `pako` in my tests. + +[`UZIP.js`](https://github.com/photopea/UZIP.js) is both faster (by up to 25%) and smaller (14 kB minified) than `pako`, and it contains a variety of innovations that make it excellent for both performance and compression ratio. However, the developer made a variety of tiny mistakes and inefficient design choices that make it imperfect. Moreover, it does not support GZIP or Zlib data directly; one must remove the headers manually to use `UZIP.js`. + +So what makes `fflate` different? It takes the brilliant innovations of `UZIP.js` and optimizes them while adding direct support for GZIP and Zlib data. And unlike all of the above libraries, it uses ES Modules to allow for partial builds through tree shaking, meaning that it can rival even `tiny-inflate` in size while maintaining excellent performance. The end result is a library that, in total, weighs 8kB minified for the core build (3kB for decompression only and 5kB for compression only), is about 25% faster than `UZIP.js` or up to 50% faster than `pako`, and achieves the same or better compression ratio than the rest. + +Before you decide that `fflate` is the end-all compression library, you should note that JavaScript simply cannot rival the performance of a native program. If you're only using Node.js, it's probably better to use the [native Zlib bindings](https://nodejs.org/api/zlib.html), which tend to offer the best performance. Though note that even against Zlib, `fflate` is only around 30% slower in decompression and 10% slower in compression, and can still achieve better compression ratios! + +## What about `CompressionStream`? +Like `fflate`, the [Compression Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API) provides DEFLATE, GZIP, and Zlib compression and decompression support. It's a good option if you'd like to compress or decompress data without installing any third-party libraries, and it wraps native Zlib bindings to achieve better performance than what most JavaScript programs can achieve. + +However, browsers do not offer any native non-streaming compression API, and `CompressionStream` has surprisingly poor performance on data already loaded into memory; `fflate` tends to be faster even for files that are dozens of megabytes large. Similarly, `fflate` is much faster for files under a megabyte because it avoids marshalling overheads. Even when streaming hundreds of megabytes of data, the native API usually performs between 30% faster and 10% slower than `fflate`. And Compression Streams have many other disadvantages - no ability to control compression level, poor support for older browsers, no ZIP support, etc. + +If you'd still prefer to depend upon a native browser API but want to support older browsers, you can use an `fflate`-based [Compression Streams ponyfill](https://github.com/101arrowz/compression-streams-polyfill). + +## Browser support +`fflate` makes heavy use of typed arrays (`Uint8Array`, `Uint16Array`, etc.). Typed arrays can be polyfilled at the cost of performance, but the most recent browser that doesn't support them [is from 2011](https://caniuse.com/typedarrays), so I wouldn't bother. + +The asynchronous APIs also use `Worker`, which is not supported in a few browsers (however, the vast majority of browsers that support typed arrays support `Worker`). + +Other than that, `fflate` is completely ES3, meaning you probably won't even need a bundler to use it. + +## Testing +You can validate the performance of `fflate` with `npm test`. It validates that the module is working as expected, ensures the outputs are no more than 5% larger than competitors at max compression, and outputs performance metrics to `test/results`. + +Note that the time it takes for the CLI to show the completion of each test is not representative of the time each package took, so please check the JSON output if you want accurate measurements. + +## License + +This software is [MIT Licensed](./LICENSE), with special exemptions for projects +and organizations as noted below: + +- [SheetJS](https://github.com/SheetJS/) is exempt from MIT licensing and may + license any source code from this software under the BSD Zero Clause License diff --git a/node_modules/fflate/esm/browser.d.ts b/node_modules/fflate/esm/browser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d430faf2b555c978d66c89f46155b72c2c45a971 --- /dev/null +++ b/node_modules/fflate/esm/browser.d.ts @@ -0,0 +1,1539 @@ +/** + * Codes for errors generated within this library + */ +export declare const FlateErrorCode: { + readonly UnexpectedEOF: 0; + readonly InvalidBlockType: 1; + readonly InvalidLengthLiteral: 2; + readonly InvalidDistance: 3; + readonly StreamFinished: 4; + readonly NoStreamHandler: 5; + readonly InvalidHeader: 6; + readonly NoCallback: 7; + readonly InvalidUTF8: 8; + readonly ExtraFieldTooLong: 9; + readonly InvalidDate: 10; + readonly FilenameTooLong: 11; + readonly StreamFinishing: 12; + readonly InvalidZipData: 13; + readonly UnknownCompressionMethod: 14; +}; +/** + * An error generated within this library + */ +export interface FlateError extends Error { + /** + * The code associated with this error + */ + code: number; +} +/** + * Options for decompressing a DEFLATE stream + */ +export interface InflateStreamOptions { + /** + * The dictionary used to compress the original data. If no dictionary was used during compression, this option has no effect. + * + * Supplying the wrong dictionary during decompression usually yields corrupt output or causes an invalid distance error. + */ + dictionary?: Uint8Array; +} +/** + * Options for decompressing DEFLATE data + */ +export interface InflateOptions extends InflateStreamOptions { + /** + * The buffer into which to write the decompressed data. Saves memory if you know the decompressed size in advance. + * + * Note that if the decompression result is larger than the size of this buffer, it will be truncated to fit. + */ + out?: Uint8Array; +} +/** + * Options for decompressing a GZIP stream + */ +export interface GunzipStreamOptions extends InflateStreamOptions { +} +/** + * Options for decompressing GZIP data + */ +export interface GunzipOptions extends InflateStreamOptions { + /** + * The buffer into which to write the decompressed data. GZIP already encodes the output size, so providing this doesn't save memory. + * + * Note that if the decompression result is larger than the size of this buffer, it will be truncated to fit. + */ + out?: Uint8Array; +} +/** + * Options for decompressing a Zlib stream + */ +export interface UnzlibStreamOptions extends InflateStreamOptions { +} +/** + * Options for decompressing Zlib data + */ +export interface UnzlibOptions extends InflateOptions { +} +/** + * Options for compressing data into a DEFLATE format + */ +export interface DeflateOptions { + /** + * The level of compression to use, ranging from 0-9. + * + * 0 will store the data without compression. + * 1 is fastest but compresses the worst, 9 is slowest but compresses the best. + * The default level is 6. + * + * Typically, binary data benefits much more from higher values than text data. + * In both cases, higher values usually take disproportionately longer than the reduction in final size that results. + * + * For example, a 1 MB text file could: + * - become 1.01 MB with level 0 in 1ms + * - become 400 kB with level 1 in 10ms + * - become 320 kB with level 9 in 100ms + */ + level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + /** + * The memory level to use, ranging from 0-12. Increasing this increases speed and compression ratio at the cost of memory. + * + * Note that this is exponential: while level 0 uses 8 kB, level 4 uses 128 kB, level 8 uses 2 MB, and level 12 uses 32 MB. + * It is recommended not to lower the value below 4, since that tends to hurt performance. + * In addition, values above 8 tend to help very little on most data and can even hurt performance. + * + * The default value is automatically determined based on the size of the input data. + */ + mem?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; + /** + * A buffer containing common byte sequences in the input data that can be used to significantly improve compression ratios. + * + * Dictionaries should be 32kB or smaller and include strings or byte sequences likely to appear in the input. + * The decompressor must supply the same dictionary as the compressor to extract the original data. + * + * Dictionaries only improve aggregate compression ratio when reused across multiple small inputs. They should typically not be used otherwise. + * + * Avoid using dictionaries with GZIP and ZIP to maximize software compatibility. + */ + dictionary?: Uint8Array; +} +/** + * Options for compressing data into a GZIP format + */ +export interface GzipOptions extends DeflateOptions { + /** + * When the file was last modified. Defaults to the current time. + * Set this to 0 to avoid revealing a modification date entirely. + */ + mtime?: Date | string | number; + /** + * The filename of the data. If the `gunzip` command is used to decompress the data, it will output a file + * with this name instead of the name of the compressed file. + */ + filename?: string; +} +/** + * Options for compressing data into a Zlib format + */ +export interface ZlibOptions extends DeflateOptions { +} +/** + * Handler for data (de)compression streams + * @param data The data output from the stream processor + * @param final Whether this is the final block + */ +export type FlateStreamHandler = (data: Uint8Array, final: boolean) => void; +/** + * Handler for asynchronous data (de)compression streams + * @param err Any error that occurred + * @param data The data output from the stream processor + * @param final Whether this is the final block + */ +export type AsyncFlateStreamHandler = (err: FlateError | null, data: Uint8Array, final: boolean) => void; +/** + * Handler for the asynchronous completion of (de)compression for a data chunk + * @param size The number of bytes that were processed. This is measured in terms of the input + * (i.e. compressed bytes for decompression, uncompressed bytes for compression.) + */ +export type AsyncFlateDrainHandler = (size: number) => void; +/** + * Callback for asynchronous (de)compression methods + * @param err Any error that occurred + * @param data The resulting data. Only present if `err` is null + */ +export type FlateCallback = (err: FlateError | null, data: Uint8Array) => void; +interface AsyncOptions { + /** + * Whether or not to "consume" the source data. This will make the typed array/buffer you pass in + * unusable but will increase performance and reduce memory usage. + */ + consume?: boolean; +} +/** + * Options for compressing data asynchronously into a DEFLATE format + */ +export interface AsyncDeflateOptions extends DeflateOptions, AsyncOptions { +} +/** + * Options for decompressing DEFLATE data asynchronously + */ +export interface AsyncInflateOptions extends AsyncOptions, InflateStreamOptions { + /** + * The original size of the data. Currently, the asynchronous API disallows + * writing into a buffer you provide; the best you can do is provide the + * size in bytes and be given back a new typed array. + */ + size?: number; +} +/** + * Options for compressing data asynchronously into a GZIP format + */ +export interface AsyncGzipOptions extends GzipOptions, AsyncOptions { +} +/** + * Options for decompressing GZIP data asynchronously + */ +export interface AsyncGunzipOptions extends AsyncOptions, InflateStreamOptions { +} +/** + * Options for compressing data asynchronously into a Zlib format + */ +export interface AsyncZlibOptions extends ZlibOptions, AsyncOptions { +} +/** + * Options for decompressing Zlib data asynchronously + */ +export interface AsyncUnzlibOptions extends AsyncInflateOptions { +} +/** + * A terminable compression/decompression process + */ +export interface AsyncTerminable { + /** + * Terminates the worker thread immediately. The callback will not be called. + */ + (): void; +} +/** + * Streaming DEFLATE compression + */ +export declare class Deflate { + /** + * Creates a DEFLATE stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: DeflateOptions, cb?: FlateStreamHandler); + /** + * Creates a DEFLATE stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + private b; + private s; + private o; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + private p; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE compression + */ +export declare class AsyncDeflate { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous DEFLATE stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: DeflateOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous DEFLATE stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function deflate(data: Uint8Array, opts: AsyncDeflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param cb The function to be called upon compression completion + */ +export declare function deflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @returns The deflated version of the data + */ +export declare function deflateSync(data: Uint8Array, opts?: DeflateOptions): Uint8Array; +/** + * Streaming DEFLATE decompression + */ +export declare class Inflate { + private s; + private o; + private p; + private d; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a DEFLATE decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: InflateStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a DEFLATE decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + private e; + private c; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE decompression + */ +export declare class AsyncInflate { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous DEFLATE decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: InflateStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous DEFLATE decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function inflate(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function inflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands DEFLATE data with no wrapper + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function inflateSync(data: Uint8Array): Uint8Array; +/** + * Expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function inflateSync(data: Uint8Array, opts?: InflateOptions): Uint8Array; +/** + * Streaming GZIP compression + */ +export declare class Gzip { + private c; + private l; + private v; + private o; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a GZIP stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: GzipOptions, cb?: FlateStreamHandler); + /** + * Creates a GZIP stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + private p; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming GZIP compression + */ +export declare class AsyncGzip { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous GZIP stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: GzipOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous GZIP stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function gzip(data: Uint8Array, opts: AsyncGzipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with GZIP + * @param data The data to compress + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @returns The gzipped version of the data + */ +export declare function gzipSync(data: Uint8Array, opts?: GzipOptions): Uint8Array; +/** + * Handler for new GZIP members in concatenated GZIP streams. Useful for building indices used to perform random-access reads on compressed files. + * @param offset The offset of the new member relative to the start of the stream + */ +export type GunzipMemberHandler = (offset: number) => void; +/** + * Streaming single or multi-member GZIP decompression + */ +export declare class Gunzip { + private v; + private r; + private o; + private p; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * The handler to call whenever a new GZIP member is found + */ + onmember?: GunzipMemberHandler; + /** + * Creates a GUNZIP stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: GunzipStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a GUNZIP stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming single or multi-member GZIP decompression + */ +export declare class AsyncGunzip { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * The handler to call whenever a new GZIP member is found + */ + onmember?: GunzipMemberHandler; + /** + * Creates an asynchronous GUNZIP stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: GunzipStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous GUNZIP stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands GZIP data + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gunzip(data: Uint8Array, opts: AsyncGunzipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands GZIP data + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gunzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands GZIP data + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function gunzipSync(data: Uint8Array): Uint8Array; +/** + * Expands GZIP data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function gunzipSync(data: Uint8Array, opts?: GunzipOptions): Uint8Array; +/** + * Streaming Zlib compression + */ +export declare class Zlib { + private c; + private v; + private o; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a Zlib stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: ZlibOptions, cb?: FlateStreamHandler); + /** + * Creates a Zlib stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + private p; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming Zlib compression + */ +export declare class AsyncZlib { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous Zlib stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: ZlibOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous Zlib stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with Zlib + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + */ +export declare function zlib(data: Uint8Array, opts: AsyncZlibOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with Zlib + * @param data The data to compress + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compress data with Zlib + * @param data The data to compress + * @param opts The compression options + * @returns The zlib-compressed version of the data + */ +export declare function zlibSync(data: Uint8Array, opts?: ZlibOptions): Uint8Array; +/** + * Streaming Zlib decompression + */ +export declare class Unzlib { + private v; + private p; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a Zlib decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: UnzlibStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming Zlib decompression + */ +export declare class AsyncUnzlib { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous Zlib decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: UnzlibStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be decompressed from Zlib + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands Zlib data + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function unzlib(data: Uint8Array, opts: AsyncUnzlibOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands Zlib data + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function unzlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands Zlib data + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function unzlibSync(data: Uint8Array): Uint8Array; +/** + * Expands Zlib data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function unzlibSync(data: Uint8Array, opts?: UnzlibOptions): Uint8Array; +export { gzip as compress, AsyncGzip as AsyncCompress }; +export { gzipSync as compressSync, Gzip as Compress }; +/** + * Streaming GZIP, Zlib, or raw DEFLATE decompression + */ +export declare class Decompress { + private G; + private I; + private Z; + private o; + private s; + private p; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is decompressed + */ + constructor(opts: InflateStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a decompression stream + * @param cb The callback to call whenever data is decompressed + */ + constructor(cb?: FlateStreamHandler); + private i; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression + */ +export declare class AsyncDecompress { + private G; + private I; + private Z; + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is decompressed + */ + constructor(opts: InflateStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous decompression stream + * @param cb The callback to call whenever data is decompressed + */ + constructor(cb?: AsyncFlateStreamHandler); + private i; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function decompress(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function decompress(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function decompressSync(data: Uint8Array, opts?: InflateOptions): Uint8Array; +/** + * Attributes for files added to a ZIP archive object + */ +export interface ZipAttributes { + /** + * The operating system of origin for this file. The value is defined + * by PKZIP's APPNOTE.txt, section 4.4.2.2. For example, 0 (the default) + * is MS/DOS, 3 is Unix, 19 is macOS. + */ + os?: number; + /** + * The file's attributes. These are traditionally somewhat complicated + * and platform-dependent, so using them is scarcely necessary. However, + * here is a representation of what this is, bit by bit: + * + * `TTTTugtrwxrwxrwx0000000000ADVSHR` + * + * TTTT = file type (rarely useful) + * + * u = setuid, g = setgid, t = sticky + * + * rwx = user permissions, rwx = group permissions, rwx = other permissions + * + * 0000000000 = unused + * + * A = archive, D = directory, V = volume label, S = system file, H = hidden, R = read-only + * + * If you want to set the Unix permissions, for instance, just bit shift by 16, e.g. 0o644 << 16. + * Note that attributes usually only work in conjunction with the `os` setting: you must use + * `os` = 3 (Unix) if you want to set Unix permissions + */ + attrs?: number; + /** + * Extra metadata to add to the file. This field is defined by PKZIP's APPNOTE.txt, + * section 4.4.28. At most 65,535 bytes may be used in each ID. The ID must be an + * integer between 0 and 65,535, inclusive. + * + * This field is incredibly rare and almost never needed except for compliance with + * proprietary standards and software. + */ + extra?: Record; + /** + * The comment to attach to the file. This field is defined by PKZIP's APPNOTE.txt, + * section 4.4.26. The comment must be at most 65,535 bytes long UTF-8 encoded. This + * field is not read by consumer software. + */ + comment?: string; + /** + * When the file was last modified. Defaults to the current time. + */ + mtime?: GzipOptions['mtime']; +} +/** + * Options for creating a ZIP archive + */ +export interface ZipOptions extends DeflateOptions, ZipAttributes { +} +/** + * Options for expanding a ZIP archive + */ +export interface UnzipOptions { + /** + * A filter function to extract only certain files from a ZIP archive + */ + filter?: UnzipFileFilter; +} +/** + * Options for asynchronously creating a ZIP archive + */ +export interface AsyncZipOptions extends AsyncDeflateOptions, ZipAttributes { +} +/** + * Options for asynchronously expanding a ZIP archive + */ +export interface AsyncUnzipOptions extends UnzipOptions { +} +/** + * A file that can be used to create a ZIP archive + */ +export type ZippableFile = Uint8Array | Zippable | [Uint8Array | Zippable, ZipOptions]; +/** + * A file that can be used to asynchronously create a ZIP archive + */ +export type AsyncZippableFile = Uint8Array | AsyncZippable | [Uint8Array | AsyncZippable, AsyncZipOptions]; +/** + * The complete directory structure of a ZIPpable archive + */ +export interface Zippable { + [path: string]: ZippableFile; +} +/** + * The complete directory structure of an asynchronously ZIPpable archive + */ +export interface AsyncZippable { + [path: string]: AsyncZippableFile; +} +/** + * An unzipped archive. The full path of each file is used as the key, + * and the file is the value + */ +export interface Unzipped { + [path: string]: Uint8Array; +} +/** + * Handler for string generation streams + * @param data The string output from the stream processor + * @param final Whether this is the final block + */ +export type StringStreamHandler = (data: string, final: boolean) => void; +/** + * Callback for asynchronous ZIP decompression + * @param err Any error that occurred + * @param data The decompressed ZIP archive + */ +export type UnzipCallback = (err: FlateError | null, data: Unzipped) => void; +/** + * Handler for streaming ZIP decompression + * @param file The file that was found in the archive + */ +export type UnzipFileHandler = (file: UnzipFile) => void; +/** + * Streaming UTF-8 decoding + */ +export declare class DecodeUTF8 { + private p; + private t; + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is decoded + */ + constructor(cb?: StringStreamHandler); + /** + * Pushes a chunk to be decoded from UTF-8 binary + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * The handler to call whenever data is available + */ + ondata: StringStreamHandler; +} +/** + * Streaming UTF-8 encoding + */ +export declare class EncodeUTF8 { + private d; + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is encoded + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be encoded to UTF-8 + * @param chunk The string data to push + * @param final Whether this is the last chunk + */ + push(chunk: string, final?: boolean): void; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; +} +/** + * Converts a string into a Uint8Array for use with compression/decompression methods + * @param str The string to encode + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless decoding a binary string. + * @returns The string encoded in UTF-8/Latin-1 binary + */ +export declare function strToU8(str: string, latin1?: boolean): Uint8Array; +/** + * Converts a Uint8Array to a string + * @param dat The data to decode to string + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless encoding to binary string. + * @returns The original UTF-8/Latin-1 string + */ +export declare function strFromU8(dat: Uint8Array, latin1?: boolean): string; +/** + * A stream that can be used to create a file in a ZIP archive + */ +export interface ZipInputFile extends ZipAttributes { + /** + * The filename to associate with the data provided to this stream. If you + * want a file in a subdirectory, use forward slashes as a separator (e.g. + * `directory/filename.ext`). This will still work on Windows. + */ + filename: string; + /** + * The size of the file in bytes. This attribute may be invalid after + * the file is added to the ZIP archive; it must be correct only before the + * stream completes. + * + * If you don't want to have to compute this yourself, consider extending the + * ZipPassThrough class and overriding its process() method, or using one of + * ZipDeflate or AsyncZipDeflate. + */ + size: number; + /** + * A CRC of the original file contents. This attribute may be invalid after + * the file is added to the ZIP archive; it must be correct only before the + * stream completes. + * + * If you don't want to have to generate this yourself, consider extending the + * ZipPassThrough class and overriding its process() method, or using one of + * ZipDeflate or AsyncZipDeflate. + */ + crc: number; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA + */ + compression: number; + /** + * Bits 1 and 2 of the general purpose bit flag, specified in PKZIP's + * APPNOTE.txt, section 4.4.4. Should be between 0 and 3. This is unlikely + * to be necessary. + */ + flag?: number; + /** + * The handler to be called when data is added. After passing this stream to + * the ZIP file object, this handler will always be defined. To call it: + * + * `stream.ondata(error, chunk, final)` + * + * error = any error that occurred (null if there was no error) + * + * chunk = a Uint8Array of the data that was added (null if there was an + * error) + * + * final = boolean, whether this is the final chunk in the stream + */ + ondata?: AsyncFlateStreamHandler; + /** + * A method called when the stream is no longer needed, for clean-up + * purposes. This will not always be called after the stream completes, + * so you may wish to call this.terminate() after the final chunk is + * processed if you have clean-up logic. + */ + terminate?: AsyncTerminable; +} +/** + * A pass-through stream to keep data uncompressed in a ZIP archive. + */ +export declare class ZipPassThrough implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private c; + /** + * Creates a pass-through stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + */ + constructor(filename: string); + /** + * Processes a chunk and pushes to the output stream. You can override this + * method in a subclass for custom behavior, but by default this passes + * the data through. You must call this.ondata(err, chunk, final) at some + * point in this method. + * @param chunk The chunk to process + * @param final Whether this is the last chunk + */ + protected process(chunk: Uint8Array, final: boolean): void; + /** + * Pushes a chunk to be added. If you are subclassing this with a custom + * compression algorithm, note that you must push data from the source + * file only, pre-compression. + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate + * for better performance + */ +export declare class ZipDeflate implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + flag: 0 | 1 | 2 | 3; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private d; + /** + * Creates a DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + constructor(filename: string, opts?: DeflateOptions); + private process; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE compression for ZIP archives + */ +export declare class AsyncZipDeflate implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + flag: 0 | 1 | 2 | 3; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private d; + terminate: AsyncTerminable; + /** + * Creates an asynchronous DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + constructor(filename: string, opts?: DeflateOptions); + private process; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * A zippable archive to which files can incrementally be added + */ +export declare class Zip { + private u; + private d; + /** + * Creates an empty ZIP archive to which files can be added + * @param cb The callback to call whenever data for the generated ZIP archive + * is available + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Adds a file to the ZIP archive + * @param file The file stream to add + */ + add(file: ZipInputFile): void; + /** + * Ends the process of adding files and prepares to emit the final chunks. + * This *must* be called after adding all desired files for the resulting + * ZIP file to work properly. + */ + end(): void; + private e; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to add() will fail. + */ + terminate(): void; + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; +} +/** + * Asynchronously creates a ZIP file + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @param cb The callback to call with the generated ZIP archive + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zip(data: AsyncZippable, opts: AsyncZipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously creates a ZIP file + * @param data The directory structure for the ZIP archive + * @param cb The callback to call with the generated ZIP archive + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zip(data: AsyncZippable, cb: FlateCallback): AsyncTerminable; +/** + * Synchronously creates a ZIP file. Prefer using `zip` for better performance + * with more than one file. + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @returns The generated ZIP archive + */ +export declare function zipSync(data: Zippable, opts?: ZipOptions): Uint8Array; +/** + * A decoder for files in ZIP streams + */ +export interface UnzipDecoder { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * Pushes a chunk to be decompressed + * @param chunk The data in this chunk. Do not consume (detach) this buffer. + * @param final Whether this is the last chunk in the data stream + */ + push(chunk: Uint8Array, final: boolean): void; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to push() should silently fail. + */ + terminate?: AsyncTerminable; +} +/** + * A constructor for a decoder for unzip streams + */ +export interface UnzipDecoderConstructor { + /** + * Creates an instance of the decoder + * @param filename The name of the file + * @param size The compressed size of the file + * @param originalSize The original size of the file + */ + new (filename: string, size?: number, originalSize?: number): UnzipDecoder; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA + */ + compression: number; +} +/** + * Information about a file to be extracted from a ZIP archive + */ +export interface UnzipFileInfo { + /** + * The name of the file + */ + name: string; + /** + * The compressed size of the file + */ + size: number; + /** + * The original size of the file + */ + originalSize: number; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA. If the filter function returns true + * but this value is not 8, the unzip function will throw. + */ + compression: number; +} +/** + * A filter for files to be extracted during the unzipping process + * @param file The info for the current file being processed + * @returns Whether or not to extract the current file + */ +export type UnzipFileFilter = (file: UnzipFileInfo) => boolean; +/** + * Streaming file extraction from ZIP archives + */ +export interface UnzipFile { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The name of the file + */ + name: string; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA. If start() is called but there is no + * decompression stream available for this method, start() will throw. + */ + compression: number; + /** + * The compressed size of the file. Will not be present for archives created + * in a streaming fashion. + */ + size?: number; + /** + * The original size of the file. Will not be present for archives created + * in a streaming fashion. + */ + originalSize?: number; + /** + * Starts reading from the stream. Calling this function will always enable + * this stream, but ocassionally the stream will be enabled even without + * this being called. + */ + start(): void; + /** + * A method to terminate any internal workers used by the stream. ondata + * will not be called any further. + */ + terminate: AsyncTerminable; +} +/** + * Streaming pass-through decompression for ZIP archives + */ +export declare class UnzipPassThrough implements UnzipDecoder { + static compression: number; + ondata: AsyncFlateStreamHandler; + push(chunk: Uint8Array, final: boolean): void; +} +/** + * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for + * better performance. + */ +export declare class UnzipInflate implements UnzipDecoder { + static compression: number; + private i; + ondata: AsyncFlateStreamHandler; + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + constructor(); + push(chunk: Uint8Array, final: boolean): void; +} +/** + * Asynchronous streaming DEFLATE decompression for ZIP archives + */ +export declare class AsyncUnzipInflate implements UnzipDecoder { + static compression: number; + private i; + ondata: AsyncFlateStreamHandler; + terminate: AsyncTerminable; + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + constructor(_: string, sz?: number); + push(chunk: Uint8Array, final: boolean): void; +} +/** + * A ZIP archive decompression stream that emits files as they are discovered + */ +export declare class Unzip { + private d; + private c; + private p; + private k; + private o; + /** + * Creates a ZIP decompression stream + * @param cb The callback to call whenever a file in the ZIP archive is found + */ + constructor(cb?: UnzipFileHandler); + /** + * Pushes a chunk to be unzipped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Registers a decoder with the stream, allowing for files compressed with + * the compression type provided to be expanded correctly + * @param decoder The decoder constructor + */ + register(decoder: UnzipDecoderConstructor): void; + /** + * The handler to call whenever a file is discovered + */ + onfile: UnzipFileHandler; +} +/** + * Asynchronously decompresses a ZIP archive + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @param cb The callback to call with the decompressed files + * @returns A function that can be used to immediately terminate the unzipping + */ +export declare function unzip(data: Uint8Array, opts: AsyncUnzipOptions, cb: UnzipCallback): AsyncTerminable; +/** + * Asynchronously decompresses a ZIP archive + * @param data The raw compressed ZIP file + * @param cb The callback to call with the decompressed files + * @returns A function that can be used to immediately terminate the unzipping + */ +export declare function unzip(data: Uint8Array, cb: UnzipCallback): AsyncTerminable; +/** + * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better + * performance with more than one file. + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @returns The decompressed files + */ +export declare function unzipSync(data: Uint8Array, opts?: UnzipOptions): Unzipped; diff --git a/node_modules/fflate/esm/browser.js b/node_modules/fflate/esm/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..82af0fdb655f00655d2da3354c4533744edcde6e --- /dev/null +++ b/node_modules/fflate/esm/browser.js @@ -0,0 +1,2692 @@ +// DEFLATE is a complex format; to read this code, you should probably check the RFC first: +// https://tools.ietf.org/html/rfc1951 +// You may also wish to take a look at the guide I made about this program: +// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad +// Some of the following code is similar to that of UZIP.js: +// https://github.com/photopea/UZIP.js +// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. +// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint +// is better for memory in most engines (I *think*). +var ch2 = {}; +var wk = (function (c, id, msg, transfer, cb) { + var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([ + c + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})' + ], { type: 'text/javascript' })))); + w.onmessage = function (e) { + var d = e.data, ed = d.$e$; + if (ed) { + var err = new Error(ed[0]); + err['code'] = ed[1]; + err.stack = ed[2]; + cb(err, null); + } + else + cb(null, d); + }; + w.postMessage(msg, transfer); + return w; +}); + +// aliases for shorter compressed code (most minifers don't do this) +var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array; +// fixed length extra bits +var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); +// fixed distance extra bits +var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); +// code length index map +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +// get base, reverse index map from extra bits +var freb = function (eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + // numbers here are at max 18 bits + var r = new i32(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = ((j - b[i]) << 5) | i; + } + } + return { b: b, r: r }; +}; +var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r; +// we can ignore the fact that the other numbers are wrong; they never happen anyway +fl[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r; +// map of value to reverse (assuming 16 bits) +var rev = new u16(32768); +for (var i = 0; i < 32768; ++i) { + // reverse table algorithm from SO + var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1); + x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2); + x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4); + rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1; +} +// create huffman tree from u8 "map": index -> code length for code index +// mb (max bits) must be at most 15 +// TODO: optimize/split up? +var hMap = (function (cd, mb, r) { + var s = cd.length; + // index + var i = 0; + // u16 "map": index -> # of codes with bit length = index + var l = new u16(mb); + // length of cd must be 288 (total # of codes) + for (; i < s; ++i) { + if (cd[i]) + ++l[cd[i] - 1]; + } + // u16 "map": index -> minimum code for bit length = index + var le = new u16(mb); + for (i = 1; i < mb; ++i) { + le[i] = (le[i - 1] + l[i - 1]) << 1; + } + var co; + if (r) { + // u16 "map": index -> number of actual bits, symbol for code + co = new u16(1 << mb); + // bits to remove for reverser + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + // ignore 0 lengths + if (cd[i]) { + // num encoding both symbol and bits read + var sv = (i << 4) | cd[i]; + // free bits + var r_1 = mb - cd[i]; + // start value + var v = le[cd[i] - 1]++ << r_1; + // m is end value + for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { + // every 16 bit value starting with the code yields the same result + co[rev[v] >> rvb] = sv; + } + } + } + } + else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]); + } + } + } + return co; +}); +// fixed length tree +var flt = new u8(288); +for (var i = 0; i < 144; ++i) + flt[i] = 8; +for (var i = 144; i < 256; ++i) + flt[i] = 9; +for (var i = 256; i < 280; ++i) + flt[i] = 7; +for (var i = 280; i < 288; ++i) + flt[i] = 8; +// fixed distance tree +var fdt = new u8(32); +for (var i = 0; i < 32; ++i) + fdt[i] = 5; +// fixed length map +var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); +// fixed distance map +var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); +// find max of array +var max = function (a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; +}; +// read d, starting at bit p and mask with m +var bits = function (d, p, m) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; +}; +// read d, starting at bit p continuing for at least 16 bits +var bits16 = function (d, p) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); +}; +// get end of byte +var shft = function (p) { return ((p + 7) / 8) | 0; }; +// typed array slice - allows garbage collector to free original reference, +// while being more compatible than .slice +var slc = function (v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + // can't use .constructor in case user-supplied + return new u8(v.subarray(s, e)); +}; +/** + * Codes for errors generated within this library + */ +export var FlateErrorCode = { + UnexpectedEOF: 0, + InvalidBlockType: 1, + InvalidLengthLiteral: 2, + InvalidDistance: 3, + StreamFinished: 4, + NoStreamHandler: 5, + InvalidHeader: 6, + NoCallback: 7, + InvalidUTF8: 8, + ExtraFieldTooLong: 9, + InvalidDate: 10, + FilenameTooLong: 11, + StreamFinishing: 12, + InvalidZipData: 13, + UnknownCompressionMethod: 14 +}; +// error codes +var ec = [ + 'unexpected EOF', + 'invalid block type', + 'invalid length/literal', + 'invalid distance', + 'stream finished', + 'no stream handler', + , // determined by compression function + 'no callback', + 'invalid UTF-8 data', + 'extra field too long', + 'date not in range 1980-2099', + 'filename too long', + 'stream finishing', + 'invalid zip data' + // determined by unknown compression method +]; +; +var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; +}; +// expands raw DEFLATE data +var inflt = function (dat, st, buf, dict) { + // source length dict length + var sl = dat.length, dl = dict ? dict.length : 0; + if (!sl || st.f && !st.l) + return buf || new u8(0); + var noBuf = !buf; + // have to estimate size + var resize = noBuf || st.i != 2; + // no state + var noSt = st.i; + // Assumes roughly 33% compression ratio average + if (noBuf) + buf = new u8(sl * 3); + // ensure buffer can fit at least l elements + var cbuf = function (l) { + var bl = buf.length; + // need to increase size to fit + if (l > bl) { + // Double or set to necessary, whichever is greater + var nbuf = new u8(Math.max(bl * 2, l)); + nbuf.set(buf); + buf = nbuf; + } + }; + // last chunk bitpos bytes + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + // total bits + var tbts = sl * 8; + do { + if (!lm) { + // BFINAL - this is only 1 when last chunk is next + final = bits(dat, pos, 1); + // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + // go to end of byte boundary + var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; + if (t > sl) { + if (noSt) + err(0); + break; + } + // ensure size + if (resize) + cbuf(bt + l); + // Copy over uncompressed data + buf.set(dat.subarray(s, t), bt); + // Get new bitpos, update byte count + st.b = bt += l, st.p = pos = t * 8, st.f = final; + continue; + } + else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + // literal lengths + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + // length+distance tree + var ldt = new u8(tl); + // code length tree + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + // use index map to get real code + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + // code lengths bits + var clb = max(clt), clbmsk = (1 << clb) - 1; + // code lengths map + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl;) { + var r = clm[bits(dat, pos, clbmsk)]; + // bits read + pos += r & 15; + // symbol + var s = r >> 4; + // code length to copy + if (s < 16) { + ldt[i++] = s; + } + else { + // copy count + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + // length tree distance tree + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + // max length bits + lbt = max(lt); + // max dist bits + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } + else + err(1); + if (pos > tbts) { + if (noSt) + err(0); + break; + } + } + // Make sure the buffer can hold this + the largest possible addition + // Maximum chunk size (practically, theoretically infinite) is 2^17 + if (resize) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (;; lpos = pos) { + // bits read, code + var c = lm[bits16(dat, pos) & lms], sym = c >> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (!c) + err(2); + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } + else { + var add = sym - 254; + // no extra bits needed if less + if (sym > 264) { + // index + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + // dist + var d = dm[bits16(dat, pos) & dms], dsym = d >> 4; + if (!d) + err(3); + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & (1 << b) - 1, pos += b; + } + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (resize) + cbuf(bt + 131072); + var end = bt + add; + if (bt < dt) { + var shift = dl - dt, dend = Math.min(dt, end); + if (shift + bt < 0) + err(3); + for (; bt < dend; ++bt) + buf[bt] = dict[shift + bt]; + } + for (; bt < end; ++bt) + buf[bt] = buf[bt - dt]; + } + } + st.l = lm, st.p = lpos, st.b = bt, st.f = final; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + // don't reallocate for streams or user buffers + return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt); +}; +// starting at p, write the minimum number of bits that can hold v to d +var wbits = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; +}; +// starting at p, write the minimum number of bits (>8) that can hold v to d +var wbits16 = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; + d[o + 2] |= v >> 16; +}; +// creates code lengths from a frequency table +var hTree = function (d, mb) { + // Need extra info to make a tree + var t = []; + for (var i = 0; i < d.length; ++i) { + if (d[i]) + t.push({ s: i, f: d[i] }); + } + var s = t.length; + var t2 = t.slice(); + if (!s) + return { t: et, l: 0 }; + if (s == 1) { + var v = new u8(t[0].s + 1); + v[t[0].s] = 1; + return { t: v, l: 1 }; + } + t.sort(function (a, b) { return a.f - b.f; }); + // after i2 reaches last ind, will be stopped + // freq must be greater than largest possible number of symbols + t.push({ s: -1, f: 25001 }); + var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; + t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; + // efficient algorithm from UZIP.js + // i0 is lookbehind, i2 is lookahead - after processing two low-freq + // symbols that combined have high freq, will start processing i2 (high-freq, + // non-composite) symbols instead + // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ + while (i1 != s - 1) { + l = t[t[i0].f < t[i2].f ? i0++ : i2++]; + r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; + t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; + } + var maxSym = t2[0].s; + for (var i = 1; i < s; ++i) { + if (t2[i].s > maxSym) + maxSym = t2[i].s; + } + // code lengths + var tr = new u16(maxSym + 1); + // max bits in tree + var mbt = ln(t[i1 - 1], tr, 0); + if (mbt > mb) { + // more algorithms from UZIP.js + // TODO: find out how this code works (debt) + // ind debt + var i = 0, dt = 0; + // left cost + var lft = mbt - mb, cst = 1 << lft; + t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); + for (; i < s; ++i) { + var i2_1 = t2[i].s; + if (tr[i2_1] > mb) { + dt += cst - (1 << (mbt - tr[i2_1])); + tr[i2_1] = mb; + } + else + break; + } + dt >>= lft; + while (dt > 0) { + var i2_2 = t2[i].s; + if (tr[i2_2] < mb) + dt -= 1 << (mb - tr[i2_2]++ - 1); + else + ++i; + } + for (; i >= 0 && dt; --i) { + var i2_3 = t2[i].s; + if (tr[i2_3] == mb) { + --tr[i2_3]; + ++dt; + } + } + mbt = mb; + } + return { t: new u8(tr), l: mbt }; +}; +// get the max length and assign length codes +var ln = function (n, l, d) { + return n.s == -1 + ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) + : (l[n.s] = d); +}; +// length codes generation +var lc = function (c) { + var s = c.length; + // Note that the semicolon was intentional + while (s && !c[--s]) + ; + var cl = new u16(++s); + // ind num streak + var cli = 0, cln = c[0], cls = 1; + var w = function (v) { cl[cli++] = v; }; + for (var i = 1; i <= s; ++i) { + if (c[i] == cln && i != s) + ++cls; + else { + if (!cln && cls > 2) { + for (; cls > 138; cls -= 138) + w(32754); + if (cls > 2) { + w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); + cls = 0; + } + } + else if (cls > 3) { + w(cln), --cls; + for (; cls > 6; cls -= 6) + w(8304); + if (cls > 2) + w(((cls - 3) << 5) | 8208), cls = 0; + } + while (cls--) + w(cln); + cls = 1; + cln = c[i]; + } + } + return { c: cl.subarray(0, cli), n: s }; +}; +// calculate the length of output from tree, code lengths +var clen = function (cf, cl) { + var l = 0; + for (var i = 0; i < cl.length; ++i) + l += cf[i] * cl[i]; + return l; +}; +// writes a fixed block +// returns the new bit pos +var wfblk = function (out, pos, dat) { + // no need to write 00 as type: TypedArray defaults to 0 + var s = dat.length; + var o = shft(pos + 2); + out[o] = s & 255; + out[o + 1] = s >> 8; + out[o + 2] = out[o] ^ 255; + out[o + 3] = out[o + 1] ^ 255; + for (var i = 0; i < s; ++i) + out[o + i + 4] = dat[i]; + return (o + 4 + s) * 8; +}; +// writes a block +var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { + wbits(out, p++, final); + ++lf[256]; + var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l; + var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l; + var _c = lc(dlt), lclt = _c.c, nlc = _c.n; + var _d = lc(ddt), lcdt = _d.c, ndc = _d.n; + var lcfreq = new u16(19); + for (var i = 0; i < lclt.length; ++i) + ++lcfreq[lclt[i] & 31]; + for (var i = 0; i < lcdt.length; ++i) + ++lcfreq[lcdt[i] & 31]; + var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l; + var nlcc = 19; + for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) + ; + var flen = (bl + 5) << 3; + var ftlen = clen(lf, flt) + clen(df, fdt) + eb; + var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]; + if (bs >= 0 && flen <= ftlen && flen <= dtlen) + return wfblk(out, p, dat.subarray(bs, bs + bl)); + var lm, ll, dm, dl; + wbits(out, p, 1 + (dtlen < ftlen)), p += 2; + if (dtlen < ftlen) { + lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; + var llm = hMap(lct, mlcb, 0); + wbits(out, p, nlc - 257); + wbits(out, p + 5, ndc - 1); + wbits(out, p + 10, nlcc - 4); + p += 14; + for (var i = 0; i < nlcc; ++i) + wbits(out, p + 3 * i, lct[clim[i]]); + p += 3 * nlcc; + var lcts = [lclt, lcdt]; + for (var it = 0; it < 2; ++it) { + var clct = lcts[it]; + for (var i = 0; i < clct.length; ++i) { + var len = clct[i] & 31; + wbits(out, p, llm[len]), p += lct[len]; + if (len > 15) + wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12; + } + } + } + else { + lm = flm, ll = flt, dm = fdm, dl = fdt; + } + for (var i = 0; i < li; ++i) { + var sym = syms[i]; + if (sym > 255) { + var len = (sym >> 18) & 31; + wbits16(out, p, lm[len + 257]), p += ll[len + 257]; + if (len > 7) + wbits(out, p, (sym >> 23) & 31), p += fleb[len]; + var dst = sym & 31; + wbits16(out, p, dm[dst]), p += dl[dst]; + if (dst > 3) + wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst]; + } + else { + wbits16(out, p, lm[sym]), p += ll[sym]; + } + } + wbits16(out, p, lm[256]); + return p + ll[256]; +}; +// deflate options (nice << 13) | chain +var deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); +// empty +var et = /*#__PURE__*/ new u8(0); +// compresses data into a raw DEFLATE buffer +var dflt = function (dat, lvl, plvl, pre, post, st) { + var s = st.z || dat.length; + var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); + // writing to this writes to the output buffer + var w = o.subarray(pre, o.length - post); + var lst = st.l; + var pos = (st.r || 0) & 7; + if (lvl) { + if (pos) + w[0] = st.r >> 3; + var opt = deo[lvl - 1]; + var n = opt >> 13, c = opt & 8191; + var msk_1 = (1 << plvl) - 1; + // prev 2-byte val map curr 2-byte val map + var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1); + var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; + var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; + // 24576 is an arbitrary number of maximum symbols per block + // 424 buffer for last block + var syms = new i32(25000); + // length/literal freq distance freq + var lf = new u16(288), df = new u16(32); + // l/lcnt exbits index l/lind waitdx blkpos + var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0; + for (; i + 2 < s; ++i) { + // hash value + var hv = hsh(i); + // index mod 32768 previous index mod + var imod = i & 32767, pimod = head[hv]; + prev[imod] = pimod; + head[hv] = imod; + // We always should modify head and prev, but only add symbols if + // this data is not yet processed ("wait" for wait index) + if (wi <= i) { + // bytes remaining + var rem = s - i; + if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) { + pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); + li = lc_1 = eb = 0, bs = i; + for (var j = 0; j < 286; ++j) + lf[j] = 0; + for (var j = 0; j < 30; ++j) + df[j] = 0; + } + // len dist chain + var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767; + if (rem > 2 && hv == hsh(i - dif)) { + var maxn = Math.min(n, rem) - 1; + var maxd = Math.min(32767, i); + // max possible length + // not capped at dif because decompressors implement "rolling" index population + var ml = Math.min(258, rem); + while (dif <= maxd && --ch_1 && imod != pimod) { + if (dat[i + l] == dat[i + l - dif]) { + var nl = 0; + for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) + ; + if (nl > l) { + l = nl, d = dif; + // break out early when we reach "nice" (we are satisfied enough) + if (nl > maxn) + break; + // now, find the rarest 2-byte sequence within this + // length of literals and search for that instead. + // Much faster than just using the start + var mmd = Math.min(dif, nl - 2); + var md = 0; + for (var j = 0; j < mmd; ++j) { + var ti = i - dif + j & 32767; + var pti = prev[ti]; + var cd = ti - pti & 32767; + if (cd > md) + md = cd, pimod = ti; + } + } + } + // check the previous match + imod = pimod, pimod = prev[imod]; + dif += imod - pimod & 32767; + } + } + // d will be nonzero only when a match was found + if (d) { + // store both dist and len data in one int32 + // Make sure this is recognized as a len/dist with 28th bit (2^28) + syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; + var lin = revfl[l] & 31, din = revfd[d] & 31; + eb += fleb[lin] + fdeb[din]; + ++lf[257 + lin]; + ++df[din]; + wi = i + l; + ++lc_1; + } + else { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + } + } + for (i = Math.max(i, wi); i < s; ++i) { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); + if (!lst) { + st.r = (pos & 7) | w[(pos / 8) | 0] << 3; + // shft(pos) now 1 less if pos & 7 != 0 + pos -= 7; + st.h = head, st.p = prev, st.i = i, st.w = wi; + } + } + else { + for (var i = st.w || 0; i < s + lst; i += 65535) { + // end + var e = i + 65535; + if (e >= s) { + // write final block + w[(pos / 8) | 0] = lst; + e = s; + } + pos = wfblk(w, pos + 1, dat.subarray(i, e)); + } + st.i = s; + } + return slc(o, 0, pre + shft(pos) + post); +}; +// CRC32 table +var crct = /*#__PURE__*/ (function () { + var t = new Int32Array(256); + for (var i = 0; i < 256; ++i) { + var c = i, k = 9; + while (--k) + c = ((c & 1) && -306674912) ^ (c >>> 1); + t[i] = c; + } + return t; +})(); +// CRC32 +var crc = function () { + var c = -1; + return { + p: function (d) { + // closures have awful performance + var cr = c; + for (var i = 0; i < d.length; ++i) + cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8); + c = cr; + }, + d: function () { return ~c; } + }; +}; +// Adler32 +var adler = function () { + var a = 1, b = 0; + return { + p: function (d) { + // closures have awful performance + var n = a, m = b; + var l = d.length | 0; + for (var i = 0; i != l;) { + var e = Math.min(i + 2655, l); + for (; i < e; ++i) + m += n += d[i]; + n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); + } + a = n, b = m; + }, + d: function () { + a %= 65521, b %= 65521; + return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8); + } + }; +}; +; +// deflate with opts +var dopt = function (dat, opt, pre, post, st) { + if (!st) { + st = { l: 1 }; + if (opt.dictionary) { + var dict = opt.dictionary.subarray(-32768); + var newDat = new u8(dict.length + dat.length); + newDat.set(dict); + newDat.set(dat, dict.length); + dat = newDat; + st.w = dict.length; + } + } + return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st); +}; +// Walmart object spread +var mrg = function (a, b) { + var o = {}; + for (var k in a) + o[k] = a[k]; + for (var k in b) + o[k] = b[k]; + return o; +}; +// worker clone +// This is possibly the craziest part of the entire codebase, despite how simple it may seem. +// The only parameter to this function is a closure that returns an array of variables outside of the function scope. +// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization. +// We will return an object mapping of true variable name to value (basically, the current scope as a JS object). +// The reason we can't just use the original variable names is minifiers mangling the toplevel scope. +// This took me three weeks to figure out how to do. +var wcln = function (fn, fnStr, td) { + var dt = fn(); + var st = fn.toString(); + var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(','); + for (var i = 0; i < dt.length; ++i) { + var v = dt[i], k = ks[i]; + if (typeof v == 'function') { + fnStr += ';' + k + '='; + var st_1 = v.toString(); + if (v.prototype) { + // for global objects + if (st_1.indexOf('[native code]') != -1) { + var spInd = st_1.indexOf(' ', 8) + 1; + fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd)); + } + else { + fnStr += st_1; + for (var t in v.prototype) + fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString(); + } + } + else + fnStr += st_1; + } + else + td[k] = v; + } + return fnStr; +}; +var ch = []; +// clone bufs +var cbfs = function (v) { + var tl = []; + for (var k in v) { + if (v[k].buffer) { + tl.push((v[k] = new v[k].constructor(v[k])).buffer); + } + } + return tl; +}; +// use a worker to execute code +var wrkr = function (fns, init, id, cb) { + if (!ch[id]) { + var fnStr = '', td_1 = {}, m = fns.length - 1; + for (var i = 0; i < m; ++i) + fnStr = wcln(fns[i], fnStr, td_1); + ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 }; + } + var td = mrg({}, ch[id].e); + return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb); +}; +// base async inflate fn +var bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; }; +var bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; }; +// gzip extra +var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; }; +// gunzip extra +var guze = function () { return [gzs, gzl]; }; +// zlib extra +var zle = function () { return [zlh, wbytes, adler]; }; +// unzlib extra +var zule = function () { return [zls]; }; +// post buf +var pbf = function (msg) { return postMessage(msg, [msg.buffer]); }; +// get opts +var gopt = function (o) { return o && { + out: o.size && new u8(o.size), + dictionary: o.dictionary +}; }; +// async helper +var cbify = function (dat, opts, fns, init, id, cb) { + var w = wrkr(fns, init, id, function (err, dat) { + w.terminate(); + cb(err, dat); + }); + w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []); + return function () { w.terminate(); }; +}; +// auto stream +var astrm = function (strm) { + strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); }; + return function (ev) { + if (ev.data[0]) { + strm.push(ev.data[0], ev.data[1]); + postMessage([ev.data[0].length]); + } + else + strm.flush(ev.data[1]); + }; +}; +// async stream attach +var astrmify = function (fns, strm, opts, init, id, flush, ext) { + var t; + var w = wrkr(fns, init, id, function (err, dat) { + if (err) + w.terminate(), strm.ondata.call(strm, err); + else if (!Array.isArray(dat)) + ext(dat); + else if (dat.length == 1) { + strm.queuedSize -= dat[0]; + if (strm.ondrain) + strm.ondrain(dat[0]); + } + else { + if (dat[1]) + w.terminate(); + strm.ondata.call(strm, err, dat[0], dat[1]); + } + }); + w.postMessage(opts); + strm.queuedSize = 0; + strm.push = function (d, f) { + if (!strm.ondata) + err(5); + if (t) + strm.ondata(err(4, 0, 1), null, !!f); + strm.queuedSize += d.length; + // can fail for cross-realm Uint8Array, but ok - only a small performance penalty + w.postMessage([d, t = f], d.buffer instanceof ArrayBuffer ? [d.buffer] : []); + }; + strm.terminate = function () { w.terminate(); }; + if (flush) { + strm.flush = function (sync) { w.postMessage([0, sync]); }; + } +}; +// read 2 bytes +var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); }; +// read 4 bytes +var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; }; +// read 8 bytes +var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); }; +// write bytes +var wbytes = function (d, b, v) { + for (; v; ++b) + d[b] = v, v >>>= 8; +}; +// gzip header +var gzh = function (c, o) { + var fn = o.filename; + c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix + if (o.mtime != 0) + wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000)); + if (fn) { + c[3] = 8; + for (var i = 0; i <= fn.length; ++i) + c[i + 10] = fn.charCodeAt(i); + } +}; +// gzip footer: -8 to -4 = CRC, -4 to -0 is length +// gzip start +var gzs = function (d) { + if (d[0] != 31 || d[1] != 139 || d[2] != 8) + err(6, 'invalid gzip data'); + var flg = d[3]; + var st = 10; + if (flg & 4) + st += (d[10] | d[11] << 8) + 2; + for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]) + ; + return st + (flg & 2); +}; +// gzip length +var gzl = function (d) { + var l = d.length; + return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0; +}; +// gzip header length +var gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); }; +// zlib header +var zlh = function (c, o) { + var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; + c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32); + c[1] |= 31 - ((c[0] << 8) | c[1]) % 31; + if (o.dictionary) { + var h = adler(); + h.p(o.dictionary); + wbytes(c, 2, h.d()); + } +}; +// zlib start +var zls = function (d, dict) { + if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31)) + err(6, 'invalid zlib data'); + if ((d[1] >> 5 & 1) == +!dict) + err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary'); + return (d[1] >> 3 & 4) + 2; +}; +function StrmOpt(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + return opts; +} +/** + * Streaming DEFLATE compression + */ +var Deflate = /*#__PURE__*/ (function () { + function Deflate(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + this.o = opts || {}; + this.s = { l: 0, i: 32768, w: 32768, z: 32768 }; + // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev + // 98304 = 32768 (lookback) + 65536 (common chunk size) + this.b = new u8(98304); + if (this.o.dictionary) { + var dict = this.o.dictionary.subarray(-32768); + this.b.set(dict, 32768 - dict.length); + this.s.i = 32768 - dict.length; + } + } + Deflate.prototype.p = function (c, f) { + this.ondata(dopt(c, this.o, 0, 0, this.s), f); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Deflate.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + var endLen = chunk.length + this.s.z; + if (endLen > this.b.length) { + if (endLen > 2 * this.b.length - 32768) { + var newBuf = new u8(endLen & -32768); + newBuf.set(this.b.subarray(0, this.s.z)); + this.b = newBuf; + } + var split = this.b.length - this.s.z; + this.b.set(chunk.subarray(0, split), this.s.z); + this.s.z = this.b.length; + this.p(this.b, false); + this.b.set(this.b.subarray(-32768)); + this.b.set(chunk.subarray(split), 32768); + this.s.z = chunk.length - split + 32768; + this.s.i = 32766, this.s.w = 32768; + } + else { + this.b.set(chunk, this.s.z); + this.s.z += chunk.length; + } + this.s.l = final & 1; + if (this.s.z > this.s.w + 8191 || final) { + this.p(this.b, final || false); + this.s.w = this.s.i, this.s.i -= 2; + } + if (final) { + // cleanup unneeded buffers/state to reduce memory usage + this.s = this.o = {}; + this.b = et; + } + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + Deflate.prototype.flush = function (sync) { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + this.p(this.b, false); + this.s.w = this.s.i, this.s.i -= 2; + // could technically skip writing the type-0 block for (this.s.r & 7) == 0, + // but the deterministic trailer (00 00 FF FF) is useful in some situations + if (sync) { + var c = new u8(6); + c[0] = this.s.r >> 3; + // write empty, non-final type-0 block + var ep = wfblk(c, this.s.r, et); + this.s.r = 0; + this.ondata(c.subarray(0, ep >> 3), false); + } + }; + return Deflate; +}()); +export { Deflate }; +/** + * Asynchronous streaming DEFLATE compression + */ +var AsyncDeflate = /*#__PURE__*/ (function () { + function AsyncDeflate(opts, cb) { + astrmify([ + bDflt, + function () { return [astrm, Deflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Deflate(ev.data); + onmessage = astrm(strm); + }, 6, 1); + } + return AsyncDeflate; +}()); +export { AsyncDeflate }; +export function deflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb); +} +/** + * Compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @returns The deflated version of the data + */ +export function deflateSync(data, opts) { + return dopt(data, opts || {}, 0, 0); +} +/** + * Streaming DEFLATE decompression + */ +var Inflate = /*#__PURE__*/ (function () { + function Inflate(opts, cb) { + // no StrmOpt here to avoid adding to workerizer + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768); + this.s = { i: 0, b: dict ? dict.length : 0 }; + this.o = new u8(32768); + this.p = new u8(0); + if (dict) + this.o.set(dict); + } + Inflate.prototype.e = function (c) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + if (!this.p.length) + this.p = c; + else if (c.length) { + var n = new u8(this.p.length + c.length); + n.set(this.p), n.set(c, this.p.length), this.p = n; + } + }; + Inflate.prototype.c = function (final) { + this.s.i = +(this.d = final || false); + var bts = this.s.b; + var dt = inflt(this.p, this.s, this.o); + this.ondata(slc(dt, bts, this.s.b), this.d); + this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; + this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; + }; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + Inflate.prototype.push = function (chunk, final) { + this.e(chunk), this.c(final); + }; + return Inflate; +}()); +export { Inflate }; +/** + * Asynchronous streaming DEFLATE decompression + */ +var AsyncInflate = /*#__PURE__*/ (function () { + function AsyncInflate(opts, cb) { + astrmify([ + bInflt, + function () { return [astrm, Inflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Inflate(ev.data); + onmessage = astrm(strm); + }, 7, 0); + } + return AsyncInflate; +}()); +export { AsyncInflate }; +export function inflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt + ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb); +} +export function inflateSync(data, opts) { + return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize. +/** + * Streaming GZIP compression + */ +var Gzip = /*#__PURE__*/ (function () { + function Gzip(opts, cb) { + this.c = crc(); + this.l = 0; + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gzip.prototype.push = function (chunk, final) { + this.c.p(chunk); + this.l += chunk.length; + Deflate.prototype.push.call(this, chunk, final); + }; + Gzip.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s); + if (this.v) + gzh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + Gzip.prototype.flush = function (sync) { + Deflate.prototype.flush.call(this, sync); + }; + return Gzip; +}()); +export { Gzip }; +/** + * Asynchronous streaming GZIP compression + */ +var AsyncGzip = /*#__PURE__*/ (function () { + function AsyncGzip(opts, cb) { + astrmify([ + bDflt, + gze, + function () { return [astrm, Deflate, Gzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gzip(ev.data); + onmessage = astrm(strm); + }, 8, 1); + } + return AsyncGzip; +}()); +export { AsyncGzip }; +export function gzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + gze, + function () { return [gzipSync]; } + ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb); +} +/** + * Compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @returns The gzipped version of the data + */ +export function gzipSync(data, opts) { + if (!opts) + opts = {}; + var c = crc(), l = data.length; + c.p(data); + var d = dopt(data, opts, gzhl(opts), 8), s = d.length; + return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d; +} +/** + * Streaming single or multi-member GZIP decompression + */ +var Gunzip = /*#__PURE__*/ (function () { + function Gunzip(opts, cb) { + this.v = 1; + this.r = 0; + Inflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gunzip.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + this.r += chunk.length; + if (this.v) { + var p = this.p.subarray(this.v - 1); + var s = p.length > 3 ? gzs(p) : 4; + if (s > p.length) { + if (!final) + return; + } + else if (this.v > 1 && this.onmember) { + this.onmember(this.r - p.length); + } + this.p = p.subarray(s), this.v = 0; + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, 0); + // process concatenated GZIP + if (this.s.f && !this.s.l) { + this.v = shft(this.s.p) + 9; + this.s = { i: 0 }; + this.o = new u8(0); + this.push(new u8(0), final); + } + else if (final) { + Inflate.prototype.c.call(this, final); + } + }; + return Gunzip; +}()); +export { Gunzip }; +/** + * Asynchronous streaming single or multi-member GZIP decompression + */ +var AsyncGunzip = /*#__PURE__*/ (function () { + function AsyncGunzip(opts, cb) { + var _this = this; + astrmify([ + bInflt, + guze, + function () { return [astrm, Inflate, Gunzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gunzip(ev.data); + strm.onmember = function (offset) { return postMessage(offset); }; + onmessage = astrm(strm); + }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); }); + } + return AsyncGunzip; +}()); +export { AsyncGunzip }; +export function gunzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + guze, + function () { return [gunzipSync]; } + ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb); +} +export function gunzipSync(data, opts) { + var st = gzs(data); + if (st + 8 > data.length) + err(6, 'invalid gzip data'); + return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary); +} +/** + * Streaming Zlib compression + */ +var Zlib = /*#__PURE__*/ (function () { + function Zlib(opts, cb) { + this.c = adler(); + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Zlib.prototype.push = function (chunk, final) { + this.c.p(chunk); + Deflate.prototype.push.call(this, chunk, final); + }; + Zlib.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s); + if (this.v) + zlh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 4, this.c.d()); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + Zlib.prototype.flush = function (sync) { + Deflate.prototype.flush.call(this, sync); + }; + return Zlib; +}()); +export { Zlib }; +/** + * Asynchronous streaming Zlib compression + */ +var AsyncZlib = /*#__PURE__*/ (function () { + function AsyncZlib(opts, cb) { + astrmify([ + bDflt, + zle, + function () { return [astrm, Deflate, Zlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Zlib(ev.data); + onmessage = astrm(strm); + }, 10, 1); + } + return AsyncZlib; +}()); +export { AsyncZlib }; +export function zlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + zle, + function () { return [zlibSync]; } + ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb); +} +/** + * Compress data with Zlib + * @param data The data to compress + * @param opts The compression options + * @returns The zlib-compressed version of the data + */ +export function zlibSync(data, opts) { + if (!opts) + opts = {}; + var a = adler(); + a.p(data); + var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4); + return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d; +} +/** + * Streaming Zlib decompression + */ +var Unzlib = /*#__PURE__*/ (function () { + function Unzlib(opts, cb) { + Inflate.call(this, opts, cb); + this.v = opts && opts.dictionary ? 2 : 1; + } + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzlib.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + if (this.v) { + if (this.p.length < 6 && !final) + return; + this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0; + } + if (final) { + if (this.p.length < 4) + err(6, 'invalid zlib data'); + this.p = this.p.subarray(0, -4); + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + }; + return Unzlib; +}()); +export { Unzlib }; +/** + * Asynchronous streaming Zlib decompression + */ +var AsyncUnzlib = /*#__PURE__*/ (function () { + function AsyncUnzlib(opts, cb) { + astrmify([ + bInflt, + zule, + function () { return [astrm, Inflate, Unzlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Unzlib(ev.data); + onmessage = astrm(strm); + }, 11, 0); + } + return AsyncUnzlib; +}()); +export { AsyncUnzlib }; +export function unzlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + zule, + function () { return [unzlibSync]; } + ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb); +} +export function unzlibSync(data, opts) { + return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +// Default algorithm for compression (used because having a known output size allows faster decompression) +export { gzip as compress, AsyncGzip as AsyncCompress }; +export { gzipSync as compressSync, Gzip as Compress }; +/** + * Streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var Decompress = /*#__PURE__*/ (function () { + function Decompress(opts, cb) { + this.o = StrmOpt.call(this, opts, cb) || {}; + this.G = Gunzip; + this.I = Inflate; + this.Z = Unzlib; + } + // init substream + // overriden by AsyncDecompress + Decompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (dat, final) { + _this.ondata(dat, final); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Decompress.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (!this.s) { + if (this.p && this.p.length) { + var n = new u8(this.p.length + chunk.length); + n.set(this.p), n.set(chunk, this.p.length); + } + else + this.p = chunk; + if (this.p.length > 2) { + this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8) + ? new this.G(this.o) + : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31)) + ? new this.I(this.o) + : new this.Z(this.o); + this.i(); + this.s.push(this.p, final); + this.p = null; + } + } + else + this.s.push(chunk, final); + }; + return Decompress; +}()); +export { Decompress }; +/** + * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var AsyncDecompress = /*#__PURE__*/ (function () { + function AsyncDecompress(opts, cb) { + Decompress.call(this, opts, cb); + this.queuedSize = 0; + this.G = AsyncGunzip; + this.I = AsyncInflate; + this.Z = AsyncUnzlib; + } + AsyncDecompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (err, dat, final) { + _this.ondata(err, dat, final); + }; + this.s.ondrain = function (size) { + _this.queuedSize -= size; + if (_this.ondrain) + _this.ondrain(size); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncDecompress.prototype.push = function (chunk, final) { + this.queuedSize += chunk.length; + Decompress.prototype.push.call(this, chunk, final); + }; + return AsyncDecompress; +}()); +export { AsyncDecompress }; +export function decompress(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzip(data, opts, cb) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflate(data, opts, cb) + : unzlib(data, opts, cb); +} +/** + * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export function decompressSync(data, opts) { + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzipSync(data, opts) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflateSync(data, opts) + : unzlibSync(data, opts); +} +// flatten a directory structure +var fltn = function (d, p, t, o) { + for (var k in d) { + var val = d[k], n = p + k, op = o; + if (Array.isArray(val)) + op = mrg(o, val[1]), val = val[0]; + if (ArrayBuffer.isView(val)) + t[n] = [val, op]; + else { + t[n += '/'] = [new u8(0), op]; + fltn(val, n, t, o); + } + } +}; +// text encoder +var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder(); +// text decoder +var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); +// text decoder stream +var tds = 0; +try { + td.decode(et, { stream: true }); + tds = 1; +} +catch (e) { } +// decode UTF8 +var dutf8 = function (d) { + for (var r = '', i = 0;;) { + var c = d[i++]; + var eb = (c > 127) + (c > 223) + (c > 239); + if (i + eb > d.length) + return { s: r, r: slc(d, i - 1) }; + if (!eb) + r += String.fromCharCode(c); + else if (eb == 3) { + c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536, + r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023)); + } + else if (eb & 1) + r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63)); + else + r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)); + } +}; +/** + * Streaming UTF-8 decoding + */ +var DecodeUTF8 = /*#__PURE__*/ (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is decoded + */ + function DecodeUTF8(cb) { + this.ondata = cb; + if (tds) + this.t = new TextDecoder(); + else + this.p = et; + } + /** + * Pushes a chunk to be decoded from UTF-8 binary + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + DecodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + final = !!final; + if (this.t) { + this.ondata(this.t.decode(chunk, { stream: true }), final); + if (final) { + if (this.t.decode().length) + err(8); + this.t = null; + } + return; + } + if (!this.p) + err(4); + var dat = new u8(this.p.length + chunk.length); + dat.set(this.p); + dat.set(chunk, this.p.length); + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (final) { + if (r.length) + err(8); + this.p = null; + } + else + this.p = r; + this.ondata(s, final); + }; + return DecodeUTF8; +}()); +export { DecodeUTF8 }; +/** + * Streaming UTF-8 encoding + */ +var EncodeUTF8 = /*#__PURE__*/ (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is encoded + */ + function EncodeUTF8(cb) { + this.ondata = cb; + } + /** + * Pushes a chunk to be encoded to UTF-8 + * @param chunk The string data to push + * @param final Whether this is the last chunk + */ + EncodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + this.ondata(strToU8(chunk), this.d = final || false); + }; + return EncodeUTF8; +}()); +export { EncodeUTF8 }; +/** + * Converts a string into a Uint8Array for use with compression/decompression methods + * @param str The string to encode + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless decoding a binary string. + * @returns The string encoded in UTF-8/Latin-1 binary + */ +export function strToU8(str, latin1) { + if (latin1) { + var ar_1 = new u8(str.length); + for (var i = 0; i < str.length; ++i) + ar_1[i] = str.charCodeAt(i); + return ar_1; + } + if (te) + return te.encode(str); + var l = str.length; + var ar = new u8(str.length + (str.length >> 1)); + var ai = 0; + var w = function (v) { ar[ai++] = v; }; + for (var i = 0; i < l; ++i) { + if (ai + 5 > ar.length) { + var n = new u8(ai + 8 + ((l - i) << 1)); + n.set(ar); + ar = n; + } + var c = str.charCodeAt(i); + if (c < 128 || latin1) + w(c); + else if (c < 2048) + w(192 | (c >> 6)), w(128 | (c & 63)); + else if (c > 55295 && c < 57344) + c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023), + w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + else + w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + } + return slc(ar, 0, ai); +} +/** + * Converts a Uint8Array to a string + * @param dat The data to decode to string + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless encoding to binary string. + * @returns The original UTF-8/Latin-1 string + */ +export function strFromU8(dat, latin1) { + if (latin1) { + var r = ''; + for (var i = 0; i < dat.length; i += 16384) + r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384)); + return r; + } + else if (td) { + return td.decode(dat); + } + else { + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (r.length) + err(8); + return s; + } +} +; +// deflate bit flag +var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; }; +// skip local zip header +var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); }; +// read zip header +var zh = function (d, b, z) { + var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl; + var _a = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a[0], su = _a[1], off = _a[2]; + return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off]; +}; +// read zip64 header sizes +var z64hs = function (d, b, l, z, sc, su, off) { + var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l; + var nf = nsc + nsu + noff; + if (z && nf) { + for (; b + 4 < e; b += 4 + b2(d, b + 2)) { + if (b2(d, b) == 1) { + return [ + nsc ? b8(d, b + 4 + 8 * nsu) : sc, + nsu ? b8(d, b + 4) : su, + noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off, + 1 + ]; + } + } + // z == 2 for unknown whether or not zip64 + if (z < 2) + err(13); + } + return [sc, su, off, 0]; +}; +// extra field length +var exfl = function (ex) { + var le = 0; + if (ex) { + for (var k in ex) { + var l = ex[k].length; + if (l > 65535) + err(9); + le += l + 4; + } + } + return le; +}; +// write zip header +var wzh = function (d, b, f, fn, u, c, ce, co) { + var fl = fn.length, ex = f.extra, col = co && co.length; + var exl = exfl(ex); + wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4; + if (ce != null) + d[b++] = 20, d[b++] = f.os; + d[b] = 20, b += 2; // spec compliance? what's that? + d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8; + d[b++] = f.compression & 255, d[b++] = f.compression >> 8; + var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980; + if (y < 0 || y > 119) + err(10); + wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4; + if (c != -1) { + wbytes(d, b, f.crc); + wbytes(d, b + 4, c < 0 ? -c - 2 : c); + wbytes(d, b + 8, f.size); + } + wbytes(d, b + 12, fl); + wbytes(d, b + 14, exl), b += 16; + if (ce != null) { + wbytes(d, b, col); + wbytes(d, b + 6, f.attrs); + wbytes(d, b + 10, ce), b += 14; + } + d.set(fn, b); + b += fl; + if (exl) { + for (var k in ex) { + var exf = ex[k], l = exf.length; + wbytes(d, b, +k); + wbytes(d, b + 2, l); + d.set(exf, b + 4), b += 4 + l; + } + } + if (col) + d.set(co, b), b += col; + return b; +}; +// write zip footer (end of central directory) +var wzf = function (o, b, c, d, e) { + wbytes(o, b, 0x6054B50); // skip disk + wbytes(o, b + 8, c); + wbytes(o, b + 10, c); + wbytes(o, b + 12, d); + wbytes(o, b + 16, e); +}; +/** + * A pass-through stream to keep data uncompressed in a ZIP archive. + */ +var ZipPassThrough = /*#__PURE__*/ (function () { + /** + * Creates a pass-through stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + */ + function ZipPassThrough(filename) { + this.filename = filename; + this.c = crc(); + this.size = 0; + this.compression = 0; + } + /** + * Processes a chunk and pushes to the output stream. You can override this + * method in a subclass for custom behavior, but by default this passes + * the data through. You must call this.ondata(err, chunk, final) at some + * point in this method. + * @param chunk The chunk to process + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.process = function (chunk, final) { + this.ondata(null, chunk, final); + }; + /** + * Pushes a chunk to be added. If you are subclassing this with a custom + * compression algorithm, note that you must push data from the source + * file only, pre-compression. + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + this.c.p(chunk); + this.size += chunk.length; + if (final) + this.crc = this.c.d(); + // we shouldn't really do this cast, but properly handling ArrayBufferLike + // makes the API unergonomic with Buffer + this.process(chunk, final || false); + }; + return ZipPassThrough; +}()); +export { ZipPassThrough }; +// I don't extend because TypeScript extension adds 1kB of runtime bloat +/** + * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate + * for better performance + */ +var ZipDeflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function ZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new Deflate(opts, function (dat, final) { + _this.ondata(null, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + } + ZipDeflate.prototype.process = function (chunk, final) { + try { + this.d.push(chunk, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return ZipDeflate; +}()); +export { ZipDeflate }; +/** + * Asynchronous streaming DEFLATE compression for ZIP archives + */ +var AsyncZipDeflate = /*#__PURE__*/ (function () { + /** + * Creates an asynchronous DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function AsyncZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new AsyncDeflate(opts, function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + this.terminate = this.d.terminate; + } + AsyncZipDeflate.prototype.process = function (chunk, final) { + this.d.push(chunk, final); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return AsyncZipDeflate; +}()); +export { AsyncZipDeflate }; +// TODO: Better tree shaking +/** + * A zippable archive to which files can incrementally be added + */ +var Zip = /*#__PURE__*/ (function () { + /** + * Creates an empty ZIP archive to which files can be added + * @param cb The callback to call whenever data for the generated ZIP archive + * is available + */ + function Zip(cb) { + this.ondata = cb; + this.u = []; + this.d = 1; + } + /** + * Adds a file to the ZIP archive + * @param file The file stream to add + */ + Zip.prototype.add = function (file) { + var _this = this; + if (!this.ondata) + err(5); + // finishing or finished + if (this.d & 2) + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false); + else { + var f = strToU8(file.filename), fl_1 = f.length; + var com = file.comment, o = com && strToU8(com); + var u = fl_1 != file.filename.length || (o && (com.length != o.length)); + var hl_1 = fl_1 + exfl(file.extra) + 30; + if (fl_1 > 65535) + this.ondata(err(11, 0, 1), null, false); + var header = new u8(hl_1); + wzh(header, 0, file, f, u, -1); + var chks_1 = [header]; + var pAll_1 = function () { + for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) { + var chk = chks_2[_i]; + _this.ondata(null, chk, false); + } + chks_1 = []; + }; + var tr_1 = this.d; + this.d = 0; + var ind_1 = this.u.length; + var uf_1 = mrg(file, { + f: f, + u: u, + o: o, + t: function () { + if (file.terminate) + file.terminate(); + }, + r: function () { + pAll_1(); + if (tr_1) { + var nxt = _this.u[ind_1 + 1]; + if (nxt) + nxt.r(); + else + _this.d = 1; + } + tr_1 = 1; + } + }); + var cl_1 = 0; + file.ondata = function (err, dat, final) { + if (err) { + _this.ondata(err, dat, final); + _this.terminate(); + } + else { + cl_1 += dat.length; + chks_1.push(dat); + if (final) { + var dd = new u8(16); + wbytes(dd, 0, 0x8074B50); + wbytes(dd, 4, file.crc); + wbytes(dd, 8, cl_1); + wbytes(dd, 12, file.size); + chks_1.push(dd); + uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size; + if (tr_1) + uf_1.r(); + tr_1 = 1; + } + else if (tr_1) + pAll_1(); + } + }; + this.u.push(uf_1); + } + }; + /** + * Ends the process of adding files and prepares to emit the final chunks. + * This *must* be called after adding all desired files for the resulting + * ZIP file to work properly. + */ + Zip.prototype.end = function () { + var _this = this; + if (this.d & 2) { + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true); + return; + } + if (this.d) + this.e(); + else + this.u.push({ + r: function () { + if (!(_this.d & 1)) + return; + _this.u.splice(-1, 1); + _this.e(); + }, + t: function () { } + }); + this.d = 3; + }; + Zip.prototype.e = function () { + var bt = 0, l = 0, tl = 0; + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0); + } + var out = new u8(tl + 22); + for (var _b = 0, _c = this.u; _b < _c.length; _b++) { + var f = _c[_b]; + wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o); + bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b; + } + wzf(out, bt, this.u.length, tl, l); + this.ondata(null, out, true); + this.d = 2; + }; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to add() will fail. + */ + Zip.prototype.terminate = function () { + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + f.t(); + } + this.d = 2; + }; + return Zip; +}()); +export { Zip }; +export function zip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var r = {}; + fltn(data, '', r, opts); + var k = Object.keys(r); + var lft = k.length, o = 0, tot = 0; + var slft = lft, files = new Array(lft); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var cbf = function () { + var out = new u8(tot + 22), oe = o, cdl = tot - o; + tot = 0; + for (var i = 0; i < slft; ++i) { + var f = files[i]; + try { + var l = f.c.length; + wzh(out, tot, f, f.f, f.u, l); + var badd = 30 + f.f.length + exfl(f.extra); + var loc = tot + badd; + out.set(f.c, loc); + wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l; + } + catch (e) { + return cbd(e, null); + } + } + wzf(out, o, files.length, cdl, oe); + cbd(null, out); + }; + if (!lft) + cbf(); + var _loop_1 = function (i) { + var fn = k[i]; + var _a = r[fn], file = _a[0], p = _a[1]; + var c = crc(), size = file.length; + c.p(file); + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + var compression = p.level == 0 ? 0 : 8; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + var l = d.length; + files[i] = mrg(p, { + size: size, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + compression: compression + }); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + if (!--lft) + cbf(); + } + }; + if (s > 65535) + cbl(err(11, 0, 1), null); + if (!compression) + cbl(null, file); + else if (size < 160000) { + try { + cbl(null, deflateSync(file, p)); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(deflate(file, p, cbl)); + }; + // Cannot use lft because it can decrease + for (var i = 0; i < slft; ++i) { + _loop_1(i); + } + return tAll; +} +/** + * Synchronously creates a ZIP file. Prefer using `zip` for better performance + * with more than one file. + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @returns The generated ZIP archive + */ +export function zipSync(data, opts) { + if (!opts) + opts = {}; + var r = {}; + var files = []; + fltn(data, '', r, opts); + var o = 0; + var tot = 0; + for (var fn in r) { + var _a = r[fn], file = _a[0], p = _a[1]; + var compression = p.level == 0 ? 0 : 8; + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + if (s > 65535) + err(11); + var d = compression ? deflateSync(file, p) : file, l = d.length; + var c = crc(); + c.p(file); + files.push(mrg(p, { + size: file.length, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + o: o, + compression: compression + })); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + } + var out = new u8(tot + 22), oe = o, cdl = tot - o; + for (var i = 0; i < files.length; ++i) { + var f = files[i]; + wzh(out, f.o, f, f.f, f.u, f.c.length); + var badd = 30 + f.f.length + exfl(f.extra); + out.set(f.c, f.o + badd); + wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0); + } + wzf(out, o, files.length, cdl, oe); + return out; +} +/** + * Streaming pass-through decompression for ZIP archives + */ +var UnzipPassThrough = /*#__PURE__*/ (function () { + function UnzipPassThrough() { + } + UnzipPassThrough.prototype.push = function (chunk, final) { + // same as ZipPassThrough: cast to retain Buffer ergonomics + this.ondata(null, chunk, final); + }; + UnzipPassThrough.compression = 0; + return UnzipPassThrough; +}()); +export { UnzipPassThrough }; +/** + * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for + * better performance. + */ +var UnzipInflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function UnzipInflate() { + var _this = this; + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + UnzipInflate.prototype.push = function (chunk, final) { + try { + this.i.push(chunk, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + UnzipInflate.compression = 8; + return UnzipInflate; +}()); +export { UnzipInflate }; +/** + * Asynchronous streaming DEFLATE decompression for ZIP archives + */ +var AsyncUnzipInflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function AsyncUnzipInflate(_, sz) { + var _this = this; + if (sz < 320000) { + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + else { + this.i = new AsyncInflate(function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.terminate = this.i.terminate; + } + } + AsyncUnzipInflate.prototype.push = function (chunk, final) { + if (this.i.terminate) + chunk = slc(chunk, 0); + this.i.push(chunk, final); + }; + AsyncUnzipInflate.compression = 8; + return AsyncUnzipInflate; +}()); +export { AsyncUnzipInflate }; +/** + * A ZIP archive decompression stream that emits files as they are discovered + */ +var Unzip = /*#__PURE__*/ (function () { + /** + * Creates a ZIP decompression stream + * @param cb The callback to call whenever a file in the ZIP archive is found + */ + function Unzip(cb) { + this.onfile = cb; + this.k = []; + this.o = { + 0: UnzipPassThrough + }; + this.p = et; + } + /** + * Pushes a chunk to be unzipped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzip.prototype.push = function (chunk, final) { + var _this = this; + if (!this.onfile) + err(5); + if (!this.p) + err(4); + if (this.c > 0) { + var len = Math.min(this.c, chunk.length); + var toAdd = chunk.subarray(0, len); + this.c -= len; + if (this.d) + this.d.push(toAdd, !this.c); + else + this.k[0].push(toAdd); + chunk = chunk.subarray(len); + if (chunk.length) + return this.push(chunk, final); + } + else { + var f = 0, i = 0, is = void 0, buf = void 0; + if (!this.p.length) + buf = chunk; + else if (!chunk.length) + buf = this.p; + else { + buf = new u8(this.p.length + chunk.length); + buf.set(this.p), buf.set(chunk, this.p.length); + } + var l = buf.length, oc = this.c, add = oc && this.d; + var _loop_2 = function () { + var sig = b4(buf, i); + if (sig == 0x4034B50) { + f = 1, is = i; + this_1.d = null; + this_1.c = 0; + var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28); + if (l > i + 30 + fnl + es) { + var chks_3 = []; + this_1.k.unshift(chks_3); + f = 2; + var lsc = b4(buf, i + 18), lsu = b4(buf, i + 22); + var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u); + var _a = z64hs(buf, i, es, 2, lsc, lsu, 0), sc_1 = _a[0], su_1 = _a[1], z64 = _a[3]; + if (dd) + sc_1 = -1 - z64; + i += es; + this_1.c = sc_1; + var d_1; + var file_1 = { + name: fn_1, + compression: cmp_1, + start: function () { + if (!file_1.ondata) + err(5); + if (!sc_1) + file_1.ondata(null, et, true); + else { + var ctr = _this.o[cmp_1]; + if (!ctr) + file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false); + d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1); + d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); }; + for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) { + var dat = chks_4[_i]; + d_1.push(dat, false); + } + if (_this.k[0] == chks_3 && _this.c) + _this.d = d_1; + else + d_1.push(et, true); + } + }, + terminate: function () { + if (d_1 && d_1.terminate) + d_1.terminate(); + } + }; + if (sc_1 >= 0) + file_1.size = sc_1, file_1.originalSize = su_1; + this_1.onfile(file_1); + } + return "break"; + } + else if (oc) { + if (sig == 0x8074B50) { + is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0; + return "break"; + } + else if (sig == 0x2014B50) { + is = i -= 4, f = 3, this_1.c = 0; + return "break"; + } + } + }; + var this_1 = this; + for (; i < l - 4; ++i) { + var state_1 = _loop_2(); + if (state_1 === "break") + break; + } + this.p = et; + if (oc < 0) { + var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i); + if (add) + add.push(dat, !!f); + else + this.k[+(f == 2)].push(dat); + } + if (f & 2) + return this.push(buf.subarray(i), final); + this.p = buf.subarray(i); + } + if (final) { + if (this.c) + err(13); + this.p = null; + } + }; + /** + * Registers a decoder with the stream, allowing for files compressed with + * the compression type provided to be expanded correctly + * @param decoder The decoder constructor + */ + Unzip.prototype.register = function (decoder) { + this.o[decoder.compression] = decoder; + }; + return Unzip; +}()); +export { Unzip }; +var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); }; +export function unzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var files = {}; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) { + cbd(err(13, 0, 1), null); + return tAll; + } + } + ; + var lft = b2(data, e + 8); + if (lft) { + var c = lft; + var o = b4(data, e + 16); + var z = b4(data, e - 20) == 0x7064B50; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = lft = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + var _loop_3 = function (i) { + var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + if (d) + files[fn] = d; + if (!--lft) + cbd(null, files); + } + }; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_1 + })) { + if (!c_1) + cbl(null, slc(data, b, b + sc)); + else if (c_1 == 8) { + var infl = data.subarray(b, b + sc); + // Synchronously decompress under 512KB, or barely-compressed data + if (su < 524288 || sc > 0.8 * su) { + try { + cbl(null, inflateSync(infl, { out: new u8(su) })); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(inflate(infl, { size: su }, cbl)); + } + else + cbl(err(14, 'unknown compression type ' + c_1, 1), null); + } + else + cbl(null, null); + }; + for (var i = 0; i < c; ++i) { + _loop_3(i); + } + } + else + cbd(null, {}); + return tAll; +} +/** + * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better + * performance with more than one file. + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @returns The decompressed files + */ +export function unzipSync(data, opts) { + var files = {}; + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) + err(13); + } + ; + var c = b2(data, e + 8); + if (!c) + return {}; + var o = b4(data, e + 16); + var z = b4(data, e - 20) == 0x7064B50; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + for (var i = 0; i < c; ++i) { + var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_2 + })) { + if (!c_2) + files[fn] = slc(data, b, b + sc); + else if (c_2 == 8) + files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) }); + else + err(14, 'unknown compression type ' + c_2); + } + } + return files; +} diff --git a/node_modules/fflate/esm/index.d.mts b/node_modules/fflate/esm/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d430faf2b555c978d66c89f46155b72c2c45a971 --- /dev/null +++ b/node_modules/fflate/esm/index.d.mts @@ -0,0 +1,1539 @@ +/** + * Codes for errors generated within this library + */ +export declare const FlateErrorCode: { + readonly UnexpectedEOF: 0; + readonly InvalidBlockType: 1; + readonly InvalidLengthLiteral: 2; + readonly InvalidDistance: 3; + readonly StreamFinished: 4; + readonly NoStreamHandler: 5; + readonly InvalidHeader: 6; + readonly NoCallback: 7; + readonly InvalidUTF8: 8; + readonly ExtraFieldTooLong: 9; + readonly InvalidDate: 10; + readonly FilenameTooLong: 11; + readonly StreamFinishing: 12; + readonly InvalidZipData: 13; + readonly UnknownCompressionMethod: 14; +}; +/** + * An error generated within this library + */ +export interface FlateError extends Error { + /** + * The code associated with this error + */ + code: number; +} +/** + * Options for decompressing a DEFLATE stream + */ +export interface InflateStreamOptions { + /** + * The dictionary used to compress the original data. If no dictionary was used during compression, this option has no effect. + * + * Supplying the wrong dictionary during decompression usually yields corrupt output or causes an invalid distance error. + */ + dictionary?: Uint8Array; +} +/** + * Options for decompressing DEFLATE data + */ +export interface InflateOptions extends InflateStreamOptions { + /** + * The buffer into which to write the decompressed data. Saves memory if you know the decompressed size in advance. + * + * Note that if the decompression result is larger than the size of this buffer, it will be truncated to fit. + */ + out?: Uint8Array; +} +/** + * Options for decompressing a GZIP stream + */ +export interface GunzipStreamOptions extends InflateStreamOptions { +} +/** + * Options for decompressing GZIP data + */ +export interface GunzipOptions extends InflateStreamOptions { + /** + * The buffer into which to write the decompressed data. GZIP already encodes the output size, so providing this doesn't save memory. + * + * Note that if the decompression result is larger than the size of this buffer, it will be truncated to fit. + */ + out?: Uint8Array; +} +/** + * Options for decompressing a Zlib stream + */ +export interface UnzlibStreamOptions extends InflateStreamOptions { +} +/** + * Options for decompressing Zlib data + */ +export interface UnzlibOptions extends InflateOptions { +} +/** + * Options for compressing data into a DEFLATE format + */ +export interface DeflateOptions { + /** + * The level of compression to use, ranging from 0-9. + * + * 0 will store the data without compression. + * 1 is fastest but compresses the worst, 9 is slowest but compresses the best. + * The default level is 6. + * + * Typically, binary data benefits much more from higher values than text data. + * In both cases, higher values usually take disproportionately longer than the reduction in final size that results. + * + * For example, a 1 MB text file could: + * - become 1.01 MB with level 0 in 1ms + * - become 400 kB with level 1 in 10ms + * - become 320 kB with level 9 in 100ms + */ + level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + /** + * The memory level to use, ranging from 0-12. Increasing this increases speed and compression ratio at the cost of memory. + * + * Note that this is exponential: while level 0 uses 8 kB, level 4 uses 128 kB, level 8 uses 2 MB, and level 12 uses 32 MB. + * It is recommended not to lower the value below 4, since that tends to hurt performance. + * In addition, values above 8 tend to help very little on most data and can even hurt performance. + * + * The default value is automatically determined based on the size of the input data. + */ + mem?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; + /** + * A buffer containing common byte sequences in the input data that can be used to significantly improve compression ratios. + * + * Dictionaries should be 32kB or smaller and include strings or byte sequences likely to appear in the input. + * The decompressor must supply the same dictionary as the compressor to extract the original data. + * + * Dictionaries only improve aggregate compression ratio when reused across multiple small inputs. They should typically not be used otherwise. + * + * Avoid using dictionaries with GZIP and ZIP to maximize software compatibility. + */ + dictionary?: Uint8Array; +} +/** + * Options for compressing data into a GZIP format + */ +export interface GzipOptions extends DeflateOptions { + /** + * When the file was last modified. Defaults to the current time. + * Set this to 0 to avoid revealing a modification date entirely. + */ + mtime?: Date | string | number; + /** + * The filename of the data. If the `gunzip` command is used to decompress the data, it will output a file + * with this name instead of the name of the compressed file. + */ + filename?: string; +} +/** + * Options for compressing data into a Zlib format + */ +export interface ZlibOptions extends DeflateOptions { +} +/** + * Handler for data (de)compression streams + * @param data The data output from the stream processor + * @param final Whether this is the final block + */ +export type FlateStreamHandler = (data: Uint8Array, final: boolean) => void; +/** + * Handler for asynchronous data (de)compression streams + * @param err Any error that occurred + * @param data The data output from the stream processor + * @param final Whether this is the final block + */ +export type AsyncFlateStreamHandler = (err: FlateError | null, data: Uint8Array, final: boolean) => void; +/** + * Handler for the asynchronous completion of (de)compression for a data chunk + * @param size The number of bytes that were processed. This is measured in terms of the input + * (i.e. compressed bytes for decompression, uncompressed bytes for compression.) + */ +export type AsyncFlateDrainHandler = (size: number) => void; +/** + * Callback for asynchronous (de)compression methods + * @param err Any error that occurred + * @param data The resulting data. Only present if `err` is null + */ +export type FlateCallback = (err: FlateError | null, data: Uint8Array) => void; +interface AsyncOptions { + /** + * Whether or not to "consume" the source data. This will make the typed array/buffer you pass in + * unusable but will increase performance and reduce memory usage. + */ + consume?: boolean; +} +/** + * Options for compressing data asynchronously into a DEFLATE format + */ +export interface AsyncDeflateOptions extends DeflateOptions, AsyncOptions { +} +/** + * Options for decompressing DEFLATE data asynchronously + */ +export interface AsyncInflateOptions extends AsyncOptions, InflateStreamOptions { + /** + * The original size of the data. Currently, the asynchronous API disallows + * writing into a buffer you provide; the best you can do is provide the + * size in bytes and be given back a new typed array. + */ + size?: number; +} +/** + * Options for compressing data asynchronously into a GZIP format + */ +export interface AsyncGzipOptions extends GzipOptions, AsyncOptions { +} +/** + * Options for decompressing GZIP data asynchronously + */ +export interface AsyncGunzipOptions extends AsyncOptions, InflateStreamOptions { +} +/** + * Options for compressing data asynchronously into a Zlib format + */ +export interface AsyncZlibOptions extends ZlibOptions, AsyncOptions { +} +/** + * Options for decompressing Zlib data asynchronously + */ +export interface AsyncUnzlibOptions extends AsyncInflateOptions { +} +/** + * A terminable compression/decompression process + */ +export interface AsyncTerminable { + /** + * Terminates the worker thread immediately. The callback will not be called. + */ + (): void; +} +/** + * Streaming DEFLATE compression + */ +export declare class Deflate { + /** + * Creates a DEFLATE stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: DeflateOptions, cb?: FlateStreamHandler); + /** + * Creates a DEFLATE stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + private b; + private s; + private o; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + private p; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE compression + */ +export declare class AsyncDeflate { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous DEFLATE stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: DeflateOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous DEFLATE stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function deflate(data: Uint8Array, opts: AsyncDeflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param cb The function to be called upon compression completion + */ +export declare function deflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @returns The deflated version of the data + */ +export declare function deflateSync(data: Uint8Array, opts?: DeflateOptions): Uint8Array; +/** + * Streaming DEFLATE decompression + */ +export declare class Inflate { + private s; + private o; + private p; + private d; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a DEFLATE decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: InflateStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a DEFLATE decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + private e; + private c; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE decompression + */ +export declare class AsyncInflate { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous DEFLATE decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: InflateStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous DEFLATE decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function inflate(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function inflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands DEFLATE data with no wrapper + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function inflateSync(data: Uint8Array): Uint8Array; +/** + * Expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function inflateSync(data: Uint8Array, opts?: InflateOptions): Uint8Array; +/** + * Streaming GZIP compression + */ +export declare class Gzip { + private c; + private l; + private v; + private o; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a GZIP stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: GzipOptions, cb?: FlateStreamHandler); + /** + * Creates a GZIP stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + private p; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming GZIP compression + */ +export declare class AsyncGzip { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous GZIP stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: GzipOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous GZIP stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function gzip(data: Uint8Array, opts: AsyncGzipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with GZIP + * @param data The data to compress + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @returns The gzipped version of the data + */ +export declare function gzipSync(data: Uint8Array, opts?: GzipOptions): Uint8Array; +/** + * Handler for new GZIP members in concatenated GZIP streams. Useful for building indices used to perform random-access reads on compressed files. + * @param offset The offset of the new member relative to the start of the stream + */ +export type GunzipMemberHandler = (offset: number) => void; +/** + * Streaming single or multi-member GZIP decompression + */ +export declare class Gunzip { + private v; + private r; + private o; + private p; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * The handler to call whenever a new GZIP member is found + */ + onmember?: GunzipMemberHandler; + /** + * Creates a GUNZIP stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: GunzipStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a GUNZIP stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming single or multi-member GZIP decompression + */ +export declare class AsyncGunzip { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * The handler to call whenever a new GZIP member is found + */ + onmember?: GunzipMemberHandler; + /** + * Creates an asynchronous GUNZIP stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: GunzipStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous GUNZIP stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands GZIP data + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gunzip(data: Uint8Array, opts: AsyncGunzipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands GZIP data + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gunzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands GZIP data + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function gunzipSync(data: Uint8Array): Uint8Array; +/** + * Expands GZIP data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function gunzipSync(data: Uint8Array, opts?: GunzipOptions): Uint8Array; +/** + * Streaming Zlib compression + */ +export declare class Zlib { + private c; + private v; + private o; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a Zlib stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: ZlibOptions, cb?: FlateStreamHandler); + /** + * Creates a Zlib stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + private p; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming Zlib compression + */ +export declare class AsyncZlib { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous Zlib stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: ZlibOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous Zlib stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with Zlib + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + */ +export declare function zlib(data: Uint8Array, opts: AsyncZlibOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with Zlib + * @param data The data to compress + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compress data with Zlib + * @param data The data to compress + * @param opts The compression options + * @returns The zlib-compressed version of the data + */ +export declare function zlibSync(data: Uint8Array, opts?: ZlibOptions): Uint8Array; +/** + * Streaming Zlib decompression + */ +export declare class Unzlib { + private v; + private p; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a Zlib decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: UnzlibStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming Zlib decompression + */ +export declare class AsyncUnzlib { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous Zlib decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: UnzlibStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be decompressed from Zlib + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands Zlib data + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function unzlib(data: Uint8Array, opts: AsyncUnzlibOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands Zlib data + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function unzlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands Zlib data + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function unzlibSync(data: Uint8Array): Uint8Array; +/** + * Expands Zlib data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function unzlibSync(data: Uint8Array, opts?: UnzlibOptions): Uint8Array; +export { gzip as compress, AsyncGzip as AsyncCompress }; +export { gzipSync as compressSync, Gzip as Compress }; +/** + * Streaming GZIP, Zlib, or raw DEFLATE decompression + */ +export declare class Decompress { + private G; + private I; + private Z; + private o; + private s; + private p; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is decompressed + */ + constructor(opts: InflateStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a decompression stream + * @param cb The callback to call whenever data is decompressed + */ + constructor(cb?: FlateStreamHandler); + private i; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression + */ +export declare class AsyncDecompress { + private G; + private I; + private Z; + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is decompressed + */ + constructor(opts: InflateStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous decompression stream + * @param cb The callback to call whenever data is decompressed + */ + constructor(cb?: AsyncFlateStreamHandler); + private i; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function decompress(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function decompress(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function decompressSync(data: Uint8Array, opts?: InflateOptions): Uint8Array; +/** + * Attributes for files added to a ZIP archive object + */ +export interface ZipAttributes { + /** + * The operating system of origin for this file. The value is defined + * by PKZIP's APPNOTE.txt, section 4.4.2.2. For example, 0 (the default) + * is MS/DOS, 3 is Unix, 19 is macOS. + */ + os?: number; + /** + * The file's attributes. These are traditionally somewhat complicated + * and platform-dependent, so using them is scarcely necessary. However, + * here is a representation of what this is, bit by bit: + * + * `TTTTugtrwxrwxrwx0000000000ADVSHR` + * + * TTTT = file type (rarely useful) + * + * u = setuid, g = setgid, t = sticky + * + * rwx = user permissions, rwx = group permissions, rwx = other permissions + * + * 0000000000 = unused + * + * A = archive, D = directory, V = volume label, S = system file, H = hidden, R = read-only + * + * If you want to set the Unix permissions, for instance, just bit shift by 16, e.g. 0o644 << 16. + * Note that attributes usually only work in conjunction with the `os` setting: you must use + * `os` = 3 (Unix) if you want to set Unix permissions + */ + attrs?: number; + /** + * Extra metadata to add to the file. This field is defined by PKZIP's APPNOTE.txt, + * section 4.4.28. At most 65,535 bytes may be used in each ID. The ID must be an + * integer between 0 and 65,535, inclusive. + * + * This field is incredibly rare and almost never needed except for compliance with + * proprietary standards and software. + */ + extra?: Record; + /** + * The comment to attach to the file. This field is defined by PKZIP's APPNOTE.txt, + * section 4.4.26. The comment must be at most 65,535 bytes long UTF-8 encoded. This + * field is not read by consumer software. + */ + comment?: string; + /** + * When the file was last modified. Defaults to the current time. + */ + mtime?: GzipOptions['mtime']; +} +/** + * Options for creating a ZIP archive + */ +export interface ZipOptions extends DeflateOptions, ZipAttributes { +} +/** + * Options for expanding a ZIP archive + */ +export interface UnzipOptions { + /** + * A filter function to extract only certain files from a ZIP archive + */ + filter?: UnzipFileFilter; +} +/** + * Options for asynchronously creating a ZIP archive + */ +export interface AsyncZipOptions extends AsyncDeflateOptions, ZipAttributes { +} +/** + * Options for asynchronously expanding a ZIP archive + */ +export interface AsyncUnzipOptions extends UnzipOptions { +} +/** + * A file that can be used to create a ZIP archive + */ +export type ZippableFile = Uint8Array | Zippable | [Uint8Array | Zippable, ZipOptions]; +/** + * A file that can be used to asynchronously create a ZIP archive + */ +export type AsyncZippableFile = Uint8Array | AsyncZippable | [Uint8Array | AsyncZippable, AsyncZipOptions]; +/** + * The complete directory structure of a ZIPpable archive + */ +export interface Zippable { + [path: string]: ZippableFile; +} +/** + * The complete directory structure of an asynchronously ZIPpable archive + */ +export interface AsyncZippable { + [path: string]: AsyncZippableFile; +} +/** + * An unzipped archive. The full path of each file is used as the key, + * and the file is the value + */ +export interface Unzipped { + [path: string]: Uint8Array; +} +/** + * Handler for string generation streams + * @param data The string output from the stream processor + * @param final Whether this is the final block + */ +export type StringStreamHandler = (data: string, final: boolean) => void; +/** + * Callback for asynchronous ZIP decompression + * @param err Any error that occurred + * @param data The decompressed ZIP archive + */ +export type UnzipCallback = (err: FlateError | null, data: Unzipped) => void; +/** + * Handler for streaming ZIP decompression + * @param file The file that was found in the archive + */ +export type UnzipFileHandler = (file: UnzipFile) => void; +/** + * Streaming UTF-8 decoding + */ +export declare class DecodeUTF8 { + private p; + private t; + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is decoded + */ + constructor(cb?: StringStreamHandler); + /** + * Pushes a chunk to be decoded from UTF-8 binary + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * The handler to call whenever data is available + */ + ondata: StringStreamHandler; +} +/** + * Streaming UTF-8 encoding + */ +export declare class EncodeUTF8 { + private d; + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is encoded + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be encoded to UTF-8 + * @param chunk The string data to push + * @param final Whether this is the last chunk + */ + push(chunk: string, final?: boolean): void; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; +} +/** + * Converts a string into a Uint8Array for use with compression/decompression methods + * @param str The string to encode + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless decoding a binary string. + * @returns The string encoded in UTF-8/Latin-1 binary + */ +export declare function strToU8(str: string, latin1?: boolean): Uint8Array; +/** + * Converts a Uint8Array to a string + * @param dat The data to decode to string + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless encoding to binary string. + * @returns The original UTF-8/Latin-1 string + */ +export declare function strFromU8(dat: Uint8Array, latin1?: boolean): string; +/** + * A stream that can be used to create a file in a ZIP archive + */ +export interface ZipInputFile extends ZipAttributes { + /** + * The filename to associate with the data provided to this stream. If you + * want a file in a subdirectory, use forward slashes as a separator (e.g. + * `directory/filename.ext`). This will still work on Windows. + */ + filename: string; + /** + * The size of the file in bytes. This attribute may be invalid after + * the file is added to the ZIP archive; it must be correct only before the + * stream completes. + * + * If you don't want to have to compute this yourself, consider extending the + * ZipPassThrough class and overriding its process() method, or using one of + * ZipDeflate or AsyncZipDeflate. + */ + size: number; + /** + * A CRC of the original file contents. This attribute may be invalid after + * the file is added to the ZIP archive; it must be correct only before the + * stream completes. + * + * If you don't want to have to generate this yourself, consider extending the + * ZipPassThrough class and overriding its process() method, or using one of + * ZipDeflate or AsyncZipDeflate. + */ + crc: number; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA + */ + compression: number; + /** + * Bits 1 and 2 of the general purpose bit flag, specified in PKZIP's + * APPNOTE.txt, section 4.4.4. Should be between 0 and 3. This is unlikely + * to be necessary. + */ + flag?: number; + /** + * The handler to be called when data is added. After passing this stream to + * the ZIP file object, this handler will always be defined. To call it: + * + * `stream.ondata(error, chunk, final)` + * + * error = any error that occurred (null if there was no error) + * + * chunk = a Uint8Array of the data that was added (null if there was an + * error) + * + * final = boolean, whether this is the final chunk in the stream + */ + ondata?: AsyncFlateStreamHandler; + /** + * A method called when the stream is no longer needed, for clean-up + * purposes. This will not always be called after the stream completes, + * so you may wish to call this.terminate() after the final chunk is + * processed if you have clean-up logic. + */ + terminate?: AsyncTerminable; +} +/** + * A pass-through stream to keep data uncompressed in a ZIP archive. + */ +export declare class ZipPassThrough implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private c; + /** + * Creates a pass-through stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + */ + constructor(filename: string); + /** + * Processes a chunk and pushes to the output stream. You can override this + * method in a subclass for custom behavior, but by default this passes + * the data through. You must call this.ondata(err, chunk, final) at some + * point in this method. + * @param chunk The chunk to process + * @param final Whether this is the last chunk + */ + protected process(chunk: Uint8Array, final: boolean): void; + /** + * Pushes a chunk to be added. If you are subclassing this with a custom + * compression algorithm, note that you must push data from the source + * file only, pre-compression. + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate + * for better performance + */ +export declare class ZipDeflate implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + flag: 0 | 1 | 2 | 3; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private d; + /** + * Creates a DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + constructor(filename: string, opts?: DeflateOptions); + private process; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE compression for ZIP archives + */ +export declare class AsyncZipDeflate implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + flag: 0 | 1 | 2 | 3; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private d; + terminate: AsyncTerminable; + /** + * Creates an asynchronous DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + constructor(filename: string, opts?: DeflateOptions); + private process; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * A zippable archive to which files can incrementally be added + */ +export declare class Zip { + private u; + private d; + /** + * Creates an empty ZIP archive to which files can be added + * @param cb The callback to call whenever data for the generated ZIP archive + * is available + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Adds a file to the ZIP archive + * @param file The file stream to add + */ + add(file: ZipInputFile): void; + /** + * Ends the process of adding files and prepares to emit the final chunks. + * This *must* be called after adding all desired files for the resulting + * ZIP file to work properly. + */ + end(): void; + private e; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to add() will fail. + */ + terminate(): void; + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; +} +/** + * Asynchronously creates a ZIP file + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @param cb The callback to call with the generated ZIP archive + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zip(data: AsyncZippable, opts: AsyncZipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously creates a ZIP file + * @param data The directory structure for the ZIP archive + * @param cb The callback to call with the generated ZIP archive + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zip(data: AsyncZippable, cb: FlateCallback): AsyncTerminable; +/** + * Synchronously creates a ZIP file. Prefer using `zip` for better performance + * with more than one file. + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @returns The generated ZIP archive + */ +export declare function zipSync(data: Zippable, opts?: ZipOptions): Uint8Array; +/** + * A decoder for files in ZIP streams + */ +export interface UnzipDecoder { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * Pushes a chunk to be decompressed + * @param chunk The data in this chunk. Do not consume (detach) this buffer. + * @param final Whether this is the last chunk in the data stream + */ + push(chunk: Uint8Array, final: boolean): void; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to push() should silently fail. + */ + terminate?: AsyncTerminable; +} +/** + * A constructor for a decoder for unzip streams + */ +export interface UnzipDecoderConstructor { + /** + * Creates an instance of the decoder + * @param filename The name of the file + * @param size The compressed size of the file + * @param originalSize The original size of the file + */ + new (filename: string, size?: number, originalSize?: number): UnzipDecoder; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA + */ + compression: number; +} +/** + * Information about a file to be extracted from a ZIP archive + */ +export interface UnzipFileInfo { + /** + * The name of the file + */ + name: string; + /** + * The compressed size of the file + */ + size: number; + /** + * The original size of the file + */ + originalSize: number; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA. If the filter function returns true + * but this value is not 8, the unzip function will throw. + */ + compression: number; +} +/** + * A filter for files to be extracted during the unzipping process + * @param file The info for the current file being processed + * @returns Whether or not to extract the current file + */ +export type UnzipFileFilter = (file: UnzipFileInfo) => boolean; +/** + * Streaming file extraction from ZIP archives + */ +export interface UnzipFile { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The name of the file + */ + name: string; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA. If start() is called but there is no + * decompression stream available for this method, start() will throw. + */ + compression: number; + /** + * The compressed size of the file. Will not be present for archives created + * in a streaming fashion. + */ + size?: number; + /** + * The original size of the file. Will not be present for archives created + * in a streaming fashion. + */ + originalSize?: number; + /** + * Starts reading from the stream. Calling this function will always enable + * this stream, but ocassionally the stream will be enabled even without + * this being called. + */ + start(): void; + /** + * A method to terminate any internal workers used by the stream. ondata + * will not be called any further. + */ + terminate: AsyncTerminable; +} +/** + * Streaming pass-through decompression for ZIP archives + */ +export declare class UnzipPassThrough implements UnzipDecoder { + static compression: number; + ondata: AsyncFlateStreamHandler; + push(chunk: Uint8Array, final: boolean): void; +} +/** + * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for + * better performance. + */ +export declare class UnzipInflate implements UnzipDecoder { + static compression: number; + private i; + ondata: AsyncFlateStreamHandler; + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + constructor(); + push(chunk: Uint8Array, final: boolean): void; +} +/** + * Asynchronous streaming DEFLATE decompression for ZIP archives + */ +export declare class AsyncUnzipInflate implements UnzipDecoder { + static compression: number; + private i; + ondata: AsyncFlateStreamHandler; + terminate: AsyncTerminable; + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + constructor(_: string, sz?: number); + push(chunk: Uint8Array, final: boolean): void; +} +/** + * A ZIP archive decompression stream that emits files as they are discovered + */ +export declare class Unzip { + private d; + private c; + private p; + private k; + private o; + /** + * Creates a ZIP decompression stream + * @param cb The callback to call whenever a file in the ZIP archive is found + */ + constructor(cb?: UnzipFileHandler); + /** + * Pushes a chunk to be unzipped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Registers a decoder with the stream, allowing for files compressed with + * the compression type provided to be expanded correctly + * @param decoder The decoder constructor + */ + register(decoder: UnzipDecoderConstructor): void; + /** + * The handler to call whenever a file is discovered + */ + onfile: UnzipFileHandler; +} +/** + * Asynchronously decompresses a ZIP archive + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @param cb The callback to call with the decompressed files + * @returns A function that can be used to immediately terminate the unzipping + */ +export declare function unzip(data: Uint8Array, opts: AsyncUnzipOptions, cb: UnzipCallback): AsyncTerminable; +/** + * Asynchronously decompresses a ZIP archive + * @param data The raw compressed ZIP file + * @param cb The callback to call with the decompressed files + * @returns A function that can be used to immediately terminate the unzipping + */ +export declare function unzip(data: Uint8Array, cb: UnzipCallback): AsyncTerminable; +/** + * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better + * performance with more than one file. + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @returns The decompressed files + */ +export declare function unzipSync(data: Uint8Array, opts?: UnzipOptions): Unzipped; diff --git a/node_modules/fflate/esm/index.mjs b/node_modules/fflate/esm/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4c057eef8a9932d1eb80325c2f08f2975afe23bd --- /dev/null +++ b/node_modules/fflate/esm/index.mjs @@ -0,0 +1,2710 @@ +import { createRequire } from 'module'; +var require = createRequire('/'); +// DEFLATE is a complex format; to read this code, you should probably check the RFC first: +// https://tools.ietf.org/html/rfc1951 +// You may also wish to take a look at the guide I made about this program: +// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad +// Some of the following code is similar to that of UZIP.js: +// https://github.com/photopea/UZIP.js +// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. +// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint +// is better for memory in most engines (I *think*). +var _a; +// Mediocre shim +var Worker; +var isMarkedAsUntransferable; +var workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global"; +try { + (_a = require('worker_threads'), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable); +} +catch (e) { +} +var wk = Worker ? function (c, _, msg, transfer, cb) { + var done = false; + var w = new Worker(c + workerAdd, { eval: true }) + .on('error', function (e) { return cb(e, null); }) + .on('message', function (m) { return cb(null, m); }) + .on('exit', function (c) { + if (c && !done) + cb(new Error('exited with code ' + c), null); + }); + if (isMarkedAsUntransferable) + transfer = transfer.filter(function (t) { return !isMarkedAsUntransferable(t); }); + w.postMessage(msg, transfer); + w.terminate = function () { + done = true; + return Worker.prototype.terminate.call(w); + }; + return w; +} : function (_, __, ___, ____, cb) { + setImmediate(function () { return cb(new Error('async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)'), null); }); + var NOP = function () { }; + return { + terminate: NOP, + postMessage: NOP + }; +}; + +// aliases for shorter compressed code (most minifers don't do this) +var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array; +// fixed length extra bits +var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); +// fixed distance extra bits +var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); +// code length index map +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +// get base, reverse index map from extra bits +var freb = function (eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + // numbers here are at max 18 bits + var r = new i32(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = ((j - b[i]) << 5) | i; + } + } + return { b: b, r: r }; +}; +var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r; +// we can ignore the fact that the other numbers are wrong; they never happen anyway +fl[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r; +// map of value to reverse (assuming 16 bits) +var rev = new u16(32768); +for (var i = 0; i < 32768; ++i) { + // reverse table algorithm from SO + var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1); + x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2); + x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4); + rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1; +} +// create huffman tree from u8 "map": index -> code length for code index +// mb (max bits) must be at most 15 +// TODO: optimize/split up? +var hMap = (function (cd, mb, r) { + var s = cd.length; + // index + var i = 0; + // u16 "map": index -> # of codes with bit length = index + var l = new u16(mb); + // length of cd must be 288 (total # of codes) + for (; i < s; ++i) { + if (cd[i]) + ++l[cd[i] - 1]; + } + // u16 "map": index -> minimum code for bit length = index + var le = new u16(mb); + for (i = 1; i < mb; ++i) { + le[i] = (le[i - 1] + l[i - 1]) << 1; + } + var co; + if (r) { + // u16 "map": index -> number of actual bits, symbol for code + co = new u16(1 << mb); + // bits to remove for reverser + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + // ignore 0 lengths + if (cd[i]) { + // num encoding both symbol and bits read + var sv = (i << 4) | cd[i]; + // free bits + var r_1 = mb - cd[i]; + // start value + var v = le[cd[i] - 1]++ << r_1; + // m is end value + for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { + // every 16 bit value starting with the code yields the same result + co[rev[v] >> rvb] = sv; + } + } + } + } + else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]); + } + } + } + return co; +}); +// fixed length tree +var flt = new u8(288); +for (var i = 0; i < 144; ++i) + flt[i] = 8; +for (var i = 144; i < 256; ++i) + flt[i] = 9; +for (var i = 256; i < 280; ++i) + flt[i] = 7; +for (var i = 280; i < 288; ++i) + flt[i] = 8; +// fixed distance tree +var fdt = new u8(32); +for (var i = 0; i < 32; ++i) + fdt[i] = 5; +// fixed length map +var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); +// fixed distance map +var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); +// find max of array +var max = function (a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; +}; +// read d, starting at bit p and mask with m +var bits = function (d, p, m) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; +}; +// read d, starting at bit p continuing for at least 16 bits +var bits16 = function (d, p) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); +}; +// get end of byte +var shft = function (p) { return ((p + 7) / 8) | 0; }; +// typed array slice - allows garbage collector to free original reference, +// while being more compatible than .slice +var slc = function (v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + // can't use .constructor in case user-supplied + return new u8(v.subarray(s, e)); +}; +/** + * Codes for errors generated within this library + */ +export var FlateErrorCode = { + UnexpectedEOF: 0, + InvalidBlockType: 1, + InvalidLengthLiteral: 2, + InvalidDistance: 3, + StreamFinished: 4, + NoStreamHandler: 5, + InvalidHeader: 6, + NoCallback: 7, + InvalidUTF8: 8, + ExtraFieldTooLong: 9, + InvalidDate: 10, + FilenameTooLong: 11, + StreamFinishing: 12, + InvalidZipData: 13, + UnknownCompressionMethod: 14 +}; +// error codes +var ec = [ + 'unexpected EOF', + 'invalid block type', + 'invalid length/literal', + 'invalid distance', + 'stream finished', + 'no stream handler', + , // determined by compression function + 'no callback', + 'invalid UTF-8 data', + 'extra field too long', + 'date not in range 1980-2099', + 'filename too long', + 'stream finishing', + 'invalid zip data' + // determined by unknown compression method +]; +; +var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; +}; +// expands raw DEFLATE data +var inflt = function (dat, st, buf, dict) { + // source length dict length + var sl = dat.length, dl = dict ? dict.length : 0; + if (!sl || st.f && !st.l) + return buf || new u8(0); + var noBuf = !buf; + // have to estimate size + var resize = noBuf || st.i != 2; + // no state + var noSt = st.i; + // Assumes roughly 33% compression ratio average + if (noBuf) + buf = new u8(sl * 3); + // ensure buffer can fit at least l elements + var cbuf = function (l) { + var bl = buf.length; + // need to increase size to fit + if (l > bl) { + // Double or set to necessary, whichever is greater + var nbuf = new u8(Math.max(bl * 2, l)); + nbuf.set(buf); + buf = nbuf; + } + }; + // last chunk bitpos bytes + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + // total bits + var tbts = sl * 8; + do { + if (!lm) { + // BFINAL - this is only 1 when last chunk is next + final = bits(dat, pos, 1); + // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + // go to end of byte boundary + var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; + if (t > sl) { + if (noSt) + err(0); + break; + } + // ensure size + if (resize) + cbuf(bt + l); + // Copy over uncompressed data + buf.set(dat.subarray(s, t), bt); + // Get new bitpos, update byte count + st.b = bt += l, st.p = pos = t * 8, st.f = final; + continue; + } + else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + // literal lengths + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + // length+distance tree + var ldt = new u8(tl); + // code length tree + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + // use index map to get real code + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + // code lengths bits + var clb = max(clt), clbmsk = (1 << clb) - 1; + // code lengths map + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl;) { + var r = clm[bits(dat, pos, clbmsk)]; + // bits read + pos += r & 15; + // symbol + var s = r >> 4; + // code length to copy + if (s < 16) { + ldt[i++] = s; + } + else { + // copy count + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + // length tree distance tree + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + // max length bits + lbt = max(lt); + // max dist bits + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } + else + err(1); + if (pos > tbts) { + if (noSt) + err(0); + break; + } + } + // Make sure the buffer can hold this + the largest possible addition + // Maximum chunk size (practically, theoretically infinite) is 2^17 + if (resize) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (;; lpos = pos) { + // bits read, code + var c = lm[bits16(dat, pos) & lms], sym = c >> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (!c) + err(2); + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } + else { + var add = sym - 254; + // no extra bits needed if less + if (sym > 264) { + // index + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + // dist + var d = dm[bits16(dat, pos) & dms], dsym = d >> 4; + if (!d) + err(3); + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & (1 << b) - 1, pos += b; + } + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (resize) + cbuf(bt + 131072); + var end = bt + add; + if (bt < dt) { + var shift = dl - dt, dend = Math.min(dt, end); + if (shift + bt < 0) + err(3); + for (; bt < dend; ++bt) + buf[bt] = dict[shift + bt]; + } + for (; bt < end; ++bt) + buf[bt] = buf[bt - dt]; + } + } + st.l = lm, st.p = lpos, st.b = bt, st.f = final; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + // don't reallocate for streams or user buffers + return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt); +}; +// starting at p, write the minimum number of bits that can hold v to d +var wbits = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; +}; +// starting at p, write the minimum number of bits (>8) that can hold v to d +var wbits16 = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; + d[o + 2] |= v >> 16; +}; +// creates code lengths from a frequency table +var hTree = function (d, mb) { + // Need extra info to make a tree + var t = []; + for (var i = 0; i < d.length; ++i) { + if (d[i]) + t.push({ s: i, f: d[i] }); + } + var s = t.length; + var t2 = t.slice(); + if (!s) + return { t: et, l: 0 }; + if (s == 1) { + var v = new u8(t[0].s + 1); + v[t[0].s] = 1; + return { t: v, l: 1 }; + } + t.sort(function (a, b) { return a.f - b.f; }); + // after i2 reaches last ind, will be stopped + // freq must be greater than largest possible number of symbols + t.push({ s: -1, f: 25001 }); + var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; + t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; + // efficient algorithm from UZIP.js + // i0 is lookbehind, i2 is lookahead - after processing two low-freq + // symbols that combined have high freq, will start processing i2 (high-freq, + // non-composite) symbols instead + // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ + while (i1 != s - 1) { + l = t[t[i0].f < t[i2].f ? i0++ : i2++]; + r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; + t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; + } + var maxSym = t2[0].s; + for (var i = 1; i < s; ++i) { + if (t2[i].s > maxSym) + maxSym = t2[i].s; + } + // code lengths + var tr = new u16(maxSym + 1); + // max bits in tree + var mbt = ln(t[i1 - 1], tr, 0); + if (mbt > mb) { + // more algorithms from UZIP.js + // TODO: find out how this code works (debt) + // ind debt + var i = 0, dt = 0; + // left cost + var lft = mbt - mb, cst = 1 << lft; + t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); + for (; i < s; ++i) { + var i2_1 = t2[i].s; + if (tr[i2_1] > mb) { + dt += cst - (1 << (mbt - tr[i2_1])); + tr[i2_1] = mb; + } + else + break; + } + dt >>= lft; + while (dt > 0) { + var i2_2 = t2[i].s; + if (tr[i2_2] < mb) + dt -= 1 << (mb - tr[i2_2]++ - 1); + else + ++i; + } + for (; i >= 0 && dt; --i) { + var i2_3 = t2[i].s; + if (tr[i2_3] == mb) { + --tr[i2_3]; + ++dt; + } + } + mbt = mb; + } + return { t: new u8(tr), l: mbt }; +}; +// get the max length and assign length codes +var ln = function (n, l, d) { + return n.s == -1 + ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) + : (l[n.s] = d); +}; +// length codes generation +var lc = function (c) { + var s = c.length; + // Note that the semicolon was intentional + while (s && !c[--s]) + ; + var cl = new u16(++s); + // ind num streak + var cli = 0, cln = c[0], cls = 1; + var w = function (v) { cl[cli++] = v; }; + for (var i = 1; i <= s; ++i) { + if (c[i] == cln && i != s) + ++cls; + else { + if (!cln && cls > 2) { + for (; cls > 138; cls -= 138) + w(32754); + if (cls > 2) { + w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); + cls = 0; + } + } + else if (cls > 3) { + w(cln), --cls; + for (; cls > 6; cls -= 6) + w(8304); + if (cls > 2) + w(((cls - 3) << 5) | 8208), cls = 0; + } + while (cls--) + w(cln); + cls = 1; + cln = c[i]; + } + } + return { c: cl.subarray(0, cli), n: s }; +}; +// calculate the length of output from tree, code lengths +var clen = function (cf, cl) { + var l = 0; + for (var i = 0; i < cl.length; ++i) + l += cf[i] * cl[i]; + return l; +}; +// writes a fixed block +// returns the new bit pos +var wfblk = function (out, pos, dat) { + // no need to write 00 as type: TypedArray defaults to 0 + var s = dat.length; + var o = shft(pos + 2); + out[o] = s & 255; + out[o + 1] = s >> 8; + out[o + 2] = out[o] ^ 255; + out[o + 3] = out[o + 1] ^ 255; + for (var i = 0; i < s; ++i) + out[o + i + 4] = dat[i]; + return (o + 4 + s) * 8; +}; +// writes a block +var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { + wbits(out, p++, final); + ++lf[256]; + var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l; + var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l; + var _c = lc(dlt), lclt = _c.c, nlc = _c.n; + var _d = lc(ddt), lcdt = _d.c, ndc = _d.n; + var lcfreq = new u16(19); + for (var i = 0; i < lclt.length; ++i) + ++lcfreq[lclt[i] & 31]; + for (var i = 0; i < lcdt.length; ++i) + ++lcfreq[lcdt[i] & 31]; + var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l; + var nlcc = 19; + for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) + ; + var flen = (bl + 5) << 3; + var ftlen = clen(lf, flt) + clen(df, fdt) + eb; + var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]; + if (bs >= 0 && flen <= ftlen && flen <= dtlen) + return wfblk(out, p, dat.subarray(bs, bs + bl)); + var lm, ll, dm, dl; + wbits(out, p, 1 + (dtlen < ftlen)), p += 2; + if (dtlen < ftlen) { + lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; + var llm = hMap(lct, mlcb, 0); + wbits(out, p, nlc - 257); + wbits(out, p + 5, ndc - 1); + wbits(out, p + 10, nlcc - 4); + p += 14; + for (var i = 0; i < nlcc; ++i) + wbits(out, p + 3 * i, lct[clim[i]]); + p += 3 * nlcc; + var lcts = [lclt, lcdt]; + for (var it = 0; it < 2; ++it) { + var clct = lcts[it]; + for (var i = 0; i < clct.length; ++i) { + var len = clct[i] & 31; + wbits(out, p, llm[len]), p += lct[len]; + if (len > 15) + wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12; + } + } + } + else { + lm = flm, ll = flt, dm = fdm, dl = fdt; + } + for (var i = 0; i < li; ++i) { + var sym = syms[i]; + if (sym > 255) { + var len = (sym >> 18) & 31; + wbits16(out, p, lm[len + 257]), p += ll[len + 257]; + if (len > 7) + wbits(out, p, (sym >> 23) & 31), p += fleb[len]; + var dst = sym & 31; + wbits16(out, p, dm[dst]), p += dl[dst]; + if (dst > 3) + wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst]; + } + else { + wbits16(out, p, lm[sym]), p += ll[sym]; + } + } + wbits16(out, p, lm[256]); + return p + ll[256]; +}; +// deflate options (nice << 13) | chain +var deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); +// empty +var et = /*#__PURE__*/ new u8(0); +// compresses data into a raw DEFLATE buffer +var dflt = function (dat, lvl, plvl, pre, post, st) { + var s = st.z || dat.length; + var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); + // writing to this writes to the output buffer + var w = o.subarray(pre, o.length - post); + var lst = st.l; + var pos = (st.r || 0) & 7; + if (lvl) { + if (pos) + w[0] = st.r >> 3; + var opt = deo[lvl - 1]; + var n = opt >> 13, c = opt & 8191; + var msk_1 = (1 << plvl) - 1; + // prev 2-byte val map curr 2-byte val map + var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1); + var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; + var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; + // 24576 is an arbitrary number of maximum symbols per block + // 424 buffer for last block + var syms = new i32(25000); + // length/literal freq distance freq + var lf = new u16(288), df = new u16(32); + // l/lcnt exbits index l/lind waitdx blkpos + var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0; + for (; i + 2 < s; ++i) { + // hash value + var hv = hsh(i); + // index mod 32768 previous index mod + var imod = i & 32767, pimod = head[hv]; + prev[imod] = pimod; + head[hv] = imod; + // We always should modify head and prev, but only add symbols if + // this data is not yet processed ("wait" for wait index) + if (wi <= i) { + // bytes remaining + var rem = s - i; + if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) { + pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); + li = lc_1 = eb = 0, bs = i; + for (var j = 0; j < 286; ++j) + lf[j] = 0; + for (var j = 0; j < 30; ++j) + df[j] = 0; + } + // len dist chain + var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767; + if (rem > 2 && hv == hsh(i - dif)) { + var maxn = Math.min(n, rem) - 1; + var maxd = Math.min(32767, i); + // max possible length + // not capped at dif because decompressors implement "rolling" index population + var ml = Math.min(258, rem); + while (dif <= maxd && --ch_1 && imod != pimod) { + if (dat[i + l] == dat[i + l - dif]) { + var nl = 0; + for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) + ; + if (nl > l) { + l = nl, d = dif; + // break out early when we reach "nice" (we are satisfied enough) + if (nl > maxn) + break; + // now, find the rarest 2-byte sequence within this + // length of literals and search for that instead. + // Much faster than just using the start + var mmd = Math.min(dif, nl - 2); + var md = 0; + for (var j = 0; j < mmd; ++j) { + var ti = i - dif + j & 32767; + var pti = prev[ti]; + var cd = ti - pti & 32767; + if (cd > md) + md = cd, pimod = ti; + } + } + } + // check the previous match + imod = pimod, pimod = prev[imod]; + dif += imod - pimod & 32767; + } + } + // d will be nonzero only when a match was found + if (d) { + // store both dist and len data in one int32 + // Make sure this is recognized as a len/dist with 28th bit (2^28) + syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; + var lin = revfl[l] & 31, din = revfd[d] & 31; + eb += fleb[lin] + fdeb[din]; + ++lf[257 + lin]; + ++df[din]; + wi = i + l; + ++lc_1; + } + else { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + } + } + for (i = Math.max(i, wi); i < s; ++i) { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); + if (!lst) { + st.r = (pos & 7) | w[(pos / 8) | 0] << 3; + // shft(pos) now 1 less if pos & 7 != 0 + pos -= 7; + st.h = head, st.p = prev, st.i = i, st.w = wi; + } + } + else { + for (var i = st.w || 0; i < s + lst; i += 65535) { + // end + var e = i + 65535; + if (e >= s) { + // write final block + w[(pos / 8) | 0] = lst; + e = s; + } + pos = wfblk(w, pos + 1, dat.subarray(i, e)); + } + st.i = s; + } + return slc(o, 0, pre + shft(pos) + post); +}; +// CRC32 table +var crct = /*#__PURE__*/ (function () { + var t = new Int32Array(256); + for (var i = 0; i < 256; ++i) { + var c = i, k = 9; + while (--k) + c = ((c & 1) && -306674912) ^ (c >>> 1); + t[i] = c; + } + return t; +})(); +// CRC32 +var crc = function () { + var c = -1; + return { + p: function (d) { + // closures have awful performance + var cr = c; + for (var i = 0; i < d.length; ++i) + cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8); + c = cr; + }, + d: function () { return ~c; } + }; +}; +// Adler32 +var adler = function () { + var a = 1, b = 0; + return { + p: function (d) { + // closures have awful performance + var n = a, m = b; + var l = d.length | 0; + for (var i = 0; i != l;) { + var e = Math.min(i + 2655, l); + for (; i < e; ++i) + m += n += d[i]; + n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); + } + a = n, b = m; + }, + d: function () { + a %= 65521, b %= 65521; + return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8); + } + }; +}; +; +// deflate with opts +var dopt = function (dat, opt, pre, post, st) { + if (!st) { + st = { l: 1 }; + if (opt.dictionary) { + var dict = opt.dictionary.subarray(-32768); + var newDat = new u8(dict.length + dat.length); + newDat.set(dict); + newDat.set(dat, dict.length); + dat = newDat; + st.w = dict.length; + } + } + return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st); +}; +// Walmart object spread +var mrg = function (a, b) { + var o = {}; + for (var k in a) + o[k] = a[k]; + for (var k in b) + o[k] = b[k]; + return o; +}; +// worker clone +// This is possibly the craziest part of the entire codebase, despite how simple it may seem. +// The only parameter to this function is a closure that returns an array of variables outside of the function scope. +// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization. +// We will return an object mapping of true variable name to value (basically, the current scope as a JS object). +// The reason we can't just use the original variable names is minifiers mangling the toplevel scope. +// This took me three weeks to figure out how to do. +var wcln = function (fn, fnStr, td) { + var dt = fn(); + var st = fn.toString(); + var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(','); + for (var i = 0; i < dt.length; ++i) { + var v = dt[i], k = ks[i]; + if (typeof v == 'function') { + fnStr += ';' + k + '='; + var st_1 = v.toString(); + if (v.prototype) { + // for global objects + if (st_1.indexOf('[native code]') != -1) { + var spInd = st_1.indexOf(' ', 8) + 1; + fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd)); + } + else { + fnStr += st_1; + for (var t in v.prototype) + fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString(); + } + } + else + fnStr += st_1; + } + else + td[k] = v; + } + return fnStr; +}; +var ch = []; +// clone bufs +var cbfs = function (v) { + var tl = []; + for (var k in v) { + if (v[k].buffer) { + tl.push((v[k] = new v[k].constructor(v[k])).buffer); + } + } + return tl; +}; +// use a worker to execute code +var wrkr = function (fns, init, id, cb) { + if (!ch[id]) { + var fnStr = '', td_1 = {}, m = fns.length - 1; + for (var i = 0; i < m; ++i) + fnStr = wcln(fns[i], fnStr, td_1); + ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 }; + } + var td = mrg({}, ch[id].e); + return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb); +}; +// base async inflate fn +var bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; }; +var bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; }; +// gzip extra +var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; }; +// gunzip extra +var guze = function () { return [gzs, gzl]; }; +// zlib extra +var zle = function () { return [zlh, wbytes, adler]; }; +// unzlib extra +var zule = function () { return [zls]; }; +// post buf +var pbf = function (msg) { return postMessage(msg, [msg.buffer]); }; +// get opts +var gopt = function (o) { return o && { + out: o.size && new u8(o.size), + dictionary: o.dictionary +}; }; +// async helper +var cbify = function (dat, opts, fns, init, id, cb) { + var w = wrkr(fns, init, id, function (err, dat) { + w.terminate(); + cb(err, dat); + }); + w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []); + return function () { w.terminate(); }; +}; +// auto stream +var astrm = function (strm) { + strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); }; + return function (ev) { + if (ev.data[0]) { + strm.push(ev.data[0], ev.data[1]); + postMessage([ev.data[0].length]); + } + else + strm.flush(ev.data[1]); + }; +}; +// async stream attach +var astrmify = function (fns, strm, opts, init, id, flush, ext) { + var t; + var w = wrkr(fns, init, id, function (err, dat) { + if (err) + w.terminate(), strm.ondata.call(strm, err); + else if (!Array.isArray(dat)) + ext(dat); + else if (dat.length == 1) { + strm.queuedSize -= dat[0]; + if (strm.ondrain) + strm.ondrain(dat[0]); + } + else { + if (dat[1]) + w.terminate(); + strm.ondata.call(strm, err, dat[0], dat[1]); + } + }); + w.postMessage(opts); + strm.queuedSize = 0; + strm.push = function (d, f) { + if (!strm.ondata) + err(5); + if (t) + strm.ondata(err(4, 0, 1), null, !!f); + strm.queuedSize += d.length; + // can fail for cross-realm Uint8Array, but ok - only a small performance penalty + w.postMessage([d, t = f], d.buffer instanceof ArrayBuffer ? [d.buffer] : []); + }; + strm.terminate = function () { w.terminate(); }; + if (flush) { + strm.flush = function (sync) { w.postMessage([0, sync]); }; + } +}; +// read 2 bytes +var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); }; +// read 4 bytes +var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; }; +// read 8 bytes +var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); }; +// write bytes +var wbytes = function (d, b, v) { + for (; v; ++b) + d[b] = v, v >>>= 8; +}; +// gzip header +var gzh = function (c, o) { + var fn = o.filename; + c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix + if (o.mtime != 0) + wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000)); + if (fn) { + c[3] = 8; + for (var i = 0; i <= fn.length; ++i) + c[i + 10] = fn.charCodeAt(i); + } +}; +// gzip footer: -8 to -4 = CRC, -4 to -0 is length +// gzip start +var gzs = function (d) { + if (d[0] != 31 || d[1] != 139 || d[2] != 8) + err(6, 'invalid gzip data'); + var flg = d[3]; + var st = 10; + if (flg & 4) + st += (d[10] | d[11] << 8) + 2; + for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]) + ; + return st + (flg & 2); +}; +// gzip length +var gzl = function (d) { + var l = d.length; + return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0; +}; +// gzip header length +var gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); }; +// zlib header +var zlh = function (c, o) { + var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; + c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32); + c[1] |= 31 - ((c[0] << 8) | c[1]) % 31; + if (o.dictionary) { + var h = adler(); + h.p(o.dictionary); + wbytes(c, 2, h.d()); + } +}; +// zlib start +var zls = function (d, dict) { + if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31)) + err(6, 'invalid zlib data'); + if ((d[1] >> 5 & 1) == +!dict) + err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary'); + return (d[1] >> 3 & 4) + 2; +}; +function StrmOpt(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + return opts; +} +/** + * Streaming DEFLATE compression + */ +var Deflate = /*#__PURE__*/ (function () { + function Deflate(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + this.o = opts || {}; + this.s = { l: 0, i: 32768, w: 32768, z: 32768 }; + // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev + // 98304 = 32768 (lookback) + 65536 (common chunk size) + this.b = new u8(98304); + if (this.o.dictionary) { + var dict = this.o.dictionary.subarray(-32768); + this.b.set(dict, 32768 - dict.length); + this.s.i = 32768 - dict.length; + } + } + Deflate.prototype.p = function (c, f) { + this.ondata(dopt(c, this.o, 0, 0, this.s), f); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Deflate.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + var endLen = chunk.length + this.s.z; + if (endLen > this.b.length) { + if (endLen > 2 * this.b.length - 32768) { + var newBuf = new u8(endLen & -32768); + newBuf.set(this.b.subarray(0, this.s.z)); + this.b = newBuf; + } + var split = this.b.length - this.s.z; + this.b.set(chunk.subarray(0, split), this.s.z); + this.s.z = this.b.length; + this.p(this.b, false); + this.b.set(this.b.subarray(-32768)); + this.b.set(chunk.subarray(split), 32768); + this.s.z = chunk.length - split + 32768; + this.s.i = 32766, this.s.w = 32768; + } + else { + this.b.set(chunk, this.s.z); + this.s.z += chunk.length; + } + this.s.l = final & 1; + if (this.s.z > this.s.w + 8191 || final) { + this.p(this.b, final || false); + this.s.w = this.s.i, this.s.i -= 2; + } + if (final) { + // cleanup unneeded buffers/state to reduce memory usage + this.s = this.o = {}; + this.b = et; + } + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + Deflate.prototype.flush = function (sync) { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + this.p(this.b, false); + this.s.w = this.s.i, this.s.i -= 2; + // could technically skip writing the type-0 block for (this.s.r & 7) == 0, + // but the deterministic trailer (00 00 FF FF) is useful in some situations + if (sync) { + var c = new u8(6); + c[0] = this.s.r >> 3; + // write empty, non-final type-0 block + var ep = wfblk(c, this.s.r, et); + this.s.r = 0; + this.ondata(c.subarray(0, ep >> 3), false); + } + }; + return Deflate; +}()); +export { Deflate }; +/** + * Asynchronous streaming DEFLATE compression + */ +var AsyncDeflate = /*#__PURE__*/ (function () { + function AsyncDeflate(opts, cb) { + astrmify([ + bDflt, + function () { return [astrm, Deflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Deflate(ev.data); + onmessage = astrm(strm); + }, 6, 1); + } + return AsyncDeflate; +}()); +export { AsyncDeflate }; +export function deflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb); +} +/** + * Compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @returns The deflated version of the data + */ +export function deflateSync(data, opts) { + return dopt(data, opts || {}, 0, 0); +} +/** + * Streaming DEFLATE decompression + */ +var Inflate = /*#__PURE__*/ (function () { + function Inflate(opts, cb) { + // no StrmOpt here to avoid adding to workerizer + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768); + this.s = { i: 0, b: dict ? dict.length : 0 }; + this.o = new u8(32768); + this.p = new u8(0); + if (dict) + this.o.set(dict); + } + Inflate.prototype.e = function (c) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + if (!this.p.length) + this.p = c; + else if (c.length) { + var n = new u8(this.p.length + c.length); + n.set(this.p), n.set(c, this.p.length), this.p = n; + } + }; + Inflate.prototype.c = function (final) { + this.s.i = +(this.d = final || false); + var bts = this.s.b; + var dt = inflt(this.p, this.s, this.o); + this.ondata(slc(dt, bts, this.s.b), this.d); + this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; + this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; + }; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + Inflate.prototype.push = function (chunk, final) { + this.e(chunk), this.c(final); + }; + return Inflate; +}()); +export { Inflate }; +/** + * Asynchronous streaming DEFLATE decompression + */ +var AsyncInflate = /*#__PURE__*/ (function () { + function AsyncInflate(opts, cb) { + astrmify([ + bInflt, + function () { return [astrm, Inflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Inflate(ev.data); + onmessage = astrm(strm); + }, 7, 0); + } + return AsyncInflate; +}()); +export { AsyncInflate }; +export function inflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt + ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb); +} +export function inflateSync(data, opts) { + return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize. +/** + * Streaming GZIP compression + */ +var Gzip = /*#__PURE__*/ (function () { + function Gzip(opts, cb) { + this.c = crc(); + this.l = 0; + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gzip.prototype.push = function (chunk, final) { + this.c.p(chunk); + this.l += chunk.length; + Deflate.prototype.push.call(this, chunk, final); + }; + Gzip.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s); + if (this.v) + gzh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + Gzip.prototype.flush = function (sync) { + Deflate.prototype.flush.call(this, sync); + }; + return Gzip; +}()); +export { Gzip }; +/** + * Asynchronous streaming GZIP compression + */ +var AsyncGzip = /*#__PURE__*/ (function () { + function AsyncGzip(opts, cb) { + astrmify([ + bDflt, + gze, + function () { return [astrm, Deflate, Gzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gzip(ev.data); + onmessage = astrm(strm); + }, 8, 1); + } + return AsyncGzip; +}()); +export { AsyncGzip }; +export function gzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + gze, + function () { return [gzipSync]; } + ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb); +} +/** + * Compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @returns The gzipped version of the data + */ +export function gzipSync(data, opts) { + if (!opts) + opts = {}; + var c = crc(), l = data.length; + c.p(data); + var d = dopt(data, opts, gzhl(opts), 8), s = d.length; + return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d; +} +/** + * Streaming single or multi-member GZIP decompression + */ +var Gunzip = /*#__PURE__*/ (function () { + function Gunzip(opts, cb) { + this.v = 1; + this.r = 0; + Inflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gunzip.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + this.r += chunk.length; + if (this.v) { + var p = this.p.subarray(this.v - 1); + var s = p.length > 3 ? gzs(p) : 4; + if (s > p.length) { + if (!final) + return; + } + else if (this.v > 1 && this.onmember) { + this.onmember(this.r - p.length); + } + this.p = p.subarray(s), this.v = 0; + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, 0); + // process concatenated GZIP + if (this.s.f && !this.s.l) { + this.v = shft(this.s.p) + 9; + this.s = { i: 0 }; + this.o = new u8(0); + this.push(new u8(0), final); + } + else if (final) { + Inflate.prototype.c.call(this, final); + } + }; + return Gunzip; +}()); +export { Gunzip }; +/** + * Asynchronous streaming single or multi-member GZIP decompression + */ +var AsyncGunzip = /*#__PURE__*/ (function () { + function AsyncGunzip(opts, cb) { + var _this = this; + astrmify([ + bInflt, + guze, + function () { return [astrm, Inflate, Gunzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gunzip(ev.data); + strm.onmember = function (offset) { return postMessage(offset); }; + onmessage = astrm(strm); + }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); }); + } + return AsyncGunzip; +}()); +export { AsyncGunzip }; +export function gunzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + guze, + function () { return [gunzipSync]; } + ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb); +} +export function gunzipSync(data, opts) { + var st = gzs(data); + if (st + 8 > data.length) + err(6, 'invalid gzip data'); + return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary); +} +/** + * Streaming Zlib compression + */ +var Zlib = /*#__PURE__*/ (function () { + function Zlib(opts, cb) { + this.c = adler(); + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Zlib.prototype.push = function (chunk, final) { + this.c.p(chunk); + Deflate.prototype.push.call(this, chunk, final); + }; + Zlib.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s); + if (this.v) + zlh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 4, this.c.d()); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + Zlib.prototype.flush = function (sync) { + Deflate.prototype.flush.call(this, sync); + }; + return Zlib; +}()); +export { Zlib }; +/** + * Asynchronous streaming Zlib compression + */ +var AsyncZlib = /*#__PURE__*/ (function () { + function AsyncZlib(opts, cb) { + astrmify([ + bDflt, + zle, + function () { return [astrm, Deflate, Zlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Zlib(ev.data); + onmessage = astrm(strm); + }, 10, 1); + } + return AsyncZlib; +}()); +export { AsyncZlib }; +export function zlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + zle, + function () { return [zlibSync]; } + ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb); +} +/** + * Compress data with Zlib + * @param data The data to compress + * @param opts The compression options + * @returns The zlib-compressed version of the data + */ +export function zlibSync(data, opts) { + if (!opts) + opts = {}; + var a = adler(); + a.p(data); + var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4); + return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d; +} +/** + * Streaming Zlib decompression + */ +var Unzlib = /*#__PURE__*/ (function () { + function Unzlib(opts, cb) { + Inflate.call(this, opts, cb); + this.v = opts && opts.dictionary ? 2 : 1; + } + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzlib.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + if (this.v) { + if (this.p.length < 6 && !final) + return; + this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0; + } + if (final) { + if (this.p.length < 4) + err(6, 'invalid zlib data'); + this.p = this.p.subarray(0, -4); + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + }; + return Unzlib; +}()); +export { Unzlib }; +/** + * Asynchronous streaming Zlib decompression + */ +var AsyncUnzlib = /*#__PURE__*/ (function () { + function AsyncUnzlib(opts, cb) { + astrmify([ + bInflt, + zule, + function () { return [astrm, Inflate, Unzlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Unzlib(ev.data); + onmessage = astrm(strm); + }, 11, 0); + } + return AsyncUnzlib; +}()); +export { AsyncUnzlib }; +export function unzlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + zule, + function () { return [unzlibSync]; } + ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb); +} +export function unzlibSync(data, opts) { + return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +// Default algorithm for compression (used because having a known output size allows faster decompression) +export { gzip as compress, AsyncGzip as AsyncCompress }; +export { gzipSync as compressSync, Gzip as Compress }; +/** + * Streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var Decompress = /*#__PURE__*/ (function () { + function Decompress(opts, cb) { + this.o = StrmOpt.call(this, opts, cb) || {}; + this.G = Gunzip; + this.I = Inflate; + this.Z = Unzlib; + } + // init substream + // overriden by AsyncDecompress + Decompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (dat, final) { + _this.ondata(dat, final); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Decompress.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (!this.s) { + if (this.p && this.p.length) { + var n = new u8(this.p.length + chunk.length); + n.set(this.p), n.set(chunk, this.p.length); + } + else + this.p = chunk; + if (this.p.length > 2) { + this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8) + ? new this.G(this.o) + : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31)) + ? new this.I(this.o) + : new this.Z(this.o); + this.i(); + this.s.push(this.p, final); + this.p = null; + } + } + else + this.s.push(chunk, final); + }; + return Decompress; +}()); +export { Decompress }; +/** + * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var AsyncDecompress = /*#__PURE__*/ (function () { + function AsyncDecompress(opts, cb) { + Decompress.call(this, opts, cb); + this.queuedSize = 0; + this.G = AsyncGunzip; + this.I = AsyncInflate; + this.Z = AsyncUnzlib; + } + AsyncDecompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (err, dat, final) { + _this.ondata(err, dat, final); + }; + this.s.ondrain = function (size) { + _this.queuedSize -= size; + if (_this.ondrain) + _this.ondrain(size); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncDecompress.prototype.push = function (chunk, final) { + this.queuedSize += chunk.length; + Decompress.prototype.push.call(this, chunk, final); + }; + return AsyncDecompress; +}()); +export { AsyncDecompress }; +export function decompress(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzip(data, opts, cb) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflate(data, opts, cb) + : unzlib(data, opts, cb); +} +/** + * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export function decompressSync(data, opts) { + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzipSync(data, opts) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflateSync(data, opts) + : unzlibSync(data, opts); +} +// flatten a directory structure +var fltn = function (d, p, t, o) { + for (var k in d) { + var val = d[k], n = p + k, op = o; + if (Array.isArray(val)) + op = mrg(o, val[1]), val = val[0]; + if (ArrayBuffer.isView(val)) + t[n] = [val, op]; + else { + t[n += '/'] = [new u8(0), op]; + fltn(val, n, t, o); + } + } +}; +// text encoder +var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder(); +// text decoder +var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); +// text decoder stream +var tds = 0; +try { + td.decode(et, { stream: true }); + tds = 1; +} +catch (e) { } +// decode UTF8 +var dutf8 = function (d) { + for (var r = '', i = 0;;) { + var c = d[i++]; + var eb = (c > 127) + (c > 223) + (c > 239); + if (i + eb > d.length) + return { s: r, r: slc(d, i - 1) }; + if (!eb) + r += String.fromCharCode(c); + else if (eb == 3) { + c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536, + r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023)); + } + else if (eb & 1) + r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63)); + else + r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)); + } +}; +/** + * Streaming UTF-8 decoding + */ +var DecodeUTF8 = /*#__PURE__*/ (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is decoded + */ + function DecodeUTF8(cb) { + this.ondata = cb; + if (tds) + this.t = new TextDecoder(); + else + this.p = et; + } + /** + * Pushes a chunk to be decoded from UTF-8 binary + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + DecodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + final = !!final; + if (this.t) { + this.ondata(this.t.decode(chunk, { stream: true }), final); + if (final) { + if (this.t.decode().length) + err(8); + this.t = null; + } + return; + } + if (!this.p) + err(4); + var dat = new u8(this.p.length + chunk.length); + dat.set(this.p); + dat.set(chunk, this.p.length); + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (final) { + if (r.length) + err(8); + this.p = null; + } + else + this.p = r; + this.ondata(s, final); + }; + return DecodeUTF8; +}()); +export { DecodeUTF8 }; +/** + * Streaming UTF-8 encoding + */ +var EncodeUTF8 = /*#__PURE__*/ (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is encoded + */ + function EncodeUTF8(cb) { + this.ondata = cb; + } + /** + * Pushes a chunk to be encoded to UTF-8 + * @param chunk The string data to push + * @param final Whether this is the last chunk + */ + EncodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + this.ondata(strToU8(chunk), this.d = final || false); + }; + return EncodeUTF8; +}()); +export { EncodeUTF8 }; +/** + * Converts a string into a Uint8Array for use with compression/decompression methods + * @param str The string to encode + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless decoding a binary string. + * @returns The string encoded in UTF-8/Latin-1 binary + */ +export function strToU8(str, latin1) { + if (latin1) { + var ar_1 = new u8(str.length); + for (var i = 0; i < str.length; ++i) + ar_1[i] = str.charCodeAt(i); + return ar_1; + } + if (te) + return te.encode(str); + var l = str.length; + var ar = new u8(str.length + (str.length >> 1)); + var ai = 0; + var w = function (v) { ar[ai++] = v; }; + for (var i = 0; i < l; ++i) { + if (ai + 5 > ar.length) { + var n = new u8(ai + 8 + ((l - i) << 1)); + n.set(ar); + ar = n; + } + var c = str.charCodeAt(i); + if (c < 128 || latin1) + w(c); + else if (c < 2048) + w(192 | (c >> 6)), w(128 | (c & 63)); + else if (c > 55295 && c < 57344) + c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023), + w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + else + w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + } + return slc(ar, 0, ai); +} +/** + * Converts a Uint8Array to a string + * @param dat The data to decode to string + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless encoding to binary string. + * @returns The original UTF-8/Latin-1 string + */ +export function strFromU8(dat, latin1) { + if (latin1) { + var r = ''; + for (var i = 0; i < dat.length; i += 16384) + r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384)); + return r; + } + else if (td) { + return td.decode(dat); + } + else { + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (r.length) + err(8); + return s; + } +} +; +// deflate bit flag +var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; }; +// skip local zip header +var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); }; +// read zip header +var zh = function (d, b, z) { + var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl; + var _a = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a[0], su = _a[1], off = _a[2]; + return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off]; +}; +// read zip64 header sizes +var z64hs = function (d, b, l, z, sc, su, off) { + var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l; + var nf = nsc + nsu + noff; + if (z && nf) { + for (; b + 4 < e; b += 4 + b2(d, b + 2)) { + if (b2(d, b) == 1) { + return [ + nsc ? b8(d, b + 4 + 8 * nsu) : sc, + nsu ? b8(d, b + 4) : su, + noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off, + 1 + ]; + } + } + // z == 2 for unknown whether or not zip64 + if (z < 2) + err(13); + } + return [sc, su, off, 0]; +}; +// extra field length +var exfl = function (ex) { + var le = 0; + if (ex) { + for (var k in ex) { + var l = ex[k].length; + if (l > 65535) + err(9); + le += l + 4; + } + } + return le; +}; +// write zip header +var wzh = function (d, b, f, fn, u, c, ce, co) { + var fl = fn.length, ex = f.extra, col = co && co.length; + var exl = exfl(ex); + wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4; + if (ce != null) + d[b++] = 20, d[b++] = f.os; + d[b] = 20, b += 2; // spec compliance? what's that? + d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8; + d[b++] = f.compression & 255, d[b++] = f.compression >> 8; + var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980; + if (y < 0 || y > 119) + err(10); + wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4; + if (c != -1) { + wbytes(d, b, f.crc); + wbytes(d, b + 4, c < 0 ? -c - 2 : c); + wbytes(d, b + 8, f.size); + } + wbytes(d, b + 12, fl); + wbytes(d, b + 14, exl), b += 16; + if (ce != null) { + wbytes(d, b, col); + wbytes(d, b + 6, f.attrs); + wbytes(d, b + 10, ce), b += 14; + } + d.set(fn, b); + b += fl; + if (exl) { + for (var k in ex) { + var exf = ex[k], l = exf.length; + wbytes(d, b, +k); + wbytes(d, b + 2, l); + d.set(exf, b + 4), b += 4 + l; + } + } + if (col) + d.set(co, b), b += col; + return b; +}; +// write zip footer (end of central directory) +var wzf = function (o, b, c, d, e) { + wbytes(o, b, 0x6054B50); // skip disk + wbytes(o, b + 8, c); + wbytes(o, b + 10, c); + wbytes(o, b + 12, d); + wbytes(o, b + 16, e); +}; +/** + * A pass-through stream to keep data uncompressed in a ZIP archive. + */ +var ZipPassThrough = /*#__PURE__*/ (function () { + /** + * Creates a pass-through stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + */ + function ZipPassThrough(filename) { + this.filename = filename; + this.c = crc(); + this.size = 0; + this.compression = 0; + } + /** + * Processes a chunk and pushes to the output stream. You can override this + * method in a subclass for custom behavior, but by default this passes + * the data through. You must call this.ondata(err, chunk, final) at some + * point in this method. + * @param chunk The chunk to process + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.process = function (chunk, final) { + this.ondata(null, chunk, final); + }; + /** + * Pushes a chunk to be added. If you are subclassing this with a custom + * compression algorithm, note that you must push data from the source + * file only, pre-compression. + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + this.c.p(chunk); + this.size += chunk.length; + if (final) + this.crc = this.c.d(); + // we shouldn't really do this cast, but properly handling ArrayBufferLike + // makes the API unergonomic with Buffer + this.process(chunk, final || false); + }; + return ZipPassThrough; +}()); +export { ZipPassThrough }; +// I don't extend because TypeScript extension adds 1kB of runtime bloat +/** + * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate + * for better performance + */ +var ZipDeflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function ZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new Deflate(opts, function (dat, final) { + _this.ondata(null, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + } + ZipDeflate.prototype.process = function (chunk, final) { + try { + this.d.push(chunk, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return ZipDeflate; +}()); +export { ZipDeflate }; +/** + * Asynchronous streaming DEFLATE compression for ZIP archives + */ +var AsyncZipDeflate = /*#__PURE__*/ (function () { + /** + * Creates an asynchronous DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function AsyncZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new AsyncDeflate(opts, function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + this.terminate = this.d.terminate; + } + AsyncZipDeflate.prototype.process = function (chunk, final) { + this.d.push(chunk, final); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return AsyncZipDeflate; +}()); +export { AsyncZipDeflate }; +// TODO: Better tree shaking +/** + * A zippable archive to which files can incrementally be added + */ +var Zip = /*#__PURE__*/ (function () { + /** + * Creates an empty ZIP archive to which files can be added + * @param cb The callback to call whenever data for the generated ZIP archive + * is available + */ + function Zip(cb) { + this.ondata = cb; + this.u = []; + this.d = 1; + } + /** + * Adds a file to the ZIP archive + * @param file The file stream to add + */ + Zip.prototype.add = function (file) { + var _this = this; + if (!this.ondata) + err(5); + // finishing or finished + if (this.d & 2) + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false); + else { + var f = strToU8(file.filename), fl_1 = f.length; + var com = file.comment, o = com && strToU8(com); + var u = fl_1 != file.filename.length || (o && (com.length != o.length)); + var hl_1 = fl_1 + exfl(file.extra) + 30; + if (fl_1 > 65535) + this.ondata(err(11, 0, 1), null, false); + var header = new u8(hl_1); + wzh(header, 0, file, f, u, -1); + var chks_1 = [header]; + var pAll_1 = function () { + for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) { + var chk = chks_2[_i]; + _this.ondata(null, chk, false); + } + chks_1 = []; + }; + var tr_1 = this.d; + this.d = 0; + var ind_1 = this.u.length; + var uf_1 = mrg(file, { + f: f, + u: u, + o: o, + t: function () { + if (file.terminate) + file.terminate(); + }, + r: function () { + pAll_1(); + if (tr_1) { + var nxt = _this.u[ind_1 + 1]; + if (nxt) + nxt.r(); + else + _this.d = 1; + } + tr_1 = 1; + } + }); + var cl_1 = 0; + file.ondata = function (err, dat, final) { + if (err) { + _this.ondata(err, dat, final); + _this.terminate(); + } + else { + cl_1 += dat.length; + chks_1.push(dat); + if (final) { + var dd = new u8(16); + wbytes(dd, 0, 0x8074B50); + wbytes(dd, 4, file.crc); + wbytes(dd, 8, cl_1); + wbytes(dd, 12, file.size); + chks_1.push(dd); + uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size; + if (tr_1) + uf_1.r(); + tr_1 = 1; + } + else if (tr_1) + pAll_1(); + } + }; + this.u.push(uf_1); + } + }; + /** + * Ends the process of adding files and prepares to emit the final chunks. + * This *must* be called after adding all desired files for the resulting + * ZIP file to work properly. + */ + Zip.prototype.end = function () { + var _this = this; + if (this.d & 2) { + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true); + return; + } + if (this.d) + this.e(); + else + this.u.push({ + r: function () { + if (!(_this.d & 1)) + return; + _this.u.splice(-1, 1); + _this.e(); + }, + t: function () { } + }); + this.d = 3; + }; + Zip.prototype.e = function () { + var bt = 0, l = 0, tl = 0; + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0); + } + var out = new u8(tl + 22); + for (var _b = 0, _c = this.u; _b < _c.length; _b++) { + var f = _c[_b]; + wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o); + bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b; + } + wzf(out, bt, this.u.length, tl, l); + this.ondata(null, out, true); + this.d = 2; + }; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to add() will fail. + */ + Zip.prototype.terminate = function () { + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + f.t(); + } + this.d = 2; + }; + return Zip; +}()); +export { Zip }; +export function zip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var r = {}; + fltn(data, '', r, opts); + var k = Object.keys(r); + var lft = k.length, o = 0, tot = 0; + var slft = lft, files = new Array(lft); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var cbf = function () { + var out = new u8(tot + 22), oe = o, cdl = tot - o; + tot = 0; + for (var i = 0; i < slft; ++i) { + var f = files[i]; + try { + var l = f.c.length; + wzh(out, tot, f, f.f, f.u, l); + var badd = 30 + f.f.length + exfl(f.extra); + var loc = tot + badd; + out.set(f.c, loc); + wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l; + } + catch (e) { + return cbd(e, null); + } + } + wzf(out, o, files.length, cdl, oe); + cbd(null, out); + }; + if (!lft) + cbf(); + var _loop_1 = function (i) { + var fn = k[i]; + var _a = r[fn], file = _a[0], p = _a[1]; + var c = crc(), size = file.length; + c.p(file); + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + var compression = p.level == 0 ? 0 : 8; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + var l = d.length; + files[i] = mrg(p, { + size: size, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + compression: compression + }); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + if (!--lft) + cbf(); + } + }; + if (s > 65535) + cbl(err(11, 0, 1), null); + if (!compression) + cbl(null, file); + else if (size < 160000) { + try { + cbl(null, deflateSync(file, p)); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(deflate(file, p, cbl)); + }; + // Cannot use lft because it can decrease + for (var i = 0; i < slft; ++i) { + _loop_1(i); + } + return tAll; +} +/** + * Synchronously creates a ZIP file. Prefer using `zip` for better performance + * with more than one file. + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @returns The generated ZIP archive + */ +export function zipSync(data, opts) { + if (!opts) + opts = {}; + var r = {}; + var files = []; + fltn(data, '', r, opts); + var o = 0; + var tot = 0; + for (var fn in r) { + var _a = r[fn], file = _a[0], p = _a[1]; + var compression = p.level == 0 ? 0 : 8; + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + if (s > 65535) + err(11); + var d = compression ? deflateSync(file, p) : file, l = d.length; + var c = crc(); + c.p(file); + files.push(mrg(p, { + size: file.length, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + o: o, + compression: compression + })); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + } + var out = new u8(tot + 22), oe = o, cdl = tot - o; + for (var i = 0; i < files.length; ++i) { + var f = files[i]; + wzh(out, f.o, f, f.f, f.u, f.c.length); + var badd = 30 + f.f.length + exfl(f.extra); + out.set(f.c, f.o + badd); + wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0); + } + wzf(out, o, files.length, cdl, oe); + return out; +} +/** + * Streaming pass-through decompression for ZIP archives + */ +var UnzipPassThrough = /*#__PURE__*/ (function () { + function UnzipPassThrough() { + } + UnzipPassThrough.prototype.push = function (chunk, final) { + // same as ZipPassThrough: cast to retain Buffer ergonomics + this.ondata(null, chunk, final); + }; + UnzipPassThrough.compression = 0; + return UnzipPassThrough; +}()); +export { UnzipPassThrough }; +/** + * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for + * better performance. + */ +var UnzipInflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function UnzipInflate() { + var _this = this; + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + UnzipInflate.prototype.push = function (chunk, final) { + try { + this.i.push(chunk, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + UnzipInflate.compression = 8; + return UnzipInflate; +}()); +export { UnzipInflate }; +/** + * Asynchronous streaming DEFLATE decompression for ZIP archives + */ +var AsyncUnzipInflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function AsyncUnzipInflate(_, sz) { + var _this = this; + if (sz < 320000) { + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + else { + this.i = new AsyncInflate(function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.terminate = this.i.terminate; + } + } + AsyncUnzipInflate.prototype.push = function (chunk, final) { + if (this.i.terminate) + chunk = slc(chunk, 0); + this.i.push(chunk, final); + }; + AsyncUnzipInflate.compression = 8; + return AsyncUnzipInflate; +}()); +export { AsyncUnzipInflate }; +/** + * A ZIP archive decompression stream that emits files as they are discovered + */ +var Unzip = /*#__PURE__*/ (function () { + /** + * Creates a ZIP decompression stream + * @param cb The callback to call whenever a file in the ZIP archive is found + */ + function Unzip(cb) { + this.onfile = cb; + this.k = []; + this.o = { + 0: UnzipPassThrough + }; + this.p = et; + } + /** + * Pushes a chunk to be unzipped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzip.prototype.push = function (chunk, final) { + var _this = this; + if (!this.onfile) + err(5); + if (!this.p) + err(4); + if (this.c > 0) { + var len = Math.min(this.c, chunk.length); + var toAdd = chunk.subarray(0, len); + this.c -= len; + if (this.d) + this.d.push(toAdd, !this.c); + else + this.k[0].push(toAdd); + chunk = chunk.subarray(len); + if (chunk.length) + return this.push(chunk, final); + } + else { + var f = 0, i = 0, is = void 0, buf = void 0; + if (!this.p.length) + buf = chunk; + else if (!chunk.length) + buf = this.p; + else { + buf = new u8(this.p.length + chunk.length); + buf.set(this.p), buf.set(chunk, this.p.length); + } + var l = buf.length, oc = this.c, add = oc && this.d; + var _loop_2 = function () { + var sig = b4(buf, i); + if (sig == 0x4034B50) { + f = 1, is = i; + this_1.d = null; + this_1.c = 0; + var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28); + if (l > i + 30 + fnl + es) { + var chks_3 = []; + this_1.k.unshift(chks_3); + f = 2; + var lsc = b4(buf, i + 18), lsu = b4(buf, i + 22); + var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u); + var _a = z64hs(buf, i, es, 2, lsc, lsu, 0), sc_1 = _a[0], su_1 = _a[1], z64 = _a[3]; + if (dd) + sc_1 = -1 - z64; + i += es; + this_1.c = sc_1; + var d_1; + var file_1 = { + name: fn_1, + compression: cmp_1, + start: function () { + if (!file_1.ondata) + err(5); + if (!sc_1) + file_1.ondata(null, et, true); + else { + var ctr = _this.o[cmp_1]; + if (!ctr) + file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false); + d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1); + d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); }; + for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) { + var dat = chks_4[_i]; + d_1.push(dat, false); + } + if (_this.k[0] == chks_3 && _this.c) + _this.d = d_1; + else + d_1.push(et, true); + } + }, + terminate: function () { + if (d_1 && d_1.terminate) + d_1.terminate(); + } + }; + if (sc_1 >= 0) + file_1.size = sc_1, file_1.originalSize = su_1; + this_1.onfile(file_1); + } + return "break"; + } + else if (oc) { + if (sig == 0x8074B50) { + is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0; + return "break"; + } + else if (sig == 0x2014B50) { + is = i -= 4, f = 3, this_1.c = 0; + return "break"; + } + } + }; + var this_1 = this; + for (; i < l - 4; ++i) { + var state_1 = _loop_2(); + if (state_1 === "break") + break; + } + this.p = et; + if (oc < 0) { + var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i); + if (add) + add.push(dat, !!f); + else + this.k[+(f == 2)].push(dat); + } + if (f & 2) + return this.push(buf.subarray(i), final); + this.p = buf.subarray(i); + } + if (final) { + if (this.c) + err(13); + this.p = null; + } + }; + /** + * Registers a decoder with the stream, allowing for files compressed with + * the compression type provided to be expanded correctly + * @param decoder The decoder constructor + */ + Unzip.prototype.register = function (decoder) { + this.o[decoder.compression] = decoder; + }; + return Unzip; +}()); +export { Unzip }; +var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); }; +export function unzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var files = {}; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) { + cbd(err(13, 0, 1), null); + return tAll; + } + } + ; + var lft = b2(data, e + 8); + if (lft) { + var c = lft; + var o = b4(data, e + 16); + var z = b4(data, e - 20) == 0x7064B50; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = lft = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + var _loop_3 = function (i) { + var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + if (d) + files[fn] = d; + if (!--lft) + cbd(null, files); + } + }; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_1 + })) { + if (!c_1) + cbl(null, slc(data, b, b + sc)); + else if (c_1 == 8) { + var infl = data.subarray(b, b + sc); + // Synchronously decompress under 512KB, or barely-compressed data + if (su < 524288 || sc > 0.8 * su) { + try { + cbl(null, inflateSync(infl, { out: new u8(su) })); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(inflate(infl, { size: su }, cbl)); + } + else + cbl(err(14, 'unknown compression type ' + c_1, 1), null); + } + else + cbl(null, null); + }; + for (var i = 0; i < c; ++i) { + _loop_3(i); + } + } + else + cbd(null, {}); + return tAll; +} +/** + * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better + * performance with more than one file. + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @returns The decompressed files + */ +export function unzipSync(data, opts) { + var files = {}; + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) + err(13); + } + ; + var c = b2(data, e + 8); + if (!c) + return {}; + var o = b4(data, e + 16); + var z = b4(data, e - 20) == 0x7064B50; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + for (var i = 0; i < c; ++i) { + var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_2 + })) { + if (!c_2) + files[fn] = slc(data, b, b + sc); + else if (c_2 == 8) + files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) }); + else + err(14, 'unknown compression type ' + c_2); + } + } + return files; +} diff --git a/node_modules/fflate/lib/browser.cjs b/node_modules/fflate/lib/browser.cjs new file mode 100644 index 0000000000000000000000000000000000000000..d3427caca233f968e8b3dc9c1a2d96e81abe42d3 --- /dev/null +++ b/node_modules/fflate/lib/browser.cjs @@ -0,0 +1,2717 @@ +"use strict"; +// DEFLATE is a complex format; to read this code, you should probably check the RFC first: +// https://tools.ietf.org/html/rfc1951 +// You may also wish to take a look at the guide I made about this program: +// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad +exports.deflate = deflate; +exports.deflateSync = deflateSync; +exports.inflate = inflate; +exports.inflateSync = inflateSync; +exports.gzip = gzip; +exports.compress = gzip; +exports.gzipSync = gzipSync; +exports.compressSync = gzipSync; +exports.gunzip = gunzip; +exports.gunzipSync = gunzipSync; +exports.zlib = zlib; +exports.zlibSync = zlibSync; +exports.unzlib = unzlib; +exports.unzlibSync = unzlibSync; +exports.gzip = gzip; +exports.compress = gzip; +exports.decompress = decompress; +exports.decompressSync = decompressSync; +exports.strToU8 = strToU8; +exports.strFromU8 = strFromU8; +exports.zip = zip; +exports.zipSync = zipSync; +exports.unzip = unzip; +exports.unzipSync = unzipSync; +// Some of the following code is similar to that of UZIP.js: +// https://github.com/photopea/UZIP.js +// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. +// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint +// is better for memory in most engines (I *think*). +var ch2 = {}; +var node_worker_1 = {}; +node_worker_1["default"] = (function (c, id, msg, transfer, cb) { + var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([ + c + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})' + ], { type: 'text/javascript' })))); + w.onmessage = function (e) { + var d = e.data, ed = d.$e$; + if (ed) { + var err = new Error(ed[0]); + err['code'] = ed[1]; + err.stack = ed[2]; + cb(err, null); + } + else + cb(null, d); + }; + w.postMessage(msg, transfer); + return w; +}); + +// aliases for shorter compressed code (most minifers don't do this) +var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array; +// fixed length extra bits +var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); +// fixed distance extra bits +var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); +// code length index map +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +// get base, reverse index map from extra bits +var freb = function (eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + // numbers here are at max 18 bits + var r = new i32(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = ((j - b[i]) << 5) | i; + } + } + return { b: b, r: r }; +}; +var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r; +// we can ignore the fact that the other numbers are wrong; they never happen anyway +fl[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r; +// map of value to reverse (assuming 16 bits) +var rev = new u16(32768); +for (var i = 0; i < 32768; ++i) { + // reverse table algorithm from SO + var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1); + x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2); + x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4); + rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1; +} +// create huffman tree from u8 "map": index -> code length for code index +// mb (max bits) must be at most 15 +// TODO: optimize/split up? +var hMap = (function (cd, mb, r) { + var s = cd.length; + // index + var i = 0; + // u16 "map": index -> # of codes with bit length = index + var l = new u16(mb); + // length of cd must be 288 (total # of codes) + for (; i < s; ++i) { + if (cd[i]) + ++l[cd[i] - 1]; + } + // u16 "map": index -> minimum code for bit length = index + var le = new u16(mb); + for (i = 1; i < mb; ++i) { + le[i] = (le[i - 1] + l[i - 1]) << 1; + } + var co; + if (r) { + // u16 "map": index -> number of actual bits, symbol for code + co = new u16(1 << mb); + // bits to remove for reverser + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + // ignore 0 lengths + if (cd[i]) { + // num encoding both symbol and bits read + var sv = (i << 4) | cd[i]; + // free bits + var r_1 = mb - cd[i]; + // start value + var v = le[cd[i] - 1]++ << r_1; + // m is end value + for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { + // every 16 bit value starting with the code yields the same result + co[rev[v] >> rvb] = sv; + } + } + } + } + else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]); + } + } + } + return co; +}); +// fixed length tree +var flt = new u8(288); +for (var i = 0; i < 144; ++i) + flt[i] = 8; +for (var i = 144; i < 256; ++i) + flt[i] = 9; +for (var i = 256; i < 280; ++i) + flt[i] = 7; +for (var i = 280; i < 288; ++i) + flt[i] = 8; +// fixed distance tree +var fdt = new u8(32); +for (var i = 0; i < 32; ++i) + fdt[i] = 5; +// fixed length map +var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); +// fixed distance map +var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); +// find max of array +var max = function (a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; +}; +// read d, starting at bit p and mask with m +var bits = function (d, p, m) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; +}; +// read d, starting at bit p continuing for at least 16 bits +var bits16 = function (d, p) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); +}; +// get end of byte +var shft = function (p) { return ((p + 7) / 8) | 0; }; +// typed array slice - allows garbage collector to free original reference, +// while being more compatible than .slice +var slc = function (v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + // can't use .constructor in case user-supplied + return new u8(v.subarray(s, e)); +}; +/** + * Codes for errors generated within this library + */ +exports.FlateErrorCode = { + UnexpectedEOF: 0, + InvalidBlockType: 1, + InvalidLengthLiteral: 2, + InvalidDistance: 3, + StreamFinished: 4, + NoStreamHandler: 5, + InvalidHeader: 6, + NoCallback: 7, + InvalidUTF8: 8, + ExtraFieldTooLong: 9, + InvalidDate: 10, + FilenameTooLong: 11, + StreamFinishing: 12, + InvalidZipData: 13, + UnknownCompressionMethod: 14 +}; +// error codes +var ec = [ + 'unexpected EOF', + 'invalid block type', + 'invalid length/literal', + 'invalid distance', + 'stream finished', + 'no stream handler', + , // determined by compression function + 'no callback', + 'invalid UTF-8 data', + 'extra field too long', + 'date not in range 1980-2099', + 'filename too long', + 'stream finishing', + 'invalid zip data' + // determined by unknown compression method +]; +; +var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; +}; +// expands raw DEFLATE data +var inflt = function (dat, st, buf, dict) { + // source length dict length + var sl = dat.length, dl = dict ? dict.length : 0; + if (!sl || st.f && !st.l) + return buf || new u8(0); + var noBuf = !buf; + // have to estimate size + var resize = noBuf || st.i != 2; + // no state + var noSt = st.i; + // Assumes roughly 33% compression ratio average + if (noBuf) + buf = new u8(sl * 3); + // ensure buffer can fit at least l elements + var cbuf = function (l) { + var bl = buf.length; + // need to increase size to fit + if (l > bl) { + // Double or set to necessary, whichever is greater + var nbuf = new u8(Math.max(bl * 2, l)); + nbuf.set(buf); + buf = nbuf; + } + }; + // last chunk bitpos bytes + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + // total bits + var tbts = sl * 8; + do { + if (!lm) { + // BFINAL - this is only 1 when last chunk is next + final = bits(dat, pos, 1); + // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + // go to end of byte boundary + var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; + if (t > sl) { + if (noSt) + err(0); + break; + } + // ensure size + if (resize) + cbuf(bt + l); + // Copy over uncompressed data + buf.set(dat.subarray(s, t), bt); + // Get new bitpos, update byte count + st.b = bt += l, st.p = pos = t * 8, st.f = final; + continue; + } + else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + // literal lengths + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + // length+distance tree + var ldt = new u8(tl); + // code length tree + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + // use index map to get real code + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + // code lengths bits + var clb = max(clt), clbmsk = (1 << clb) - 1; + // code lengths map + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl;) { + var r = clm[bits(dat, pos, clbmsk)]; + // bits read + pos += r & 15; + // symbol + var s = r >> 4; + // code length to copy + if (s < 16) { + ldt[i++] = s; + } + else { + // copy count + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + // length tree distance tree + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + // max length bits + lbt = max(lt); + // max dist bits + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } + else + err(1); + if (pos > tbts) { + if (noSt) + err(0); + break; + } + } + // Make sure the buffer can hold this + the largest possible addition + // Maximum chunk size (practically, theoretically infinite) is 2^17 + if (resize) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (;; lpos = pos) { + // bits read, code + var c = lm[bits16(dat, pos) & lms], sym = c >> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (!c) + err(2); + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } + else { + var add = sym - 254; + // no extra bits needed if less + if (sym > 264) { + // index + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + // dist + var d = dm[bits16(dat, pos) & dms], dsym = d >> 4; + if (!d) + err(3); + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & (1 << b) - 1, pos += b; + } + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (resize) + cbuf(bt + 131072); + var end = bt + add; + if (bt < dt) { + var shift = dl - dt, dend = Math.min(dt, end); + if (shift + bt < 0) + err(3); + for (; bt < dend; ++bt) + buf[bt] = dict[shift + bt]; + } + for (; bt < end; ++bt) + buf[bt] = buf[bt - dt]; + } + } + st.l = lm, st.p = lpos, st.b = bt, st.f = final; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + // don't reallocate for streams or user buffers + return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt); +}; +// starting at p, write the minimum number of bits that can hold v to d +var wbits = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; +}; +// starting at p, write the minimum number of bits (>8) that can hold v to d +var wbits16 = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; + d[o + 2] |= v >> 16; +}; +// creates code lengths from a frequency table +var hTree = function (d, mb) { + // Need extra info to make a tree + var t = []; + for (var i = 0; i < d.length; ++i) { + if (d[i]) + t.push({ s: i, f: d[i] }); + } + var s = t.length; + var t2 = t.slice(); + if (!s) + return { t: et, l: 0 }; + if (s == 1) { + var v = new u8(t[0].s + 1); + v[t[0].s] = 1; + return { t: v, l: 1 }; + } + t.sort(function (a, b) { return a.f - b.f; }); + // after i2 reaches last ind, will be stopped + // freq must be greater than largest possible number of symbols + t.push({ s: -1, f: 25001 }); + var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; + t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; + // efficient algorithm from UZIP.js + // i0 is lookbehind, i2 is lookahead - after processing two low-freq + // symbols that combined have high freq, will start processing i2 (high-freq, + // non-composite) symbols instead + // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ + while (i1 != s - 1) { + l = t[t[i0].f < t[i2].f ? i0++ : i2++]; + r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; + t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; + } + var maxSym = t2[0].s; + for (var i = 1; i < s; ++i) { + if (t2[i].s > maxSym) + maxSym = t2[i].s; + } + // code lengths + var tr = new u16(maxSym + 1); + // max bits in tree + var mbt = ln(t[i1 - 1], tr, 0); + if (mbt > mb) { + // more algorithms from UZIP.js + // TODO: find out how this code works (debt) + // ind debt + var i = 0, dt = 0; + // left cost + var lft = mbt - mb, cst = 1 << lft; + t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); + for (; i < s; ++i) { + var i2_1 = t2[i].s; + if (tr[i2_1] > mb) { + dt += cst - (1 << (mbt - tr[i2_1])); + tr[i2_1] = mb; + } + else + break; + } + dt >>= lft; + while (dt > 0) { + var i2_2 = t2[i].s; + if (tr[i2_2] < mb) + dt -= 1 << (mb - tr[i2_2]++ - 1); + else + ++i; + } + for (; i >= 0 && dt; --i) { + var i2_3 = t2[i].s; + if (tr[i2_3] == mb) { + --tr[i2_3]; + ++dt; + } + } + mbt = mb; + } + return { t: new u8(tr), l: mbt }; +}; +// get the max length and assign length codes +var ln = function (n, l, d) { + return n.s == -1 + ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) + : (l[n.s] = d); +}; +// length codes generation +var lc = function (c) { + var s = c.length; + // Note that the semicolon was intentional + while (s && !c[--s]) + ; + var cl = new u16(++s); + // ind num streak + var cli = 0, cln = c[0], cls = 1; + var w = function (v) { cl[cli++] = v; }; + for (var i = 1; i <= s; ++i) { + if (c[i] == cln && i != s) + ++cls; + else { + if (!cln && cls > 2) { + for (; cls > 138; cls -= 138) + w(32754); + if (cls > 2) { + w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); + cls = 0; + } + } + else if (cls > 3) { + w(cln), --cls; + for (; cls > 6; cls -= 6) + w(8304); + if (cls > 2) + w(((cls - 3) << 5) | 8208), cls = 0; + } + while (cls--) + w(cln); + cls = 1; + cln = c[i]; + } + } + return { c: cl.subarray(0, cli), n: s }; +}; +// calculate the length of output from tree, code lengths +var clen = function (cf, cl) { + var l = 0; + for (var i = 0; i < cl.length; ++i) + l += cf[i] * cl[i]; + return l; +}; +// writes a fixed block +// returns the new bit pos +var wfblk = function (out, pos, dat) { + // no need to write 00 as type: TypedArray defaults to 0 + var s = dat.length; + var o = shft(pos + 2); + out[o] = s & 255; + out[o + 1] = s >> 8; + out[o + 2] = out[o] ^ 255; + out[o + 3] = out[o + 1] ^ 255; + for (var i = 0; i < s; ++i) + out[o + i + 4] = dat[i]; + return (o + 4 + s) * 8; +}; +// writes a block +var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { + wbits(out, p++, final); + ++lf[256]; + var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l; + var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l; + var _c = lc(dlt), lclt = _c.c, nlc = _c.n; + var _d = lc(ddt), lcdt = _d.c, ndc = _d.n; + var lcfreq = new u16(19); + for (var i = 0; i < lclt.length; ++i) + ++lcfreq[lclt[i] & 31]; + for (var i = 0; i < lcdt.length; ++i) + ++lcfreq[lcdt[i] & 31]; + var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l; + var nlcc = 19; + for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) + ; + var flen = (bl + 5) << 3; + var ftlen = clen(lf, flt) + clen(df, fdt) + eb; + var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]; + if (bs >= 0 && flen <= ftlen && flen <= dtlen) + return wfblk(out, p, dat.subarray(bs, bs + bl)); + var lm, ll, dm, dl; + wbits(out, p, 1 + (dtlen < ftlen)), p += 2; + if (dtlen < ftlen) { + lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; + var llm = hMap(lct, mlcb, 0); + wbits(out, p, nlc - 257); + wbits(out, p + 5, ndc - 1); + wbits(out, p + 10, nlcc - 4); + p += 14; + for (var i = 0; i < nlcc; ++i) + wbits(out, p + 3 * i, lct[clim[i]]); + p += 3 * nlcc; + var lcts = [lclt, lcdt]; + for (var it = 0; it < 2; ++it) { + var clct = lcts[it]; + for (var i = 0; i < clct.length; ++i) { + var len = clct[i] & 31; + wbits(out, p, llm[len]), p += lct[len]; + if (len > 15) + wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12; + } + } + } + else { + lm = flm, ll = flt, dm = fdm, dl = fdt; + } + for (var i = 0; i < li; ++i) { + var sym = syms[i]; + if (sym > 255) { + var len = (sym >> 18) & 31; + wbits16(out, p, lm[len + 257]), p += ll[len + 257]; + if (len > 7) + wbits(out, p, (sym >> 23) & 31), p += fleb[len]; + var dst = sym & 31; + wbits16(out, p, dm[dst]), p += dl[dst]; + if (dst > 3) + wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst]; + } + else { + wbits16(out, p, lm[sym]), p += ll[sym]; + } + } + wbits16(out, p, lm[256]); + return p + ll[256]; +}; +// deflate options (nice << 13) | chain +var deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); +// empty +var et = /*#__PURE__*/ new u8(0); +// compresses data into a raw DEFLATE buffer +var dflt = function (dat, lvl, plvl, pre, post, st) { + var s = st.z || dat.length; + var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); + // writing to this writes to the output buffer + var w = o.subarray(pre, o.length - post); + var lst = st.l; + var pos = (st.r || 0) & 7; + if (lvl) { + if (pos) + w[0] = st.r >> 3; + var opt = deo[lvl - 1]; + var n = opt >> 13, c = opt & 8191; + var msk_1 = (1 << plvl) - 1; + // prev 2-byte val map curr 2-byte val map + var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1); + var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; + var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; + // 24576 is an arbitrary number of maximum symbols per block + // 424 buffer for last block + var syms = new i32(25000); + // length/literal freq distance freq + var lf = new u16(288), df = new u16(32); + // l/lcnt exbits index l/lind waitdx blkpos + var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0; + for (; i + 2 < s; ++i) { + // hash value + var hv = hsh(i); + // index mod 32768 previous index mod + var imod = i & 32767, pimod = head[hv]; + prev[imod] = pimod; + head[hv] = imod; + // We always should modify head and prev, but only add symbols if + // this data is not yet processed ("wait" for wait index) + if (wi <= i) { + // bytes remaining + var rem = s - i; + if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) { + pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); + li = lc_1 = eb = 0, bs = i; + for (var j = 0; j < 286; ++j) + lf[j] = 0; + for (var j = 0; j < 30; ++j) + df[j] = 0; + } + // len dist chain + var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767; + if (rem > 2 && hv == hsh(i - dif)) { + var maxn = Math.min(n, rem) - 1; + var maxd = Math.min(32767, i); + // max possible length + // not capped at dif because decompressors implement "rolling" index population + var ml = Math.min(258, rem); + while (dif <= maxd && --ch_1 && imod != pimod) { + if (dat[i + l] == dat[i + l - dif]) { + var nl = 0; + for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) + ; + if (nl > l) { + l = nl, d = dif; + // break out early when we reach "nice" (we are satisfied enough) + if (nl > maxn) + break; + // now, find the rarest 2-byte sequence within this + // length of literals and search for that instead. + // Much faster than just using the start + var mmd = Math.min(dif, nl - 2); + var md = 0; + for (var j = 0; j < mmd; ++j) { + var ti = i - dif + j & 32767; + var pti = prev[ti]; + var cd = ti - pti & 32767; + if (cd > md) + md = cd, pimod = ti; + } + } + } + // check the previous match + imod = pimod, pimod = prev[imod]; + dif += imod - pimod & 32767; + } + } + // d will be nonzero only when a match was found + if (d) { + // store both dist and len data in one int32 + // Make sure this is recognized as a len/dist with 28th bit (2^28) + syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; + var lin = revfl[l] & 31, din = revfd[d] & 31; + eb += fleb[lin] + fdeb[din]; + ++lf[257 + lin]; + ++df[din]; + wi = i + l; + ++lc_1; + } + else { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + } + } + for (i = Math.max(i, wi); i < s; ++i) { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); + if (!lst) { + st.r = (pos & 7) | w[(pos / 8) | 0] << 3; + // shft(pos) now 1 less if pos & 7 != 0 + pos -= 7; + st.h = head, st.p = prev, st.i = i, st.w = wi; + } + } + else { + for (var i = st.w || 0; i < s + lst; i += 65535) { + // end + var e = i + 65535; + if (e >= s) { + // write final block + w[(pos / 8) | 0] = lst; + e = s; + } + pos = wfblk(w, pos + 1, dat.subarray(i, e)); + } + st.i = s; + } + return slc(o, 0, pre + shft(pos) + post); +}; +// CRC32 table +var crct = /*#__PURE__*/ (function () { + var t = new Int32Array(256); + for (var i = 0; i < 256; ++i) { + var c = i, k = 9; + while (--k) + c = ((c & 1) && -306674912) ^ (c >>> 1); + t[i] = c; + } + return t; +})(); +// CRC32 +var crc = function () { + var c = -1; + return { + p: function (d) { + // closures have awful performance + var cr = c; + for (var i = 0; i < d.length; ++i) + cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8); + c = cr; + }, + d: function () { return ~c; } + }; +}; +// Adler32 +var adler = function () { + var a = 1, b = 0; + return { + p: function (d) { + // closures have awful performance + var n = a, m = b; + var l = d.length | 0; + for (var i = 0; i != l;) { + var e = Math.min(i + 2655, l); + for (; i < e; ++i) + m += n += d[i]; + n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); + } + a = n, b = m; + }, + d: function () { + a %= 65521, b %= 65521; + return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8); + } + }; +}; +; +// deflate with opts +var dopt = function (dat, opt, pre, post, st) { + if (!st) { + st = { l: 1 }; + if (opt.dictionary) { + var dict = opt.dictionary.subarray(-32768); + var newDat = new u8(dict.length + dat.length); + newDat.set(dict); + newDat.set(dat, dict.length); + dat = newDat; + st.w = dict.length; + } + } + return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st); +}; +// Walmart object spread +var mrg = function (a, b) { + var o = {}; + for (var k in a) + o[k] = a[k]; + for (var k in b) + o[k] = b[k]; + return o; +}; +// worker clone +// This is possibly the craziest part of the entire codebase, despite how simple it may seem. +// The only parameter to this function is a closure that returns an array of variables outside of the function scope. +// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization. +// We will return an object mapping of true variable name to value (basically, the current scope as a JS object). +// The reason we can't just use the original variable names is minifiers mangling the toplevel scope. +// This took me three weeks to figure out how to do. +var wcln = function (fn, fnStr, td) { + var dt = fn(); + var st = fn.toString(); + var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(','); + for (var i = 0; i < dt.length; ++i) { + var v = dt[i], k = ks[i]; + if (typeof v == 'function') { + fnStr += ';' + k + '='; + var st_1 = v.toString(); + if (v.prototype) { + // for global objects + if (st_1.indexOf('[native code]') != -1) { + var spInd = st_1.indexOf(' ', 8) + 1; + fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd)); + } + else { + fnStr += st_1; + for (var t in v.prototype) + fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString(); + } + } + else + fnStr += st_1; + } + else + td[k] = v; + } + return fnStr; +}; +var ch = []; +// clone bufs +var cbfs = function (v) { + var tl = []; + for (var k in v) { + if (v[k].buffer) { + tl.push((v[k] = new v[k].constructor(v[k])).buffer); + } + } + return tl; +}; +// use a worker to execute code +var wrkr = function (fns, init, id, cb) { + if (!ch[id]) { + var fnStr = '', td_1 = {}, m = fns.length - 1; + for (var i = 0; i < m; ++i) + fnStr = wcln(fns[i], fnStr, td_1); + ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 }; + } + var td = mrg({}, ch[id].e); + return (0, node_worker_1.default)(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb); +}; +// base async inflate fn +var bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; }; +var bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; }; +// gzip extra +var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; }; +// gunzip extra +var guze = function () { return [gzs, gzl]; }; +// zlib extra +var zle = function () { return [zlh, wbytes, adler]; }; +// unzlib extra +var zule = function () { return [zls]; }; +// post buf +var pbf = function (msg) { return postMessage(msg, [msg.buffer]); }; +// get opts +var gopt = function (o) { return o && { + out: o.size && new u8(o.size), + dictionary: o.dictionary +}; }; +// async helper +var cbify = function (dat, opts, fns, init, id, cb) { + var w = wrkr(fns, init, id, function (err, dat) { + w.terminate(); + cb(err, dat); + }); + w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []); + return function () { w.terminate(); }; +}; +// auto stream +var astrm = function (strm) { + strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); }; + return function (ev) { + if (ev.data[0]) { + strm.push(ev.data[0], ev.data[1]); + postMessage([ev.data[0].length]); + } + else + strm.flush(ev.data[1]); + }; +}; +// async stream attach +var astrmify = function (fns, strm, opts, init, id, flush, ext) { + var t; + var w = wrkr(fns, init, id, function (err, dat) { + if (err) + w.terminate(), strm.ondata.call(strm, err); + else if (!Array.isArray(dat)) + ext(dat); + else if (dat.length == 1) { + strm.queuedSize -= dat[0]; + if (strm.ondrain) + strm.ondrain(dat[0]); + } + else { + if (dat[1]) + w.terminate(); + strm.ondata.call(strm, err, dat[0], dat[1]); + } + }); + w.postMessage(opts); + strm.queuedSize = 0; + strm.push = function (d, f) { + if (!strm.ondata) + err(5); + if (t) + strm.ondata(err(4, 0, 1), null, !!f); + strm.queuedSize += d.length; + // can fail for cross-realm Uint8Array, but ok - only a small performance penalty + w.postMessage([d, t = f], d.buffer instanceof ArrayBuffer ? [d.buffer] : []); + }; + strm.terminate = function () { w.terminate(); }; + if (flush) { + strm.flush = function (sync) { w.postMessage([0, sync]); }; + } +}; +// read 2 bytes +var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); }; +// read 4 bytes +var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; }; +// read 8 bytes +var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); }; +// write bytes +var wbytes = function (d, b, v) { + for (; v; ++b) + d[b] = v, v >>>= 8; +}; +// gzip header +var gzh = function (c, o) { + var fn = o.filename; + c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix + if (o.mtime != 0) + wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000)); + if (fn) { + c[3] = 8; + for (var i = 0; i <= fn.length; ++i) + c[i + 10] = fn.charCodeAt(i); + } +}; +// gzip footer: -8 to -4 = CRC, -4 to -0 is length +// gzip start +var gzs = function (d) { + if (d[0] != 31 || d[1] != 139 || d[2] != 8) + err(6, 'invalid gzip data'); + var flg = d[3]; + var st = 10; + if (flg & 4) + st += (d[10] | d[11] << 8) + 2; + for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]) + ; + return st + (flg & 2); +}; +// gzip length +var gzl = function (d) { + var l = d.length; + return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0; +}; +// gzip header length +var gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); }; +// zlib header +var zlh = function (c, o) { + var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; + c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32); + c[1] |= 31 - ((c[0] << 8) | c[1]) % 31; + if (o.dictionary) { + var h = adler(); + h.p(o.dictionary); + wbytes(c, 2, h.d()); + } +}; +// zlib start +var zls = function (d, dict) { + if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31)) + err(6, 'invalid zlib data'); + if ((d[1] >> 5 & 1) == +!dict) + err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary'); + return (d[1] >> 3 & 4) + 2; +}; +function StrmOpt(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + return opts; +} +/** + * Streaming DEFLATE compression + */ +var Deflate = /*#__PURE__*/ (function () { + function Deflate(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + this.o = opts || {}; + this.s = { l: 0, i: 32768, w: 32768, z: 32768 }; + // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev + // 98304 = 32768 (lookback) + 65536 (common chunk size) + this.b = new u8(98304); + if (this.o.dictionary) { + var dict = this.o.dictionary.subarray(-32768); + this.b.set(dict, 32768 - dict.length); + this.s.i = 32768 - dict.length; + } + } + Deflate.prototype.p = function (c, f) { + this.ondata(dopt(c, this.o, 0, 0, this.s), f); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Deflate.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + var endLen = chunk.length + this.s.z; + if (endLen > this.b.length) { + if (endLen > 2 * this.b.length - 32768) { + var newBuf = new u8(endLen & -32768); + newBuf.set(this.b.subarray(0, this.s.z)); + this.b = newBuf; + } + var split = this.b.length - this.s.z; + this.b.set(chunk.subarray(0, split), this.s.z); + this.s.z = this.b.length; + this.p(this.b, false); + this.b.set(this.b.subarray(-32768)); + this.b.set(chunk.subarray(split), 32768); + this.s.z = chunk.length - split + 32768; + this.s.i = 32766, this.s.w = 32768; + } + else { + this.b.set(chunk, this.s.z); + this.s.z += chunk.length; + } + this.s.l = final & 1; + if (this.s.z > this.s.w + 8191 || final) { + this.p(this.b, final || false); + this.s.w = this.s.i, this.s.i -= 2; + } + if (final) { + // cleanup unneeded buffers/state to reduce memory usage + this.s = this.o = {}; + this.b = et; + } + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + Deflate.prototype.flush = function (sync) { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + this.p(this.b, false); + this.s.w = this.s.i, this.s.i -= 2; + // could technically skip writing the type-0 block for (this.s.r & 7) == 0, + // but the deterministic trailer (00 00 FF FF) is useful in some situations + if (sync) { + var c = new u8(6); + c[0] = this.s.r >> 3; + // write empty, non-final type-0 block + var ep = wfblk(c, this.s.r, et); + this.s.r = 0; + this.ondata(c.subarray(0, ep >> 3), false); + } + }; + return Deflate; +}()); +exports.Deflate = Deflate; +/** + * Asynchronous streaming DEFLATE compression + */ +var AsyncDeflate = /*#__PURE__*/ (function () { + function AsyncDeflate(opts, cb) { + astrmify([ + bDflt, + function () { return [astrm, Deflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Deflate(ev.data); + onmessage = astrm(strm); + }, 6, 1); + } + return AsyncDeflate; +}()); +exports.AsyncDeflate = AsyncDeflate; +function deflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb); +} +/** + * Compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @returns The deflated version of the data + */ +function deflateSync(data, opts) { + return dopt(data, opts || {}, 0, 0); +} +/** + * Streaming DEFLATE decompression + */ +var Inflate = /*#__PURE__*/ (function () { + function Inflate(opts, cb) { + // no StrmOpt here to avoid adding to workerizer + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768); + this.s = { i: 0, b: dict ? dict.length : 0 }; + this.o = new u8(32768); + this.p = new u8(0); + if (dict) + this.o.set(dict); + } + Inflate.prototype.e = function (c) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + if (!this.p.length) + this.p = c; + else if (c.length) { + var n = new u8(this.p.length + c.length); + n.set(this.p), n.set(c, this.p.length), this.p = n; + } + }; + Inflate.prototype.c = function (final) { + this.s.i = +(this.d = final || false); + var bts = this.s.b; + var dt = inflt(this.p, this.s, this.o); + this.ondata(slc(dt, bts, this.s.b), this.d); + this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; + this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; + }; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + Inflate.prototype.push = function (chunk, final) { + this.e(chunk), this.c(final); + }; + return Inflate; +}()); +exports.Inflate = Inflate; +/** + * Asynchronous streaming DEFLATE decompression + */ +var AsyncInflate = /*#__PURE__*/ (function () { + function AsyncInflate(opts, cb) { + astrmify([ + bInflt, + function () { return [astrm, Inflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Inflate(ev.data); + onmessage = astrm(strm); + }, 7, 0); + } + return AsyncInflate; +}()); +exports.AsyncInflate = AsyncInflate; +function inflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt + ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb); +} +function inflateSync(data, opts) { + return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize. +/** + * Streaming GZIP compression + */ +var Gzip = /*#__PURE__*/ (function () { + function Gzip(opts, cb) { + this.c = crc(); + this.l = 0; + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gzip.prototype.push = function (chunk, final) { + this.c.p(chunk); + this.l += chunk.length; + Deflate.prototype.push.call(this, chunk, final); + }; + Gzip.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s); + if (this.v) + gzh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + Gzip.prototype.flush = function (sync) { + Deflate.prototype.flush.call(this, sync); + }; + return Gzip; +}()); +exports.Gzip = Gzip; +exports.Compress = Gzip; +/** + * Asynchronous streaming GZIP compression + */ +var AsyncGzip = /*#__PURE__*/ (function () { + function AsyncGzip(opts, cb) { + astrmify([ + bDflt, + gze, + function () { return [astrm, Deflate, Gzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gzip(ev.data); + onmessage = astrm(strm); + }, 8, 1); + } + return AsyncGzip; +}()); +exports.AsyncGzip = AsyncGzip; +exports.AsyncCompress = AsyncGzip; +function gzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + gze, + function () { return [gzipSync]; } + ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb); +} +/** + * Compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @returns The gzipped version of the data + */ +function gzipSync(data, opts) { + if (!opts) + opts = {}; + var c = crc(), l = data.length; + c.p(data); + var d = dopt(data, opts, gzhl(opts), 8), s = d.length; + return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d; +} +/** + * Streaming single or multi-member GZIP decompression + */ +var Gunzip = /*#__PURE__*/ (function () { + function Gunzip(opts, cb) { + this.v = 1; + this.r = 0; + Inflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gunzip.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + this.r += chunk.length; + if (this.v) { + var p = this.p.subarray(this.v - 1); + var s = p.length > 3 ? gzs(p) : 4; + if (s > p.length) { + if (!final) + return; + } + else if (this.v > 1 && this.onmember) { + this.onmember(this.r - p.length); + } + this.p = p.subarray(s), this.v = 0; + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, 0); + // process concatenated GZIP + if (this.s.f && !this.s.l) { + this.v = shft(this.s.p) + 9; + this.s = { i: 0 }; + this.o = new u8(0); + this.push(new u8(0), final); + } + else if (final) { + Inflate.prototype.c.call(this, final); + } + }; + return Gunzip; +}()); +exports.Gunzip = Gunzip; +/** + * Asynchronous streaming single or multi-member GZIP decompression + */ +var AsyncGunzip = /*#__PURE__*/ (function () { + function AsyncGunzip(opts, cb) { + var _this = this; + astrmify([ + bInflt, + guze, + function () { return [astrm, Inflate, Gunzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gunzip(ev.data); + strm.onmember = function (offset) { return postMessage(offset); }; + onmessage = astrm(strm); + }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); }); + } + return AsyncGunzip; +}()); +exports.AsyncGunzip = AsyncGunzip; +function gunzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + guze, + function () { return [gunzipSync]; } + ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb); +} +function gunzipSync(data, opts) { + var st = gzs(data); + if (st + 8 > data.length) + err(6, 'invalid gzip data'); + return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary); +} +/** + * Streaming Zlib compression + */ +var Zlib = /*#__PURE__*/ (function () { + function Zlib(opts, cb) { + this.c = adler(); + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Zlib.prototype.push = function (chunk, final) { + this.c.p(chunk); + Deflate.prototype.push.call(this, chunk, final); + }; + Zlib.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s); + if (this.v) + zlh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 4, this.c.d()); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + Zlib.prototype.flush = function (sync) { + Deflate.prototype.flush.call(this, sync); + }; + return Zlib; +}()); +exports.Zlib = Zlib; +/** + * Asynchronous streaming Zlib compression + */ +var AsyncZlib = /*#__PURE__*/ (function () { + function AsyncZlib(opts, cb) { + astrmify([ + bDflt, + zle, + function () { return [astrm, Deflate, Zlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Zlib(ev.data); + onmessage = astrm(strm); + }, 10, 1); + } + return AsyncZlib; +}()); +exports.AsyncZlib = AsyncZlib; +function zlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + zle, + function () { return [zlibSync]; } + ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb); +} +/** + * Compress data with Zlib + * @param data The data to compress + * @param opts The compression options + * @returns The zlib-compressed version of the data + */ +function zlibSync(data, opts) { + if (!opts) + opts = {}; + var a = adler(); + a.p(data); + var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4); + return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d; +} +/** + * Streaming Zlib decompression + */ +var Unzlib = /*#__PURE__*/ (function () { + function Unzlib(opts, cb) { + Inflate.call(this, opts, cb); + this.v = opts && opts.dictionary ? 2 : 1; + } + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzlib.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + if (this.v) { + if (this.p.length < 6 && !final) + return; + this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0; + } + if (final) { + if (this.p.length < 4) + err(6, 'invalid zlib data'); + this.p = this.p.subarray(0, -4); + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + }; + return Unzlib; +}()); +exports.Unzlib = Unzlib; +/** + * Asynchronous streaming Zlib decompression + */ +var AsyncUnzlib = /*#__PURE__*/ (function () { + function AsyncUnzlib(opts, cb) { + astrmify([ + bInflt, + zule, + function () { return [astrm, Inflate, Unzlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Unzlib(ev.data); + onmessage = astrm(strm); + }, 11, 0); + } + return AsyncUnzlib; +}()); +exports.AsyncUnzlib = AsyncUnzlib; +function unzlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + zule, + function () { return [unzlibSync]; } + ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb); +} +function unzlibSync(data, opts) { + return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +/** + * Streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var Decompress = /*#__PURE__*/ (function () { + function Decompress(opts, cb) { + this.o = StrmOpt.call(this, opts, cb) || {}; + this.G = Gunzip; + this.I = Inflate; + this.Z = Unzlib; + } + // init substream + // overriden by AsyncDecompress + Decompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (dat, final) { + _this.ondata(dat, final); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Decompress.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (!this.s) { + if (this.p && this.p.length) { + var n = new u8(this.p.length + chunk.length); + n.set(this.p), n.set(chunk, this.p.length); + } + else + this.p = chunk; + if (this.p.length > 2) { + this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8) + ? new this.G(this.o) + : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31)) + ? new this.I(this.o) + : new this.Z(this.o); + this.i(); + this.s.push(this.p, final); + this.p = null; + } + } + else + this.s.push(chunk, final); + }; + return Decompress; +}()); +exports.Decompress = Decompress; +/** + * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var AsyncDecompress = /*#__PURE__*/ (function () { + function AsyncDecompress(opts, cb) { + Decompress.call(this, opts, cb); + this.queuedSize = 0; + this.G = AsyncGunzip; + this.I = AsyncInflate; + this.Z = AsyncUnzlib; + } + AsyncDecompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (err, dat, final) { + _this.ondata(err, dat, final); + }; + this.s.ondrain = function (size) { + _this.queuedSize -= size; + if (_this.ondrain) + _this.ondrain(size); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncDecompress.prototype.push = function (chunk, final) { + this.queuedSize += chunk.length; + Decompress.prototype.push.call(this, chunk, final); + }; + return AsyncDecompress; +}()); +exports.AsyncDecompress = AsyncDecompress; +function decompress(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzip(data, opts, cb) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflate(data, opts, cb) + : unzlib(data, opts, cb); +} +/** + * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +function decompressSync(data, opts) { + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzipSync(data, opts) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflateSync(data, opts) + : unzlibSync(data, opts); +} +// flatten a directory structure +var fltn = function (d, p, t, o) { + for (var k in d) { + var val = d[k], n = p + k, op = o; + if (Array.isArray(val)) + op = mrg(o, val[1]), val = val[0]; + if (ArrayBuffer.isView(val)) + t[n] = [val, op]; + else { + t[n += '/'] = [new u8(0), op]; + fltn(val, n, t, o); + } + } +}; +// text encoder +var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder(); +// text decoder +var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); +// text decoder stream +var tds = 0; +try { + td.decode(et, { stream: true }); + tds = 1; +} +catch (e) { } +// decode UTF8 +var dutf8 = function (d) { + for (var r = '', i = 0;;) { + var c = d[i++]; + var eb = (c > 127) + (c > 223) + (c > 239); + if (i + eb > d.length) + return { s: r, r: slc(d, i - 1) }; + if (!eb) + r += String.fromCharCode(c); + else if (eb == 3) { + c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536, + r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023)); + } + else if (eb & 1) + r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63)); + else + r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)); + } +}; +/** + * Streaming UTF-8 decoding + */ +var DecodeUTF8 = /*#__PURE__*/ (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is decoded + */ + function DecodeUTF8(cb) { + this.ondata = cb; + if (tds) + this.t = new TextDecoder(); + else + this.p = et; + } + /** + * Pushes a chunk to be decoded from UTF-8 binary + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + DecodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + final = !!final; + if (this.t) { + this.ondata(this.t.decode(chunk, { stream: true }), final); + if (final) { + if (this.t.decode().length) + err(8); + this.t = null; + } + return; + } + if (!this.p) + err(4); + var dat = new u8(this.p.length + chunk.length); + dat.set(this.p); + dat.set(chunk, this.p.length); + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (final) { + if (r.length) + err(8); + this.p = null; + } + else + this.p = r; + this.ondata(s, final); + }; + return DecodeUTF8; +}()); +exports.DecodeUTF8 = DecodeUTF8; +/** + * Streaming UTF-8 encoding + */ +var EncodeUTF8 = /*#__PURE__*/ (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is encoded + */ + function EncodeUTF8(cb) { + this.ondata = cb; + } + /** + * Pushes a chunk to be encoded to UTF-8 + * @param chunk The string data to push + * @param final Whether this is the last chunk + */ + EncodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + this.ondata(strToU8(chunk), this.d = final || false); + }; + return EncodeUTF8; +}()); +exports.EncodeUTF8 = EncodeUTF8; +/** + * Converts a string into a Uint8Array for use with compression/decompression methods + * @param str The string to encode + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless decoding a binary string. + * @returns The string encoded in UTF-8/Latin-1 binary + */ +function strToU8(str, latin1) { + if (latin1) { + var ar_1 = new u8(str.length); + for (var i = 0; i < str.length; ++i) + ar_1[i] = str.charCodeAt(i); + return ar_1; + } + if (te) + return te.encode(str); + var l = str.length; + var ar = new u8(str.length + (str.length >> 1)); + var ai = 0; + var w = function (v) { ar[ai++] = v; }; + for (var i = 0; i < l; ++i) { + if (ai + 5 > ar.length) { + var n = new u8(ai + 8 + ((l - i) << 1)); + n.set(ar); + ar = n; + } + var c = str.charCodeAt(i); + if (c < 128 || latin1) + w(c); + else if (c < 2048) + w(192 | (c >> 6)), w(128 | (c & 63)); + else if (c > 55295 && c < 57344) + c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023), + w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + else + w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + } + return slc(ar, 0, ai); +} +/** + * Converts a Uint8Array to a string + * @param dat The data to decode to string + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless encoding to binary string. + * @returns The original UTF-8/Latin-1 string + */ +function strFromU8(dat, latin1) { + if (latin1) { + var r = ''; + for (var i = 0; i < dat.length; i += 16384) + r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384)); + return r; + } + else if (td) { + return td.decode(dat); + } + else { + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (r.length) + err(8); + return s; + } +} +; +// deflate bit flag +var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; }; +// skip local zip header +var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); }; +// read zip header +var zh = function (d, b, z) { + var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl; + var _a = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a[0], su = _a[1], off = _a[2]; + return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off]; +}; +// read zip64 header sizes +var z64hs = function (d, b, l, z, sc, su, off) { + var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l; + var nf = nsc + nsu + noff; + if (z && nf) { + for (; b + 4 < e; b += 4 + b2(d, b + 2)) { + if (b2(d, b) == 1) { + return [ + nsc ? b8(d, b + 4 + 8 * nsu) : sc, + nsu ? b8(d, b + 4) : su, + noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off, + 1 + ]; + } + } + // z == 2 for unknown whether or not zip64 + if (z < 2) + err(13); + } + return [sc, su, off, 0]; +}; +// extra field length +var exfl = function (ex) { + var le = 0; + if (ex) { + for (var k in ex) { + var l = ex[k].length; + if (l > 65535) + err(9); + le += l + 4; + } + } + return le; +}; +// write zip header +var wzh = function (d, b, f, fn, u, c, ce, co) { + var fl = fn.length, ex = f.extra, col = co && co.length; + var exl = exfl(ex); + wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4; + if (ce != null) + d[b++] = 20, d[b++] = f.os; + d[b] = 20, b += 2; // spec compliance? what's that? + d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8; + d[b++] = f.compression & 255, d[b++] = f.compression >> 8; + var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980; + if (y < 0 || y > 119) + err(10); + wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4; + if (c != -1) { + wbytes(d, b, f.crc); + wbytes(d, b + 4, c < 0 ? -c - 2 : c); + wbytes(d, b + 8, f.size); + } + wbytes(d, b + 12, fl); + wbytes(d, b + 14, exl), b += 16; + if (ce != null) { + wbytes(d, b, col); + wbytes(d, b + 6, f.attrs); + wbytes(d, b + 10, ce), b += 14; + } + d.set(fn, b); + b += fl; + if (exl) { + for (var k in ex) { + var exf = ex[k], l = exf.length; + wbytes(d, b, +k); + wbytes(d, b + 2, l); + d.set(exf, b + 4), b += 4 + l; + } + } + if (col) + d.set(co, b), b += col; + return b; +}; +// write zip footer (end of central directory) +var wzf = function (o, b, c, d, e) { + wbytes(o, b, 0x6054B50); // skip disk + wbytes(o, b + 8, c); + wbytes(o, b + 10, c); + wbytes(o, b + 12, d); + wbytes(o, b + 16, e); +}; +/** + * A pass-through stream to keep data uncompressed in a ZIP archive. + */ +var ZipPassThrough = /*#__PURE__*/ (function () { + /** + * Creates a pass-through stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + */ + function ZipPassThrough(filename) { + this.filename = filename; + this.c = crc(); + this.size = 0; + this.compression = 0; + } + /** + * Processes a chunk and pushes to the output stream. You can override this + * method in a subclass for custom behavior, but by default this passes + * the data through. You must call this.ondata(err, chunk, final) at some + * point in this method. + * @param chunk The chunk to process + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.process = function (chunk, final) { + this.ondata(null, chunk, final); + }; + /** + * Pushes a chunk to be added. If you are subclassing this with a custom + * compression algorithm, note that you must push data from the source + * file only, pre-compression. + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + this.c.p(chunk); + this.size += chunk.length; + if (final) + this.crc = this.c.d(); + // we shouldn't really do this cast, but properly handling ArrayBufferLike + // makes the API unergonomic with Buffer + this.process(chunk, final || false); + }; + return ZipPassThrough; +}()); +exports.ZipPassThrough = ZipPassThrough; +// I don't extend because TypeScript extension adds 1kB of runtime bloat +/** + * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate + * for better performance + */ +var ZipDeflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function ZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new Deflate(opts, function (dat, final) { + _this.ondata(null, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + } + ZipDeflate.prototype.process = function (chunk, final) { + try { + this.d.push(chunk, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return ZipDeflate; +}()); +exports.ZipDeflate = ZipDeflate; +/** + * Asynchronous streaming DEFLATE compression for ZIP archives + */ +var AsyncZipDeflate = /*#__PURE__*/ (function () { + /** + * Creates an asynchronous DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function AsyncZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new AsyncDeflate(opts, function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + this.terminate = this.d.terminate; + } + AsyncZipDeflate.prototype.process = function (chunk, final) { + this.d.push(chunk, final); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return AsyncZipDeflate; +}()); +exports.AsyncZipDeflate = AsyncZipDeflate; +// TODO: Better tree shaking +/** + * A zippable archive to which files can incrementally be added + */ +var Zip = /*#__PURE__*/ (function () { + /** + * Creates an empty ZIP archive to which files can be added + * @param cb The callback to call whenever data for the generated ZIP archive + * is available + */ + function Zip(cb) { + this.ondata = cb; + this.u = []; + this.d = 1; + } + /** + * Adds a file to the ZIP archive + * @param file The file stream to add + */ + Zip.prototype.add = function (file) { + var _this = this; + if (!this.ondata) + err(5); + // finishing or finished + if (this.d & 2) + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false); + else { + var f = strToU8(file.filename), fl_1 = f.length; + var com = file.comment, o = com && strToU8(com); + var u = fl_1 != file.filename.length || (o && (com.length != o.length)); + var hl_1 = fl_1 + exfl(file.extra) + 30; + if (fl_1 > 65535) + this.ondata(err(11, 0, 1), null, false); + var header = new u8(hl_1); + wzh(header, 0, file, f, u, -1); + var chks_1 = [header]; + var pAll_1 = function () { + for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) { + var chk = chks_2[_i]; + _this.ondata(null, chk, false); + } + chks_1 = []; + }; + var tr_1 = this.d; + this.d = 0; + var ind_1 = this.u.length; + var uf_1 = mrg(file, { + f: f, + u: u, + o: o, + t: function () { + if (file.terminate) + file.terminate(); + }, + r: function () { + pAll_1(); + if (tr_1) { + var nxt = _this.u[ind_1 + 1]; + if (nxt) + nxt.r(); + else + _this.d = 1; + } + tr_1 = 1; + } + }); + var cl_1 = 0; + file.ondata = function (err, dat, final) { + if (err) { + _this.ondata(err, dat, final); + _this.terminate(); + } + else { + cl_1 += dat.length; + chks_1.push(dat); + if (final) { + var dd = new u8(16); + wbytes(dd, 0, 0x8074B50); + wbytes(dd, 4, file.crc); + wbytes(dd, 8, cl_1); + wbytes(dd, 12, file.size); + chks_1.push(dd); + uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size; + if (tr_1) + uf_1.r(); + tr_1 = 1; + } + else if (tr_1) + pAll_1(); + } + }; + this.u.push(uf_1); + } + }; + /** + * Ends the process of adding files and prepares to emit the final chunks. + * This *must* be called after adding all desired files for the resulting + * ZIP file to work properly. + */ + Zip.prototype.end = function () { + var _this = this; + if (this.d & 2) { + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true); + return; + } + if (this.d) + this.e(); + else + this.u.push({ + r: function () { + if (!(_this.d & 1)) + return; + _this.u.splice(-1, 1); + _this.e(); + }, + t: function () { } + }); + this.d = 3; + }; + Zip.prototype.e = function () { + var bt = 0, l = 0, tl = 0; + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0); + } + var out = new u8(tl + 22); + for (var _b = 0, _c = this.u; _b < _c.length; _b++) { + var f = _c[_b]; + wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o); + bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b; + } + wzf(out, bt, this.u.length, tl, l); + this.ondata(null, out, true); + this.d = 2; + }; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to add() will fail. + */ + Zip.prototype.terminate = function () { + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + f.t(); + } + this.d = 2; + }; + return Zip; +}()); +exports.Zip = Zip; +function zip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var r = {}; + fltn(data, '', r, opts); + var k = Object.keys(r); + var lft = k.length, o = 0, tot = 0; + var slft = lft, files = new Array(lft); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var cbf = function () { + var out = new u8(tot + 22), oe = o, cdl = tot - o; + tot = 0; + for (var i = 0; i < slft; ++i) { + var f = files[i]; + try { + var l = f.c.length; + wzh(out, tot, f, f.f, f.u, l); + var badd = 30 + f.f.length + exfl(f.extra); + var loc = tot + badd; + out.set(f.c, loc); + wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l; + } + catch (e) { + return cbd(e, null); + } + } + wzf(out, o, files.length, cdl, oe); + cbd(null, out); + }; + if (!lft) + cbf(); + var _loop_1 = function (i) { + var fn = k[i]; + var _a = r[fn], file = _a[0], p = _a[1]; + var c = crc(), size = file.length; + c.p(file); + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + var compression = p.level == 0 ? 0 : 8; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + var l = d.length; + files[i] = mrg(p, { + size: size, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + compression: compression + }); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + if (!--lft) + cbf(); + } + }; + if (s > 65535) + cbl(err(11, 0, 1), null); + if (!compression) + cbl(null, file); + else if (size < 160000) { + try { + cbl(null, deflateSync(file, p)); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(deflate(file, p, cbl)); + }; + // Cannot use lft because it can decrease + for (var i = 0; i < slft; ++i) { + _loop_1(i); + } + return tAll; +} +/** + * Synchronously creates a ZIP file. Prefer using `zip` for better performance + * with more than one file. + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @returns The generated ZIP archive + */ +function zipSync(data, opts) { + if (!opts) + opts = {}; + var r = {}; + var files = []; + fltn(data, '', r, opts); + var o = 0; + var tot = 0; + for (var fn in r) { + var _a = r[fn], file = _a[0], p = _a[1]; + var compression = p.level == 0 ? 0 : 8; + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + if (s > 65535) + err(11); + var d = compression ? deflateSync(file, p) : file, l = d.length; + var c = crc(); + c.p(file); + files.push(mrg(p, { + size: file.length, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + o: o, + compression: compression + })); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + } + var out = new u8(tot + 22), oe = o, cdl = tot - o; + for (var i = 0; i < files.length; ++i) { + var f = files[i]; + wzh(out, f.o, f, f.f, f.u, f.c.length); + var badd = 30 + f.f.length + exfl(f.extra); + out.set(f.c, f.o + badd); + wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0); + } + wzf(out, o, files.length, cdl, oe); + return out; +} +/** + * Streaming pass-through decompression for ZIP archives + */ +var UnzipPassThrough = /*#__PURE__*/ (function () { + function UnzipPassThrough() { + } + UnzipPassThrough.prototype.push = function (chunk, final) { + // same as ZipPassThrough: cast to retain Buffer ergonomics + this.ondata(null, chunk, final); + }; + UnzipPassThrough.compression = 0; + return UnzipPassThrough; +}()); +exports.UnzipPassThrough = UnzipPassThrough; +/** + * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for + * better performance. + */ +var UnzipInflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function UnzipInflate() { + var _this = this; + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + UnzipInflate.prototype.push = function (chunk, final) { + try { + this.i.push(chunk, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + UnzipInflate.compression = 8; + return UnzipInflate; +}()); +exports.UnzipInflate = UnzipInflate; +/** + * Asynchronous streaming DEFLATE decompression for ZIP archives + */ +var AsyncUnzipInflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function AsyncUnzipInflate(_, sz) { + var _this = this; + if (sz < 320000) { + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + else { + this.i = new AsyncInflate(function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.terminate = this.i.terminate; + } + } + AsyncUnzipInflate.prototype.push = function (chunk, final) { + if (this.i.terminate) + chunk = slc(chunk, 0); + this.i.push(chunk, final); + }; + AsyncUnzipInflate.compression = 8; + return AsyncUnzipInflate; +}()); +exports.AsyncUnzipInflate = AsyncUnzipInflate; +/** + * A ZIP archive decompression stream that emits files as they are discovered + */ +var Unzip = /*#__PURE__*/ (function () { + /** + * Creates a ZIP decompression stream + * @param cb The callback to call whenever a file in the ZIP archive is found + */ + function Unzip(cb) { + this.onfile = cb; + this.k = []; + this.o = { + 0: UnzipPassThrough + }; + this.p = et; + } + /** + * Pushes a chunk to be unzipped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzip.prototype.push = function (chunk, final) { + var _this = this; + if (!this.onfile) + err(5); + if (!this.p) + err(4); + if (this.c > 0) { + var len = Math.min(this.c, chunk.length); + var toAdd = chunk.subarray(0, len); + this.c -= len; + if (this.d) + this.d.push(toAdd, !this.c); + else + this.k[0].push(toAdd); + chunk = chunk.subarray(len); + if (chunk.length) + return this.push(chunk, final); + } + else { + var f = 0, i = 0, is = void 0, buf = void 0; + if (!this.p.length) + buf = chunk; + else if (!chunk.length) + buf = this.p; + else { + buf = new u8(this.p.length + chunk.length); + buf.set(this.p), buf.set(chunk, this.p.length); + } + var l = buf.length, oc = this.c, add = oc && this.d; + var _loop_2 = function () { + var sig = b4(buf, i); + if (sig == 0x4034B50) { + f = 1, is = i; + this_1.d = null; + this_1.c = 0; + var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28); + if (l > i + 30 + fnl + es) { + var chks_3 = []; + this_1.k.unshift(chks_3); + f = 2; + var lsc = b4(buf, i + 18), lsu = b4(buf, i + 22); + var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u); + var _a = z64hs(buf, i, es, 2, lsc, lsu, 0), sc_1 = _a[0], su_1 = _a[1], z64 = _a[3]; + if (dd) + sc_1 = -1 - z64; + i += es; + this_1.c = sc_1; + var d_1; + var file_1 = { + name: fn_1, + compression: cmp_1, + start: function () { + if (!file_1.ondata) + err(5); + if (!sc_1) + file_1.ondata(null, et, true); + else { + var ctr = _this.o[cmp_1]; + if (!ctr) + file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false); + d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1); + d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); }; + for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) { + var dat = chks_4[_i]; + d_1.push(dat, false); + } + if (_this.k[0] == chks_3 && _this.c) + _this.d = d_1; + else + d_1.push(et, true); + } + }, + terminate: function () { + if (d_1 && d_1.terminate) + d_1.terminate(); + } + }; + if (sc_1 >= 0) + file_1.size = sc_1, file_1.originalSize = su_1; + this_1.onfile(file_1); + } + return "break"; + } + else if (oc) { + if (sig == 0x8074B50) { + is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0; + return "break"; + } + else if (sig == 0x2014B50) { + is = i -= 4, f = 3, this_1.c = 0; + return "break"; + } + } + }; + var this_1 = this; + for (; i < l - 4; ++i) { + var state_1 = _loop_2(); + if (state_1 === "break") + break; + } + this.p = et; + if (oc < 0) { + var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i); + if (add) + add.push(dat, !!f); + else + this.k[+(f == 2)].push(dat); + } + if (f & 2) + return this.push(buf.subarray(i), final); + this.p = buf.subarray(i); + } + if (final) { + if (this.c) + err(13); + this.p = null; + } + }; + /** + * Registers a decoder with the stream, allowing for files compressed with + * the compression type provided to be expanded correctly + * @param decoder The decoder constructor + */ + Unzip.prototype.register = function (decoder) { + this.o[decoder.compression] = decoder; + }; + return Unzip; +}()); +exports.Unzip = Unzip; +var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); }; +function unzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var files = {}; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) { + cbd(err(13, 0, 1), null); + return tAll; + } + } + ; + var lft = b2(data, e + 8); + if (lft) { + var c = lft; + var o = b4(data, e + 16); + var z = b4(data, e - 20) == 0x7064B50; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = lft = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + var _loop_3 = function (i) { + var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + if (d) + files[fn] = d; + if (!--lft) + cbd(null, files); + } + }; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_1 + })) { + if (!c_1) + cbl(null, slc(data, b, b + sc)); + else if (c_1 == 8) { + var infl = data.subarray(b, b + sc); + // Synchronously decompress under 512KB, or barely-compressed data + if (su < 524288 || sc > 0.8 * su) { + try { + cbl(null, inflateSync(infl, { out: new u8(su) })); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(inflate(infl, { size: su }, cbl)); + } + else + cbl(err(14, 'unknown compression type ' + c_1, 1), null); + } + else + cbl(null, null); + }; + for (var i = 0; i < c; ++i) { + _loop_3(i); + } + } + else + cbd(null, {}); + return tAll; +} +/** + * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better + * performance with more than one file. + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @returns The decompressed files + */ +function unzipSync(data, opts) { + var files = {}; + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) + err(13); + } + ; + var c = b2(data, e + 8); + if (!c) + return {}; + var o = b4(data, e + 16); + var z = b4(data, e - 20) == 0x7064B50; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + for (var i = 0; i < c; ++i) { + var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_2 + })) { + if (!c_2) + files[fn] = slc(data, b, b + sc); + else if (c_2 == 8) + files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) }); + else + err(14, 'unknown compression type ' + c_2); + } + } + return files; +} diff --git a/node_modules/fflate/lib/browser.d.cts b/node_modules/fflate/lib/browser.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..d430faf2b555c978d66c89f46155b72c2c45a971 --- /dev/null +++ b/node_modules/fflate/lib/browser.d.cts @@ -0,0 +1,1539 @@ +/** + * Codes for errors generated within this library + */ +export declare const FlateErrorCode: { + readonly UnexpectedEOF: 0; + readonly InvalidBlockType: 1; + readonly InvalidLengthLiteral: 2; + readonly InvalidDistance: 3; + readonly StreamFinished: 4; + readonly NoStreamHandler: 5; + readonly InvalidHeader: 6; + readonly NoCallback: 7; + readonly InvalidUTF8: 8; + readonly ExtraFieldTooLong: 9; + readonly InvalidDate: 10; + readonly FilenameTooLong: 11; + readonly StreamFinishing: 12; + readonly InvalidZipData: 13; + readonly UnknownCompressionMethod: 14; +}; +/** + * An error generated within this library + */ +export interface FlateError extends Error { + /** + * The code associated with this error + */ + code: number; +} +/** + * Options for decompressing a DEFLATE stream + */ +export interface InflateStreamOptions { + /** + * The dictionary used to compress the original data. If no dictionary was used during compression, this option has no effect. + * + * Supplying the wrong dictionary during decompression usually yields corrupt output or causes an invalid distance error. + */ + dictionary?: Uint8Array; +} +/** + * Options for decompressing DEFLATE data + */ +export interface InflateOptions extends InflateStreamOptions { + /** + * The buffer into which to write the decompressed data. Saves memory if you know the decompressed size in advance. + * + * Note that if the decompression result is larger than the size of this buffer, it will be truncated to fit. + */ + out?: Uint8Array; +} +/** + * Options for decompressing a GZIP stream + */ +export interface GunzipStreamOptions extends InflateStreamOptions { +} +/** + * Options for decompressing GZIP data + */ +export interface GunzipOptions extends InflateStreamOptions { + /** + * The buffer into which to write the decompressed data. GZIP already encodes the output size, so providing this doesn't save memory. + * + * Note that if the decompression result is larger than the size of this buffer, it will be truncated to fit. + */ + out?: Uint8Array; +} +/** + * Options for decompressing a Zlib stream + */ +export interface UnzlibStreamOptions extends InflateStreamOptions { +} +/** + * Options for decompressing Zlib data + */ +export interface UnzlibOptions extends InflateOptions { +} +/** + * Options for compressing data into a DEFLATE format + */ +export interface DeflateOptions { + /** + * The level of compression to use, ranging from 0-9. + * + * 0 will store the data without compression. + * 1 is fastest but compresses the worst, 9 is slowest but compresses the best. + * The default level is 6. + * + * Typically, binary data benefits much more from higher values than text data. + * In both cases, higher values usually take disproportionately longer than the reduction in final size that results. + * + * For example, a 1 MB text file could: + * - become 1.01 MB with level 0 in 1ms + * - become 400 kB with level 1 in 10ms + * - become 320 kB with level 9 in 100ms + */ + level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + /** + * The memory level to use, ranging from 0-12. Increasing this increases speed and compression ratio at the cost of memory. + * + * Note that this is exponential: while level 0 uses 8 kB, level 4 uses 128 kB, level 8 uses 2 MB, and level 12 uses 32 MB. + * It is recommended not to lower the value below 4, since that tends to hurt performance. + * In addition, values above 8 tend to help very little on most data and can even hurt performance. + * + * The default value is automatically determined based on the size of the input data. + */ + mem?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; + /** + * A buffer containing common byte sequences in the input data that can be used to significantly improve compression ratios. + * + * Dictionaries should be 32kB or smaller and include strings or byte sequences likely to appear in the input. + * The decompressor must supply the same dictionary as the compressor to extract the original data. + * + * Dictionaries only improve aggregate compression ratio when reused across multiple small inputs. They should typically not be used otherwise. + * + * Avoid using dictionaries with GZIP and ZIP to maximize software compatibility. + */ + dictionary?: Uint8Array; +} +/** + * Options for compressing data into a GZIP format + */ +export interface GzipOptions extends DeflateOptions { + /** + * When the file was last modified. Defaults to the current time. + * Set this to 0 to avoid revealing a modification date entirely. + */ + mtime?: Date | string | number; + /** + * The filename of the data. If the `gunzip` command is used to decompress the data, it will output a file + * with this name instead of the name of the compressed file. + */ + filename?: string; +} +/** + * Options for compressing data into a Zlib format + */ +export interface ZlibOptions extends DeflateOptions { +} +/** + * Handler for data (de)compression streams + * @param data The data output from the stream processor + * @param final Whether this is the final block + */ +export type FlateStreamHandler = (data: Uint8Array, final: boolean) => void; +/** + * Handler for asynchronous data (de)compression streams + * @param err Any error that occurred + * @param data The data output from the stream processor + * @param final Whether this is the final block + */ +export type AsyncFlateStreamHandler = (err: FlateError | null, data: Uint8Array, final: boolean) => void; +/** + * Handler for the asynchronous completion of (de)compression for a data chunk + * @param size The number of bytes that were processed. This is measured in terms of the input + * (i.e. compressed bytes for decompression, uncompressed bytes for compression.) + */ +export type AsyncFlateDrainHandler = (size: number) => void; +/** + * Callback for asynchronous (de)compression methods + * @param err Any error that occurred + * @param data The resulting data. Only present if `err` is null + */ +export type FlateCallback = (err: FlateError | null, data: Uint8Array) => void; +interface AsyncOptions { + /** + * Whether or not to "consume" the source data. This will make the typed array/buffer you pass in + * unusable but will increase performance and reduce memory usage. + */ + consume?: boolean; +} +/** + * Options for compressing data asynchronously into a DEFLATE format + */ +export interface AsyncDeflateOptions extends DeflateOptions, AsyncOptions { +} +/** + * Options for decompressing DEFLATE data asynchronously + */ +export interface AsyncInflateOptions extends AsyncOptions, InflateStreamOptions { + /** + * The original size of the data. Currently, the asynchronous API disallows + * writing into a buffer you provide; the best you can do is provide the + * size in bytes and be given back a new typed array. + */ + size?: number; +} +/** + * Options for compressing data asynchronously into a GZIP format + */ +export interface AsyncGzipOptions extends GzipOptions, AsyncOptions { +} +/** + * Options for decompressing GZIP data asynchronously + */ +export interface AsyncGunzipOptions extends AsyncOptions, InflateStreamOptions { +} +/** + * Options for compressing data asynchronously into a Zlib format + */ +export interface AsyncZlibOptions extends ZlibOptions, AsyncOptions { +} +/** + * Options for decompressing Zlib data asynchronously + */ +export interface AsyncUnzlibOptions extends AsyncInflateOptions { +} +/** + * A terminable compression/decompression process + */ +export interface AsyncTerminable { + /** + * Terminates the worker thread immediately. The callback will not be called. + */ + (): void; +} +/** + * Streaming DEFLATE compression + */ +export declare class Deflate { + /** + * Creates a DEFLATE stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: DeflateOptions, cb?: FlateStreamHandler); + /** + * Creates a DEFLATE stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + private b; + private s; + private o; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + private p; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE compression + */ +export declare class AsyncDeflate { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous DEFLATE stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: DeflateOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous DEFLATE stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function deflate(data: Uint8Array, opts: AsyncDeflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param cb The function to be called upon compression completion + */ +export declare function deflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @returns The deflated version of the data + */ +export declare function deflateSync(data: Uint8Array, opts?: DeflateOptions): Uint8Array; +/** + * Streaming DEFLATE decompression + */ +export declare class Inflate { + private s; + private o; + private p; + private d; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a DEFLATE decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: InflateStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a DEFLATE decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + private e; + private c; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE decompression + */ +export declare class AsyncInflate { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous DEFLATE decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: InflateStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous DEFLATE decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function inflate(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function inflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands DEFLATE data with no wrapper + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function inflateSync(data: Uint8Array): Uint8Array; +/** + * Expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function inflateSync(data: Uint8Array, opts?: InflateOptions): Uint8Array; +/** + * Streaming GZIP compression + */ +export declare class Gzip { + private c; + private l; + private v; + private o; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a GZIP stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: GzipOptions, cb?: FlateStreamHandler); + /** + * Creates a GZIP stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + private p; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming GZIP compression + */ +export declare class AsyncGzip { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous GZIP stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: GzipOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous GZIP stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function gzip(data: Uint8Array, opts: AsyncGzipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with GZIP + * @param data The data to compress + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @returns The gzipped version of the data + */ +export declare function gzipSync(data: Uint8Array, opts?: GzipOptions): Uint8Array; +/** + * Handler for new GZIP members in concatenated GZIP streams. Useful for building indices used to perform random-access reads on compressed files. + * @param offset The offset of the new member relative to the start of the stream + */ +export type GunzipMemberHandler = (offset: number) => void; +/** + * Streaming single or multi-member GZIP decompression + */ +export declare class Gunzip { + private v; + private r; + private o; + private p; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * The handler to call whenever a new GZIP member is found + */ + onmember?: GunzipMemberHandler; + /** + * Creates a GUNZIP stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: GunzipStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a GUNZIP stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming single or multi-member GZIP decompression + */ +export declare class AsyncGunzip { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * The handler to call whenever a new GZIP member is found + */ + onmember?: GunzipMemberHandler; + /** + * Creates an asynchronous GUNZIP stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: GunzipStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous GUNZIP stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands GZIP data + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gunzip(data: Uint8Array, opts: AsyncGunzipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands GZIP data + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gunzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands GZIP data + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function gunzipSync(data: Uint8Array): Uint8Array; +/** + * Expands GZIP data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function gunzipSync(data: Uint8Array, opts?: GunzipOptions): Uint8Array; +/** + * Streaming Zlib compression + */ +export declare class Zlib { + private c; + private v; + private o; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a Zlib stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: ZlibOptions, cb?: FlateStreamHandler); + /** + * Creates a Zlib stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + private p; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming Zlib compression + */ +export declare class AsyncZlib { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous Zlib stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: ZlibOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous Zlib stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with Zlib + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + */ +export declare function zlib(data: Uint8Array, opts: AsyncZlibOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with Zlib + * @param data The data to compress + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compress data with Zlib + * @param data The data to compress + * @param opts The compression options + * @returns The zlib-compressed version of the data + */ +export declare function zlibSync(data: Uint8Array, opts?: ZlibOptions): Uint8Array; +/** + * Streaming Zlib decompression + */ +export declare class Unzlib { + private v; + private p; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a Zlib decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: UnzlibStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming Zlib decompression + */ +export declare class AsyncUnzlib { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous Zlib decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: UnzlibStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be decompressed from Zlib + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands Zlib data + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function unzlib(data: Uint8Array, opts: AsyncUnzlibOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands Zlib data + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function unzlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands Zlib data + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function unzlibSync(data: Uint8Array): Uint8Array; +/** + * Expands Zlib data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function unzlibSync(data: Uint8Array, opts?: UnzlibOptions): Uint8Array; +export { gzip as compress, AsyncGzip as AsyncCompress }; +export { gzipSync as compressSync, Gzip as Compress }; +/** + * Streaming GZIP, Zlib, or raw DEFLATE decompression + */ +export declare class Decompress { + private G; + private I; + private Z; + private o; + private s; + private p; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is decompressed + */ + constructor(opts: InflateStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a decompression stream + * @param cb The callback to call whenever data is decompressed + */ + constructor(cb?: FlateStreamHandler); + private i; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression + */ +export declare class AsyncDecompress { + private G; + private I; + private Z; + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is decompressed + */ + constructor(opts: InflateStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous decompression stream + * @param cb The callback to call whenever data is decompressed + */ + constructor(cb?: AsyncFlateStreamHandler); + private i; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function decompress(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function decompress(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function decompressSync(data: Uint8Array, opts?: InflateOptions): Uint8Array; +/** + * Attributes for files added to a ZIP archive object + */ +export interface ZipAttributes { + /** + * The operating system of origin for this file. The value is defined + * by PKZIP's APPNOTE.txt, section 4.4.2.2. For example, 0 (the default) + * is MS/DOS, 3 is Unix, 19 is macOS. + */ + os?: number; + /** + * The file's attributes. These are traditionally somewhat complicated + * and platform-dependent, so using them is scarcely necessary. However, + * here is a representation of what this is, bit by bit: + * + * `TTTTugtrwxrwxrwx0000000000ADVSHR` + * + * TTTT = file type (rarely useful) + * + * u = setuid, g = setgid, t = sticky + * + * rwx = user permissions, rwx = group permissions, rwx = other permissions + * + * 0000000000 = unused + * + * A = archive, D = directory, V = volume label, S = system file, H = hidden, R = read-only + * + * If you want to set the Unix permissions, for instance, just bit shift by 16, e.g. 0o644 << 16. + * Note that attributes usually only work in conjunction with the `os` setting: you must use + * `os` = 3 (Unix) if you want to set Unix permissions + */ + attrs?: number; + /** + * Extra metadata to add to the file. This field is defined by PKZIP's APPNOTE.txt, + * section 4.4.28. At most 65,535 bytes may be used in each ID. The ID must be an + * integer between 0 and 65,535, inclusive. + * + * This field is incredibly rare and almost never needed except for compliance with + * proprietary standards and software. + */ + extra?: Record; + /** + * The comment to attach to the file. This field is defined by PKZIP's APPNOTE.txt, + * section 4.4.26. The comment must be at most 65,535 bytes long UTF-8 encoded. This + * field is not read by consumer software. + */ + comment?: string; + /** + * When the file was last modified. Defaults to the current time. + */ + mtime?: GzipOptions['mtime']; +} +/** + * Options for creating a ZIP archive + */ +export interface ZipOptions extends DeflateOptions, ZipAttributes { +} +/** + * Options for expanding a ZIP archive + */ +export interface UnzipOptions { + /** + * A filter function to extract only certain files from a ZIP archive + */ + filter?: UnzipFileFilter; +} +/** + * Options for asynchronously creating a ZIP archive + */ +export interface AsyncZipOptions extends AsyncDeflateOptions, ZipAttributes { +} +/** + * Options for asynchronously expanding a ZIP archive + */ +export interface AsyncUnzipOptions extends UnzipOptions { +} +/** + * A file that can be used to create a ZIP archive + */ +export type ZippableFile = Uint8Array | Zippable | [Uint8Array | Zippable, ZipOptions]; +/** + * A file that can be used to asynchronously create a ZIP archive + */ +export type AsyncZippableFile = Uint8Array | AsyncZippable | [Uint8Array | AsyncZippable, AsyncZipOptions]; +/** + * The complete directory structure of a ZIPpable archive + */ +export interface Zippable { + [path: string]: ZippableFile; +} +/** + * The complete directory structure of an asynchronously ZIPpable archive + */ +export interface AsyncZippable { + [path: string]: AsyncZippableFile; +} +/** + * An unzipped archive. The full path of each file is used as the key, + * and the file is the value + */ +export interface Unzipped { + [path: string]: Uint8Array; +} +/** + * Handler for string generation streams + * @param data The string output from the stream processor + * @param final Whether this is the final block + */ +export type StringStreamHandler = (data: string, final: boolean) => void; +/** + * Callback for asynchronous ZIP decompression + * @param err Any error that occurred + * @param data The decompressed ZIP archive + */ +export type UnzipCallback = (err: FlateError | null, data: Unzipped) => void; +/** + * Handler for streaming ZIP decompression + * @param file The file that was found in the archive + */ +export type UnzipFileHandler = (file: UnzipFile) => void; +/** + * Streaming UTF-8 decoding + */ +export declare class DecodeUTF8 { + private p; + private t; + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is decoded + */ + constructor(cb?: StringStreamHandler); + /** + * Pushes a chunk to be decoded from UTF-8 binary + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * The handler to call whenever data is available + */ + ondata: StringStreamHandler; +} +/** + * Streaming UTF-8 encoding + */ +export declare class EncodeUTF8 { + private d; + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is encoded + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be encoded to UTF-8 + * @param chunk The string data to push + * @param final Whether this is the last chunk + */ + push(chunk: string, final?: boolean): void; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; +} +/** + * Converts a string into a Uint8Array for use with compression/decompression methods + * @param str The string to encode + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless decoding a binary string. + * @returns The string encoded in UTF-8/Latin-1 binary + */ +export declare function strToU8(str: string, latin1?: boolean): Uint8Array; +/** + * Converts a Uint8Array to a string + * @param dat The data to decode to string + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless encoding to binary string. + * @returns The original UTF-8/Latin-1 string + */ +export declare function strFromU8(dat: Uint8Array, latin1?: boolean): string; +/** + * A stream that can be used to create a file in a ZIP archive + */ +export interface ZipInputFile extends ZipAttributes { + /** + * The filename to associate with the data provided to this stream. If you + * want a file in a subdirectory, use forward slashes as a separator (e.g. + * `directory/filename.ext`). This will still work on Windows. + */ + filename: string; + /** + * The size of the file in bytes. This attribute may be invalid after + * the file is added to the ZIP archive; it must be correct only before the + * stream completes. + * + * If you don't want to have to compute this yourself, consider extending the + * ZipPassThrough class and overriding its process() method, or using one of + * ZipDeflate or AsyncZipDeflate. + */ + size: number; + /** + * A CRC of the original file contents. This attribute may be invalid after + * the file is added to the ZIP archive; it must be correct only before the + * stream completes. + * + * If you don't want to have to generate this yourself, consider extending the + * ZipPassThrough class and overriding its process() method, or using one of + * ZipDeflate or AsyncZipDeflate. + */ + crc: number; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA + */ + compression: number; + /** + * Bits 1 and 2 of the general purpose bit flag, specified in PKZIP's + * APPNOTE.txt, section 4.4.4. Should be between 0 and 3. This is unlikely + * to be necessary. + */ + flag?: number; + /** + * The handler to be called when data is added. After passing this stream to + * the ZIP file object, this handler will always be defined. To call it: + * + * `stream.ondata(error, chunk, final)` + * + * error = any error that occurred (null if there was no error) + * + * chunk = a Uint8Array of the data that was added (null if there was an + * error) + * + * final = boolean, whether this is the final chunk in the stream + */ + ondata?: AsyncFlateStreamHandler; + /** + * A method called when the stream is no longer needed, for clean-up + * purposes. This will not always be called after the stream completes, + * so you may wish to call this.terminate() after the final chunk is + * processed if you have clean-up logic. + */ + terminate?: AsyncTerminable; +} +/** + * A pass-through stream to keep data uncompressed in a ZIP archive. + */ +export declare class ZipPassThrough implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private c; + /** + * Creates a pass-through stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + */ + constructor(filename: string); + /** + * Processes a chunk and pushes to the output stream. You can override this + * method in a subclass for custom behavior, but by default this passes + * the data through. You must call this.ondata(err, chunk, final) at some + * point in this method. + * @param chunk The chunk to process + * @param final Whether this is the last chunk + */ + protected process(chunk: Uint8Array, final: boolean): void; + /** + * Pushes a chunk to be added. If you are subclassing this with a custom + * compression algorithm, note that you must push data from the source + * file only, pre-compression. + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate + * for better performance + */ +export declare class ZipDeflate implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + flag: 0 | 1 | 2 | 3; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private d; + /** + * Creates a DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + constructor(filename: string, opts?: DeflateOptions); + private process; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE compression for ZIP archives + */ +export declare class AsyncZipDeflate implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + flag: 0 | 1 | 2 | 3; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private d; + terminate: AsyncTerminable; + /** + * Creates an asynchronous DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + constructor(filename: string, opts?: DeflateOptions); + private process; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * A zippable archive to which files can incrementally be added + */ +export declare class Zip { + private u; + private d; + /** + * Creates an empty ZIP archive to which files can be added + * @param cb The callback to call whenever data for the generated ZIP archive + * is available + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Adds a file to the ZIP archive + * @param file The file stream to add + */ + add(file: ZipInputFile): void; + /** + * Ends the process of adding files and prepares to emit the final chunks. + * This *must* be called after adding all desired files for the resulting + * ZIP file to work properly. + */ + end(): void; + private e; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to add() will fail. + */ + terminate(): void; + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; +} +/** + * Asynchronously creates a ZIP file + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @param cb The callback to call with the generated ZIP archive + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zip(data: AsyncZippable, opts: AsyncZipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously creates a ZIP file + * @param data The directory structure for the ZIP archive + * @param cb The callback to call with the generated ZIP archive + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zip(data: AsyncZippable, cb: FlateCallback): AsyncTerminable; +/** + * Synchronously creates a ZIP file. Prefer using `zip` for better performance + * with more than one file. + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @returns The generated ZIP archive + */ +export declare function zipSync(data: Zippable, opts?: ZipOptions): Uint8Array; +/** + * A decoder for files in ZIP streams + */ +export interface UnzipDecoder { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * Pushes a chunk to be decompressed + * @param chunk The data in this chunk. Do not consume (detach) this buffer. + * @param final Whether this is the last chunk in the data stream + */ + push(chunk: Uint8Array, final: boolean): void; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to push() should silently fail. + */ + terminate?: AsyncTerminable; +} +/** + * A constructor for a decoder for unzip streams + */ +export interface UnzipDecoderConstructor { + /** + * Creates an instance of the decoder + * @param filename The name of the file + * @param size The compressed size of the file + * @param originalSize The original size of the file + */ + new (filename: string, size?: number, originalSize?: number): UnzipDecoder; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA + */ + compression: number; +} +/** + * Information about a file to be extracted from a ZIP archive + */ +export interface UnzipFileInfo { + /** + * The name of the file + */ + name: string; + /** + * The compressed size of the file + */ + size: number; + /** + * The original size of the file + */ + originalSize: number; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA. If the filter function returns true + * but this value is not 8, the unzip function will throw. + */ + compression: number; +} +/** + * A filter for files to be extracted during the unzipping process + * @param file The info for the current file being processed + * @returns Whether or not to extract the current file + */ +export type UnzipFileFilter = (file: UnzipFileInfo) => boolean; +/** + * Streaming file extraction from ZIP archives + */ +export interface UnzipFile { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The name of the file + */ + name: string; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA. If start() is called but there is no + * decompression stream available for this method, start() will throw. + */ + compression: number; + /** + * The compressed size of the file. Will not be present for archives created + * in a streaming fashion. + */ + size?: number; + /** + * The original size of the file. Will not be present for archives created + * in a streaming fashion. + */ + originalSize?: number; + /** + * Starts reading from the stream. Calling this function will always enable + * this stream, but ocassionally the stream will be enabled even without + * this being called. + */ + start(): void; + /** + * A method to terminate any internal workers used by the stream. ondata + * will not be called any further. + */ + terminate: AsyncTerminable; +} +/** + * Streaming pass-through decompression for ZIP archives + */ +export declare class UnzipPassThrough implements UnzipDecoder { + static compression: number; + ondata: AsyncFlateStreamHandler; + push(chunk: Uint8Array, final: boolean): void; +} +/** + * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for + * better performance. + */ +export declare class UnzipInflate implements UnzipDecoder { + static compression: number; + private i; + ondata: AsyncFlateStreamHandler; + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + constructor(); + push(chunk: Uint8Array, final: boolean): void; +} +/** + * Asynchronous streaming DEFLATE decompression for ZIP archives + */ +export declare class AsyncUnzipInflate implements UnzipDecoder { + static compression: number; + private i; + ondata: AsyncFlateStreamHandler; + terminate: AsyncTerminable; + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + constructor(_: string, sz?: number); + push(chunk: Uint8Array, final: boolean): void; +} +/** + * A ZIP archive decompression stream that emits files as they are discovered + */ +export declare class Unzip { + private d; + private c; + private p; + private k; + private o; + /** + * Creates a ZIP decompression stream + * @param cb The callback to call whenever a file in the ZIP archive is found + */ + constructor(cb?: UnzipFileHandler); + /** + * Pushes a chunk to be unzipped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Registers a decoder with the stream, allowing for files compressed with + * the compression type provided to be expanded correctly + * @param decoder The decoder constructor + */ + register(decoder: UnzipDecoderConstructor): void; + /** + * The handler to call whenever a file is discovered + */ + onfile: UnzipFileHandler; +} +/** + * Asynchronously decompresses a ZIP archive + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @param cb The callback to call with the decompressed files + * @returns A function that can be used to immediately terminate the unzipping + */ +export declare function unzip(data: Uint8Array, opts: AsyncUnzipOptions, cb: UnzipCallback): AsyncTerminable; +/** + * Asynchronously decompresses a ZIP archive + * @param data The raw compressed ZIP file + * @param cb The callback to call with the decompressed files + * @returns A function that can be used to immediately terminate the unzipping + */ +export declare function unzip(data: Uint8Array, cb: UnzipCallback): AsyncTerminable; +/** + * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better + * performance with more than one file. + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @returns The decompressed files + */ +export declare function unzipSync(data: Uint8Array, opts?: UnzipOptions): Unzipped; diff --git a/node_modules/fflate/lib/index.cjs b/node_modules/fflate/lib/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..ea4da56d93b2462ca17e4220840416d561b4a645 --- /dev/null +++ b/node_modules/fflate/lib/index.cjs @@ -0,0 +1,2697 @@ +"use strict"; +// DEFLATE is a complex format; to read this code, you should probably check the RFC first: +// https://tools.ietf.org/html/rfc1951 +// You may also wish to take a look at the guide I made about this program: +// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad +exports.deflate = deflate; +exports.deflateSync = deflateSync; +exports.inflate = inflate; +exports.inflateSync = inflateSync; +exports.gzip = gzip; +exports.compress = gzip; +exports.gzipSync = gzipSync; +exports.compressSync = gzipSync; +exports.gunzip = gunzip; +exports.gunzipSync = gunzipSync; +exports.zlib = zlib; +exports.zlibSync = zlibSync; +exports.unzlib = unzlib; +exports.unzlibSync = unzlibSync; +exports.gzip = gzip; +exports.compress = gzip; +exports.decompress = decompress; +exports.decompressSync = decompressSync; +exports.strToU8 = strToU8; +exports.strFromU8 = strFromU8; +exports.zip = zip; +exports.zipSync = zipSync; +exports.unzip = unzip; +exports.unzipSync = unzipSync; +// Some of the following code is similar to that of UZIP.js: +// https://github.com/photopea/UZIP.js +// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. +// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint +// is better for memory in most engines (I *think*). +var node_worker_1 = require("./node-worker.cjs"); +// aliases for shorter compressed code (most minifers don't do this) +var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array; +// fixed length extra bits +var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); +// fixed distance extra bits +var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); +// code length index map +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +// get base, reverse index map from extra bits +var freb = function (eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + // numbers here are at max 18 bits + var r = new i32(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = ((j - b[i]) << 5) | i; + } + } + return { b: b, r: r }; +}; +var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r; +// we can ignore the fact that the other numbers are wrong; they never happen anyway +fl[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r; +// map of value to reverse (assuming 16 bits) +var rev = new u16(32768); +for (var i = 0; i < 32768; ++i) { + // reverse table algorithm from SO + var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1); + x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2); + x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4); + rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1; +} +// create huffman tree from u8 "map": index -> code length for code index +// mb (max bits) must be at most 15 +// TODO: optimize/split up? +var hMap = (function (cd, mb, r) { + var s = cd.length; + // index + var i = 0; + // u16 "map": index -> # of codes with bit length = index + var l = new u16(mb); + // length of cd must be 288 (total # of codes) + for (; i < s; ++i) { + if (cd[i]) + ++l[cd[i] - 1]; + } + // u16 "map": index -> minimum code for bit length = index + var le = new u16(mb); + for (i = 1; i < mb; ++i) { + le[i] = (le[i - 1] + l[i - 1]) << 1; + } + var co; + if (r) { + // u16 "map": index -> number of actual bits, symbol for code + co = new u16(1 << mb); + // bits to remove for reverser + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + // ignore 0 lengths + if (cd[i]) { + // num encoding both symbol and bits read + var sv = (i << 4) | cd[i]; + // free bits + var r_1 = mb - cd[i]; + // start value + var v = le[cd[i] - 1]++ << r_1; + // m is end value + for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { + // every 16 bit value starting with the code yields the same result + co[rev[v] >> rvb] = sv; + } + } + } + } + else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]); + } + } + } + return co; +}); +// fixed length tree +var flt = new u8(288); +for (var i = 0; i < 144; ++i) + flt[i] = 8; +for (var i = 144; i < 256; ++i) + flt[i] = 9; +for (var i = 256; i < 280; ++i) + flt[i] = 7; +for (var i = 280; i < 288; ++i) + flt[i] = 8; +// fixed distance tree +var fdt = new u8(32); +for (var i = 0; i < 32; ++i) + fdt[i] = 5; +// fixed length map +var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); +// fixed distance map +var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); +// find max of array +var max = function (a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; +}; +// read d, starting at bit p and mask with m +var bits = function (d, p, m) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; +}; +// read d, starting at bit p continuing for at least 16 bits +var bits16 = function (d, p) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); +}; +// get end of byte +var shft = function (p) { return ((p + 7) / 8) | 0; }; +// typed array slice - allows garbage collector to free original reference, +// while being more compatible than .slice +var slc = function (v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + // can't use .constructor in case user-supplied + return new u8(v.subarray(s, e)); +}; +/** + * Codes for errors generated within this library + */ +exports.FlateErrorCode = { + UnexpectedEOF: 0, + InvalidBlockType: 1, + InvalidLengthLiteral: 2, + InvalidDistance: 3, + StreamFinished: 4, + NoStreamHandler: 5, + InvalidHeader: 6, + NoCallback: 7, + InvalidUTF8: 8, + ExtraFieldTooLong: 9, + InvalidDate: 10, + FilenameTooLong: 11, + StreamFinishing: 12, + InvalidZipData: 13, + UnknownCompressionMethod: 14 +}; +// error codes +var ec = [ + 'unexpected EOF', + 'invalid block type', + 'invalid length/literal', + 'invalid distance', + 'stream finished', + 'no stream handler', + , // determined by compression function + 'no callback', + 'invalid UTF-8 data', + 'extra field too long', + 'date not in range 1980-2099', + 'filename too long', + 'stream finishing', + 'invalid zip data' + // determined by unknown compression method +]; +; +var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; +}; +// expands raw DEFLATE data +var inflt = function (dat, st, buf, dict) { + // source length dict length + var sl = dat.length, dl = dict ? dict.length : 0; + if (!sl || st.f && !st.l) + return buf || new u8(0); + var noBuf = !buf; + // have to estimate size + var resize = noBuf || st.i != 2; + // no state + var noSt = st.i; + // Assumes roughly 33% compression ratio average + if (noBuf) + buf = new u8(sl * 3); + // ensure buffer can fit at least l elements + var cbuf = function (l) { + var bl = buf.length; + // need to increase size to fit + if (l > bl) { + // Double or set to necessary, whichever is greater + var nbuf = new u8(Math.max(bl * 2, l)); + nbuf.set(buf); + buf = nbuf; + } + }; + // last chunk bitpos bytes + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + // total bits + var tbts = sl * 8; + do { + if (!lm) { + // BFINAL - this is only 1 when last chunk is next + final = bits(dat, pos, 1); + // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + // go to end of byte boundary + var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; + if (t > sl) { + if (noSt) + err(0); + break; + } + // ensure size + if (resize) + cbuf(bt + l); + // Copy over uncompressed data + buf.set(dat.subarray(s, t), bt); + // Get new bitpos, update byte count + st.b = bt += l, st.p = pos = t * 8, st.f = final; + continue; + } + else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + // literal lengths + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + // length+distance tree + var ldt = new u8(tl); + // code length tree + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + // use index map to get real code + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + // code lengths bits + var clb = max(clt), clbmsk = (1 << clb) - 1; + // code lengths map + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl;) { + var r = clm[bits(dat, pos, clbmsk)]; + // bits read + pos += r & 15; + // symbol + var s = r >> 4; + // code length to copy + if (s < 16) { + ldt[i++] = s; + } + else { + // copy count + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + // length tree distance tree + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + // max length bits + lbt = max(lt); + // max dist bits + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } + else + err(1); + if (pos > tbts) { + if (noSt) + err(0); + break; + } + } + // Make sure the buffer can hold this + the largest possible addition + // Maximum chunk size (practically, theoretically infinite) is 2^17 + if (resize) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (;; lpos = pos) { + // bits read, code + var c = lm[bits16(dat, pos) & lms], sym = c >> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (!c) + err(2); + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } + else { + var add = sym - 254; + // no extra bits needed if less + if (sym > 264) { + // index + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + // dist + var d = dm[bits16(dat, pos) & dms], dsym = d >> 4; + if (!d) + err(3); + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & (1 << b) - 1, pos += b; + } + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (resize) + cbuf(bt + 131072); + var end = bt + add; + if (bt < dt) { + var shift = dl - dt, dend = Math.min(dt, end); + if (shift + bt < 0) + err(3); + for (; bt < dend; ++bt) + buf[bt] = dict[shift + bt]; + } + for (; bt < end; ++bt) + buf[bt] = buf[bt - dt]; + } + } + st.l = lm, st.p = lpos, st.b = bt, st.f = final; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + // don't reallocate for streams or user buffers + return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt); +}; +// starting at p, write the minimum number of bits that can hold v to d +var wbits = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; +}; +// starting at p, write the minimum number of bits (>8) that can hold v to d +var wbits16 = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; + d[o + 2] |= v >> 16; +}; +// creates code lengths from a frequency table +var hTree = function (d, mb) { + // Need extra info to make a tree + var t = []; + for (var i = 0; i < d.length; ++i) { + if (d[i]) + t.push({ s: i, f: d[i] }); + } + var s = t.length; + var t2 = t.slice(); + if (!s) + return { t: et, l: 0 }; + if (s == 1) { + var v = new u8(t[0].s + 1); + v[t[0].s] = 1; + return { t: v, l: 1 }; + } + t.sort(function (a, b) { return a.f - b.f; }); + // after i2 reaches last ind, will be stopped + // freq must be greater than largest possible number of symbols + t.push({ s: -1, f: 25001 }); + var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; + t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; + // efficient algorithm from UZIP.js + // i0 is lookbehind, i2 is lookahead - after processing two low-freq + // symbols that combined have high freq, will start processing i2 (high-freq, + // non-composite) symbols instead + // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ + while (i1 != s - 1) { + l = t[t[i0].f < t[i2].f ? i0++ : i2++]; + r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; + t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; + } + var maxSym = t2[0].s; + for (var i = 1; i < s; ++i) { + if (t2[i].s > maxSym) + maxSym = t2[i].s; + } + // code lengths + var tr = new u16(maxSym + 1); + // max bits in tree + var mbt = ln(t[i1 - 1], tr, 0); + if (mbt > mb) { + // more algorithms from UZIP.js + // TODO: find out how this code works (debt) + // ind debt + var i = 0, dt = 0; + // left cost + var lft = mbt - mb, cst = 1 << lft; + t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); + for (; i < s; ++i) { + var i2_1 = t2[i].s; + if (tr[i2_1] > mb) { + dt += cst - (1 << (mbt - tr[i2_1])); + tr[i2_1] = mb; + } + else + break; + } + dt >>= lft; + while (dt > 0) { + var i2_2 = t2[i].s; + if (tr[i2_2] < mb) + dt -= 1 << (mb - tr[i2_2]++ - 1); + else + ++i; + } + for (; i >= 0 && dt; --i) { + var i2_3 = t2[i].s; + if (tr[i2_3] == mb) { + --tr[i2_3]; + ++dt; + } + } + mbt = mb; + } + return { t: new u8(tr), l: mbt }; +}; +// get the max length and assign length codes +var ln = function (n, l, d) { + return n.s == -1 + ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) + : (l[n.s] = d); +}; +// length codes generation +var lc = function (c) { + var s = c.length; + // Note that the semicolon was intentional + while (s && !c[--s]) + ; + var cl = new u16(++s); + // ind num streak + var cli = 0, cln = c[0], cls = 1; + var w = function (v) { cl[cli++] = v; }; + for (var i = 1; i <= s; ++i) { + if (c[i] == cln && i != s) + ++cls; + else { + if (!cln && cls > 2) { + for (; cls > 138; cls -= 138) + w(32754); + if (cls > 2) { + w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); + cls = 0; + } + } + else if (cls > 3) { + w(cln), --cls; + for (; cls > 6; cls -= 6) + w(8304); + if (cls > 2) + w(((cls - 3) << 5) | 8208), cls = 0; + } + while (cls--) + w(cln); + cls = 1; + cln = c[i]; + } + } + return { c: cl.subarray(0, cli), n: s }; +}; +// calculate the length of output from tree, code lengths +var clen = function (cf, cl) { + var l = 0; + for (var i = 0; i < cl.length; ++i) + l += cf[i] * cl[i]; + return l; +}; +// writes a fixed block +// returns the new bit pos +var wfblk = function (out, pos, dat) { + // no need to write 00 as type: TypedArray defaults to 0 + var s = dat.length; + var o = shft(pos + 2); + out[o] = s & 255; + out[o + 1] = s >> 8; + out[o + 2] = out[o] ^ 255; + out[o + 3] = out[o + 1] ^ 255; + for (var i = 0; i < s; ++i) + out[o + i + 4] = dat[i]; + return (o + 4 + s) * 8; +}; +// writes a block +var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { + wbits(out, p++, final); + ++lf[256]; + var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l; + var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l; + var _c = lc(dlt), lclt = _c.c, nlc = _c.n; + var _d = lc(ddt), lcdt = _d.c, ndc = _d.n; + var lcfreq = new u16(19); + for (var i = 0; i < lclt.length; ++i) + ++lcfreq[lclt[i] & 31]; + for (var i = 0; i < lcdt.length; ++i) + ++lcfreq[lcdt[i] & 31]; + var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l; + var nlcc = 19; + for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) + ; + var flen = (bl + 5) << 3; + var ftlen = clen(lf, flt) + clen(df, fdt) + eb; + var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]; + if (bs >= 0 && flen <= ftlen && flen <= dtlen) + return wfblk(out, p, dat.subarray(bs, bs + bl)); + var lm, ll, dm, dl; + wbits(out, p, 1 + (dtlen < ftlen)), p += 2; + if (dtlen < ftlen) { + lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; + var llm = hMap(lct, mlcb, 0); + wbits(out, p, nlc - 257); + wbits(out, p + 5, ndc - 1); + wbits(out, p + 10, nlcc - 4); + p += 14; + for (var i = 0; i < nlcc; ++i) + wbits(out, p + 3 * i, lct[clim[i]]); + p += 3 * nlcc; + var lcts = [lclt, lcdt]; + for (var it = 0; it < 2; ++it) { + var clct = lcts[it]; + for (var i = 0; i < clct.length; ++i) { + var len = clct[i] & 31; + wbits(out, p, llm[len]), p += lct[len]; + if (len > 15) + wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12; + } + } + } + else { + lm = flm, ll = flt, dm = fdm, dl = fdt; + } + for (var i = 0; i < li; ++i) { + var sym = syms[i]; + if (sym > 255) { + var len = (sym >> 18) & 31; + wbits16(out, p, lm[len + 257]), p += ll[len + 257]; + if (len > 7) + wbits(out, p, (sym >> 23) & 31), p += fleb[len]; + var dst = sym & 31; + wbits16(out, p, dm[dst]), p += dl[dst]; + if (dst > 3) + wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst]; + } + else { + wbits16(out, p, lm[sym]), p += ll[sym]; + } + } + wbits16(out, p, lm[256]); + return p + ll[256]; +}; +// deflate options (nice << 13) | chain +var deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); +// empty +var et = /*#__PURE__*/ new u8(0); +// compresses data into a raw DEFLATE buffer +var dflt = function (dat, lvl, plvl, pre, post, st) { + var s = st.z || dat.length; + var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); + // writing to this writes to the output buffer + var w = o.subarray(pre, o.length - post); + var lst = st.l; + var pos = (st.r || 0) & 7; + if (lvl) { + if (pos) + w[0] = st.r >> 3; + var opt = deo[lvl - 1]; + var n = opt >> 13, c = opt & 8191; + var msk_1 = (1 << plvl) - 1; + // prev 2-byte val map curr 2-byte val map + var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1); + var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; + var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; + // 24576 is an arbitrary number of maximum symbols per block + // 424 buffer for last block + var syms = new i32(25000); + // length/literal freq distance freq + var lf = new u16(288), df = new u16(32); + // l/lcnt exbits index l/lind waitdx blkpos + var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0; + for (; i + 2 < s; ++i) { + // hash value + var hv = hsh(i); + // index mod 32768 previous index mod + var imod = i & 32767, pimod = head[hv]; + prev[imod] = pimod; + head[hv] = imod; + // We always should modify head and prev, but only add symbols if + // this data is not yet processed ("wait" for wait index) + if (wi <= i) { + // bytes remaining + var rem = s - i; + if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) { + pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); + li = lc_1 = eb = 0, bs = i; + for (var j = 0; j < 286; ++j) + lf[j] = 0; + for (var j = 0; j < 30; ++j) + df[j] = 0; + } + // len dist chain + var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767; + if (rem > 2 && hv == hsh(i - dif)) { + var maxn = Math.min(n, rem) - 1; + var maxd = Math.min(32767, i); + // max possible length + // not capped at dif because decompressors implement "rolling" index population + var ml = Math.min(258, rem); + while (dif <= maxd && --ch_1 && imod != pimod) { + if (dat[i + l] == dat[i + l - dif]) { + var nl = 0; + for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) + ; + if (nl > l) { + l = nl, d = dif; + // break out early when we reach "nice" (we are satisfied enough) + if (nl > maxn) + break; + // now, find the rarest 2-byte sequence within this + // length of literals and search for that instead. + // Much faster than just using the start + var mmd = Math.min(dif, nl - 2); + var md = 0; + for (var j = 0; j < mmd; ++j) { + var ti = i - dif + j & 32767; + var pti = prev[ti]; + var cd = ti - pti & 32767; + if (cd > md) + md = cd, pimod = ti; + } + } + } + // check the previous match + imod = pimod, pimod = prev[imod]; + dif += imod - pimod & 32767; + } + } + // d will be nonzero only when a match was found + if (d) { + // store both dist and len data in one int32 + // Make sure this is recognized as a len/dist with 28th bit (2^28) + syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; + var lin = revfl[l] & 31, din = revfd[d] & 31; + eb += fleb[lin] + fdeb[din]; + ++lf[257 + lin]; + ++df[din]; + wi = i + l; + ++lc_1; + } + else { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + } + } + for (i = Math.max(i, wi); i < s; ++i) { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); + if (!lst) { + st.r = (pos & 7) | w[(pos / 8) | 0] << 3; + // shft(pos) now 1 less if pos & 7 != 0 + pos -= 7; + st.h = head, st.p = prev, st.i = i, st.w = wi; + } + } + else { + for (var i = st.w || 0; i < s + lst; i += 65535) { + // end + var e = i + 65535; + if (e >= s) { + // write final block + w[(pos / 8) | 0] = lst; + e = s; + } + pos = wfblk(w, pos + 1, dat.subarray(i, e)); + } + st.i = s; + } + return slc(o, 0, pre + shft(pos) + post); +}; +// CRC32 table +var crct = /*#__PURE__*/ (function () { + var t = new Int32Array(256); + for (var i = 0; i < 256; ++i) { + var c = i, k = 9; + while (--k) + c = ((c & 1) && -306674912) ^ (c >>> 1); + t[i] = c; + } + return t; +})(); +// CRC32 +var crc = function () { + var c = -1; + return { + p: function (d) { + // closures have awful performance + var cr = c; + for (var i = 0; i < d.length; ++i) + cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8); + c = cr; + }, + d: function () { return ~c; } + }; +}; +// Adler32 +var adler = function () { + var a = 1, b = 0; + return { + p: function (d) { + // closures have awful performance + var n = a, m = b; + var l = d.length | 0; + for (var i = 0; i != l;) { + var e = Math.min(i + 2655, l); + for (; i < e; ++i) + m += n += d[i]; + n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); + } + a = n, b = m; + }, + d: function () { + a %= 65521, b %= 65521; + return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8); + } + }; +}; +; +// deflate with opts +var dopt = function (dat, opt, pre, post, st) { + if (!st) { + st = { l: 1 }; + if (opt.dictionary) { + var dict = opt.dictionary.subarray(-32768); + var newDat = new u8(dict.length + dat.length); + newDat.set(dict); + newDat.set(dat, dict.length); + dat = newDat; + st.w = dict.length; + } + } + return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st); +}; +// Walmart object spread +var mrg = function (a, b) { + var o = {}; + for (var k in a) + o[k] = a[k]; + for (var k in b) + o[k] = b[k]; + return o; +}; +// worker clone +// This is possibly the craziest part of the entire codebase, despite how simple it may seem. +// The only parameter to this function is a closure that returns an array of variables outside of the function scope. +// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization. +// We will return an object mapping of true variable name to value (basically, the current scope as a JS object). +// The reason we can't just use the original variable names is minifiers mangling the toplevel scope. +// This took me three weeks to figure out how to do. +var wcln = function (fn, fnStr, td) { + var dt = fn(); + var st = fn.toString(); + var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(','); + for (var i = 0; i < dt.length; ++i) { + var v = dt[i], k = ks[i]; + if (typeof v == 'function') { + fnStr += ';' + k + '='; + var st_1 = v.toString(); + if (v.prototype) { + // for global objects + if (st_1.indexOf('[native code]') != -1) { + var spInd = st_1.indexOf(' ', 8) + 1; + fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd)); + } + else { + fnStr += st_1; + for (var t in v.prototype) + fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString(); + } + } + else + fnStr += st_1; + } + else + td[k] = v; + } + return fnStr; +}; +var ch = []; +// clone bufs +var cbfs = function (v) { + var tl = []; + for (var k in v) { + if (v[k].buffer) { + tl.push((v[k] = new v[k].constructor(v[k])).buffer); + } + } + return tl; +}; +// use a worker to execute code +var wrkr = function (fns, init, id, cb) { + if (!ch[id]) { + var fnStr = '', td_1 = {}, m = fns.length - 1; + for (var i = 0; i < m; ++i) + fnStr = wcln(fns[i], fnStr, td_1); + ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 }; + } + var td = mrg({}, ch[id].e); + return (0, node_worker_1.default)(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb); +}; +// base async inflate fn +var bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; }; +var bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; }; +// gzip extra +var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; }; +// gunzip extra +var guze = function () { return [gzs, gzl]; }; +// zlib extra +var zle = function () { return [zlh, wbytes, adler]; }; +// unzlib extra +var zule = function () { return [zls]; }; +// post buf +var pbf = function (msg) { return postMessage(msg, [msg.buffer]); }; +// get opts +var gopt = function (o) { return o && { + out: o.size && new u8(o.size), + dictionary: o.dictionary +}; }; +// async helper +var cbify = function (dat, opts, fns, init, id, cb) { + var w = wrkr(fns, init, id, function (err, dat) { + w.terminate(); + cb(err, dat); + }); + w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []); + return function () { w.terminate(); }; +}; +// auto stream +var astrm = function (strm) { + strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); }; + return function (ev) { + if (ev.data[0]) { + strm.push(ev.data[0], ev.data[1]); + postMessage([ev.data[0].length]); + } + else + strm.flush(ev.data[1]); + }; +}; +// async stream attach +var astrmify = function (fns, strm, opts, init, id, flush, ext) { + var t; + var w = wrkr(fns, init, id, function (err, dat) { + if (err) + w.terminate(), strm.ondata.call(strm, err); + else if (!Array.isArray(dat)) + ext(dat); + else if (dat.length == 1) { + strm.queuedSize -= dat[0]; + if (strm.ondrain) + strm.ondrain(dat[0]); + } + else { + if (dat[1]) + w.terminate(); + strm.ondata.call(strm, err, dat[0], dat[1]); + } + }); + w.postMessage(opts); + strm.queuedSize = 0; + strm.push = function (d, f) { + if (!strm.ondata) + err(5); + if (t) + strm.ondata(err(4, 0, 1), null, !!f); + strm.queuedSize += d.length; + // can fail for cross-realm Uint8Array, but ok - only a small performance penalty + w.postMessage([d, t = f], d.buffer instanceof ArrayBuffer ? [d.buffer] : []); + }; + strm.terminate = function () { w.terminate(); }; + if (flush) { + strm.flush = function (sync) { w.postMessage([0, sync]); }; + } +}; +// read 2 bytes +var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); }; +// read 4 bytes +var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; }; +// read 8 bytes +var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); }; +// write bytes +var wbytes = function (d, b, v) { + for (; v; ++b) + d[b] = v, v >>>= 8; +}; +// gzip header +var gzh = function (c, o) { + var fn = o.filename; + c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix + if (o.mtime != 0) + wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000)); + if (fn) { + c[3] = 8; + for (var i = 0; i <= fn.length; ++i) + c[i + 10] = fn.charCodeAt(i); + } +}; +// gzip footer: -8 to -4 = CRC, -4 to -0 is length +// gzip start +var gzs = function (d) { + if (d[0] != 31 || d[1] != 139 || d[2] != 8) + err(6, 'invalid gzip data'); + var flg = d[3]; + var st = 10; + if (flg & 4) + st += (d[10] | d[11] << 8) + 2; + for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]) + ; + return st + (flg & 2); +}; +// gzip length +var gzl = function (d) { + var l = d.length; + return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0; +}; +// gzip header length +var gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); }; +// zlib header +var zlh = function (c, o) { + var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; + c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32); + c[1] |= 31 - ((c[0] << 8) | c[1]) % 31; + if (o.dictionary) { + var h = adler(); + h.p(o.dictionary); + wbytes(c, 2, h.d()); + } +}; +// zlib start +var zls = function (d, dict) { + if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31)) + err(6, 'invalid zlib data'); + if ((d[1] >> 5 & 1) == +!dict) + err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary'); + return (d[1] >> 3 & 4) + 2; +}; +function StrmOpt(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + return opts; +} +/** + * Streaming DEFLATE compression + */ +var Deflate = /*#__PURE__*/ (function () { + function Deflate(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + this.o = opts || {}; + this.s = { l: 0, i: 32768, w: 32768, z: 32768 }; + // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev + // 98304 = 32768 (lookback) + 65536 (common chunk size) + this.b = new u8(98304); + if (this.o.dictionary) { + var dict = this.o.dictionary.subarray(-32768); + this.b.set(dict, 32768 - dict.length); + this.s.i = 32768 - dict.length; + } + } + Deflate.prototype.p = function (c, f) { + this.ondata(dopt(c, this.o, 0, 0, this.s), f); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Deflate.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + var endLen = chunk.length + this.s.z; + if (endLen > this.b.length) { + if (endLen > 2 * this.b.length - 32768) { + var newBuf = new u8(endLen & -32768); + newBuf.set(this.b.subarray(0, this.s.z)); + this.b = newBuf; + } + var split = this.b.length - this.s.z; + this.b.set(chunk.subarray(0, split), this.s.z); + this.s.z = this.b.length; + this.p(this.b, false); + this.b.set(this.b.subarray(-32768)); + this.b.set(chunk.subarray(split), 32768); + this.s.z = chunk.length - split + 32768; + this.s.i = 32766, this.s.w = 32768; + } + else { + this.b.set(chunk, this.s.z); + this.s.z += chunk.length; + } + this.s.l = final & 1; + if (this.s.z > this.s.w + 8191 || final) { + this.p(this.b, final || false); + this.s.w = this.s.i, this.s.i -= 2; + } + if (final) { + // cleanup unneeded buffers/state to reduce memory usage + this.s = this.o = {}; + this.b = et; + } + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + Deflate.prototype.flush = function (sync) { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + this.p(this.b, false); + this.s.w = this.s.i, this.s.i -= 2; + // could technically skip writing the type-0 block for (this.s.r & 7) == 0, + // but the deterministic trailer (00 00 FF FF) is useful in some situations + if (sync) { + var c = new u8(6); + c[0] = this.s.r >> 3; + // write empty, non-final type-0 block + var ep = wfblk(c, this.s.r, et); + this.s.r = 0; + this.ondata(c.subarray(0, ep >> 3), false); + } + }; + return Deflate; +}()); +exports.Deflate = Deflate; +/** + * Asynchronous streaming DEFLATE compression + */ +var AsyncDeflate = /*#__PURE__*/ (function () { + function AsyncDeflate(opts, cb) { + astrmify([ + bDflt, + function () { return [astrm, Deflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Deflate(ev.data); + onmessage = astrm(strm); + }, 6, 1); + } + return AsyncDeflate; +}()); +exports.AsyncDeflate = AsyncDeflate; +function deflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb); +} +/** + * Compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @returns The deflated version of the data + */ +function deflateSync(data, opts) { + return dopt(data, opts || {}, 0, 0); +} +/** + * Streaming DEFLATE decompression + */ +var Inflate = /*#__PURE__*/ (function () { + function Inflate(opts, cb) { + // no StrmOpt here to avoid adding to workerizer + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768); + this.s = { i: 0, b: dict ? dict.length : 0 }; + this.o = new u8(32768); + this.p = new u8(0); + if (dict) + this.o.set(dict); + } + Inflate.prototype.e = function (c) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + if (!this.p.length) + this.p = c; + else if (c.length) { + var n = new u8(this.p.length + c.length); + n.set(this.p), n.set(c, this.p.length), this.p = n; + } + }; + Inflate.prototype.c = function (final) { + this.s.i = +(this.d = final || false); + var bts = this.s.b; + var dt = inflt(this.p, this.s, this.o); + this.ondata(slc(dt, bts, this.s.b), this.d); + this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; + this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; + }; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + Inflate.prototype.push = function (chunk, final) { + this.e(chunk), this.c(final); + }; + return Inflate; +}()); +exports.Inflate = Inflate; +/** + * Asynchronous streaming DEFLATE decompression + */ +var AsyncInflate = /*#__PURE__*/ (function () { + function AsyncInflate(opts, cb) { + astrmify([ + bInflt, + function () { return [astrm, Inflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Inflate(ev.data); + onmessage = astrm(strm); + }, 7, 0); + } + return AsyncInflate; +}()); +exports.AsyncInflate = AsyncInflate; +function inflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt + ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb); +} +function inflateSync(data, opts) { + return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize. +/** + * Streaming GZIP compression + */ +var Gzip = /*#__PURE__*/ (function () { + function Gzip(opts, cb) { + this.c = crc(); + this.l = 0; + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gzip.prototype.push = function (chunk, final) { + this.c.p(chunk); + this.l += chunk.length; + Deflate.prototype.push.call(this, chunk, final); + }; + Gzip.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s); + if (this.v) + gzh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + Gzip.prototype.flush = function (sync) { + Deflate.prototype.flush.call(this, sync); + }; + return Gzip; +}()); +exports.Gzip = Gzip; +exports.Compress = Gzip; +/** + * Asynchronous streaming GZIP compression + */ +var AsyncGzip = /*#__PURE__*/ (function () { + function AsyncGzip(opts, cb) { + astrmify([ + bDflt, + gze, + function () { return [astrm, Deflate, Gzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gzip(ev.data); + onmessage = astrm(strm); + }, 8, 1); + } + return AsyncGzip; +}()); +exports.AsyncGzip = AsyncGzip; +exports.AsyncCompress = AsyncGzip; +function gzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + gze, + function () { return [gzipSync]; } + ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb); +} +/** + * Compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @returns The gzipped version of the data + */ +function gzipSync(data, opts) { + if (!opts) + opts = {}; + var c = crc(), l = data.length; + c.p(data); + var d = dopt(data, opts, gzhl(opts), 8), s = d.length; + return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d; +} +/** + * Streaming single or multi-member GZIP decompression + */ +var Gunzip = /*#__PURE__*/ (function () { + function Gunzip(opts, cb) { + this.v = 1; + this.r = 0; + Inflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gunzip.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + this.r += chunk.length; + if (this.v) { + var p = this.p.subarray(this.v - 1); + var s = p.length > 3 ? gzs(p) : 4; + if (s > p.length) { + if (!final) + return; + } + else if (this.v > 1 && this.onmember) { + this.onmember(this.r - p.length); + } + this.p = p.subarray(s), this.v = 0; + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, 0); + // process concatenated GZIP + if (this.s.f && !this.s.l) { + this.v = shft(this.s.p) + 9; + this.s = { i: 0 }; + this.o = new u8(0); + this.push(new u8(0), final); + } + else if (final) { + Inflate.prototype.c.call(this, final); + } + }; + return Gunzip; +}()); +exports.Gunzip = Gunzip; +/** + * Asynchronous streaming single or multi-member GZIP decompression + */ +var AsyncGunzip = /*#__PURE__*/ (function () { + function AsyncGunzip(opts, cb) { + var _this = this; + astrmify([ + bInflt, + guze, + function () { return [astrm, Inflate, Gunzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gunzip(ev.data); + strm.onmember = function (offset) { return postMessage(offset); }; + onmessage = astrm(strm); + }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); }); + } + return AsyncGunzip; +}()); +exports.AsyncGunzip = AsyncGunzip; +function gunzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + guze, + function () { return [gunzipSync]; } + ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb); +} +function gunzipSync(data, opts) { + var st = gzs(data); + if (st + 8 > data.length) + err(6, 'invalid gzip data'); + return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary); +} +/** + * Streaming Zlib compression + */ +var Zlib = /*#__PURE__*/ (function () { + function Zlib(opts, cb) { + this.c = adler(); + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Zlib.prototype.push = function (chunk, final) { + this.c.p(chunk); + Deflate.prototype.push.call(this, chunk, final); + }; + Zlib.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s); + if (this.v) + zlh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 4, this.c.d()); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + Zlib.prototype.flush = function (sync) { + Deflate.prototype.flush.call(this, sync); + }; + return Zlib; +}()); +exports.Zlib = Zlib; +/** + * Asynchronous streaming Zlib compression + */ +var AsyncZlib = /*#__PURE__*/ (function () { + function AsyncZlib(opts, cb) { + astrmify([ + bDflt, + zle, + function () { return [astrm, Deflate, Zlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Zlib(ev.data); + onmessage = astrm(strm); + }, 10, 1); + } + return AsyncZlib; +}()); +exports.AsyncZlib = AsyncZlib; +function zlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + zle, + function () { return [zlibSync]; } + ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb); +} +/** + * Compress data with Zlib + * @param data The data to compress + * @param opts The compression options + * @returns The zlib-compressed version of the data + */ +function zlibSync(data, opts) { + if (!opts) + opts = {}; + var a = adler(); + a.p(data); + var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4); + return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d; +} +/** + * Streaming Zlib decompression + */ +var Unzlib = /*#__PURE__*/ (function () { + function Unzlib(opts, cb) { + Inflate.call(this, opts, cb); + this.v = opts && opts.dictionary ? 2 : 1; + } + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzlib.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + if (this.v) { + if (this.p.length < 6 && !final) + return; + this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0; + } + if (final) { + if (this.p.length < 4) + err(6, 'invalid zlib data'); + this.p = this.p.subarray(0, -4); + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + }; + return Unzlib; +}()); +exports.Unzlib = Unzlib; +/** + * Asynchronous streaming Zlib decompression + */ +var AsyncUnzlib = /*#__PURE__*/ (function () { + function AsyncUnzlib(opts, cb) { + astrmify([ + bInflt, + zule, + function () { return [astrm, Inflate, Unzlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Unzlib(ev.data); + onmessage = astrm(strm); + }, 11, 0); + } + return AsyncUnzlib; +}()); +exports.AsyncUnzlib = AsyncUnzlib; +function unzlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + zule, + function () { return [unzlibSync]; } + ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb); +} +function unzlibSync(data, opts) { + return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +/** + * Streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var Decompress = /*#__PURE__*/ (function () { + function Decompress(opts, cb) { + this.o = StrmOpt.call(this, opts, cb) || {}; + this.G = Gunzip; + this.I = Inflate; + this.Z = Unzlib; + } + // init substream + // overriden by AsyncDecompress + Decompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (dat, final) { + _this.ondata(dat, final); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Decompress.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (!this.s) { + if (this.p && this.p.length) { + var n = new u8(this.p.length + chunk.length); + n.set(this.p), n.set(chunk, this.p.length); + } + else + this.p = chunk; + if (this.p.length > 2) { + this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8) + ? new this.G(this.o) + : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31)) + ? new this.I(this.o) + : new this.Z(this.o); + this.i(); + this.s.push(this.p, final); + this.p = null; + } + } + else + this.s.push(chunk, final); + }; + return Decompress; +}()); +exports.Decompress = Decompress; +/** + * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var AsyncDecompress = /*#__PURE__*/ (function () { + function AsyncDecompress(opts, cb) { + Decompress.call(this, opts, cb); + this.queuedSize = 0; + this.G = AsyncGunzip; + this.I = AsyncInflate; + this.Z = AsyncUnzlib; + } + AsyncDecompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (err, dat, final) { + _this.ondata(err, dat, final); + }; + this.s.ondrain = function (size) { + _this.queuedSize -= size; + if (_this.ondrain) + _this.ondrain(size); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncDecompress.prototype.push = function (chunk, final) { + this.queuedSize += chunk.length; + Decompress.prototype.push.call(this, chunk, final); + }; + return AsyncDecompress; +}()); +exports.AsyncDecompress = AsyncDecompress; +function decompress(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzip(data, opts, cb) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflate(data, opts, cb) + : unzlib(data, opts, cb); +} +/** + * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +function decompressSync(data, opts) { + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzipSync(data, opts) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflateSync(data, opts) + : unzlibSync(data, opts); +} +// flatten a directory structure +var fltn = function (d, p, t, o) { + for (var k in d) { + var val = d[k], n = p + k, op = o; + if (Array.isArray(val)) + op = mrg(o, val[1]), val = val[0]; + if (ArrayBuffer.isView(val)) + t[n] = [val, op]; + else { + t[n += '/'] = [new u8(0), op]; + fltn(val, n, t, o); + } + } +}; +// text encoder +var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder(); +// text decoder +var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); +// text decoder stream +var tds = 0; +try { + td.decode(et, { stream: true }); + tds = 1; +} +catch (e) { } +// decode UTF8 +var dutf8 = function (d) { + for (var r = '', i = 0;;) { + var c = d[i++]; + var eb = (c > 127) + (c > 223) + (c > 239); + if (i + eb > d.length) + return { s: r, r: slc(d, i - 1) }; + if (!eb) + r += String.fromCharCode(c); + else if (eb == 3) { + c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536, + r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023)); + } + else if (eb & 1) + r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63)); + else + r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)); + } +}; +/** + * Streaming UTF-8 decoding + */ +var DecodeUTF8 = /*#__PURE__*/ (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is decoded + */ + function DecodeUTF8(cb) { + this.ondata = cb; + if (tds) + this.t = new TextDecoder(); + else + this.p = et; + } + /** + * Pushes a chunk to be decoded from UTF-8 binary + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + DecodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + final = !!final; + if (this.t) { + this.ondata(this.t.decode(chunk, { stream: true }), final); + if (final) { + if (this.t.decode().length) + err(8); + this.t = null; + } + return; + } + if (!this.p) + err(4); + var dat = new u8(this.p.length + chunk.length); + dat.set(this.p); + dat.set(chunk, this.p.length); + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (final) { + if (r.length) + err(8); + this.p = null; + } + else + this.p = r; + this.ondata(s, final); + }; + return DecodeUTF8; +}()); +exports.DecodeUTF8 = DecodeUTF8; +/** + * Streaming UTF-8 encoding + */ +var EncodeUTF8 = /*#__PURE__*/ (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is encoded + */ + function EncodeUTF8(cb) { + this.ondata = cb; + } + /** + * Pushes a chunk to be encoded to UTF-8 + * @param chunk The string data to push + * @param final Whether this is the last chunk + */ + EncodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + this.ondata(strToU8(chunk), this.d = final || false); + }; + return EncodeUTF8; +}()); +exports.EncodeUTF8 = EncodeUTF8; +/** + * Converts a string into a Uint8Array for use with compression/decompression methods + * @param str The string to encode + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless decoding a binary string. + * @returns The string encoded in UTF-8/Latin-1 binary + */ +function strToU8(str, latin1) { + if (latin1) { + var ar_1 = new u8(str.length); + for (var i = 0; i < str.length; ++i) + ar_1[i] = str.charCodeAt(i); + return ar_1; + } + if (te) + return te.encode(str); + var l = str.length; + var ar = new u8(str.length + (str.length >> 1)); + var ai = 0; + var w = function (v) { ar[ai++] = v; }; + for (var i = 0; i < l; ++i) { + if (ai + 5 > ar.length) { + var n = new u8(ai + 8 + ((l - i) << 1)); + n.set(ar); + ar = n; + } + var c = str.charCodeAt(i); + if (c < 128 || latin1) + w(c); + else if (c < 2048) + w(192 | (c >> 6)), w(128 | (c & 63)); + else if (c > 55295 && c < 57344) + c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023), + w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + else + w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + } + return slc(ar, 0, ai); +} +/** + * Converts a Uint8Array to a string + * @param dat The data to decode to string + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless encoding to binary string. + * @returns The original UTF-8/Latin-1 string + */ +function strFromU8(dat, latin1) { + if (latin1) { + var r = ''; + for (var i = 0; i < dat.length; i += 16384) + r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384)); + return r; + } + else if (td) { + return td.decode(dat); + } + else { + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (r.length) + err(8); + return s; + } +} +; +// deflate bit flag +var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; }; +// skip local zip header +var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); }; +// read zip header +var zh = function (d, b, z) { + var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl; + var _a = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a[0], su = _a[1], off = _a[2]; + return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off]; +}; +// read zip64 header sizes +var z64hs = function (d, b, l, z, sc, su, off) { + var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l; + var nf = nsc + nsu + noff; + if (z && nf) { + for (; b + 4 < e; b += 4 + b2(d, b + 2)) { + if (b2(d, b) == 1) { + return [ + nsc ? b8(d, b + 4 + 8 * nsu) : sc, + nsu ? b8(d, b + 4) : su, + noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off, + 1 + ]; + } + } + // z == 2 for unknown whether or not zip64 + if (z < 2) + err(13); + } + return [sc, su, off, 0]; +}; +// extra field length +var exfl = function (ex) { + var le = 0; + if (ex) { + for (var k in ex) { + var l = ex[k].length; + if (l > 65535) + err(9); + le += l + 4; + } + } + return le; +}; +// write zip header +var wzh = function (d, b, f, fn, u, c, ce, co) { + var fl = fn.length, ex = f.extra, col = co && co.length; + var exl = exfl(ex); + wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4; + if (ce != null) + d[b++] = 20, d[b++] = f.os; + d[b] = 20, b += 2; // spec compliance? what's that? + d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8; + d[b++] = f.compression & 255, d[b++] = f.compression >> 8; + var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980; + if (y < 0 || y > 119) + err(10); + wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4; + if (c != -1) { + wbytes(d, b, f.crc); + wbytes(d, b + 4, c < 0 ? -c - 2 : c); + wbytes(d, b + 8, f.size); + } + wbytes(d, b + 12, fl); + wbytes(d, b + 14, exl), b += 16; + if (ce != null) { + wbytes(d, b, col); + wbytes(d, b + 6, f.attrs); + wbytes(d, b + 10, ce), b += 14; + } + d.set(fn, b); + b += fl; + if (exl) { + for (var k in ex) { + var exf = ex[k], l = exf.length; + wbytes(d, b, +k); + wbytes(d, b + 2, l); + d.set(exf, b + 4), b += 4 + l; + } + } + if (col) + d.set(co, b), b += col; + return b; +}; +// write zip footer (end of central directory) +var wzf = function (o, b, c, d, e) { + wbytes(o, b, 0x6054B50); // skip disk + wbytes(o, b + 8, c); + wbytes(o, b + 10, c); + wbytes(o, b + 12, d); + wbytes(o, b + 16, e); +}; +/** + * A pass-through stream to keep data uncompressed in a ZIP archive. + */ +var ZipPassThrough = /*#__PURE__*/ (function () { + /** + * Creates a pass-through stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + */ + function ZipPassThrough(filename) { + this.filename = filename; + this.c = crc(); + this.size = 0; + this.compression = 0; + } + /** + * Processes a chunk and pushes to the output stream. You can override this + * method in a subclass for custom behavior, but by default this passes + * the data through. You must call this.ondata(err, chunk, final) at some + * point in this method. + * @param chunk The chunk to process + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.process = function (chunk, final) { + this.ondata(null, chunk, final); + }; + /** + * Pushes a chunk to be added. If you are subclassing this with a custom + * compression algorithm, note that you must push data from the source + * file only, pre-compression. + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + this.c.p(chunk); + this.size += chunk.length; + if (final) + this.crc = this.c.d(); + // we shouldn't really do this cast, but properly handling ArrayBufferLike + // makes the API unergonomic with Buffer + this.process(chunk, final || false); + }; + return ZipPassThrough; +}()); +exports.ZipPassThrough = ZipPassThrough; +// I don't extend because TypeScript extension adds 1kB of runtime bloat +/** + * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate + * for better performance + */ +var ZipDeflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function ZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new Deflate(opts, function (dat, final) { + _this.ondata(null, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + } + ZipDeflate.prototype.process = function (chunk, final) { + try { + this.d.push(chunk, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return ZipDeflate; +}()); +exports.ZipDeflate = ZipDeflate; +/** + * Asynchronous streaming DEFLATE compression for ZIP archives + */ +var AsyncZipDeflate = /*#__PURE__*/ (function () { + /** + * Creates an asynchronous DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function AsyncZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new AsyncDeflate(opts, function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + this.terminate = this.d.terminate; + } + AsyncZipDeflate.prototype.process = function (chunk, final) { + this.d.push(chunk, final); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return AsyncZipDeflate; +}()); +exports.AsyncZipDeflate = AsyncZipDeflate; +// TODO: Better tree shaking +/** + * A zippable archive to which files can incrementally be added + */ +var Zip = /*#__PURE__*/ (function () { + /** + * Creates an empty ZIP archive to which files can be added + * @param cb The callback to call whenever data for the generated ZIP archive + * is available + */ + function Zip(cb) { + this.ondata = cb; + this.u = []; + this.d = 1; + } + /** + * Adds a file to the ZIP archive + * @param file The file stream to add + */ + Zip.prototype.add = function (file) { + var _this = this; + if (!this.ondata) + err(5); + // finishing or finished + if (this.d & 2) + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false); + else { + var f = strToU8(file.filename), fl_1 = f.length; + var com = file.comment, o = com && strToU8(com); + var u = fl_1 != file.filename.length || (o && (com.length != o.length)); + var hl_1 = fl_1 + exfl(file.extra) + 30; + if (fl_1 > 65535) + this.ondata(err(11, 0, 1), null, false); + var header = new u8(hl_1); + wzh(header, 0, file, f, u, -1); + var chks_1 = [header]; + var pAll_1 = function () { + for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) { + var chk = chks_2[_i]; + _this.ondata(null, chk, false); + } + chks_1 = []; + }; + var tr_1 = this.d; + this.d = 0; + var ind_1 = this.u.length; + var uf_1 = mrg(file, { + f: f, + u: u, + o: o, + t: function () { + if (file.terminate) + file.terminate(); + }, + r: function () { + pAll_1(); + if (tr_1) { + var nxt = _this.u[ind_1 + 1]; + if (nxt) + nxt.r(); + else + _this.d = 1; + } + tr_1 = 1; + } + }); + var cl_1 = 0; + file.ondata = function (err, dat, final) { + if (err) { + _this.ondata(err, dat, final); + _this.terminate(); + } + else { + cl_1 += dat.length; + chks_1.push(dat); + if (final) { + var dd = new u8(16); + wbytes(dd, 0, 0x8074B50); + wbytes(dd, 4, file.crc); + wbytes(dd, 8, cl_1); + wbytes(dd, 12, file.size); + chks_1.push(dd); + uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size; + if (tr_1) + uf_1.r(); + tr_1 = 1; + } + else if (tr_1) + pAll_1(); + } + }; + this.u.push(uf_1); + } + }; + /** + * Ends the process of adding files and prepares to emit the final chunks. + * This *must* be called after adding all desired files for the resulting + * ZIP file to work properly. + */ + Zip.prototype.end = function () { + var _this = this; + if (this.d & 2) { + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true); + return; + } + if (this.d) + this.e(); + else + this.u.push({ + r: function () { + if (!(_this.d & 1)) + return; + _this.u.splice(-1, 1); + _this.e(); + }, + t: function () { } + }); + this.d = 3; + }; + Zip.prototype.e = function () { + var bt = 0, l = 0, tl = 0; + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0); + } + var out = new u8(tl + 22); + for (var _b = 0, _c = this.u; _b < _c.length; _b++) { + var f = _c[_b]; + wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o); + bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b; + } + wzf(out, bt, this.u.length, tl, l); + this.ondata(null, out, true); + this.d = 2; + }; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to add() will fail. + */ + Zip.prototype.terminate = function () { + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + f.t(); + } + this.d = 2; + }; + return Zip; +}()); +exports.Zip = Zip; +function zip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var r = {}; + fltn(data, '', r, opts); + var k = Object.keys(r); + var lft = k.length, o = 0, tot = 0; + var slft = lft, files = new Array(lft); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var cbf = function () { + var out = new u8(tot + 22), oe = o, cdl = tot - o; + tot = 0; + for (var i = 0; i < slft; ++i) { + var f = files[i]; + try { + var l = f.c.length; + wzh(out, tot, f, f.f, f.u, l); + var badd = 30 + f.f.length + exfl(f.extra); + var loc = tot + badd; + out.set(f.c, loc); + wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l; + } + catch (e) { + return cbd(e, null); + } + } + wzf(out, o, files.length, cdl, oe); + cbd(null, out); + }; + if (!lft) + cbf(); + var _loop_1 = function (i) { + var fn = k[i]; + var _a = r[fn], file = _a[0], p = _a[1]; + var c = crc(), size = file.length; + c.p(file); + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + var compression = p.level == 0 ? 0 : 8; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + var l = d.length; + files[i] = mrg(p, { + size: size, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + compression: compression + }); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + if (!--lft) + cbf(); + } + }; + if (s > 65535) + cbl(err(11, 0, 1), null); + if (!compression) + cbl(null, file); + else if (size < 160000) { + try { + cbl(null, deflateSync(file, p)); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(deflate(file, p, cbl)); + }; + // Cannot use lft because it can decrease + for (var i = 0; i < slft; ++i) { + _loop_1(i); + } + return tAll; +} +/** + * Synchronously creates a ZIP file. Prefer using `zip` for better performance + * with more than one file. + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @returns The generated ZIP archive + */ +function zipSync(data, opts) { + if (!opts) + opts = {}; + var r = {}; + var files = []; + fltn(data, '', r, opts); + var o = 0; + var tot = 0; + for (var fn in r) { + var _a = r[fn], file = _a[0], p = _a[1]; + var compression = p.level == 0 ? 0 : 8; + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + if (s > 65535) + err(11); + var d = compression ? deflateSync(file, p) : file, l = d.length; + var c = crc(); + c.p(file); + files.push(mrg(p, { + size: file.length, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + o: o, + compression: compression + })); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + } + var out = new u8(tot + 22), oe = o, cdl = tot - o; + for (var i = 0; i < files.length; ++i) { + var f = files[i]; + wzh(out, f.o, f, f.f, f.u, f.c.length); + var badd = 30 + f.f.length + exfl(f.extra); + out.set(f.c, f.o + badd); + wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0); + } + wzf(out, o, files.length, cdl, oe); + return out; +} +/** + * Streaming pass-through decompression for ZIP archives + */ +var UnzipPassThrough = /*#__PURE__*/ (function () { + function UnzipPassThrough() { + } + UnzipPassThrough.prototype.push = function (chunk, final) { + // same as ZipPassThrough: cast to retain Buffer ergonomics + this.ondata(null, chunk, final); + }; + UnzipPassThrough.compression = 0; + return UnzipPassThrough; +}()); +exports.UnzipPassThrough = UnzipPassThrough; +/** + * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for + * better performance. + */ +var UnzipInflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function UnzipInflate() { + var _this = this; + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + UnzipInflate.prototype.push = function (chunk, final) { + try { + this.i.push(chunk, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + UnzipInflate.compression = 8; + return UnzipInflate; +}()); +exports.UnzipInflate = UnzipInflate; +/** + * Asynchronous streaming DEFLATE decompression for ZIP archives + */ +var AsyncUnzipInflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function AsyncUnzipInflate(_, sz) { + var _this = this; + if (sz < 320000) { + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + else { + this.i = new AsyncInflate(function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.terminate = this.i.terminate; + } + } + AsyncUnzipInflate.prototype.push = function (chunk, final) { + if (this.i.terminate) + chunk = slc(chunk, 0); + this.i.push(chunk, final); + }; + AsyncUnzipInflate.compression = 8; + return AsyncUnzipInflate; +}()); +exports.AsyncUnzipInflate = AsyncUnzipInflate; +/** + * A ZIP archive decompression stream that emits files as they are discovered + */ +var Unzip = /*#__PURE__*/ (function () { + /** + * Creates a ZIP decompression stream + * @param cb The callback to call whenever a file in the ZIP archive is found + */ + function Unzip(cb) { + this.onfile = cb; + this.k = []; + this.o = { + 0: UnzipPassThrough + }; + this.p = et; + } + /** + * Pushes a chunk to be unzipped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzip.prototype.push = function (chunk, final) { + var _this = this; + if (!this.onfile) + err(5); + if (!this.p) + err(4); + if (this.c > 0) { + var len = Math.min(this.c, chunk.length); + var toAdd = chunk.subarray(0, len); + this.c -= len; + if (this.d) + this.d.push(toAdd, !this.c); + else + this.k[0].push(toAdd); + chunk = chunk.subarray(len); + if (chunk.length) + return this.push(chunk, final); + } + else { + var f = 0, i = 0, is = void 0, buf = void 0; + if (!this.p.length) + buf = chunk; + else if (!chunk.length) + buf = this.p; + else { + buf = new u8(this.p.length + chunk.length); + buf.set(this.p), buf.set(chunk, this.p.length); + } + var l = buf.length, oc = this.c, add = oc && this.d; + var _loop_2 = function () { + var sig = b4(buf, i); + if (sig == 0x4034B50) { + f = 1, is = i; + this_1.d = null; + this_1.c = 0; + var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28); + if (l > i + 30 + fnl + es) { + var chks_3 = []; + this_1.k.unshift(chks_3); + f = 2; + var lsc = b4(buf, i + 18), lsu = b4(buf, i + 22); + var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u); + var _a = z64hs(buf, i, es, 2, lsc, lsu, 0), sc_1 = _a[0], su_1 = _a[1], z64 = _a[3]; + if (dd) + sc_1 = -1 - z64; + i += es; + this_1.c = sc_1; + var d_1; + var file_1 = { + name: fn_1, + compression: cmp_1, + start: function () { + if (!file_1.ondata) + err(5); + if (!sc_1) + file_1.ondata(null, et, true); + else { + var ctr = _this.o[cmp_1]; + if (!ctr) + file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false); + d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1); + d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); }; + for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) { + var dat = chks_4[_i]; + d_1.push(dat, false); + } + if (_this.k[0] == chks_3 && _this.c) + _this.d = d_1; + else + d_1.push(et, true); + } + }, + terminate: function () { + if (d_1 && d_1.terminate) + d_1.terminate(); + } + }; + if (sc_1 >= 0) + file_1.size = sc_1, file_1.originalSize = su_1; + this_1.onfile(file_1); + } + return "break"; + } + else if (oc) { + if (sig == 0x8074B50) { + is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0; + return "break"; + } + else if (sig == 0x2014B50) { + is = i -= 4, f = 3, this_1.c = 0; + return "break"; + } + } + }; + var this_1 = this; + for (; i < l - 4; ++i) { + var state_1 = _loop_2(); + if (state_1 === "break") + break; + } + this.p = et; + if (oc < 0) { + var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i); + if (add) + add.push(dat, !!f); + else + this.k[+(f == 2)].push(dat); + } + if (f & 2) + return this.push(buf.subarray(i), final); + this.p = buf.subarray(i); + } + if (final) { + if (this.c) + err(13); + this.p = null; + } + }; + /** + * Registers a decoder with the stream, allowing for files compressed with + * the compression type provided to be expanded correctly + * @param decoder The decoder constructor + */ + Unzip.prototype.register = function (decoder) { + this.o[decoder.compression] = decoder; + }; + return Unzip; +}()); +exports.Unzip = Unzip; +var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); }; +function unzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var files = {}; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) { + cbd(err(13, 0, 1), null); + return tAll; + } + } + ; + var lft = b2(data, e + 8); + if (lft) { + var c = lft; + var o = b4(data, e + 16); + var z = b4(data, e - 20) == 0x7064B50; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = lft = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + var _loop_3 = function (i) { + var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + if (d) + files[fn] = d; + if (!--lft) + cbd(null, files); + } + }; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_1 + })) { + if (!c_1) + cbl(null, slc(data, b, b + sc)); + else if (c_1 == 8) { + var infl = data.subarray(b, b + sc); + // Synchronously decompress under 512KB, or barely-compressed data + if (su < 524288 || sc > 0.8 * su) { + try { + cbl(null, inflateSync(infl, { out: new u8(su) })); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(inflate(infl, { size: su }, cbl)); + } + else + cbl(err(14, 'unknown compression type ' + c_1, 1), null); + } + else + cbl(null, null); + }; + for (var i = 0; i < c; ++i) { + _loop_3(i); + } + } + else + cbd(null, {}); + return tAll; +} +/** + * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better + * performance with more than one file. + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @returns The decompressed files + */ +function unzipSync(data, opts) { + var files = {}; + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) + err(13); + } + ; + var c = b2(data, e + 8); + if (!c) + return {}; + var o = b4(data, e + 16); + var z = b4(data, e - 20) == 0x7064B50; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + for (var i = 0; i < c; ++i) { + var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_2 + })) { + if (!c_2) + files[fn] = slc(data, b, b + sc); + else if (c_2 == 8) + files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) }); + else + err(14, 'unknown compression type ' + c_2); + } + } + return files; +} diff --git a/node_modules/fflate/lib/index.d.ts b/node_modules/fflate/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d430faf2b555c978d66c89f46155b72c2c45a971 --- /dev/null +++ b/node_modules/fflate/lib/index.d.ts @@ -0,0 +1,1539 @@ +/** + * Codes for errors generated within this library + */ +export declare const FlateErrorCode: { + readonly UnexpectedEOF: 0; + readonly InvalidBlockType: 1; + readonly InvalidLengthLiteral: 2; + readonly InvalidDistance: 3; + readonly StreamFinished: 4; + readonly NoStreamHandler: 5; + readonly InvalidHeader: 6; + readonly NoCallback: 7; + readonly InvalidUTF8: 8; + readonly ExtraFieldTooLong: 9; + readonly InvalidDate: 10; + readonly FilenameTooLong: 11; + readonly StreamFinishing: 12; + readonly InvalidZipData: 13; + readonly UnknownCompressionMethod: 14; +}; +/** + * An error generated within this library + */ +export interface FlateError extends Error { + /** + * The code associated with this error + */ + code: number; +} +/** + * Options for decompressing a DEFLATE stream + */ +export interface InflateStreamOptions { + /** + * The dictionary used to compress the original data. If no dictionary was used during compression, this option has no effect. + * + * Supplying the wrong dictionary during decompression usually yields corrupt output or causes an invalid distance error. + */ + dictionary?: Uint8Array; +} +/** + * Options for decompressing DEFLATE data + */ +export interface InflateOptions extends InflateStreamOptions { + /** + * The buffer into which to write the decompressed data. Saves memory if you know the decompressed size in advance. + * + * Note that if the decompression result is larger than the size of this buffer, it will be truncated to fit. + */ + out?: Uint8Array; +} +/** + * Options for decompressing a GZIP stream + */ +export interface GunzipStreamOptions extends InflateStreamOptions { +} +/** + * Options for decompressing GZIP data + */ +export interface GunzipOptions extends InflateStreamOptions { + /** + * The buffer into which to write the decompressed data. GZIP already encodes the output size, so providing this doesn't save memory. + * + * Note that if the decompression result is larger than the size of this buffer, it will be truncated to fit. + */ + out?: Uint8Array; +} +/** + * Options for decompressing a Zlib stream + */ +export interface UnzlibStreamOptions extends InflateStreamOptions { +} +/** + * Options for decompressing Zlib data + */ +export interface UnzlibOptions extends InflateOptions { +} +/** + * Options for compressing data into a DEFLATE format + */ +export interface DeflateOptions { + /** + * The level of compression to use, ranging from 0-9. + * + * 0 will store the data without compression. + * 1 is fastest but compresses the worst, 9 is slowest but compresses the best. + * The default level is 6. + * + * Typically, binary data benefits much more from higher values than text data. + * In both cases, higher values usually take disproportionately longer than the reduction in final size that results. + * + * For example, a 1 MB text file could: + * - become 1.01 MB with level 0 in 1ms + * - become 400 kB with level 1 in 10ms + * - become 320 kB with level 9 in 100ms + */ + level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + /** + * The memory level to use, ranging from 0-12. Increasing this increases speed and compression ratio at the cost of memory. + * + * Note that this is exponential: while level 0 uses 8 kB, level 4 uses 128 kB, level 8 uses 2 MB, and level 12 uses 32 MB. + * It is recommended not to lower the value below 4, since that tends to hurt performance. + * In addition, values above 8 tend to help very little on most data and can even hurt performance. + * + * The default value is automatically determined based on the size of the input data. + */ + mem?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; + /** + * A buffer containing common byte sequences in the input data that can be used to significantly improve compression ratios. + * + * Dictionaries should be 32kB or smaller and include strings or byte sequences likely to appear in the input. + * The decompressor must supply the same dictionary as the compressor to extract the original data. + * + * Dictionaries only improve aggregate compression ratio when reused across multiple small inputs. They should typically not be used otherwise. + * + * Avoid using dictionaries with GZIP and ZIP to maximize software compatibility. + */ + dictionary?: Uint8Array; +} +/** + * Options for compressing data into a GZIP format + */ +export interface GzipOptions extends DeflateOptions { + /** + * When the file was last modified. Defaults to the current time. + * Set this to 0 to avoid revealing a modification date entirely. + */ + mtime?: Date | string | number; + /** + * The filename of the data. If the `gunzip` command is used to decompress the data, it will output a file + * with this name instead of the name of the compressed file. + */ + filename?: string; +} +/** + * Options for compressing data into a Zlib format + */ +export interface ZlibOptions extends DeflateOptions { +} +/** + * Handler for data (de)compression streams + * @param data The data output from the stream processor + * @param final Whether this is the final block + */ +export type FlateStreamHandler = (data: Uint8Array, final: boolean) => void; +/** + * Handler for asynchronous data (de)compression streams + * @param err Any error that occurred + * @param data The data output from the stream processor + * @param final Whether this is the final block + */ +export type AsyncFlateStreamHandler = (err: FlateError | null, data: Uint8Array, final: boolean) => void; +/** + * Handler for the asynchronous completion of (de)compression for a data chunk + * @param size The number of bytes that were processed. This is measured in terms of the input + * (i.e. compressed bytes for decompression, uncompressed bytes for compression.) + */ +export type AsyncFlateDrainHandler = (size: number) => void; +/** + * Callback for asynchronous (de)compression methods + * @param err Any error that occurred + * @param data The resulting data. Only present if `err` is null + */ +export type FlateCallback = (err: FlateError | null, data: Uint8Array) => void; +interface AsyncOptions { + /** + * Whether or not to "consume" the source data. This will make the typed array/buffer you pass in + * unusable but will increase performance and reduce memory usage. + */ + consume?: boolean; +} +/** + * Options for compressing data asynchronously into a DEFLATE format + */ +export interface AsyncDeflateOptions extends DeflateOptions, AsyncOptions { +} +/** + * Options for decompressing DEFLATE data asynchronously + */ +export interface AsyncInflateOptions extends AsyncOptions, InflateStreamOptions { + /** + * The original size of the data. Currently, the asynchronous API disallows + * writing into a buffer you provide; the best you can do is provide the + * size in bytes and be given back a new typed array. + */ + size?: number; +} +/** + * Options for compressing data asynchronously into a GZIP format + */ +export interface AsyncGzipOptions extends GzipOptions, AsyncOptions { +} +/** + * Options for decompressing GZIP data asynchronously + */ +export interface AsyncGunzipOptions extends AsyncOptions, InflateStreamOptions { +} +/** + * Options for compressing data asynchronously into a Zlib format + */ +export interface AsyncZlibOptions extends ZlibOptions, AsyncOptions { +} +/** + * Options for decompressing Zlib data asynchronously + */ +export interface AsyncUnzlibOptions extends AsyncInflateOptions { +} +/** + * A terminable compression/decompression process + */ +export interface AsyncTerminable { + /** + * Terminates the worker thread immediately. The callback will not be called. + */ + (): void; +} +/** + * Streaming DEFLATE compression + */ +export declare class Deflate { + /** + * Creates a DEFLATE stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: DeflateOptions, cb?: FlateStreamHandler); + /** + * Creates a DEFLATE stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + private b; + private s; + private o; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + private p; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE compression + */ +export declare class AsyncDeflate { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous DEFLATE stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: DeflateOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous DEFLATE stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function deflate(data: Uint8Array, opts: AsyncDeflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param cb The function to be called upon compression completion + */ +export declare function deflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @returns The deflated version of the data + */ +export declare function deflateSync(data: Uint8Array, opts?: DeflateOptions): Uint8Array; +/** + * Streaming DEFLATE decompression + */ +export declare class Inflate { + private s; + private o; + private p; + private d; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a DEFLATE decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: InflateStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a DEFLATE decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + private e; + private c; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE decompression + */ +export declare class AsyncInflate { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous DEFLATE decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: InflateStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous DEFLATE decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function inflate(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function inflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands DEFLATE data with no wrapper + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function inflateSync(data: Uint8Array): Uint8Array; +/** + * Expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function inflateSync(data: Uint8Array, opts?: InflateOptions): Uint8Array; +/** + * Streaming GZIP compression + */ +export declare class Gzip { + private c; + private l; + private v; + private o; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a GZIP stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: GzipOptions, cb?: FlateStreamHandler); + /** + * Creates a GZIP stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + private p; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming GZIP compression + */ +export declare class AsyncGzip { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous GZIP stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: GzipOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous GZIP stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function gzip(data: Uint8Array, opts: AsyncGzipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with GZIP + * @param data The data to compress + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @returns The gzipped version of the data + */ +export declare function gzipSync(data: Uint8Array, opts?: GzipOptions): Uint8Array; +/** + * Handler for new GZIP members in concatenated GZIP streams. Useful for building indices used to perform random-access reads on compressed files. + * @param offset The offset of the new member relative to the start of the stream + */ +export type GunzipMemberHandler = (offset: number) => void; +/** + * Streaming single or multi-member GZIP decompression + */ +export declare class Gunzip { + private v; + private r; + private o; + private p; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * The handler to call whenever a new GZIP member is found + */ + onmember?: GunzipMemberHandler; + /** + * Creates a GUNZIP stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: GunzipStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a GUNZIP stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming single or multi-member GZIP decompression + */ +export declare class AsyncGunzip { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * The handler to call whenever a new GZIP member is found + */ + onmember?: GunzipMemberHandler; + /** + * Creates an asynchronous GUNZIP stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: GunzipStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous GUNZIP stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands GZIP data + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gunzip(data: Uint8Array, opts: AsyncGunzipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands GZIP data + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gunzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands GZIP data + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function gunzipSync(data: Uint8Array): Uint8Array; +/** + * Expands GZIP data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function gunzipSync(data: Uint8Array, opts?: GunzipOptions): Uint8Array; +/** + * Streaming Zlib compression + */ +export declare class Zlib { + private c; + private v; + private o; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a Zlib stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: ZlibOptions, cb?: FlateStreamHandler); + /** + * Creates a Zlib stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + private p; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming Zlib compression + */ +export declare class AsyncZlib { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous Zlib stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: ZlibOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous Zlib stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with Zlib + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + */ +export declare function zlib(data: Uint8Array, opts: AsyncZlibOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with Zlib + * @param data The data to compress + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compress data with Zlib + * @param data The data to compress + * @param opts The compression options + * @returns The zlib-compressed version of the data + */ +export declare function zlibSync(data: Uint8Array, opts?: ZlibOptions): Uint8Array; +/** + * Streaming Zlib decompression + */ +export declare class Unzlib { + private v; + private p; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a Zlib decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: UnzlibStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming Zlib decompression + */ +export declare class AsyncUnzlib { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous Zlib decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: UnzlibStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be decompressed from Zlib + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands Zlib data + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function unzlib(data: Uint8Array, opts: AsyncUnzlibOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands Zlib data + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function unzlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands Zlib data + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function unzlibSync(data: Uint8Array): Uint8Array; +/** + * Expands Zlib data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function unzlibSync(data: Uint8Array, opts?: UnzlibOptions): Uint8Array; +export { gzip as compress, AsyncGzip as AsyncCompress }; +export { gzipSync as compressSync, Gzip as Compress }; +/** + * Streaming GZIP, Zlib, or raw DEFLATE decompression + */ +export declare class Decompress { + private G; + private I; + private Z; + private o; + private s; + private p; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is decompressed + */ + constructor(opts: InflateStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a decompression stream + * @param cb The callback to call whenever data is decompressed + */ + constructor(cb?: FlateStreamHandler); + private i; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression + */ +export declare class AsyncDecompress { + private G; + private I; + private Z; + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is decompressed + */ + constructor(opts: InflateStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous decompression stream + * @param cb The callback to call whenever data is decompressed + */ + constructor(cb?: AsyncFlateStreamHandler); + private i; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function decompress(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function decompress(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function decompressSync(data: Uint8Array, opts?: InflateOptions): Uint8Array; +/** + * Attributes for files added to a ZIP archive object + */ +export interface ZipAttributes { + /** + * The operating system of origin for this file. The value is defined + * by PKZIP's APPNOTE.txt, section 4.4.2.2. For example, 0 (the default) + * is MS/DOS, 3 is Unix, 19 is macOS. + */ + os?: number; + /** + * The file's attributes. These are traditionally somewhat complicated + * and platform-dependent, so using them is scarcely necessary. However, + * here is a representation of what this is, bit by bit: + * + * `TTTTugtrwxrwxrwx0000000000ADVSHR` + * + * TTTT = file type (rarely useful) + * + * u = setuid, g = setgid, t = sticky + * + * rwx = user permissions, rwx = group permissions, rwx = other permissions + * + * 0000000000 = unused + * + * A = archive, D = directory, V = volume label, S = system file, H = hidden, R = read-only + * + * If you want to set the Unix permissions, for instance, just bit shift by 16, e.g. 0o644 << 16. + * Note that attributes usually only work in conjunction with the `os` setting: you must use + * `os` = 3 (Unix) if you want to set Unix permissions + */ + attrs?: number; + /** + * Extra metadata to add to the file. This field is defined by PKZIP's APPNOTE.txt, + * section 4.4.28. At most 65,535 bytes may be used in each ID. The ID must be an + * integer between 0 and 65,535, inclusive. + * + * This field is incredibly rare and almost never needed except for compliance with + * proprietary standards and software. + */ + extra?: Record; + /** + * The comment to attach to the file. This field is defined by PKZIP's APPNOTE.txt, + * section 4.4.26. The comment must be at most 65,535 bytes long UTF-8 encoded. This + * field is not read by consumer software. + */ + comment?: string; + /** + * When the file was last modified. Defaults to the current time. + */ + mtime?: GzipOptions['mtime']; +} +/** + * Options for creating a ZIP archive + */ +export interface ZipOptions extends DeflateOptions, ZipAttributes { +} +/** + * Options for expanding a ZIP archive + */ +export interface UnzipOptions { + /** + * A filter function to extract only certain files from a ZIP archive + */ + filter?: UnzipFileFilter; +} +/** + * Options for asynchronously creating a ZIP archive + */ +export interface AsyncZipOptions extends AsyncDeflateOptions, ZipAttributes { +} +/** + * Options for asynchronously expanding a ZIP archive + */ +export interface AsyncUnzipOptions extends UnzipOptions { +} +/** + * A file that can be used to create a ZIP archive + */ +export type ZippableFile = Uint8Array | Zippable | [Uint8Array | Zippable, ZipOptions]; +/** + * A file that can be used to asynchronously create a ZIP archive + */ +export type AsyncZippableFile = Uint8Array | AsyncZippable | [Uint8Array | AsyncZippable, AsyncZipOptions]; +/** + * The complete directory structure of a ZIPpable archive + */ +export interface Zippable { + [path: string]: ZippableFile; +} +/** + * The complete directory structure of an asynchronously ZIPpable archive + */ +export interface AsyncZippable { + [path: string]: AsyncZippableFile; +} +/** + * An unzipped archive. The full path of each file is used as the key, + * and the file is the value + */ +export interface Unzipped { + [path: string]: Uint8Array; +} +/** + * Handler for string generation streams + * @param data The string output from the stream processor + * @param final Whether this is the final block + */ +export type StringStreamHandler = (data: string, final: boolean) => void; +/** + * Callback for asynchronous ZIP decompression + * @param err Any error that occurred + * @param data The decompressed ZIP archive + */ +export type UnzipCallback = (err: FlateError | null, data: Unzipped) => void; +/** + * Handler for streaming ZIP decompression + * @param file The file that was found in the archive + */ +export type UnzipFileHandler = (file: UnzipFile) => void; +/** + * Streaming UTF-8 decoding + */ +export declare class DecodeUTF8 { + private p; + private t; + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is decoded + */ + constructor(cb?: StringStreamHandler); + /** + * Pushes a chunk to be decoded from UTF-8 binary + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * The handler to call whenever data is available + */ + ondata: StringStreamHandler; +} +/** + * Streaming UTF-8 encoding + */ +export declare class EncodeUTF8 { + private d; + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is encoded + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be encoded to UTF-8 + * @param chunk The string data to push + * @param final Whether this is the last chunk + */ + push(chunk: string, final?: boolean): void; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; +} +/** + * Converts a string into a Uint8Array for use with compression/decompression methods + * @param str The string to encode + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless decoding a binary string. + * @returns The string encoded in UTF-8/Latin-1 binary + */ +export declare function strToU8(str: string, latin1?: boolean): Uint8Array; +/** + * Converts a Uint8Array to a string + * @param dat The data to decode to string + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless encoding to binary string. + * @returns The original UTF-8/Latin-1 string + */ +export declare function strFromU8(dat: Uint8Array, latin1?: boolean): string; +/** + * A stream that can be used to create a file in a ZIP archive + */ +export interface ZipInputFile extends ZipAttributes { + /** + * The filename to associate with the data provided to this stream. If you + * want a file in a subdirectory, use forward slashes as a separator (e.g. + * `directory/filename.ext`). This will still work on Windows. + */ + filename: string; + /** + * The size of the file in bytes. This attribute may be invalid after + * the file is added to the ZIP archive; it must be correct only before the + * stream completes. + * + * If you don't want to have to compute this yourself, consider extending the + * ZipPassThrough class and overriding its process() method, or using one of + * ZipDeflate or AsyncZipDeflate. + */ + size: number; + /** + * A CRC of the original file contents. This attribute may be invalid after + * the file is added to the ZIP archive; it must be correct only before the + * stream completes. + * + * If you don't want to have to generate this yourself, consider extending the + * ZipPassThrough class and overriding its process() method, or using one of + * ZipDeflate or AsyncZipDeflate. + */ + crc: number; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA + */ + compression: number; + /** + * Bits 1 and 2 of the general purpose bit flag, specified in PKZIP's + * APPNOTE.txt, section 4.4.4. Should be between 0 and 3. This is unlikely + * to be necessary. + */ + flag?: number; + /** + * The handler to be called when data is added. After passing this stream to + * the ZIP file object, this handler will always be defined. To call it: + * + * `stream.ondata(error, chunk, final)` + * + * error = any error that occurred (null if there was no error) + * + * chunk = a Uint8Array of the data that was added (null if there was an + * error) + * + * final = boolean, whether this is the final chunk in the stream + */ + ondata?: AsyncFlateStreamHandler; + /** + * A method called when the stream is no longer needed, for clean-up + * purposes. This will not always be called after the stream completes, + * so you may wish to call this.terminate() after the final chunk is + * processed if you have clean-up logic. + */ + terminate?: AsyncTerminable; +} +/** + * A pass-through stream to keep data uncompressed in a ZIP archive. + */ +export declare class ZipPassThrough implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private c; + /** + * Creates a pass-through stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + */ + constructor(filename: string); + /** + * Processes a chunk and pushes to the output stream. You can override this + * method in a subclass for custom behavior, but by default this passes + * the data through. You must call this.ondata(err, chunk, final) at some + * point in this method. + * @param chunk The chunk to process + * @param final Whether this is the last chunk + */ + protected process(chunk: Uint8Array, final: boolean): void; + /** + * Pushes a chunk to be added. If you are subclassing this with a custom + * compression algorithm, note that you must push data from the source + * file only, pre-compression. + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate + * for better performance + */ +export declare class ZipDeflate implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + flag: 0 | 1 | 2 | 3; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private d; + /** + * Creates a DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + constructor(filename: string, opts?: DeflateOptions); + private process; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE compression for ZIP archives + */ +export declare class AsyncZipDeflate implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + flag: 0 | 1 | 2 | 3; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private d; + terminate: AsyncTerminable; + /** + * Creates an asynchronous DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + constructor(filename: string, opts?: DeflateOptions); + private process; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * A zippable archive to which files can incrementally be added + */ +export declare class Zip { + private u; + private d; + /** + * Creates an empty ZIP archive to which files can be added + * @param cb The callback to call whenever data for the generated ZIP archive + * is available + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Adds a file to the ZIP archive + * @param file The file stream to add + */ + add(file: ZipInputFile): void; + /** + * Ends the process of adding files and prepares to emit the final chunks. + * This *must* be called after adding all desired files for the resulting + * ZIP file to work properly. + */ + end(): void; + private e; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to add() will fail. + */ + terminate(): void; + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; +} +/** + * Asynchronously creates a ZIP file + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @param cb The callback to call with the generated ZIP archive + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zip(data: AsyncZippable, opts: AsyncZipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously creates a ZIP file + * @param data The directory structure for the ZIP archive + * @param cb The callback to call with the generated ZIP archive + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zip(data: AsyncZippable, cb: FlateCallback): AsyncTerminable; +/** + * Synchronously creates a ZIP file. Prefer using `zip` for better performance + * with more than one file. + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @returns The generated ZIP archive + */ +export declare function zipSync(data: Zippable, opts?: ZipOptions): Uint8Array; +/** + * A decoder for files in ZIP streams + */ +export interface UnzipDecoder { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * Pushes a chunk to be decompressed + * @param chunk The data in this chunk. Do not consume (detach) this buffer. + * @param final Whether this is the last chunk in the data stream + */ + push(chunk: Uint8Array, final: boolean): void; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to push() should silently fail. + */ + terminate?: AsyncTerminable; +} +/** + * A constructor for a decoder for unzip streams + */ +export interface UnzipDecoderConstructor { + /** + * Creates an instance of the decoder + * @param filename The name of the file + * @param size The compressed size of the file + * @param originalSize The original size of the file + */ + new (filename: string, size?: number, originalSize?: number): UnzipDecoder; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA + */ + compression: number; +} +/** + * Information about a file to be extracted from a ZIP archive + */ +export interface UnzipFileInfo { + /** + * The name of the file + */ + name: string; + /** + * The compressed size of the file + */ + size: number; + /** + * The original size of the file + */ + originalSize: number; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA. If the filter function returns true + * but this value is not 8, the unzip function will throw. + */ + compression: number; +} +/** + * A filter for files to be extracted during the unzipping process + * @param file The info for the current file being processed + * @returns Whether or not to extract the current file + */ +export type UnzipFileFilter = (file: UnzipFileInfo) => boolean; +/** + * Streaming file extraction from ZIP archives + */ +export interface UnzipFile { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The name of the file + */ + name: string; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA. If start() is called but there is no + * decompression stream available for this method, start() will throw. + */ + compression: number; + /** + * The compressed size of the file. Will not be present for archives created + * in a streaming fashion. + */ + size?: number; + /** + * The original size of the file. Will not be present for archives created + * in a streaming fashion. + */ + originalSize?: number; + /** + * Starts reading from the stream. Calling this function will always enable + * this stream, but ocassionally the stream will be enabled even without + * this being called. + */ + start(): void; + /** + * A method to terminate any internal workers used by the stream. ondata + * will not be called any further. + */ + terminate: AsyncTerminable; +} +/** + * Streaming pass-through decompression for ZIP archives + */ +export declare class UnzipPassThrough implements UnzipDecoder { + static compression: number; + ondata: AsyncFlateStreamHandler; + push(chunk: Uint8Array, final: boolean): void; +} +/** + * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for + * better performance. + */ +export declare class UnzipInflate implements UnzipDecoder { + static compression: number; + private i; + ondata: AsyncFlateStreamHandler; + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + constructor(); + push(chunk: Uint8Array, final: boolean): void; +} +/** + * Asynchronous streaming DEFLATE decompression for ZIP archives + */ +export declare class AsyncUnzipInflate implements UnzipDecoder { + static compression: number; + private i; + ondata: AsyncFlateStreamHandler; + terminate: AsyncTerminable; + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + constructor(_: string, sz?: number); + push(chunk: Uint8Array, final: boolean): void; +} +/** + * A ZIP archive decompression stream that emits files as they are discovered + */ +export declare class Unzip { + private d; + private c; + private p; + private k; + private o; + /** + * Creates a ZIP decompression stream + * @param cb The callback to call whenever a file in the ZIP archive is found + */ + constructor(cb?: UnzipFileHandler); + /** + * Pushes a chunk to be unzipped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Registers a decoder with the stream, allowing for files compressed with + * the compression type provided to be expanded correctly + * @param decoder The decoder constructor + */ + register(decoder: UnzipDecoderConstructor): void; + /** + * The handler to call whenever a file is discovered + */ + onfile: UnzipFileHandler; +} +/** + * Asynchronously decompresses a ZIP archive + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @param cb The callback to call with the decompressed files + * @returns A function that can be used to immediately terminate the unzipping + */ +export declare function unzip(data: Uint8Array, opts: AsyncUnzipOptions, cb: UnzipCallback): AsyncTerminable; +/** + * Asynchronously decompresses a ZIP archive + * @param data The raw compressed ZIP file + * @param cb The callback to call with the decompressed files + * @returns A function that can be used to immediately terminate the unzipping + */ +export declare function unzip(data: Uint8Array, cb: UnzipCallback): AsyncTerminable; +/** + * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better + * performance with more than one file. + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @returns The decompressed files + */ +export declare function unzipSync(data: Uint8Array, opts?: UnzipOptions): Unzipped; diff --git a/node_modules/fflate/lib/node-worker.cjs b/node_modules/fflate/lib/node-worker.cjs new file mode 100644 index 0000000000000000000000000000000000000000..6546f8e8d7aa05fd379331631cbba0271764952c --- /dev/null +++ b/node_modules/fflate/lib/node-worker.cjs @@ -0,0 +1,36 @@ +"use strict"; +var _a; +// Mediocre shim +var Worker; +var isMarkedAsUntransferable; +var workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global"; +try { + (_a = require('worker_threads'), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable); +} +catch (e) { +} +exports.default = Worker ? function (c, _, msg, transfer, cb) { + var done = false; + var w = new Worker(c + workerAdd, { eval: true }) + .on('error', function (e) { return cb(e, null); }) + .on('message', function (m) { return cb(null, m); }) + .on('exit', function (c) { + if (c && !done) + cb(new Error('exited with code ' + c), null); + }); + if (isMarkedAsUntransferable) + transfer = transfer.filter(function (t) { return !isMarkedAsUntransferable(t); }); + w.postMessage(msg, transfer); + w.terminate = function () { + done = true; + return Worker.prototype.terminate.call(w); + }; + return w; +} : function (_, __, ___, ____, cb) { + setImmediate(function () { return cb(new Error('async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)'), null); }); + var NOP = function () { }; + return { + terminate: NOP, + postMessage: NOP + }; +}; diff --git a/node_modules/fflate/lib/node.cjs b/node_modules/fflate/lib/node.cjs new file mode 100644 index 0000000000000000000000000000000000000000..2af184ee06114ac0939176ed868915d2d48a903a --- /dev/null +++ b/node_modules/fflate/lib/node.cjs @@ -0,0 +1,2733 @@ +"use strict"; +// DEFLATE is a complex format; to read this code, you should probably check the RFC first: +// https://tools.ietf.org/html/rfc1951 +// You may also wish to take a look at the guide I made about this program: +// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad +exports.deflate = deflate; +exports.deflateSync = deflateSync; +exports.inflate = inflate; +exports.inflateSync = inflateSync; +exports.gzip = gzip; +exports.compress = gzip; +exports.gzipSync = gzipSync; +exports.compressSync = gzipSync; +exports.gunzip = gunzip; +exports.gunzipSync = gunzipSync; +exports.zlib = zlib; +exports.zlibSync = zlibSync; +exports.unzlib = unzlib; +exports.unzlibSync = unzlibSync; +exports.gzip = gzip; +exports.compress = gzip; +exports.decompress = decompress; +exports.decompressSync = decompressSync; +exports.strToU8 = strToU8; +exports.strFromU8 = strFromU8; +exports.zip = zip; +exports.zipSync = zipSync; +exports.unzip = unzip; +exports.unzipSync = unzipSync; +// Some of the following code is similar to that of UZIP.js: +// https://github.com/photopea/UZIP.js +// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size. +// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint +// is better for memory in most engines (I *think*). +var _a; +// Mediocre shim +var Worker; +var isMarkedAsUntransferable; +var workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global"; +try { + (_a = require('worker_threads'), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable); +} +catch (e) { +} +var node_worker_1 = {}; +node_worker_1["default"] = Worker ? function (c, _, msg, transfer, cb) { + var done = false; + var w = new Worker(c + workerAdd, { eval: true }) + .on('error', function (e) { return cb(e, null); }) + .on('message', function (m) { return cb(null, m); }) + .on('exit', function (c) { + if (c && !done) + cb(new Error('exited with code ' + c), null); + }); + if (isMarkedAsUntransferable) + transfer = transfer.filter(function (t) { return !isMarkedAsUntransferable(t); }); + w.postMessage(msg, transfer); + w.terminate = function () { + done = true; + return Worker.prototype.terminate.call(w); + }; + return w; +} : function (_, __, ___, ____, cb) { + setImmediate(function () { return cb(new Error('async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)'), null); }); + var NOP = function () { }; + return { + terminate: NOP, + postMessage: NOP + }; +}; + +// aliases for shorter compressed code (most minifers don't do this) +var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array; +// fixed length extra bits +var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]); +// fixed distance extra bits +var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]); +// code length index map +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +// get base, reverse index map from extra bits +var freb = function (eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + // numbers here are at max 18 bits + var r = new i32(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = ((j - b[i]) << 5) | i; + } + } + return { b: b, r: r }; +}; +var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r; +// we can ignore the fact that the other numbers are wrong; they never happen anyway +fl[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r; +// map of value to reverse (assuming 16 bits) +var rev = new u16(32768); +for (var i = 0; i < 32768; ++i) { + // reverse table algorithm from SO + var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1); + x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2); + x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4); + rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1; +} +// create huffman tree from u8 "map": index -> code length for code index +// mb (max bits) must be at most 15 +// TODO: optimize/split up? +var hMap = (function (cd, mb, r) { + var s = cd.length; + // index + var i = 0; + // u16 "map": index -> # of codes with bit length = index + var l = new u16(mb); + // length of cd must be 288 (total # of codes) + for (; i < s; ++i) { + if (cd[i]) + ++l[cd[i] - 1]; + } + // u16 "map": index -> minimum code for bit length = index + var le = new u16(mb); + for (i = 1; i < mb; ++i) { + le[i] = (le[i - 1] + l[i - 1]) << 1; + } + var co; + if (r) { + // u16 "map": index -> number of actual bits, symbol for code + co = new u16(1 << mb); + // bits to remove for reverser + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + // ignore 0 lengths + if (cd[i]) { + // num encoding both symbol and bits read + var sv = (i << 4) | cd[i]; + // free bits + var r_1 = mb - cd[i]; + // start value + var v = le[cd[i] - 1]++ << r_1; + // m is end value + for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { + // every 16 bit value starting with the code yields the same result + co[rev[v] >> rvb] = sv; + } + } + } + } + else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]); + } + } + } + return co; +}); +// fixed length tree +var flt = new u8(288); +for (var i = 0; i < 144; ++i) + flt[i] = 8; +for (var i = 144; i < 256; ++i) + flt[i] = 9; +for (var i = 256; i < 280; ++i) + flt[i] = 7; +for (var i = 280; i < 288; ++i) + flt[i] = 8; +// fixed distance tree +var fdt = new u8(32); +for (var i = 0; i < 32; ++i) + fdt[i] = 5; +// fixed length map +var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); +// fixed distance map +var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); +// find max of array +var max = function (a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; +}; +// read d, starting at bit p and mask with m +var bits = function (d, p, m) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; +}; +// read d, starting at bit p continuing for at least 16 bits +var bits16 = function (d, p) { + var o = (p / 8) | 0; + return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); +}; +// get end of byte +var shft = function (p) { return ((p + 7) / 8) | 0; }; +// typed array slice - allows garbage collector to free original reference, +// while being more compatible than .slice +var slc = function (v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + // can't use .constructor in case user-supplied + return new u8(v.subarray(s, e)); +}; +/** + * Codes for errors generated within this library + */ +exports.FlateErrorCode = { + UnexpectedEOF: 0, + InvalidBlockType: 1, + InvalidLengthLiteral: 2, + InvalidDistance: 3, + StreamFinished: 4, + NoStreamHandler: 5, + InvalidHeader: 6, + NoCallback: 7, + InvalidUTF8: 8, + ExtraFieldTooLong: 9, + InvalidDate: 10, + FilenameTooLong: 11, + StreamFinishing: 12, + InvalidZipData: 13, + UnknownCompressionMethod: 14 +}; +// error codes +var ec = [ + 'unexpected EOF', + 'invalid block type', + 'invalid length/literal', + 'invalid distance', + 'stream finished', + 'no stream handler', + , // determined by compression function + 'no callback', + 'invalid UTF-8 data', + 'extra field too long', + 'date not in range 1980-2099', + 'filename too long', + 'stream finishing', + 'invalid zip data' + // determined by unknown compression method +]; +; +var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; +}; +// expands raw DEFLATE data +var inflt = function (dat, st, buf, dict) { + // source length dict length + var sl = dat.length, dl = dict ? dict.length : 0; + if (!sl || st.f && !st.l) + return buf || new u8(0); + var noBuf = !buf; + // have to estimate size + var resize = noBuf || st.i != 2; + // no state + var noSt = st.i; + // Assumes roughly 33% compression ratio average + if (noBuf) + buf = new u8(sl * 3); + // ensure buffer can fit at least l elements + var cbuf = function (l) { + var bl = buf.length; + // need to increase size to fit + if (l > bl) { + // Double or set to necessary, whichever is greater + var nbuf = new u8(Math.max(bl * 2, l)); + nbuf.set(buf); + buf = nbuf; + } + }; + // last chunk bitpos bytes + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + // total bits + var tbts = sl * 8; + do { + if (!lm) { + // BFINAL - this is only 1 when last chunk is next + final = bits(dat, pos, 1); + // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + // go to end of byte boundary + var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; + if (t > sl) { + if (noSt) + err(0); + break; + } + // ensure size + if (resize) + cbuf(bt + l); + // Copy over uncompressed data + buf.set(dat.subarray(s, t), bt); + // Get new bitpos, update byte count + st.b = bt += l, st.p = pos = t * 8, st.f = final; + continue; + } + else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + // literal lengths + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + // length+distance tree + var ldt = new u8(tl); + // code length tree + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + // use index map to get real code + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + // code lengths bits + var clb = max(clt), clbmsk = (1 << clb) - 1; + // code lengths map + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl;) { + var r = clm[bits(dat, pos, clbmsk)]; + // bits read + pos += r & 15; + // symbol + var s = r >> 4; + // code length to copy + if (s < 16) { + ldt[i++] = s; + } + else { + // copy count + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + // length tree distance tree + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + // max length bits + lbt = max(lt); + // max dist bits + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } + else + err(1); + if (pos > tbts) { + if (noSt) + err(0); + break; + } + } + // Make sure the buffer can hold this + the largest possible addition + // Maximum chunk size (practically, theoretically infinite) is 2^17 + if (resize) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (;; lpos = pos) { + // bits read, code + var c = lm[bits16(dat, pos) & lms], sym = c >> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (!c) + err(2); + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } + else { + var add = sym - 254; + // no extra bits needed if less + if (sym > 264) { + // index + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + // dist + var d = dm[bits16(dat, pos) & dms], dsym = d >> 4; + if (!d) + err(3); + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & (1 << b) - 1, pos += b; + } + if (pos > tbts) { + if (noSt) + err(0); + break; + } + if (resize) + cbuf(bt + 131072); + var end = bt + add; + if (bt < dt) { + var shift = dl - dt, dend = Math.min(dt, end); + if (shift + bt < 0) + err(3); + for (; bt < dend; ++bt) + buf[bt] = dict[shift + bt]; + } + for (; bt < end; ++bt) + buf[bt] = buf[bt - dt]; + } + } + st.l = lm, st.p = lpos, st.b = bt, st.f = final; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + // don't reallocate for streams or user buffers + return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt); +}; +// starting at p, write the minimum number of bits that can hold v to d +var wbits = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; +}; +// starting at p, write the minimum number of bits (>8) that can hold v to d +var wbits16 = function (d, p, v) { + v <<= p & 7; + var o = (p / 8) | 0; + d[o] |= v; + d[o + 1] |= v >> 8; + d[o + 2] |= v >> 16; +}; +// creates code lengths from a frequency table +var hTree = function (d, mb) { + // Need extra info to make a tree + var t = []; + for (var i = 0; i < d.length; ++i) { + if (d[i]) + t.push({ s: i, f: d[i] }); + } + var s = t.length; + var t2 = t.slice(); + if (!s) + return { t: et, l: 0 }; + if (s == 1) { + var v = new u8(t[0].s + 1); + v[t[0].s] = 1; + return { t: v, l: 1 }; + } + t.sort(function (a, b) { return a.f - b.f; }); + // after i2 reaches last ind, will be stopped + // freq must be greater than largest possible number of symbols + t.push({ s: -1, f: 25001 }); + var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; + t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; + // efficient algorithm from UZIP.js + // i0 is lookbehind, i2 is lookahead - after processing two low-freq + // symbols that combined have high freq, will start processing i2 (high-freq, + // non-composite) symbols instead + // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ + while (i1 != s - 1) { + l = t[t[i0].f < t[i2].f ? i0++ : i2++]; + r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; + t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; + } + var maxSym = t2[0].s; + for (var i = 1; i < s; ++i) { + if (t2[i].s > maxSym) + maxSym = t2[i].s; + } + // code lengths + var tr = new u16(maxSym + 1); + // max bits in tree + var mbt = ln(t[i1 - 1], tr, 0); + if (mbt > mb) { + // more algorithms from UZIP.js + // TODO: find out how this code works (debt) + // ind debt + var i = 0, dt = 0; + // left cost + var lft = mbt - mb, cst = 1 << lft; + t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); + for (; i < s; ++i) { + var i2_1 = t2[i].s; + if (tr[i2_1] > mb) { + dt += cst - (1 << (mbt - tr[i2_1])); + tr[i2_1] = mb; + } + else + break; + } + dt >>= lft; + while (dt > 0) { + var i2_2 = t2[i].s; + if (tr[i2_2] < mb) + dt -= 1 << (mb - tr[i2_2]++ - 1); + else + ++i; + } + for (; i >= 0 && dt; --i) { + var i2_3 = t2[i].s; + if (tr[i2_3] == mb) { + --tr[i2_3]; + ++dt; + } + } + mbt = mb; + } + return { t: new u8(tr), l: mbt }; +}; +// get the max length and assign length codes +var ln = function (n, l, d) { + return n.s == -1 + ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) + : (l[n.s] = d); +}; +// length codes generation +var lc = function (c) { + var s = c.length; + // Note that the semicolon was intentional + while (s && !c[--s]) + ; + var cl = new u16(++s); + // ind num streak + var cli = 0, cln = c[0], cls = 1; + var w = function (v) { cl[cli++] = v; }; + for (var i = 1; i <= s; ++i) { + if (c[i] == cln && i != s) + ++cls; + else { + if (!cln && cls > 2) { + for (; cls > 138; cls -= 138) + w(32754); + if (cls > 2) { + w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); + cls = 0; + } + } + else if (cls > 3) { + w(cln), --cls; + for (; cls > 6; cls -= 6) + w(8304); + if (cls > 2) + w(((cls - 3) << 5) | 8208), cls = 0; + } + while (cls--) + w(cln); + cls = 1; + cln = c[i]; + } + } + return { c: cl.subarray(0, cli), n: s }; +}; +// calculate the length of output from tree, code lengths +var clen = function (cf, cl) { + var l = 0; + for (var i = 0; i < cl.length; ++i) + l += cf[i] * cl[i]; + return l; +}; +// writes a fixed block +// returns the new bit pos +var wfblk = function (out, pos, dat) { + // no need to write 00 as type: TypedArray defaults to 0 + var s = dat.length; + var o = shft(pos + 2); + out[o] = s & 255; + out[o + 1] = s >> 8; + out[o + 2] = out[o] ^ 255; + out[o + 3] = out[o + 1] ^ 255; + for (var i = 0; i < s; ++i) + out[o + i + 4] = dat[i]; + return (o + 4 + s) * 8; +}; +// writes a block +var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { + wbits(out, p++, final); + ++lf[256]; + var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l; + var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l; + var _c = lc(dlt), lclt = _c.c, nlc = _c.n; + var _d = lc(ddt), lcdt = _d.c, ndc = _d.n; + var lcfreq = new u16(19); + for (var i = 0; i < lclt.length; ++i) + ++lcfreq[lclt[i] & 31]; + for (var i = 0; i < lcdt.length; ++i) + ++lcfreq[lcdt[i] & 31]; + var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l; + var nlcc = 19; + for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) + ; + var flen = (bl + 5) << 3; + var ftlen = clen(lf, flt) + clen(df, fdt) + eb; + var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]; + if (bs >= 0 && flen <= ftlen && flen <= dtlen) + return wfblk(out, p, dat.subarray(bs, bs + bl)); + var lm, ll, dm, dl; + wbits(out, p, 1 + (dtlen < ftlen)), p += 2; + if (dtlen < ftlen) { + lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; + var llm = hMap(lct, mlcb, 0); + wbits(out, p, nlc - 257); + wbits(out, p + 5, ndc - 1); + wbits(out, p + 10, nlcc - 4); + p += 14; + for (var i = 0; i < nlcc; ++i) + wbits(out, p + 3 * i, lct[clim[i]]); + p += 3 * nlcc; + var lcts = [lclt, lcdt]; + for (var it = 0; it < 2; ++it) { + var clct = lcts[it]; + for (var i = 0; i < clct.length; ++i) { + var len = clct[i] & 31; + wbits(out, p, llm[len]), p += lct[len]; + if (len > 15) + wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12; + } + } + } + else { + lm = flm, ll = flt, dm = fdm, dl = fdt; + } + for (var i = 0; i < li; ++i) { + var sym = syms[i]; + if (sym > 255) { + var len = (sym >> 18) & 31; + wbits16(out, p, lm[len + 257]), p += ll[len + 257]; + if (len > 7) + wbits(out, p, (sym >> 23) & 31), p += fleb[len]; + var dst = sym & 31; + wbits16(out, p, dm[dst]), p += dl[dst]; + if (dst > 3) + wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst]; + } + else { + wbits16(out, p, lm[sym]), p += ll[sym]; + } + } + wbits16(out, p, lm[256]); + return p + ll[256]; +}; +// deflate options (nice << 13) | chain +var deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); +// empty +var et = /*#__PURE__*/ new u8(0); +// compresses data into a raw DEFLATE buffer +var dflt = function (dat, lvl, plvl, pre, post, st) { + var s = st.z || dat.length; + var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); + // writing to this writes to the output buffer + var w = o.subarray(pre, o.length - post); + var lst = st.l; + var pos = (st.r || 0) & 7; + if (lvl) { + if (pos) + w[0] = st.r >> 3; + var opt = deo[lvl - 1]; + var n = opt >> 13, c = opt & 8191; + var msk_1 = (1 << plvl) - 1; + // prev 2-byte val map curr 2-byte val map + var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1); + var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; + var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; + // 24576 is an arbitrary number of maximum symbols per block + // 424 buffer for last block + var syms = new i32(25000); + // length/literal freq distance freq + var lf = new u16(288), df = new u16(32); + // l/lcnt exbits index l/lind waitdx blkpos + var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0; + for (; i + 2 < s; ++i) { + // hash value + var hv = hsh(i); + // index mod 32768 previous index mod + var imod = i & 32767, pimod = head[hv]; + prev[imod] = pimod; + head[hv] = imod; + // We always should modify head and prev, but only add symbols if + // this data is not yet processed ("wait" for wait index) + if (wi <= i) { + // bytes remaining + var rem = s - i; + if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) { + pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); + li = lc_1 = eb = 0, bs = i; + for (var j = 0; j < 286; ++j) + lf[j] = 0; + for (var j = 0; j < 30; ++j) + df[j] = 0; + } + // len dist chain + var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767; + if (rem > 2 && hv == hsh(i - dif)) { + var maxn = Math.min(n, rem) - 1; + var maxd = Math.min(32767, i); + // max possible length + // not capped at dif because decompressors implement "rolling" index population + var ml = Math.min(258, rem); + while (dif <= maxd && --ch_1 && imod != pimod) { + if (dat[i + l] == dat[i + l - dif]) { + var nl = 0; + for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) + ; + if (nl > l) { + l = nl, d = dif; + // break out early when we reach "nice" (we are satisfied enough) + if (nl > maxn) + break; + // now, find the rarest 2-byte sequence within this + // length of literals and search for that instead. + // Much faster than just using the start + var mmd = Math.min(dif, nl - 2); + var md = 0; + for (var j = 0; j < mmd; ++j) { + var ti = i - dif + j & 32767; + var pti = prev[ti]; + var cd = ti - pti & 32767; + if (cd > md) + md = cd, pimod = ti; + } + } + } + // check the previous match + imod = pimod, pimod = prev[imod]; + dif += imod - pimod & 32767; + } + } + // d will be nonzero only when a match was found + if (d) { + // store both dist and len data in one int32 + // Make sure this is recognized as a len/dist with 28th bit (2^28) + syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; + var lin = revfl[l] & 31, din = revfd[d] & 31; + eb += fleb[lin] + fdeb[din]; + ++lf[257 + lin]; + ++df[din]; + wi = i + l; + ++lc_1; + } + else { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + } + } + for (i = Math.max(i, wi); i < s; ++i) { + syms[li++] = dat[i]; + ++lf[dat[i]]; + } + pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); + if (!lst) { + st.r = (pos & 7) | w[(pos / 8) | 0] << 3; + // shft(pos) now 1 less if pos & 7 != 0 + pos -= 7; + st.h = head, st.p = prev, st.i = i, st.w = wi; + } + } + else { + for (var i = st.w || 0; i < s + lst; i += 65535) { + // end + var e = i + 65535; + if (e >= s) { + // write final block + w[(pos / 8) | 0] = lst; + e = s; + } + pos = wfblk(w, pos + 1, dat.subarray(i, e)); + } + st.i = s; + } + return slc(o, 0, pre + shft(pos) + post); +}; +// CRC32 table +var crct = /*#__PURE__*/ (function () { + var t = new Int32Array(256); + for (var i = 0; i < 256; ++i) { + var c = i, k = 9; + while (--k) + c = ((c & 1) && -306674912) ^ (c >>> 1); + t[i] = c; + } + return t; +})(); +// CRC32 +var crc = function () { + var c = -1; + return { + p: function (d) { + // closures have awful performance + var cr = c; + for (var i = 0; i < d.length; ++i) + cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8); + c = cr; + }, + d: function () { return ~c; } + }; +}; +// Adler32 +var adler = function () { + var a = 1, b = 0; + return { + p: function (d) { + // closures have awful performance + var n = a, m = b; + var l = d.length | 0; + for (var i = 0; i != l;) { + var e = Math.min(i + 2655, l); + for (; i < e; ++i) + m += n += d[i]; + n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); + } + a = n, b = m; + }, + d: function () { + a %= 65521, b %= 65521; + return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8); + } + }; +}; +; +// deflate with opts +var dopt = function (dat, opt, pre, post, st) { + if (!st) { + st = { l: 1 }; + if (opt.dictionary) { + var dict = opt.dictionary.subarray(-32768); + var newDat = new u8(dict.length + dat.length); + newDat.set(dict); + newDat.set(dat, dict.length); + dat = newDat; + st.w = dict.length; + } + } + return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st); +}; +// Walmart object spread +var mrg = function (a, b) { + var o = {}; + for (var k in a) + o[k] = a[k]; + for (var k in b) + o[k] = b[k]; + return o; +}; +// worker clone +// This is possibly the craziest part of the entire codebase, despite how simple it may seem. +// The only parameter to this function is a closure that returns an array of variables outside of the function scope. +// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization. +// We will return an object mapping of true variable name to value (basically, the current scope as a JS object). +// The reason we can't just use the original variable names is minifiers mangling the toplevel scope. +// This took me three weeks to figure out how to do. +var wcln = function (fn, fnStr, td) { + var dt = fn(); + var st = fn.toString(); + var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(','); + for (var i = 0; i < dt.length; ++i) { + var v = dt[i], k = ks[i]; + if (typeof v == 'function') { + fnStr += ';' + k + '='; + var st_1 = v.toString(); + if (v.prototype) { + // for global objects + if (st_1.indexOf('[native code]') != -1) { + var spInd = st_1.indexOf(' ', 8) + 1; + fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd)); + } + else { + fnStr += st_1; + for (var t in v.prototype) + fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString(); + } + } + else + fnStr += st_1; + } + else + td[k] = v; + } + return fnStr; +}; +var ch = []; +// clone bufs +var cbfs = function (v) { + var tl = []; + for (var k in v) { + if (v[k].buffer) { + tl.push((v[k] = new v[k].constructor(v[k])).buffer); + } + } + return tl; +}; +// use a worker to execute code +var wrkr = function (fns, init, id, cb) { + if (!ch[id]) { + var fnStr = '', td_1 = {}, m = fns.length - 1; + for (var i = 0; i < m; ++i) + fnStr = wcln(fns[i], fnStr, td_1); + ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 }; + } + var td = mrg({}, ch[id].e); + return (0, node_worker_1.default)(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb); +}; +// base async inflate fn +var bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; }; +var bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; }; +// gzip extra +var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; }; +// gunzip extra +var guze = function () { return [gzs, gzl]; }; +// zlib extra +var zle = function () { return [zlh, wbytes, adler]; }; +// unzlib extra +var zule = function () { return [zls]; }; +// post buf +var pbf = function (msg) { return postMessage(msg, [msg.buffer]); }; +// get opts +var gopt = function (o) { return o && { + out: o.size && new u8(o.size), + dictionary: o.dictionary +}; }; +// async helper +var cbify = function (dat, opts, fns, init, id, cb) { + var w = wrkr(fns, init, id, function (err, dat) { + w.terminate(); + cb(err, dat); + }); + w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []); + return function () { w.terminate(); }; +}; +// auto stream +var astrm = function (strm) { + strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); }; + return function (ev) { + if (ev.data[0]) { + strm.push(ev.data[0], ev.data[1]); + postMessage([ev.data[0].length]); + } + else + strm.flush(ev.data[1]); + }; +}; +// async stream attach +var astrmify = function (fns, strm, opts, init, id, flush, ext) { + var t; + var w = wrkr(fns, init, id, function (err, dat) { + if (err) + w.terminate(), strm.ondata.call(strm, err); + else if (!Array.isArray(dat)) + ext(dat); + else if (dat.length == 1) { + strm.queuedSize -= dat[0]; + if (strm.ondrain) + strm.ondrain(dat[0]); + } + else { + if (dat[1]) + w.terminate(); + strm.ondata.call(strm, err, dat[0], dat[1]); + } + }); + w.postMessage(opts); + strm.queuedSize = 0; + strm.push = function (d, f) { + if (!strm.ondata) + err(5); + if (t) + strm.ondata(err(4, 0, 1), null, !!f); + strm.queuedSize += d.length; + // can fail for cross-realm Uint8Array, but ok - only a small performance penalty + w.postMessage([d, t = f], d.buffer instanceof ArrayBuffer ? [d.buffer] : []); + }; + strm.terminate = function () { w.terminate(); }; + if (flush) { + strm.flush = function (sync) { w.postMessage([0, sync]); }; + } +}; +// read 2 bytes +var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); }; +// read 4 bytes +var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; }; +// read 8 bytes +var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); }; +// write bytes +var wbytes = function (d, b, v) { + for (; v; ++b) + d[b] = v, v >>>= 8; +}; +// gzip header +var gzh = function (c, o) { + var fn = o.filename; + c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix + if (o.mtime != 0) + wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000)); + if (fn) { + c[3] = 8; + for (var i = 0; i <= fn.length; ++i) + c[i + 10] = fn.charCodeAt(i); + } +}; +// gzip footer: -8 to -4 = CRC, -4 to -0 is length +// gzip start +var gzs = function (d) { + if (d[0] != 31 || d[1] != 139 || d[2] != 8) + err(6, 'invalid gzip data'); + var flg = d[3]; + var st = 10; + if (flg & 4) + st += (d[10] | d[11] << 8) + 2; + for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]) + ; + return st + (flg & 2); +}; +// gzip length +var gzl = function (d) { + var l = d.length; + return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0; +}; +// gzip header length +var gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); }; +// zlib header +var zlh = function (c, o) { + var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; + c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32); + c[1] |= 31 - ((c[0] << 8) | c[1]) % 31; + if (o.dictionary) { + var h = adler(); + h.p(o.dictionary); + wbytes(c, 2, h.d()); + } +}; +// zlib start +var zls = function (d, dict) { + if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31)) + err(6, 'invalid zlib data'); + if ((d[1] >> 5 & 1) == +!dict) + err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary'); + return (d[1] >> 3 & 4) + 2; +}; +function StrmOpt(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + return opts; +} +/** + * Streaming DEFLATE compression + */ +var Deflate = /*#__PURE__*/ (function () { + function Deflate(opts, cb) { + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + this.o = opts || {}; + this.s = { l: 0, i: 32768, w: 32768, z: 32768 }; + // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev + // 98304 = 32768 (lookback) + 65536 (common chunk size) + this.b = new u8(98304); + if (this.o.dictionary) { + var dict = this.o.dictionary.subarray(-32768); + this.b.set(dict, 32768 - dict.length); + this.s.i = 32768 - dict.length; + } + } + Deflate.prototype.p = function (c, f) { + this.ondata(dopt(c, this.o, 0, 0, this.s), f); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Deflate.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + var endLen = chunk.length + this.s.z; + if (endLen > this.b.length) { + if (endLen > 2 * this.b.length - 32768) { + var newBuf = new u8(endLen & -32768); + newBuf.set(this.b.subarray(0, this.s.z)); + this.b = newBuf; + } + var split = this.b.length - this.s.z; + this.b.set(chunk.subarray(0, split), this.s.z); + this.s.z = this.b.length; + this.p(this.b, false); + this.b.set(this.b.subarray(-32768)); + this.b.set(chunk.subarray(split), 32768); + this.s.z = chunk.length - split + 32768; + this.s.i = 32766, this.s.w = 32768; + } + else { + this.b.set(chunk, this.s.z); + this.s.z += chunk.length; + } + this.s.l = final & 1; + if (this.s.z > this.s.w + 8191 || final) { + this.p(this.b, final || false); + this.s.w = this.s.i, this.s.i -= 2; + } + if (final) { + // cleanup unneeded buffers/state to reduce memory usage + this.s = this.o = {}; + this.b = et; + } + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + Deflate.prototype.flush = function (sync) { + if (!this.ondata) + err(5); + if (this.s.l) + err(4); + this.p(this.b, false); + this.s.w = this.s.i, this.s.i -= 2; + // could technically skip writing the type-0 block for (this.s.r & 7) == 0, + // but the deterministic trailer (00 00 FF FF) is useful in some situations + if (sync) { + var c = new u8(6); + c[0] = this.s.r >> 3; + // write empty, non-final type-0 block + var ep = wfblk(c, this.s.r, et); + this.s.r = 0; + this.ondata(c.subarray(0, ep >> 3), false); + } + }; + return Deflate; +}()); +exports.Deflate = Deflate; +/** + * Asynchronous streaming DEFLATE compression + */ +var AsyncDeflate = /*#__PURE__*/ (function () { + function AsyncDeflate(opts, cb) { + astrmify([ + bDflt, + function () { return [astrm, Deflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Deflate(ev.data); + onmessage = astrm(strm); + }, 6, 1); + } + return AsyncDeflate; +}()); +exports.AsyncDeflate = AsyncDeflate; +function deflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb); +} +/** + * Compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @returns The deflated version of the data + */ +function deflateSync(data, opts) { + return dopt(data, opts || {}, 0, 0); +} +/** + * Streaming DEFLATE decompression + */ +var Inflate = /*#__PURE__*/ (function () { + function Inflate(opts, cb) { + // no StrmOpt here to avoid adding to workerizer + if (typeof opts == 'function') + cb = opts, opts = {}; + this.ondata = cb; + var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768); + this.s = { i: 0, b: dict ? dict.length : 0 }; + this.o = new u8(32768); + this.p = new u8(0); + if (dict) + this.o.set(dict); + } + Inflate.prototype.e = function (c) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + if (!this.p.length) + this.p = c; + else if (c.length) { + var n = new u8(this.p.length + c.length); + n.set(this.p), n.set(c, this.p.length), this.p = n; + } + }; + Inflate.prototype.c = function (final) { + this.s.i = +(this.d = final || false); + var bts = this.s.b; + var dt = inflt(this.p, this.s, this.o); + this.ondata(slc(dt, bts, this.s.b), this.d); + this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; + this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; + }; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + Inflate.prototype.push = function (chunk, final) { + this.e(chunk), this.c(final); + }; + return Inflate; +}()); +exports.Inflate = Inflate; +/** + * Asynchronous streaming DEFLATE decompression + */ +var AsyncInflate = /*#__PURE__*/ (function () { + function AsyncInflate(opts, cb) { + astrmify([ + bInflt, + function () { return [astrm, Inflate]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Inflate(ev.data); + onmessage = astrm(strm); + }, 7, 0); + } + return AsyncInflate; +}()); +exports.AsyncInflate = AsyncInflate; +function inflate(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt + ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb); +} +function inflateSync(data, opts) { + return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize. +/** + * Streaming GZIP compression + */ +var Gzip = /*#__PURE__*/ (function () { + function Gzip(opts, cb) { + this.c = crc(); + this.l = 0; + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gzip.prototype.push = function (chunk, final) { + this.c.p(chunk); + this.l += chunk.length; + Deflate.prototype.push.call(this, chunk, final); + }; + Gzip.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s); + if (this.v) + gzh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + Gzip.prototype.flush = function (sync) { + Deflate.prototype.flush.call(this, sync); + }; + return Gzip; +}()); +exports.Gzip = Gzip; +exports.Compress = Gzip; +/** + * Asynchronous streaming GZIP compression + */ +var AsyncGzip = /*#__PURE__*/ (function () { + function AsyncGzip(opts, cb) { + astrmify([ + bDflt, + gze, + function () { return [astrm, Deflate, Gzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gzip(ev.data); + onmessage = astrm(strm); + }, 8, 1); + } + return AsyncGzip; +}()); +exports.AsyncGzip = AsyncGzip; +exports.AsyncCompress = AsyncGzip; +function gzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + gze, + function () { return [gzipSync]; } + ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb); +} +/** + * Compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @returns The gzipped version of the data + */ +function gzipSync(data, opts) { + if (!opts) + opts = {}; + var c = crc(), l = data.length; + c.p(data); + var d = dopt(data, opts, gzhl(opts), 8), s = d.length; + return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d; +} +/** + * Streaming single or multi-member GZIP decompression + */ +var Gunzip = /*#__PURE__*/ (function () { + function Gunzip(opts, cb) { + this.v = 1; + this.r = 0; + Inflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Gunzip.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + this.r += chunk.length; + if (this.v) { + var p = this.p.subarray(this.v - 1); + var s = p.length > 3 ? gzs(p) : 4; + if (s > p.length) { + if (!final) + return; + } + else if (this.v > 1 && this.onmember) { + this.onmember(this.r - p.length); + } + this.p = p.subarray(s), this.v = 0; + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, 0); + // process concatenated GZIP + if (this.s.f && !this.s.l) { + this.v = shft(this.s.p) + 9; + this.s = { i: 0 }; + this.o = new u8(0); + this.push(new u8(0), final); + } + else if (final) { + Inflate.prototype.c.call(this, final); + } + }; + return Gunzip; +}()); +exports.Gunzip = Gunzip; +/** + * Asynchronous streaming single or multi-member GZIP decompression + */ +var AsyncGunzip = /*#__PURE__*/ (function () { + function AsyncGunzip(opts, cb) { + var _this = this; + astrmify([ + bInflt, + guze, + function () { return [astrm, Inflate, Gunzip]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Gunzip(ev.data); + strm.onmember = function (offset) { return postMessage(offset); }; + onmessage = astrm(strm); + }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); }); + } + return AsyncGunzip; +}()); +exports.AsyncGunzip = AsyncGunzip; +function gunzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + guze, + function () { return [gunzipSync]; } + ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb); +} +function gunzipSync(data, opts) { + var st = gzs(data); + if (st + 8 > data.length) + err(6, 'invalid gzip data'); + return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary); +} +/** + * Streaming Zlib compression + */ +var Zlib = /*#__PURE__*/ (function () { + function Zlib(opts, cb) { + this.c = adler(); + this.v = 1; + Deflate.call(this, opts, cb); + } + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Zlib.prototype.push = function (chunk, final) { + this.c.p(chunk); + Deflate.prototype.push.call(this, chunk, final); + }; + Zlib.prototype.p = function (c, f) { + var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s); + if (this.v) + zlh(raw, this.o), this.v = 0; + if (f) + wbytes(raw, raw.length - 4, this.c.d()); + this.ondata(raw, f); + }; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + Zlib.prototype.flush = function (sync) { + Deflate.prototype.flush.call(this, sync); + }; + return Zlib; +}()); +exports.Zlib = Zlib; +/** + * Asynchronous streaming Zlib compression + */ +var AsyncZlib = /*#__PURE__*/ (function () { + function AsyncZlib(opts, cb) { + astrmify([ + bDflt, + zle, + function () { return [astrm, Deflate, Zlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Zlib(ev.data); + onmessage = astrm(strm); + }, 10, 1); + } + return AsyncZlib; +}()); +exports.AsyncZlib = AsyncZlib; +function zlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bDflt, + zle, + function () { return [zlibSync]; } + ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb); +} +/** + * Compress data with Zlib + * @param data The data to compress + * @param opts The compression options + * @returns The zlib-compressed version of the data + */ +function zlibSync(data, opts) { + if (!opts) + opts = {}; + var a = adler(); + a.p(data); + var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4); + return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d; +} +/** + * Streaming Zlib decompression + */ +var Unzlib = /*#__PURE__*/ (function () { + function Unzlib(opts, cb) { + Inflate.call(this, opts, cb); + this.v = opts && opts.dictionary ? 2 : 1; + } + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzlib.prototype.push = function (chunk, final) { + Inflate.prototype.e.call(this, chunk); + if (this.v) { + if (this.p.length < 6 && !final) + return; + this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0; + } + if (final) { + if (this.p.length < 4) + err(6, 'invalid zlib data'); + this.p = this.p.subarray(0, -4); + } + // necessary to prevent TS from using the closure value + // This allows for workerization to function correctly + Inflate.prototype.c.call(this, final); + }; + return Unzlib; +}()); +exports.Unzlib = Unzlib; +/** + * Asynchronous streaming Zlib decompression + */ +var AsyncUnzlib = /*#__PURE__*/ (function () { + function AsyncUnzlib(opts, cb) { + astrmify([ + bInflt, + zule, + function () { return [astrm, Inflate, Unzlib]; } + ], this, StrmOpt.call(this, opts, cb), function (ev) { + var strm = new Unzlib(ev.data); + onmessage = astrm(strm); + }, 11, 0); + } + return AsyncUnzlib; +}()); +exports.AsyncUnzlib = AsyncUnzlib; +function unzlib(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return cbify(data, opts, [ + bInflt, + zule, + function () { return [unzlibSync]; } + ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb); +} +function unzlibSync(data, opts) { + return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary); +} +/** + * Streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var Decompress = /*#__PURE__*/ (function () { + function Decompress(opts, cb) { + this.o = StrmOpt.call(this, opts, cb) || {}; + this.G = Gunzip; + this.I = Inflate; + this.Z = Unzlib; + } + // init substream + // overriden by AsyncDecompress + Decompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (dat, final) { + _this.ondata(dat, final); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Decompress.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (!this.s) { + if (this.p && this.p.length) { + var n = new u8(this.p.length + chunk.length); + n.set(this.p), n.set(chunk, this.p.length); + } + else + this.p = chunk; + if (this.p.length > 2) { + this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8) + ? new this.G(this.o) + : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31)) + ? new this.I(this.o) + : new this.Z(this.o); + this.i(); + this.s.push(this.p, final); + this.p = null; + } + } + else + this.s.push(chunk, final); + }; + return Decompress; +}()); +exports.Decompress = Decompress; +/** + * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression + */ +var AsyncDecompress = /*#__PURE__*/ (function () { + function AsyncDecompress(opts, cb) { + Decompress.call(this, opts, cb); + this.queuedSize = 0; + this.G = AsyncGunzip; + this.I = AsyncInflate; + this.Z = AsyncUnzlib; + } + AsyncDecompress.prototype.i = function () { + var _this = this; + this.s.ondata = function (err, dat, final) { + _this.ondata(err, dat, final); + }; + this.s.ondrain = function (size) { + _this.queuedSize -= size; + if (_this.ondrain) + _this.ondrain(size); + }; + }; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncDecompress.prototype.push = function (chunk, final) { + this.queuedSize += chunk.length; + Decompress.prototype.push.call(this, chunk, final); + }; + return AsyncDecompress; +}()); +exports.AsyncDecompress = AsyncDecompress; +function decompress(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzip(data, opts, cb) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflate(data, opts, cb) + : unzlib(data, opts, cb); +} +/** + * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +function decompressSync(data, opts) { + return (data[0] == 31 && data[1] == 139 && data[2] == 8) + ? gunzipSync(data, opts) + : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) + ? inflateSync(data, opts) + : unzlibSync(data, opts); +} +// flatten a directory structure +var fltn = function (d, p, t, o) { + for (var k in d) { + var val = d[k], n = p + k, op = o; + if (Array.isArray(val)) + op = mrg(o, val[1]), val = val[0]; + if (ArrayBuffer.isView(val)) + t[n] = [val, op]; + else { + t[n += '/'] = [new u8(0), op]; + fltn(val, n, t, o); + } + } +}; +// text encoder +var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder(); +// text decoder +var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); +// text decoder stream +var tds = 0; +try { + td.decode(et, { stream: true }); + tds = 1; +} +catch (e) { } +// decode UTF8 +var dutf8 = function (d) { + for (var r = '', i = 0;;) { + var c = d[i++]; + var eb = (c > 127) + (c > 223) + (c > 239); + if (i + eb > d.length) + return { s: r, r: slc(d, i - 1) }; + if (!eb) + r += String.fromCharCode(c); + else if (eb == 3) { + c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536, + r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023)); + } + else if (eb & 1) + r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63)); + else + r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)); + } +}; +/** + * Streaming UTF-8 decoding + */ +var DecodeUTF8 = /*#__PURE__*/ (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is decoded + */ + function DecodeUTF8(cb) { + this.ondata = cb; + if (tds) + this.t = new TextDecoder(); + else + this.p = et; + } + /** + * Pushes a chunk to be decoded from UTF-8 binary + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + DecodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + final = !!final; + if (this.t) { + this.ondata(this.t.decode(chunk, { stream: true }), final); + if (final) { + if (this.t.decode().length) + err(8); + this.t = null; + } + return; + } + if (!this.p) + err(4); + var dat = new u8(this.p.length + chunk.length); + dat.set(this.p); + dat.set(chunk, this.p.length); + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (final) { + if (r.length) + err(8); + this.p = null; + } + else + this.p = r; + this.ondata(s, final); + }; + return DecodeUTF8; +}()); +exports.DecodeUTF8 = DecodeUTF8; +/** + * Streaming UTF-8 encoding + */ +var EncodeUTF8 = /*#__PURE__*/ (function () { + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is encoded + */ + function EncodeUTF8(cb) { + this.ondata = cb; + } + /** + * Pushes a chunk to be encoded to UTF-8 + * @param chunk The string data to push + * @param final Whether this is the last chunk + */ + EncodeUTF8.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + if (this.d) + err(4); + this.ondata(strToU8(chunk), this.d = final || false); + }; + return EncodeUTF8; +}()); +exports.EncodeUTF8 = EncodeUTF8; +/** + * Converts a string into a Uint8Array for use with compression/decompression methods + * @param str The string to encode + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless decoding a binary string. + * @returns The string encoded in UTF-8/Latin-1 binary + */ +function strToU8(str, latin1) { + if (latin1) { + var ar_1 = new u8(str.length); + for (var i = 0; i < str.length; ++i) + ar_1[i] = str.charCodeAt(i); + return ar_1; + } + if (te) + return te.encode(str); + var l = str.length; + var ar = new u8(str.length + (str.length >> 1)); + var ai = 0; + var w = function (v) { ar[ai++] = v; }; + for (var i = 0; i < l; ++i) { + if (ai + 5 > ar.length) { + var n = new u8(ai + 8 + ((l - i) << 1)); + n.set(ar); + ar = n; + } + var c = str.charCodeAt(i); + if (c < 128 || latin1) + w(c); + else if (c < 2048) + w(192 | (c >> 6)), w(128 | (c & 63)); + else if (c > 55295 && c < 57344) + c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023), + w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + else + w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); + } + return slc(ar, 0, ai); +} +/** + * Converts a Uint8Array to a string + * @param dat The data to decode to string + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless encoding to binary string. + * @returns The original UTF-8/Latin-1 string + */ +function strFromU8(dat, latin1) { + if (latin1) { + var r = ''; + for (var i = 0; i < dat.length; i += 16384) + r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384)); + return r; + } + else if (td) { + return td.decode(dat); + } + else { + var _a = dutf8(dat), s = _a.s, r = _a.r; + if (r.length) + err(8); + return s; + } +} +; +// deflate bit flag +var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; }; +// skip local zip header +var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); }; +// read zip header +var zh = function (d, b, z) { + var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl; + var _a = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a[0], su = _a[1], off = _a[2]; + return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off]; +}; +// read zip64 header sizes +var z64hs = function (d, b, l, z, sc, su, off) { + var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l; + var nf = nsc + nsu + noff; + if (z && nf) { + for (; b + 4 < e; b += 4 + b2(d, b + 2)) { + if (b2(d, b) == 1) { + return [ + nsc ? b8(d, b + 4 + 8 * nsu) : sc, + nsu ? b8(d, b + 4) : su, + noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off, + 1 + ]; + } + } + // z == 2 for unknown whether or not zip64 + if (z < 2) + err(13); + } + return [sc, su, off, 0]; +}; +// extra field length +var exfl = function (ex) { + var le = 0; + if (ex) { + for (var k in ex) { + var l = ex[k].length; + if (l > 65535) + err(9); + le += l + 4; + } + } + return le; +}; +// write zip header +var wzh = function (d, b, f, fn, u, c, ce, co) { + var fl = fn.length, ex = f.extra, col = co && co.length; + var exl = exfl(ex); + wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4; + if (ce != null) + d[b++] = 20, d[b++] = f.os; + d[b] = 20, b += 2; // spec compliance? what's that? + d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8; + d[b++] = f.compression & 255, d[b++] = f.compression >> 8; + var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980; + if (y < 0 || y > 119) + err(10); + wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4; + if (c != -1) { + wbytes(d, b, f.crc); + wbytes(d, b + 4, c < 0 ? -c - 2 : c); + wbytes(d, b + 8, f.size); + } + wbytes(d, b + 12, fl); + wbytes(d, b + 14, exl), b += 16; + if (ce != null) { + wbytes(d, b, col); + wbytes(d, b + 6, f.attrs); + wbytes(d, b + 10, ce), b += 14; + } + d.set(fn, b); + b += fl; + if (exl) { + for (var k in ex) { + var exf = ex[k], l = exf.length; + wbytes(d, b, +k); + wbytes(d, b + 2, l); + d.set(exf, b + 4), b += 4 + l; + } + } + if (col) + d.set(co, b), b += col; + return b; +}; +// write zip footer (end of central directory) +var wzf = function (o, b, c, d, e) { + wbytes(o, b, 0x6054B50); // skip disk + wbytes(o, b + 8, c); + wbytes(o, b + 10, c); + wbytes(o, b + 12, d); + wbytes(o, b + 16, e); +}; +/** + * A pass-through stream to keep data uncompressed in a ZIP archive. + */ +var ZipPassThrough = /*#__PURE__*/ (function () { + /** + * Creates a pass-through stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + */ + function ZipPassThrough(filename) { + this.filename = filename; + this.c = crc(); + this.size = 0; + this.compression = 0; + } + /** + * Processes a chunk and pushes to the output stream. You can override this + * method in a subclass for custom behavior, but by default this passes + * the data through. You must call this.ondata(err, chunk, final) at some + * point in this method. + * @param chunk The chunk to process + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.process = function (chunk, final) { + this.ondata(null, chunk, final); + }; + /** + * Pushes a chunk to be added. If you are subclassing this with a custom + * compression algorithm, note that you must push data from the source + * file only, pre-compression. + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipPassThrough.prototype.push = function (chunk, final) { + if (!this.ondata) + err(5); + this.c.p(chunk); + this.size += chunk.length; + if (final) + this.crc = this.c.d(); + // we shouldn't really do this cast, but properly handling ArrayBufferLike + // makes the API unergonomic with Buffer + this.process(chunk, final || false); + }; + return ZipPassThrough; +}()); +exports.ZipPassThrough = ZipPassThrough; +// I don't extend because TypeScript extension adds 1kB of runtime bloat +/** + * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate + * for better performance + */ +var ZipDeflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function ZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new Deflate(opts, function (dat, final) { + _this.ondata(null, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + } + ZipDeflate.prototype.process = function (chunk, final) { + try { + this.d.push(chunk, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + ZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return ZipDeflate; +}()); +exports.ZipDeflate = ZipDeflate; +/** + * Asynchronous streaming DEFLATE compression for ZIP archives + */ +var AsyncZipDeflate = /*#__PURE__*/ (function () { + /** + * Creates an asynchronous DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + function AsyncZipDeflate(filename, opts) { + var _this = this; + if (!opts) + opts = {}; + ZipPassThrough.call(this, filename); + this.d = new AsyncDeflate(opts, function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.compression = 8; + this.flag = dbf(opts.level); + this.terminate = this.d.terminate; + } + AsyncZipDeflate.prototype.process = function (chunk, final) { + this.d.push(chunk, final); + }; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + AsyncZipDeflate.prototype.push = function (chunk, final) { + ZipPassThrough.prototype.push.call(this, chunk, final); + }; + return AsyncZipDeflate; +}()); +exports.AsyncZipDeflate = AsyncZipDeflate; +// TODO: Better tree shaking +/** + * A zippable archive to which files can incrementally be added + */ +var Zip = /*#__PURE__*/ (function () { + /** + * Creates an empty ZIP archive to which files can be added + * @param cb The callback to call whenever data for the generated ZIP archive + * is available + */ + function Zip(cb) { + this.ondata = cb; + this.u = []; + this.d = 1; + } + /** + * Adds a file to the ZIP archive + * @param file The file stream to add + */ + Zip.prototype.add = function (file) { + var _this = this; + if (!this.ondata) + err(5); + // finishing or finished + if (this.d & 2) + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false); + else { + var f = strToU8(file.filename), fl_1 = f.length; + var com = file.comment, o = com && strToU8(com); + var u = fl_1 != file.filename.length || (o && (com.length != o.length)); + var hl_1 = fl_1 + exfl(file.extra) + 30; + if (fl_1 > 65535) + this.ondata(err(11, 0, 1), null, false); + var header = new u8(hl_1); + wzh(header, 0, file, f, u, -1); + var chks_1 = [header]; + var pAll_1 = function () { + for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) { + var chk = chks_2[_i]; + _this.ondata(null, chk, false); + } + chks_1 = []; + }; + var tr_1 = this.d; + this.d = 0; + var ind_1 = this.u.length; + var uf_1 = mrg(file, { + f: f, + u: u, + o: o, + t: function () { + if (file.terminate) + file.terminate(); + }, + r: function () { + pAll_1(); + if (tr_1) { + var nxt = _this.u[ind_1 + 1]; + if (nxt) + nxt.r(); + else + _this.d = 1; + } + tr_1 = 1; + } + }); + var cl_1 = 0; + file.ondata = function (err, dat, final) { + if (err) { + _this.ondata(err, dat, final); + _this.terminate(); + } + else { + cl_1 += dat.length; + chks_1.push(dat); + if (final) { + var dd = new u8(16); + wbytes(dd, 0, 0x8074B50); + wbytes(dd, 4, file.crc); + wbytes(dd, 8, cl_1); + wbytes(dd, 12, file.size); + chks_1.push(dd); + uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size; + if (tr_1) + uf_1.r(); + tr_1 = 1; + } + else if (tr_1) + pAll_1(); + } + }; + this.u.push(uf_1); + } + }; + /** + * Ends the process of adding files and prepares to emit the final chunks. + * This *must* be called after adding all desired files for the resulting + * ZIP file to work properly. + */ + Zip.prototype.end = function () { + var _this = this; + if (this.d & 2) { + this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true); + return; + } + if (this.d) + this.e(); + else + this.u.push({ + r: function () { + if (!(_this.d & 1)) + return; + _this.u.splice(-1, 1); + _this.e(); + }, + t: function () { } + }); + this.d = 3; + }; + Zip.prototype.e = function () { + var bt = 0, l = 0, tl = 0; + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0); + } + var out = new u8(tl + 22); + for (var _b = 0, _c = this.u; _b < _c.length; _b++) { + var f = _c[_b]; + wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o); + bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b; + } + wzf(out, bt, this.u.length, tl, l); + this.ondata(null, out, true); + this.d = 2; + }; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to add() will fail. + */ + Zip.prototype.terminate = function () { + for (var _i = 0, _a = this.u; _i < _a.length; _i++) { + var f = _a[_i]; + f.t(); + } + this.d = 2; + }; + return Zip; +}()); +exports.Zip = Zip; +function zip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var r = {}; + fltn(data, '', r, opts); + var k = Object.keys(r); + var lft = k.length, o = 0, tot = 0; + var slft = lft, files = new Array(lft); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var cbf = function () { + var out = new u8(tot + 22), oe = o, cdl = tot - o; + tot = 0; + for (var i = 0; i < slft; ++i) { + var f = files[i]; + try { + var l = f.c.length; + wzh(out, tot, f, f.f, f.u, l); + var badd = 30 + f.f.length + exfl(f.extra); + var loc = tot + badd; + out.set(f.c, loc); + wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l; + } + catch (e) { + return cbd(e, null); + } + } + wzf(out, o, files.length, cdl, oe); + cbd(null, out); + }; + if (!lft) + cbf(); + var _loop_1 = function (i) { + var fn = k[i]; + var _a = r[fn], file = _a[0], p = _a[1]; + var c = crc(), size = file.length; + c.p(file); + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + var compression = p.level == 0 ? 0 : 8; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + var l = d.length; + files[i] = mrg(p, { + size: size, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + compression: compression + }); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + if (!--lft) + cbf(); + } + }; + if (s > 65535) + cbl(err(11, 0, 1), null); + if (!compression) + cbl(null, file); + else if (size < 160000) { + try { + cbl(null, deflateSync(file, p)); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(deflate(file, p, cbl)); + }; + // Cannot use lft because it can decrease + for (var i = 0; i < slft; ++i) { + _loop_1(i); + } + return tAll; +} +/** + * Synchronously creates a ZIP file. Prefer using `zip` for better performance + * with more than one file. + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @returns The generated ZIP archive + */ +function zipSync(data, opts) { + if (!opts) + opts = {}; + var r = {}; + var files = []; + fltn(data, '', r, opts); + var o = 0; + var tot = 0; + for (var fn in r) { + var _a = r[fn], file = _a[0], p = _a[1]; + var compression = p.level == 0 ? 0 : 8; + var f = strToU8(fn), s = f.length; + var com = p.comment, m = com && strToU8(com), ms = m && m.length; + var exl = exfl(p.extra); + if (s > 65535) + err(11); + var d = compression ? deflateSync(file, p) : file, l = d.length; + var c = crc(); + c.p(file); + files.push(mrg(p, { + size: file.length, + crc: c.d(), + c: d, + f: f, + m: m, + u: s != fn.length || (m && (com.length != ms)), + o: o, + compression: compression + })); + o += 30 + s + exl + l; + tot += 76 + 2 * (s + exl) + (ms || 0) + l; + } + var out = new u8(tot + 22), oe = o, cdl = tot - o; + for (var i = 0; i < files.length; ++i) { + var f = files[i]; + wzh(out, f.o, f, f.f, f.u, f.c.length); + var badd = 30 + f.f.length + exfl(f.extra); + out.set(f.c, f.o + badd); + wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0); + } + wzf(out, o, files.length, cdl, oe); + return out; +} +/** + * Streaming pass-through decompression for ZIP archives + */ +var UnzipPassThrough = /*#__PURE__*/ (function () { + function UnzipPassThrough() { + } + UnzipPassThrough.prototype.push = function (chunk, final) { + // same as ZipPassThrough: cast to retain Buffer ergonomics + this.ondata(null, chunk, final); + }; + UnzipPassThrough.compression = 0; + return UnzipPassThrough; +}()); +exports.UnzipPassThrough = UnzipPassThrough; +/** + * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for + * better performance. + */ +var UnzipInflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function UnzipInflate() { + var _this = this; + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + UnzipInflate.prototype.push = function (chunk, final) { + try { + this.i.push(chunk, final); + } + catch (e) { + this.ondata(e, null, final); + } + }; + UnzipInflate.compression = 8; + return UnzipInflate; +}()); +exports.UnzipInflate = UnzipInflate; +/** + * Asynchronous streaming DEFLATE decompression for ZIP archives + */ +var AsyncUnzipInflate = /*#__PURE__*/ (function () { + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + function AsyncUnzipInflate(_, sz) { + var _this = this; + if (sz < 320000) { + this.i = new Inflate(function (dat, final) { + _this.ondata(null, dat, final); + }); + } + else { + this.i = new AsyncInflate(function (err, dat, final) { + _this.ondata(err, dat, final); + }); + this.terminate = this.i.terminate; + } + } + AsyncUnzipInflate.prototype.push = function (chunk, final) { + if (this.i.terminate) + chunk = slc(chunk, 0); + this.i.push(chunk, final); + }; + AsyncUnzipInflate.compression = 8; + return AsyncUnzipInflate; +}()); +exports.AsyncUnzipInflate = AsyncUnzipInflate; +/** + * A ZIP archive decompression stream that emits files as they are discovered + */ +var Unzip = /*#__PURE__*/ (function () { + /** + * Creates a ZIP decompression stream + * @param cb The callback to call whenever a file in the ZIP archive is found + */ + function Unzip(cb) { + this.onfile = cb; + this.k = []; + this.o = { + 0: UnzipPassThrough + }; + this.p = et; + } + /** + * Pushes a chunk to be unzipped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + Unzip.prototype.push = function (chunk, final) { + var _this = this; + if (!this.onfile) + err(5); + if (!this.p) + err(4); + if (this.c > 0) { + var len = Math.min(this.c, chunk.length); + var toAdd = chunk.subarray(0, len); + this.c -= len; + if (this.d) + this.d.push(toAdd, !this.c); + else + this.k[0].push(toAdd); + chunk = chunk.subarray(len); + if (chunk.length) + return this.push(chunk, final); + } + else { + var f = 0, i = 0, is = void 0, buf = void 0; + if (!this.p.length) + buf = chunk; + else if (!chunk.length) + buf = this.p; + else { + buf = new u8(this.p.length + chunk.length); + buf.set(this.p), buf.set(chunk, this.p.length); + } + var l = buf.length, oc = this.c, add = oc && this.d; + var _loop_2 = function () { + var sig = b4(buf, i); + if (sig == 0x4034B50) { + f = 1, is = i; + this_1.d = null; + this_1.c = 0; + var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28); + if (l > i + 30 + fnl + es) { + var chks_3 = []; + this_1.k.unshift(chks_3); + f = 2; + var lsc = b4(buf, i + 18), lsu = b4(buf, i + 22); + var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u); + var _a = z64hs(buf, i, es, 2, lsc, lsu, 0), sc_1 = _a[0], su_1 = _a[1], z64 = _a[3]; + if (dd) + sc_1 = -1 - z64; + i += es; + this_1.c = sc_1; + var d_1; + var file_1 = { + name: fn_1, + compression: cmp_1, + start: function () { + if (!file_1.ondata) + err(5); + if (!sc_1) + file_1.ondata(null, et, true); + else { + var ctr = _this.o[cmp_1]; + if (!ctr) + file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false); + d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1); + d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); }; + for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) { + var dat = chks_4[_i]; + d_1.push(dat, false); + } + if (_this.k[0] == chks_3 && _this.c) + _this.d = d_1; + else + d_1.push(et, true); + } + }, + terminate: function () { + if (d_1 && d_1.terminate) + d_1.terminate(); + } + }; + if (sc_1 >= 0) + file_1.size = sc_1, file_1.originalSize = su_1; + this_1.onfile(file_1); + } + return "break"; + } + else if (oc) { + if (sig == 0x8074B50) { + is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0; + return "break"; + } + else if (sig == 0x2014B50) { + is = i -= 4, f = 3, this_1.c = 0; + return "break"; + } + } + }; + var this_1 = this; + for (; i < l - 4; ++i) { + var state_1 = _loop_2(); + if (state_1 === "break") + break; + } + this.p = et; + if (oc < 0) { + var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i); + if (add) + add.push(dat, !!f); + else + this.k[+(f == 2)].push(dat); + } + if (f & 2) + return this.push(buf.subarray(i), final); + this.p = buf.subarray(i); + } + if (final) { + if (this.c) + err(13); + this.p = null; + } + }; + /** + * Registers a decoder with the stream, allowing for files compressed with + * the compression type provided to be expanded correctly + * @param decoder The decoder constructor + */ + Unzip.prototype.register = function (decoder) { + this.o[decoder.compression] = decoder; + }; + return Unzip; +}()); +exports.Unzip = Unzip; +var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); }; +function unzip(data, opts, cb) { + if (!cb) + cb = opts, opts = {}; + if (typeof cb != 'function') + err(7); + var term = []; + var tAll = function () { + for (var i = 0; i < term.length; ++i) + term[i](); + }; + var files = {}; + var cbd = function (a, b) { + mt(function () { cb(a, b); }); + }; + mt(function () { cbd = cb; }); + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) { + cbd(err(13, 0, 1), null); + return tAll; + } + } + ; + var lft = b2(data, e + 8); + if (lft) { + var c = lft; + var o = b4(data, e + 16); + var z = b4(data, e - 20) == 0x7064B50; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = lft = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + var _loop_3 = function (i) { + var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + var cbl = function (e, d) { + if (e) { + tAll(); + cbd(e, null); + } + else { + if (d) + files[fn] = d; + if (!--lft) + cbd(null, files); + } + }; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_1 + })) { + if (!c_1) + cbl(null, slc(data, b, b + sc)); + else if (c_1 == 8) { + var infl = data.subarray(b, b + sc); + // Synchronously decompress under 512KB, or barely-compressed data + if (su < 524288 || sc > 0.8 * su) { + try { + cbl(null, inflateSync(infl, { out: new u8(su) })); + } + catch (e) { + cbl(e, null); + } + } + else + term.push(inflate(infl, { size: su }, cbl)); + } + else + cbl(err(14, 'unknown compression type ' + c_1, 1), null); + } + else + cbl(null, null); + }; + for (var i = 0; i < c; ++i) { + _loop_3(i); + } + } + else + cbd(null, {}); + return tAll; +} +/** + * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better + * performance with more than one file. + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @returns The decompressed files + */ +function unzipSync(data, opts) { + var files = {}; + var e = data.length - 22; + for (; b4(data, e) != 0x6054B50; --e) { + if (!e || data.length - e > 65558) + err(13); + } + ; + var c = b2(data, e + 8); + if (!c) + return {}; + var o = b4(data, e + 16); + var z = b4(data, e - 20) == 0x7064B50; + if (z) { + var ze = b4(data, e - 12); + z = b4(data, ze) == 0x6064B50; + if (z) { + c = b4(data, ze + 32); + o = b4(data, ze + 48); + } + } + var fltr = opts && opts.filter; + for (var i = 0; i < c; ++i) { + var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); + o = no; + if (!fltr || fltr({ + name: fn, + size: sc, + originalSize: su, + compression: c_2 + })) { + if (!c_2) + files[fn] = slc(data, b, b + sc); + else if (c_2 == 8) + files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) }); + else + err(14, 'unknown compression type ' + c_2); + } + } + return files; +} diff --git a/node_modules/fflate/lib/node.d.cts b/node_modules/fflate/lib/node.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..d430faf2b555c978d66c89f46155b72c2c45a971 --- /dev/null +++ b/node_modules/fflate/lib/node.d.cts @@ -0,0 +1,1539 @@ +/** + * Codes for errors generated within this library + */ +export declare const FlateErrorCode: { + readonly UnexpectedEOF: 0; + readonly InvalidBlockType: 1; + readonly InvalidLengthLiteral: 2; + readonly InvalidDistance: 3; + readonly StreamFinished: 4; + readonly NoStreamHandler: 5; + readonly InvalidHeader: 6; + readonly NoCallback: 7; + readonly InvalidUTF8: 8; + readonly ExtraFieldTooLong: 9; + readonly InvalidDate: 10; + readonly FilenameTooLong: 11; + readonly StreamFinishing: 12; + readonly InvalidZipData: 13; + readonly UnknownCompressionMethod: 14; +}; +/** + * An error generated within this library + */ +export interface FlateError extends Error { + /** + * The code associated with this error + */ + code: number; +} +/** + * Options for decompressing a DEFLATE stream + */ +export interface InflateStreamOptions { + /** + * The dictionary used to compress the original data. If no dictionary was used during compression, this option has no effect. + * + * Supplying the wrong dictionary during decompression usually yields corrupt output or causes an invalid distance error. + */ + dictionary?: Uint8Array; +} +/** + * Options for decompressing DEFLATE data + */ +export interface InflateOptions extends InflateStreamOptions { + /** + * The buffer into which to write the decompressed data. Saves memory if you know the decompressed size in advance. + * + * Note that if the decompression result is larger than the size of this buffer, it will be truncated to fit. + */ + out?: Uint8Array; +} +/** + * Options for decompressing a GZIP stream + */ +export interface GunzipStreamOptions extends InflateStreamOptions { +} +/** + * Options for decompressing GZIP data + */ +export interface GunzipOptions extends InflateStreamOptions { + /** + * The buffer into which to write the decompressed data. GZIP already encodes the output size, so providing this doesn't save memory. + * + * Note that if the decompression result is larger than the size of this buffer, it will be truncated to fit. + */ + out?: Uint8Array; +} +/** + * Options for decompressing a Zlib stream + */ +export interface UnzlibStreamOptions extends InflateStreamOptions { +} +/** + * Options for decompressing Zlib data + */ +export interface UnzlibOptions extends InflateOptions { +} +/** + * Options for compressing data into a DEFLATE format + */ +export interface DeflateOptions { + /** + * The level of compression to use, ranging from 0-9. + * + * 0 will store the data without compression. + * 1 is fastest but compresses the worst, 9 is slowest but compresses the best. + * The default level is 6. + * + * Typically, binary data benefits much more from higher values than text data. + * In both cases, higher values usually take disproportionately longer than the reduction in final size that results. + * + * For example, a 1 MB text file could: + * - become 1.01 MB with level 0 in 1ms + * - become 400 kB with level 1 in 10ms + * - become 320 kB with level 9 in 100ms + */ + level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + /** + * The memory level to use, ranging from 0-12. Increasing this increases speed and compression ratio at the cost of memory. + * + * Note that this is exponential: while level 0 uses 8 kB, level 4 uses 128 kB, level 8 uses 2 MB, and level 12 uses 32 MB. + * It is recommended not to lower the value below 4, since that tends to hurt performance. + * In addition, values above 8 tend to help very little on most data and can even hurt performance. + * + * The default value is automatically determined based on the size of the input data. + */ + mem?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; + /** + * A buffer containing common byte sequences in the input data that can be used to significantly improve compression ratios. + * + * Dictionaries should be 32kB or smaller and include strings or byte sequences likely to appear in the input. + * The decompressor must supply the same dictionary as the compressor to extract the original data. + * + * Dictionaries only improve aggregate compression ratio when reused across multiple small inputs. They should typically not be used otherwise. + * + * Avoid using dictionaries with GZIP and ZIP to maximize software compatibility. + */ + dictionary?: Uint8Array; +} +/** + * Options for compressing data into a GZIP format + */ +export interface GzipOptions extends DeflateOptions { + /** + * When the file was last modified. Defaults to the current time. + * Set this to 0 to avoid revealing a modification date entirely. + */ + mtime?: Date | string | number; + /** + * The filename of the data. If the `gunzip` command is used to decompress the data, it will output a file + * with this name instead of the name of the compressed file. + */ + filename?: string; +} +/** + * Options for compressing data into a Zlib format + */ +export interface ZlibOptions extends DeflateOptions { +} +/** + * Handler for data (de)compression streams + * @param data The data output from the stream processor + * @param final Whether this is the final block + */ +export type FlateStreamHandler = (data: Uint8Array, final: boolean) => void; +/** + * Handler for asynchronous data (de)compression streams + * @param err Any error that occurred + * @param data The data output from the stream processor + * @param final Whether this is the final block + */ +export type AsyncFlateStreamHandler = (err: FlateError | null, data: Uint8Array, final: boolean) => void; +/** + * Handler for the asynchronous completion of (de)compression for a data chunk + * @param size The number of bytes that were processed. This is measured in terms of the input + * (i.e. compressed bytes for decompression, uncompressed bytes for compression.) + */ +export type AsyncFlateDrainHandler = (size: number) => void; +/** + * Callback for asynchronous (de)compression methods + * @param err Any error that occurred + * @param data The resulting data. Only present if `err` is null + */ +export type FlateCallback = (err: FlateError | null, data: Uint8Array) => void; +interface AsyncOptions { + /** + * Whether or not to "consume" the source data. This will make the typed array/buffer you pass in + * unusable but will increase performance and reduce memory usage. + */ + consume?: boolean; +} +/** + * Options for compressing data asynchronously into a DEFLATE format + */ +export interface AsyncDeflateOptions extends DeflateOptions, AsyncOptions { +} +/** + * Options for decompressing DEFLATE data asynchronously + */ +export interface AsyncInflateOptions extends AsyncOptions, InflateStreamOptions { + /** + * The original size of the data. Currently, the asynchronous API disallows + * writing into a buffer you provide; the best you can do is provide the + * size in bytes and be given back a new typed array. + */ + size?: number; +} +/** + * Options for compressing data asynchronously into a GZIP format + */ +export interface AsyncGzipOptions extends GzipOptions, AsyncOptions { +} +/** + * Options for decompressing GZIP data asynchronously + */ +export interface AsyncGunzipOptions extends AsyncOptions, InflateStreamOptions { +} +/** + * Options for compressing data asynchronously into a Zlib format + */ +export interface AsyncZlibOptions extends ZlibOptions, AsyncOptions { +} +/** + * Options for decompressing Zlib data asynchronously + */ +export interface AsyncUnzlibOptions extends AsyncInflateOptions { +} +/** + * A terminable compression/decompression process + */ +export interface AsyncTerminable { + /** + * Terminates the worker thread immediately. The callback will not be called. + */ + (): void; +} +/** + * Streaming DEFLATE compression + */ +export declare class Deflate { + /** + * Creates a DEFLATE stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: DeflateOptions, cb?: FlateStreamHandler); + /** + * Creates a DEFLATE stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + private b; + private s; + private o; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + private p; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE compression + */ +export declare class AsyncDeflate { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous DEFLATE stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: DeflateOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous DEFLATE stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * deflated output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. A separate DEFLATE stream may be concatenated + * with the current output after a sync flush. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function deflate(data: Uint8Array, opts: AsyncDeflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param cb The function to be called upon compression completion + */ +export declare function deflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compresses data with DEFLATE without any wrapper + * @param data The data to compress + * @param opts The compression options + * @returns The deflated version of the data + */ +export declare function deflateSync(data: Uint8Array, opts?: DeflateOptions): Uint8Array; +/** + * Streaming DEFLATE decompression + */ +export declare class Inflate { + private s; + private o; + private p; + private d; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a DEFLATE decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: InflateStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a DEFLATE decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + private e; + private c; + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the final chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE decompression + */ +export declare class AsyncInflate { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous DEFLATE decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: InflateStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous DEFLATE decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be inflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function inflate(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function inflate(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands DEFLATE data with no wrapper + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function inflateSync(data: Uint8Array): Uint8Array; +/** + * Expands DEFLATE data with no wrapper + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function inflateSync(data: Uint8Array, opts?: InflateOptions): Uint8Array; +/** + * Streaming GZIP compression + */ +export declare class Gzip { + private c; + private l; + private v; + private o; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a GZIP stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: GzipOptions, cb?: FlateStreamHandler); + /** + * Creates a GZIP stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + private p; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming GZIP compression + */ +export declare class AsyncGzip { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous GZIP stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: GzipOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous GZIP stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be GZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * GZIPped output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function gzip(data: Uint8Array, opts: AsyncGzipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with GZIP + * @param data The data to compress + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compresses data with GZIP + * @param data The data to compress + * @param opts The compression options + * @returns The gzipped version of the data + */ +export declare function gzipSync(data: Uint8Array, opts?: GzipOptions): Uint8Array; +/** + * Handler for new GZIP members in concatenated GZIP streams. Useful for building indices used to perform random-access reads on compressed files. + * @param offset The offset of the new member relative to the start of the stream + */ +export type GunzipMemberHandler = (offset: number) => void; +/** + * Streaming single or multi-member GZIP decompression + */ +export declare class Gunzip { + private v; + private r; + private o; + private p; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * The handler to call whenever a new GZIP member is found + */ + onmember?: GunzipMemberHandler; + /** + * Creates a GUNZIP stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: GunzipStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a GUNZIP stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming single or multi-member GZIP decompression + */ +export declare class AsyncGunzip { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * The handler to call whenever a new GZIP member is found + */ + onmember?: GunzipMemberHandler; + /** + * Creates an asynchronous GUNZIP stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: GunzipStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous GUNZIP stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be GUNZIPped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands GZIP data + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gunzip(data: Uint8Array, opts: AsyncGunzipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands GZIP data + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function gunzip(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands GZIP data + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function gunzipSync(data: Uint8Array): Uint8Array; +/** + * Expands GZIP data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function gunzipSync(data: Uint8Array, opts?: GunzipOptions): Uint8Array; +/** + * Streaming Zlib compression + */ +export declare class Zlib { + private c; + private v; + private o; + private s; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a Zlib stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: ZlibOptions, cb?: FlateStreamHandler); + /** + * Creates a Zlib stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be zlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + private p; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; +} +/** + * Asynchronous streaming Zlib compression + */ +export declare class AsyncZlib { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of uncompressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous Zlib stream + * @param opts The compression options + * @param cb The callback to call whenever data is deflated + */ + constructor(opts: ZlibOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous Zlib stream + * @param cb The callback to call whenever data is deflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Flushes buffered uncompressed data. Useful to immediately retrieve the + * zlibbed output for small inputs. + * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5 + * extra bytes, but guarantees all pushed data is immediately + * decompressible. + */ + flush(sync?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously compresses data with Zlib + * @param data The data to compress + * @param opts The compression options + * @param cb The function to be called upon compression completion + */ +export declare function zlib(data: Uint8Array, opts: AsyncZlibOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously compresses data with Zlib + * @param data The data to compress + * @param cb The function to be called upon compression completion + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Compress data with Zlib + * @param data The data to compress + * @param opts The compression options + * @returns The zlib-compressed version of the data + */ +export declare function zlibSync(data: Uint8Array, opts?: ZlibOptions): Uint8Array; +/** + * Streaming Zlib decompression + */ +export declare class Unzlib { + private v; + private p; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a Zlib decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: UnzlibStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be unzlibbed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming Zlib decompression + */ +export declare class AsyncUnzlib { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous Zlib decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is inflated + */ + constructor(opts: UnzlibStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous Zlib decompression stream + * @param cb The callback to call whenever data is inflated + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Pushes a chunk to be decompressed from Zlib + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * A method to terminate the stream's internal worker. Subsequent calls to + * push() will silently fail. + */ + terminate: AsyncTerminable; +} +/** + * Asynchronously expands Zlib data + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function unzlib(data: Uint8Array, opts: AsyncUnzlibOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously expands Zlib data + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function unzlib(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands Zlib data + * @param data The data to decompress + * @returns The decompressed version of the data + */ +export declare function unzlibSync(data: Uint8Array): Uint8Array; +/** + * Expands Zlib data + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function unzlibSync(data: Uint8Array, opts?: UnzlibOptions): Uint8Array; +export { gzip as compress, AsyncGzip as AsyncCompress }; +export { gzipSync as compressSync, Gzip as Compress }; +/** + * Streaming GZIP, Zlib, or raw DEFLATE decompression + */ +export declare class Decompress { + private G; + private I; + private Z; + private o; + private s; + private p; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; + /** + * Creates a decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is decompressed + */ + constructor(opts: InflateStreamOptions, cb?: FlateStreamHandler); + /** + * Creates a decompression stream + * @param cb The callback to call whenever data is decompressed + */ + constructor(cb?: FlateStreamHandler); + private i; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression + */ +export declare class AsyncDecompress { + private G; + private I; + private Z; + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The handler to call whenever buffered source data is processed (i.e. `queuedSize` updates) + */ + ondrain?: AsyncFlateDrainHandler; + /** + * The number of compressed bytes buffered in the stream + */ + queuedSize: number; + /** + * Creates an asynchronous decompression stream + * @param opts The decompression options + * @param cb The callback to call whenever data is decompressed + */ + constructor(opts: InflateStreamOptions, cb?: AsyncFlateStreamHandler); + /** + * Creates an asynchronous decompression stream + * @param cb The callback to call whenever data is decompressed + */ + constructor(cb?: AsyncFlateStreamHandler); + private i; + /** + * Pushes a chunk to be decompressed + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function decompress(data: Uint8Array, opts: AsyncInflateOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchrononously expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param cb The function to be called upon decompression completion + * @returns A function that can be used to immediately terminate the decompression + */ +export declare function decompress(data: Uint8Array, cb: FlateCallback): AsyncTerminable; +/** + * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format + * @param data The data to decompress + * @param opts The decompression options + * @returns The decompressed version of the data + */ +export declare function decompressSync(data: Uint8Array, opts?: InflateOptions): Uint8Array; +/** + * Attributes for files added to a ZIP archive object + */ +export interface ZipAttributes { + /** + * The operating system of origin for this file. The value is defined + * by PKZIP's APPNOTE.txt, section 4.4.2.2. For example, 0 (the default) + * is MS/DOS, 3 is Unix, 19 is macOS. + */ + os?: number; + /** + * The file's attributes. These are traditionally somewhat complicated + * and platform-dependent, so using them is scarcely necessary. However, + * here is a representation of what this is, bit by bit: + * + * `TTTTugtrwxrwxrwx0000000000ADVSHR` + * + * TTTT = file type (rarely useful) + * + * u = setuid, g = setgid, t = sticky + * + * rwx = user permissions, rwx = group permissions, rwx = other permissions + * + * 0000000000 = unused + * + * A = archive, D = directory, V = volume label, S = system file, H = hidden, R = read-only + * + * If you want to set the Unix permissions, for instance, just bit shift by 16, e.g. 0o644 << 16. + * Note that attributes usually only work in conjunction with the `os` setting: you must use + * `os` = 3 (Unix) if you want to set Unix permissions + */ + attrs?: number; + /** + * Extra metadata to add to the file. This field is defined by PKZIP's APPNOTE.txt, + * section 4.4.28. At most 65,535 bytes may be used in each ID. The ID must be an + * integer between 0 and 65,535, inclusive. + * + * This field is incredibly rare and almost never needed except for compliance with + * proprietary standards and software. + */ + extra?: Record; + /** + * The comment to attach to the file. This field is defined by PKZIP's APPNOTE.txt, + * section 4.4.26. The comment must be at most 65,535 bytes long UTF-8 encoded. This + * field is not read by consumer software. + */ + comment?: string; + /** + * When the file was last modified. Defaults to the current time. + */ + mtime?: GzipOptions['mtime']; +} +/** + * Options for creating a ZIP archive + */ +export interface ZipOptions extends DeflateOptions, ZipAttributes { +} +/** + * Options for expanding a ZIP archive + */ +export interface UnzipOptions { + /** + * A filter function to extract only certain files from a ZIP archive + */ + filter?: UnzipFileFilter; +} +/** + * Options for asynchronously creating a ZIP archive + */ +export interface AsyncZipOptions extends AsyncDeflateOptions, ZipAttributes { +} +/** + * Options for asynchronously expanding a ZIP archive + */ +export interface AsyncUnzipOptions extends UnzipOptions { +} +/** + * A file that can be used to create a ZIP archive + */ +export type ZippableFile = Uint8Array | Zippable | [Uint8Array | Zippable, ZipOptions]; +/** + * A file that can be used to asynchronously create a ZIP archive + */ +export type AsyncZippableFile = Uint8Array | AsyncZippable | [Uint8Array | AsyncZippable, AsyncZipOptions]; +/** + * The complete directory structure of a ZIPpable archive + */ +export interface Zippable { + [path: string]: ZippableFile; +} +/** + * The complete directory structure of an asynchronously ZIPpable archive + */ +export interface AsyncZippable { + [path: string]: AsyncZippableFile; +} +/** + * An unzipped archive. The full path of each file is used as the key, + * and the file is the value + */ +export interface Unzipped { + [path: string]: Uint8Array; +} +/** + * Handler for string generation streams + * @param data The string output from the stream processor + * @param final Whether this is the final block + */ +export type StringStreamHandler = (data: string, final: boolean) => void; +/** + * Callback for asynchronous ZIP decompression + * @param err Any error that occurred + * @param data The decompressed ZIP archive + */ +export type UnzipCallback = (err: FlateError | null, data: Unzipped) => void; +/** + * Handler for streaming ZIP decompression + * @param file The file that was found in the archive + */ +export type UnzipFileHandler = (file: UnzipFile) => void; +/** + * Streaming UTF-8 decoding + */ +export declare class DecodeUTF8 { + private p; + private t; + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is decoded + */ + constructor(cb?: StringStreamHandler); + /** + * Pushes a chunk to be decoded from UTF-8 binary + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * The handler to call whenever data is available + */ + ondata: StringStreamHandler; +} +/** + * Streaming UTF-8 encoding + */ +export declare class EncodeUTF8 { + private d; + /** + * Creates a UTF-8 decoding stream + * @param cb The callback to call whenever data is encoded + */ + constructor(cb?: FlateStreamHandler); + /** + * Pushes a chunk to be encoded to UTF-8 + * @param chunk The string data to push + * @param final Whether this is the last chunk + */ + push(chunk: string, final?: boolean): void; + /** + * The handler to call whenever data is available + */ + ondata: FlateStreamHandler; +} +/** + * Converts a string into a Uint8Array for use with compression/decompression methods + * @param str The string to encode + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless decoding a binary string. + * @returns The string encoded in UTF-8/Latin-1 binary + */ +export declare function strToU8(str: string, latin1?: boolean): Uint8Array; +/** + * Converts a Uint8Array to a string + * @param dat The data to decode to string + * @param latin1 Whether or not to interpret the data as Latin-1. This should + * not need to be true unless encoding to binary string. + * @returns The original UTF-8/Latin-1 string + */ +export declare function strFromU8(dat: Uint8Array, latin1?: boolean): string; +/** + * A stream that can be used to create a file in a ZIP archive + */ +export interface ZipInputFile extends ZipAttributes { + /** + * The filename to associate with the data provided to this stream. If you + * want a file in a subdirectory, use forward slashes as a separator (e.g. + * `directory/filename.ext`). This will still work on Windows. + */ + filename: string; + /** + * The size of the file in bytes. This attribute may be invalid after + * the file is added to the ZIP archive; it must be correct only before the + * stream completes. + * + * If you don't want to have to compute this yourself, consider extending the + * ZipPassThrough class and overriding its process() method, or using one of + * ZipDeflate or AsyncZipDeflate. + */ + size: number; + /** + * A CRC of the original file contents. This attribute may be invalid after + * the file is added to the ZIP archive; it must be correct only before the + * stream completes. + * + * If you don't want to have to generate this yourself, consider extending the + * ZipPassThrough class and overriding its process() method, or using one of + * ZipDeflate or AsyncZipDeflate. + */ + crc: number; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA + */ + compression: number; + /** + * Bits 1 and 2 of the general purpose bit flag, specified in PKZIP's + * APPNOTE.txt, section 4.4.4. Should be between 0 and 3. This is unlikely + * to be necessary. + */ + flag?: number; + /** + * The handler to be called when data is added. After passing this stream to + * the ZIP file object, this handler will always be defined. To call it: + * + * `stream.ondata(error, chunk, final)` + * + * error = any error that occurred (null if there was no error) + * + * chunk = a Uint8Array of the data that was added (null if there was an + * error) + * + * final = boolean, whether this is the final chunk in the stream + */ + ondata?: AsyncFlateStreamHandler; + /** + * A method called when the stream is no longer needed, for clean-up + * purposes. This will not always be called after the stream completes, + * so you may wish to call this.terminate() after the final chunk is + * processed if you have clean-up logic. + */ + terminate?: AsyncTerminable; +} +/** + * A pass-through stream to keep data uncompressed in a ZIP archive. + */ +export declare class ZipPassThrough implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private c; + /** + * Creates a pass-through stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + */ + constructor(filename: string); + /** + * Processes a chunk and pushes to the output stream. You can override this + * method in a subclass for custom behavior, but by default this passes + * the data through. You must call this.ondata(err, chunk, final) at some + * point in this method. + * @param chunk The chunk to process + * @param final Whether this is the last chunk + */ + protected process(chunk: Uint8Array, final: boolean): void; + /** + * Pushes a chunk to be added. If you are subclassing this with a custom + * compression algorithm, note that you must push data from the source + * file only, pre-compression. + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate + * for better performance + */ +export declare class ZipDeflate implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + flag: 0 | 1 | 2 | 3; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private d; + /** + * Creates a DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + constructor(filename: string, opts?: DeflateOptions); + private process; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * Asynchronous streaming DEFLATE compression for ZIP archives + */ +export declare class AsyncZipDeflate implements ZipInputFile { + filename: string; + crc: number; + size: number; + compression: number; + flag: 0 | 1 | 2 | 3; + os?: number; + attrs?: number; + comment?: string; + extra?: Record; + mtime?: GzipOptions['mtime']; + ondata: AsyncFlateStreamHandler; + private d; + terminate: AsyncTerminable; + /** + * Creates an asynchronous DEFLATE stream that can be added to ZIP archives + * @param filename The filename to associate with this data stream + * @param opts The compression options + */ + constructor(filename: string, opts?: DeflateOptions); + private process; + /** + * Pushes a chunk to be deflated + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; +} +/** + * A zippable archive to which files can incrementally be added + */ +export declare class Zip { + private u; + private d; + /** + * Creates an empty ZIP archive to which files can be added + * @param cb The callback to call whenever data for the generated ZIP archive + * is available + */ + constructor(cb?: AsyncFlateStreamHandler); + /** + * Adds a file to the ZIP archive + * @param file The file stream to add + */ + add(file: ZipInputFile): void; + /** + * Ends the process of adding files and prepares to emit the final chunks. + * This *must* be called after adding all desired files for the resulting + * ZIP file to work properly. + */ + end(): void; + private e; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to add() will fail. + */ + terminate(): void; + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; +} +/** + * Asynchronously creates a ZIP file + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @param cb The callback to call with the generated ZIP archive + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zip(data: AsyncZippable, opts: AsyncZipOptions, cb: FlateCallback): AsyncTerminable; +/** + * Asynchronously creates a ZIP file + * @param data The directory structure for the ZIP archive + * @param cb The callback to call with the generated ZIP archive + * @returns A function that can be used to immediately terminate the compression + */ +export declare function zip(data: AsyncZippable, cb: FlateCallback): AsyncTerminable; +/** + * Synchronously creates a ZIP file. Prefer using `zip` for better performance + * with more than one file. + * @param data The directory structure for the ZIP archive + * @param opts The main options, merged with per-file options + * @returns The generated ZIP archive + */ +export declare function zipSync(data: Zippable, opts?: ZipOptions): Uint8Array; +/** + * A decoder for files in ZIP streams + */ +export interface UnzipDecoder { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * Pushes a chunk to be decompressed + * @param chunk The data in this chunk. Do not consume (detach) this buffer. + * @param final Whether this is the last chunk in the data stream + */ + push(chunk: Uint8Array, final: boolean): void; + /** + * A method to terminate any internal workers used by the stream. Subsequent + * calls to push() should silently fail. + */ + terminate?: AsyncTerminable; +} +/** + * A constructor for a decoder for unzip streams + */ +export interface UnzipDecoderConstructor { + /** + * Creates an instance of the decoder + * @param filename The name of the file + * @param size The compressed size of the file + * @param originalSize The original size of the file + */ + new (filename: string, size?: number, originalSize?: number): UnzipDecoder; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA + */ + compression: number; +} +/** + * Information about a file to be extracted from a ZIP archive + */ +export interface UnzipFileInfo { + /** + * The name of the file + */ + name: string; + /** + * The compressed size of the file + */ + size: number; + /** + * The original size of the file + */ + originalSize: number; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA. If the filter function returns true + * but this value is not 8, the unzip function will throw. + */ + compression: number; +} +/** + * A filter for files to be extracted during the unzipping process + * @param file The info for the current file being processed + * @returns Whether or not to extract the current file + */ +export type UnzipFileFilter = (file: UnzipFileInfo) => boolean; +/** + * Streaming file extraction from ZIP archives + */ +export interface UnzipFile { + /** + * The handler to call whenever data is available + */ + ondata: AsyncFlateStreamHandler; + /** + * The name of the file + */ + name: string; + /** + * The compression format for the data stream. This number is determined by + * the spec in PKZIP's APPNOTE.txt, section 4.4.5. For example, 0 = no + * compression, 8 = deflate, 14 = LZMA. If start() is called but there is no + * decompression stream available for this method, start() will throw. + */ + compression: number; + /** + * The compressed size of the file. Will not be present for archives created + * in a streaming fashion. + */ + size?: number; + /** + * The original size of the file. Will not be present for archives created + * in a streaming fashion. + */ + originalSize?: number; + /** + * Starts reading from the stream. Calling this function will always enable + * this stream, but ocassionally the stream will be enabled even without + * this being called. + */ + start(): void; + /** + * A method to terminate any internal workers used by the stream. ondata + * will not be called any further. + */ + terminate: AsyncTerminable; +} +/** + * Streaming pass-through decompression for ZIP archives + */ +export declare class UnzipPassThrough implements UnzipDecoder { + static compression: number; + ondata: AsyncFlateStreamHandler; + push(chunk: Uint8Array, final: boolean): void; +} +/** + * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for + * better performance. + */ +export declare class UnzipInflate implements UnzipDecoder { + static compression: number; + private i; + ondata: AsyncFlateStreamHandler; + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + constructor(); + push(chunk: Uint8Array, final: boolean): void; +} +/** + * Asynchronous streaming DEFLATE decompression for ZIP archives + */ +export declare class AsyncUnzipInflate implements UnzipDecoder { + static compression: number; + private i; + ondata: AsyncFlateStreamHandler; + terminate: AsyncTerminable; + /** + * Creates a DEFLATE decompression that can be used in ZIP archives + */ + constructor(_: string, sz?: number); + push(chunk: Uint8Array, final: boolean): void; +} +/** + * A ZIP archive decompression stream that emits files as they are discovered + */ +export declare class Unzip { + private d; + private c; + private p; + private k; + private o; + /** + * Creates a ZIP decompression stream + * @param cb The callback to call whenever a file in the ZIP archive is found + */ + constructor(cb?: UnzipFileHandler); + /** + * Pushes a chunk to be unzipped + * @param chunk The chunk to push + * @param final Whether this is the last chunk + */ + push(chunk: Uint8Array, final?: boolean): void; + /** + * Registers a decoder with the stream, allowing for files compressed with + * the compression type provided to be expanded correctly + * @param decoder The decoder constructor + */ + register(decoder: UnzipDecoderConstructor): void; + /** + * The handler to call whenever a file is discovered + */ + onfile: UnzipFileHandler; +} +/** + * Asynchronously decompresses a ZIP archive + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @param cb The callback to call with the decompressed files + * @returns A function that can be used to immediately terminate the unzipping + */ +export declare function unzip(data: Uint8Array, opts: AsyncUnzipOptions, cb: UnzipCallback): AsyncTerminable; +/** + * Asynchronously decompresses a ZIP archive + * @param data The raw compressed ZIP file + * @param cb The callback to call with the decompressed files + * @returns A function that can be used to immediately terminate the unzipping + */ +export declare function unzip(data: Uint8Array, cb: UnzipCallback): AsyncTerminable; +/** + * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better + * performance with more than one file. + * @param data The raw compressed ZIP file + * @param opts The ZIP extraction options + * @returns The decompressed files + */ +export declare function unzipSync(data: Uint8Array, opts?: UnzipOptions): Unzipped; diff --git a/node_modules/fflate/lib/worker.cjs b/node_modules/fflate/lib/worker.cjs new file mode 100644 index 0000000000000000000000000000000000000000..9a283bdb82464d89f8cdc9b9c879d88b50c9acff --- /dev/null +++ b/node_modules/fflate/lib/worker.cjs @@ -0,0 +1,20 @@ +"use strict"; +var ch2 = {}; +exports.default = (function (c, id, msg, transfer, cb) { + var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([ + c + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})' + ], { type: 'text/javascript' })))); + w.onmessage = function (e) { + var d = e.data, ed = d.$e$; + if (ed) { + var err = new Error(ed[0]); + err['code'] = ed[1]; + err.stack = ed[2]; + cb(err, null); + } + else + cb(null, d); + }; + w.postMessage(msg, transfer); + return w; +}); diff --git a/node_modules/fflate/package.json b/node_modules/fflate/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c37a5362657035a5abc0fdb65dccaafde5f48764 --- /dev/null +++ b/node_modules/fflate/package.json @@ -0,0 +1,128 @@ +{ + "name": "fflate", + "version": "0.8.3", + "description": "High performance (de)compression in an 8kB package", + "main": "./lib/index.cjs", + "module": "./esm/browser.js", + "types": "./lib/index.d.ts", + "unpkg": "./umd/index.js", + "jsdelivr": "./umd/index.js", + "browser": { + "./lib/node-worker.cjs": "./lib/worker.cjs" + }, + "exports": { + ".": { + "node": { + "import": { + "types": "./esm/index.d.mts", + "default": "./esm/index.mjs" + }, + "require": { + "types": "./lib/node.d.cts", + "default": "./lib/node.cjs" + } + }, + "import": { + "types": "./esm/browser.d.ts", + "default": "./esm/browser.js" + }, + "require": { + "types": "./lib/browser.d.cts", + "default": "./lib/browser.cjs" + } + }, + "./node": { + "import": { + "types": "./esm/index.d.mts", + "default": "./esm/index.mjs" + }, + "require": { + "types": "./lib/node.d.cts", + "default": "./lib/node.cjs" + } + }, + "./browser": { + "import": { + "types": "./esm/browser.d.ts", + "default": "./esm/browser.js" + }, + "require": { + "types": "./lib/browser.d.cts", + "default": "./lib/browser.cjs" + } + }, + "./package.json": "./package.json" + }, + "targets": { + "main": false, + "module": false, + "browser": false, + "types": false + }, + "sideEffects": false, + "homepage": "https://101arrowz.github.io/fflate", + "repository": "https://github.com/101arrowz/fflate", + "bugs": { + "email": "arjunbarrett@gmail.com", + "url": "https://github.com/101arrowz/fflate/issues" + }, + "author": "Arjun Barrett ", + "license": "MIT", + "keywords": [ + "gzip", + "gunzip", + "deflate", + "inflate", + "compression", + "decompression", + "zlib", + "pako", + "jszip", + "browser", + "node.js", + "tiny", + "fast", + "zip", + "unzip", + "non-blocking" + ], + "scripts": { + "build": "npm run build:lib && npm run build:docs && npm run build:demo", + "script": "node -r ts-node/register scripts/$SC.ts", + "build:lib": "tsc && tsc --project tsconfig.esm.json && npm run build:rewrite && npm run build:umd", + "build:umd": "SC=buildUMD npm run script", + "build:rewrite": "SC=rewriteBuilds npm run script", + "build:demo": "tsc --project tsconfig.demo.json && parcel build demo/index.html --no-cache --public-url \"./\" && SC=cpGHPages npm run script", + "build:docs": "typedoc --plugin typedoc-plugin-markdown --hideBreadcrumbs --readme none --disableSources --excludePrivate --excludeProtected --expandParameters --githubPages false --out docs/ src/index.ts", + "test": "TS_NODE_PROJECT=test/tsconfig.json uvu -b -r ts-node/register test", + "prepack": "npm run build && npm run test" + }, + "devDependencies": { + "@parcel/service-worker": "^2.9.3", + "@types/node": "^25.8.0", + "@types/pako": "*", + "@types/react": "^18.2.21", + "@types/react-dom": "^18.2.7", + "jszip": "^3.10.1", + "pako": "*", + "parcel": "^2.9.3", + "preact": "^10.17.1", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "simple-git": "^3.19.1", + "terser": "^5.47.1", + "tiny-inflate": "*", + "ts-node": "^10.9.2", + "typedoc": "^0.28.19", + "typedoc-plugin-markdown": "^4.11.0", + "typescript": "^6.0.3", + "uvu": "^0.5.6", + "uzip": "*" + }, + "alias": { + "react": "preact/compat", + "react-dom": "preact/compat", + "buffer": false, + "process": false + } +} diff --git a/node_modules/fflate/umd/index.js b/node_modules/fflate/umd/index.js new file mode 100644 index 0000000000000000000000000000000000000000..df762372e3ff721a72a8e9b5cf1e58f2f3ee4ea8 --- /dev/null +++ b/node_modules/fflate/umd/index.js @@ -0,0 +1 @@ +!function(f){typeof module!='undefined'&&typeof exports=='object'?module.exports=f():typeof define!='undefined'&&define.amd?define(f):(typeof self!='undefined'?self:this).fflate=f()}(function(){var _e={};"use strict";_e.deflate=zt,_e.deflateSync=kt,_e.inflate=At,_e.inflateSync=Tt,_e.gzip=It,_e.compress=It,_e.gzipSync=Ut,_e.compressSync=Ut,_e.gunzip=Zt,_e.gunzipSync=qt,_e.zlib=Lt,_e.zlibSync=Bt,_e.unzlib=Nt,_e.unzlibSync=Pt,_e.gzip=It,_e.compress=It,_e.decompress=Jt,_e.decompressSync=Kt,_e.strToU8=nn,_e.strFromU8=rn,_e.zip=dn,_e.zipSync=gn,_e.unzip=zn,_e.unzipSync=kn;var t=(typeof module!='undefined'&&typeof exports=='object'?function(_f){"use strict";var e,r,t,n=";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global";try{e=require("worker_threads"),r=e.Worker,t=e.isMarkedAsUntransferable}catch(e){}exports.default=r?function(e,o,a,s,u){var i=!1,l=new r(e+n,{eval:!0}).on("error",function(e){return u(e,null)}).on("message",function(e){return u(null,e)}).on("exit",function(e){e&&!i&&u(Error("exited with code "+e),null)});return t&&(s=s.filter(function(e){return!t(e)})),l.postMessage(a,s),l.terminate=function(){return i=!0,r.prototype.terminate.call(l)},l}:function(e,r,t,n,o){setImmediate(function(){return o(Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)});var a=function(){};return{terminate:a,postMessage:a}};return _f}:function(_f){"use strict";var e={};_f.default=function(r,t,s,a,n){var o=new Worker(e[t]||(e[t]=URL.createObjectURL(new Blob([r+';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'],{type:"text/javascript"}))));return o.onmessage=function(e){var r=e.data,t=r.$e$;if(t){var s=Error(t[0]);s.code=t[1],s.stack=t[2],n(s,null)}else n(null,r)},o.postMessage(s,a),o};return _f})({}),n=Uint8Array,r=Uint16Array,i=Int32Array,e=new n([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),o=new n([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),s=new n([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(t,n){for(var e=new r(31),o=0;o<31;++o)e[o]=n+=1<>1|(21845&d)<<1;v[d]=((65280&(g=(61680&(g=(52428&g)>>2|(13107&g)<<2))>>4|(3855&g)<<4))>>8|(255&g)<<8)>>1}var y=function(t,n,i){for(var e=t.length,o=0,s=new r(n);o>h]=f}else for(a=new r(e),o=0;o>15-t[o]);return a},m=new n(288);for(d=0;d<144;++d)m[d]=8;for(d=144;d<256;++d)m[d]=9;for(d=256;d<280;++d)m[d]=7;for(d=280;d<288;++d)m[d]=8;var b=new n(32);for(d=0;d<32;++d)b[d]=5;var w=y(m,9,0),x=y(m,9,1),z=y(b,5,0),k=y(b,5,1),M=function(t){for(var n=t[0],r=1;rn&&(n=t[r]);return n},S=function(t,n,r){var i=n/8|0;return(t[i]|t[i+1]<<8)>>(7&n)&r},A=function(t,n){var r=n/8|0;return(t[r]|t[r+1]<<8|t[r+2]<<16)>>(7&n)},T=function(t){return(t+7)/8|0},D=function(t,r,i){return(null==r||r<0)&&(r=0),(null==i||i>t.length)&&(i=t.length),new n(t.subarray(r,i))};_e.FlateErrorCode={UnexpectedEOF:0,InvalidBlockType:1,InvalidLengthLiteral:2,InvalidDistance:3,StreamFinished:4,NoStreamHandler:5,InvalidHeader:6,NoCallback:7,InvalidUTF8:8,ExtraFieldTooLong:9,InvalidDate:10,FilenameTooLong:11,StreamFinishing:12,InvalidZipData:13,UnknownCompressionMethod:14};var C=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],I=function(t,n,r){var i=Error(n||C[t]);if(i.code=t,Error.captureStackTrace&&Error.captureStackTrace(i,I),!r)throw i;return i},U=function(t,r,i,a){var u=t.length,f=a?a.length:0;if(!u||r.f&&!r.l)return i||new n(0);var c=!i,p=c||2!=r.i,v=r.i;c&&(i=new n(3*u));var d=function(t){var r=i.length;if(t>r){var e=new n(Math.max(2*r,t));e.set(i),i=e}},g=r.f||0,m=r.p||0,b=r.b||0,w=r.l,z=r.d,C=r.m,U=r.n,F=8*u;do{if(!w){g=S(t,m,1);var E=S(t,m+1,3);if(m+=3,!E){var Z=t[(Y=T(m)+4)-4]|t[Y-3]<<8,q=Y+Z;if(q>u){v&&I(0);break}p&&d(b+Z),i.set(t.subarray(Y,q),b),r.b=b+=Z,r.p=m=8*q,r.f=g;continue}if(1==E)w=x,z=k,C=9,U=5;else if(2==E){var O=S(t,m,31)+257,G=S(t,m+10,15)+4,L=O+S(t,m+5,31)+1;m+=14;for(var B=new n(L),H=new n(19),j=0;j>4)<16)B[j++]=Y;else{var K=0,Q=0;for(16==Y?(Q=3+S(t,m,3),m+=2,K=B[j-1]):17==Y?(Q=3+S(t,m,7),m+=3):18==Y&&(Q=11+S(t,m,127),m+=7);Q--;)B[j++]=K}}var R=B.subarray(0,O),W=B.subarray(O);C=M(R),U=M(W),w=y(R,C,1),z=y(W,U,1)}else I(1);if(m>F){v&&I(0);break}}p&&d(b+131072);for(var X=(1<>4;if((m+=15&K)>F){v&&I(0);break}if(K||I(2),tt<256)i[b++]=tt;else{if(256==tt){_=m,w=null;break}var nt=tt-254;tt>264&&(nt=S(t,m,(1<<(et=e[j=tt-257]))-1)+h[j],m+=et);var rt=z[A(t,m)&$],it=rt>>4;if(rt||I(3),m+=15&rt,W=l[it],it>3){var et=o[it];W+=A(t,m)&(1<F){v&&I(0);break}p&&d(b+131072);var ot=b+nt;if(b>8},E=function(t,n,r){var i=n/8|0;t[i]|=r<<=7&n,t[i+1]|=r>>8,t[i+2]|=r>>16},Z=function(t,i){for(var e=[],o=0;ov&&(v=a[o].s);var d=new r(v+1),g=q(e[l-1],d,0);if(g>i){o=0;var y=0,m=g-i,b=1<i))break;y+=b-(1<>=m;y>0;){var x=a[o].s;d[x]=0&&y;--o){var z=a[o].s;d[z]==i&&(--d[z],++y)}g=i}return{t:new n(d),l:g}},q=function(t,n,r){return-1==t.s?Math.max(q(t.l,n,r+1),q(t.r,n,r+1)):n[t.s]=r},O=function(t){for(var n=t.length;n&&!t[--n];);for(var i=new r(++n),e=0,o=t[0],s=1,a=function(t){i[e++]=t},u=1;u<=n;++u)if(t[u]==o&&u!=n)++s;else{if(!o&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(o),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(o);s=1,o=t[u]}return{c:i.subarray(0,e),n:n}},G=function(t,n){for(var r=0,i=0;i>8,t[e+2]=255^t[e],t[e+3]=255^t[e+1];for(var o=0;o4&&!j[s[P-1]];--P);var V,Y,J,K,Q=p+5<<3,R=G(u,m)+G(h,b)+f,W=G(u,g)+G(h,M)+f+14+3*P+G(q,j)+2*q[16]+3*q[17]+7*q[18];if(l>=0&&Q<=R&&Q<=W)return L(n,v,t.subarray(l,l+p));if(F(n,v,1+(W15&&(F(n,v,tt[B]>>5&127),v+=tt[B]>>12)}}else V=w,Y=m,J=z,K=b;for(B=0;B255){var rt;E(n,v,V[257+(rt=nt>>18&31)]),v+=Y[rt+257],rt>7&&(F(n,v,nt>>23&31),v+=e[rt]);var it=31&nt;E(n,v,J[it]),v+=K[it],it>3&&(E(n,v,nt>>5&8191),v+=o[it])}else E(n,v,V[nt]),v+=Y[nt]}return E(n,v,V[256]),v+Y[256]},H=new i([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),j=new n(0),N=function(t,s,a,u,h,c){var l=c.z||t.length,v=new n(u+l+5*(1+Math.ceil(l/7e3))+h),d=v.subarray(u,v.length-h),g=c.l,y=7&(c.r||0);if(s){y&&(d[0]=c.r>>3);for(var m=H[s-1],b=m>>13,w=8191&m,x=(1<7e3||q>24576)&&(V>423||!g)){y=B(t,d,0,C,I,U,E,q,G,Z-G,y),q=F=E=0,G=Z;for(var Y=0;Y<286;++Y)I[Y]=0;for(Y=0;Y<30;++Y)U[Y]=0}var J=2,K=0,Q=w,R=N-P&32767;if(V>2&&j==A(Z-R))for(var W=Math.min(b,V)-1,X=Math.min(32767,Z),$=Math.min(258,V);R<=X&&--Q&&N!=P;){if(t[Z+J]==t[Z+J-R]){for(var _=0;_<$&&t[Z+_]==t[Z+_-R];++_);if(_>J){if(J=_,K=R,_>W)break;var tt=Math.min(R,_-2),nt=0;for(Y=0;Ynt&&(nt=it,P=rt)}}}R+=(N=P)-(P=z[N])&32767}if(K){C[q++]=268435456|f[J]<<18|p[K];var et=31&f[J],ot=31&p[K];E+=e[et]+o[ot],++I[257+et],++U[ot],O=Z+J,++F}else C[q++]=t[Z],++I[t[Z]]}}for(Z=Math.max(Z,O);Z=l&&(d[y/8|0]=g,st=l),y=L(d,y+1,t.subarray(Z,st))}c.i=l}return D(v,0,u+T(y)+h)},P=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,i=9;--i;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),V=function(){var t=-1;return{p:function(n){for(var r=t,i=0;i>>8;t=r},d:function(){return~t}}},Y=function(){var t=1,n=0;return{p:function(r){for(var i=t,e=n,o=0|r.length,s=0;s!=o;){for(var a=Math.min(s+2655,o);s>16),e=(65535&e)+15*(e>>16)}t=i,n=e},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},J=function(t,r,i,e,o){if(!o&&(o={l:1},r.dictionary)){var s=r.dictionary.subarray(-32768),a=new n(s.length+t.length);a.set(s),a.set(t,s.length),t=a,o.w=s.length}return N(t,null==r.level?6:r.level,null==r.mem?o.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):20:12+r.mem,i,e,o)},K=function(t,n){var r={};for(var i in t)r[i]=t[i];for(var i in n)r[i]=n[i];return r},Q=function(t,n,r){for(var i=t(),e=""+t,o=e.slice(e.indexOf("[")+1,e.lastIndexOf("]")).replace(/\s+/g,"").split(","),s=0;s>>0},ct=function(t,n){return ft(t,n)+4294967296*ft(t,n+4)},lt=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},pt=function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&<(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var i=0;i<=r.length;++i)t[i+10]=r.charCodeAt(i)}},vt=function(t){31==t[0]&&139==t[1]&&8==t[2]||I(6,"invalid gzip data");var n=t[3],r=10;4&n&&(r+=2+(t[10]|t[11]<<8));for(var i=(n>>3&1)+(n>>4&1);i>0;i-=!t[r++]);return r+(2&n)},dt=function(t){var n=t.length;return(t[n-4]|t[n-3]<<8|t[n-2]<<16|t[n-1]<<24)>>>0},gt=function(t){return 10+(t.filename?t.filename.length+1:0)},yt=function(t,n){var r=n.level,i=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=i<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var e=Y();e.p(n.dictionary),lt(t,2,e.d())}},mt=function(t,n){return(8!=(15&t[0])||t[0]>>4>7||(t[0]<<8|t[1])%31)&&I(6,"invalid zlib data"),(t[1]>>5&1)==+!n&&I(6,"invalid zlib data: "+(32&t[1]?"need":"unexpected")+" dictionary"),2+(t[1]>>3&4)};function bt(t,n){return"function"==typeof t&&(n=t,t={}),this.ondata=n,t}var wt=function(){function t(t,r){if("function"==typeof t&&(r=t,t={}),this.ondata=r,this.o=t||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new n(98304),this.o.dictionary){var i=this.o.dictionary.subarray(-32768);this.b.set(i,32768-i.length),this.s.i=32768-i.length}}return t.prototype.p=function(t,n){this.ondata(J(t,this.o,0,0,this.s),n)},t.prototype.push=function(t,r){this.ondata||I(5),this.s.l&&I(4);var i=t.length+this.s.z;if(i>this.b.length){if(i>2*this.b.length-32768){var e=new n(-32768&i);e.set(this.b.subarray(0,this.s.z)),this.b=e}var o=this.b.length-this.s.z;this.b.set(t.subarray(0,o),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(t.subarray(o),32768),this.s.z=t.length-o+32768,this.s.i=32766,this.s.w=32768}else this.b.set(t,this.s.z),this.s.z+=t.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2),r&&(this.s=this.o={},this.b=j)},t.prototype.flush=function(t){if(this.ondata||I(5),this.s.l&&I(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2,t){var r=new n(6);r[0]=this.s.r>>3;var i=L(r,this.s.r,j);this.s.r=0,this.ondata(r.subarray(0,i>>3),!1)}},t}();_e.Deflate=wt;var xt=function(){return function(t,n){ut([_,function(){return[at,wt]}],this,bt.call(this,t,n),function(t){var n=new wt(t.data);onmessage=at(n)},6,1)}}();function zt(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[_],function(t){return et(kt(t.data[0],t.data[1]))},0,r)}function kt(t,n){return J(t,n||{},0,0)}_e.AsyncDeflate=xt;var Mt=function(){function t(t,r){"function"==typeof t&&(r=t,t={}),this.ondata=r;var i=t&&t.dictionary&&t.dictionary.subarray(-32768);this.s={i:0,b:i?i.length:0},this.o=new n(32768),this.p=new n(0),i&&this.o.set(i)}return t.prototype.e=function(t){if(this.ondata||I(5),this.d&&I(4),this.p.length){if(t.length){var r=new n(this.p.length+t.length);r.set(this.p),r.set(t,this.p.length),this.p=r}}else this.p=t},t.prototype.c=function(t){this.s.i=+(this.d=t||!1);var n=this.s.b,r=U(this.p,this.s,this.o);this.ondata(D(r,n,this.s.b),this.d),this.o=D(r,this.s.b-32768),this.s.b=this.o.length,this.p=D(this.p,this.s.p/8|0),this.s.p&=7},t.prototype.push=function(t,n){this.e(t),this.c(n)},t}();_e.Inflate=Mt;var St=function(){return function(t,n){ut([$,function(){return[at,Mt]}],this,bt.call(this,t,n),function(t){var n=new Mt(t.data);onmessage=at(n)},7,0)}}();function At(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[$],function(t){return et(Tt(t.data[0],ot(t.data[1])))},1,r)}function Tt(t,n){return U(t,{i:2},n&&n.out,n&&n.dictionary)}_e.AsyncInflate=St;var Dt=function(){function t(t,n){this.c=V(),this.l=0,this.v=1,wt.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),this.l+=t.length,wt.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=J(t,this.o,this.v&>(this.o),n&&8,this.s);this.v&&(pt(r,this.o),this.v=0),n&&(lt(r,r.length-8,this.c.d()),lt(r,r.length-4,this.l)),this.ondata(r,n)},t.prototype.flush=function(t){wt.prototype.flush.call(this,t)},t}();_e.Gzip=Dt,_e.Compress=Dt;var Ct=function(){return function(t,n){ut([_,tt,function(){return[at,wt,Dt]}],this,bt.call(this,t,n),function(t){var n=new Dt(t.data);onmessage=at(n)},8,1)}}();function It(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[_,tt,function(){return[Ut]}],function(t){return et(Ut(t.data[0],t.data[1]))},2,r)}function Ut(t,n){n||(n={});var r=V(),i=t.length;r.p(t);var e=J(t,n,gt(n),8),o=e.length;return pt(e,n),lt(e,o-8,r.d()),lt(e,o-4,i),e}_e.AsyncGzip=Ct,_e.AsyncCompress=Ct;var Ft=function(){function t(t,n){this.v=1,this.r=0,Mt.call(this,t,n)}return t.prototype.push=function(t,r){if(Mt.prototype.e.call(this,t),this.r+=t.length,this.v){var i=this.p.subarray(this.v-1),e=i.length>3?vt(i):4;if(e>i.length){if(!r)return}else this.v>1&&this.onmember&&this.onmember(this.r-i.length);this.p=i.subarray(e),this.v=0}Mt.prototype.c.call(this,0),this.s.f&&!this.s.l?(this.v=T(this.s.p)+9,this.s={i:0},this.o=new n(0),this.push(new n(0),r)):r&&Mt.prototype.c.call(this,r)},t}();_e.Gunzip=Ft;var Et=function(){return function(t,n){var r=this;ut([$,nt,function(){return[at,Mt,Ft]}],this,bt.call(this,t,n),function(t){var n=new Ft(t.data);n.onmember=function(t){return postMessage(t)},onmessage=at(n)},9,0,function(t){return r.onmember&&r.onmember(t)})}}();function Zt(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[$,nt,function(){return[qt]}],function(t){return et(qt(t.data[0],t.data[1]))},3,r)}function qt(t,r){var i=vt(t);return i+8>t.length&&I(6,"invalid gzip data"),U(t.subarray(i,-8),{i:2},r&&r.out||new n(dt(t)),r&&r.dictionary)}_e.AsyncGunzip=Et;var Ot=function(){function t(t,n){this.c=Y(),this.v=1,wt.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),wt.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=J(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(yt(r,this.o),this.v=0),n&<(r,r.length-4,this.c.d()),this.ondata(r,n)},t.prototype.flush=function(t){wt.prototype.flush.call(this,t)},t}();_e.Zlib=Ot;var Gt=function(){return function(t,n){ut([_,rt,function(){return[at,wt,Ot]}],this,bt.call(this,t,n),function(t){var n=new Ot(t.data);onmessage=at(n)},10,1)}}();function Lt(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[_,rt,function(){return[Bt]}],function(t){return et(Bt(t.data[0],t.data[1]))},4,r)}function Bt(t,n){n||(n={});var r=Y();r.p(t);var i=J(t,n,n.dictionary?6:2,4);return yt(i,n),lt(i,i.length-4,r.d()),i}_e.AsyncZlib=Gt;var Ht=function(){function t(t,n){Mt.call(this,t,n),this.v=t&&t.dictionary?2:1}return t.prototype.push=function(t,n){if(Mt.prototype.e.call(this,t),this.v){if(this.p.length<6&&!n)return;this.p=this.p.subarray(mt(this.p,this.v-1)),this.v=0}n&&(this.p.length<4&&I(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),Mt.prototype.c.call(this,n)},t}();_e.Unzlib=Ht;var jt=function(){return function(t,n){ut([$,it,function(){return[at,Mt,Ht]}],this,bt.call(this,t,n),function(t){var n=new Ht(t.data);onmessage=at(n)},11,0)}}();function Nt(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),st(t,n,[$,it,function(){return[Pt]}],function(t){return et(Pt(t.data[0],ot(t.data[1])))},5,r)}function Pt(t,n){return U(t.subarray(mt(t,n&&n.dictionary),-4),{i:2},n&&n.out,n&&n.dictionary)}_e.AsyncUnzlib=jt;var Vt=function(){function t(t,n){this.o=bt.call(this,t,n)||{},this.G=Ft,this.I=Mt,this.Z=Ht}return t.prototype.i=function(){var t=this;this.s.ondata=function(n,r){t.ondata(n,r)}},t.prototype.push=function(t,r){if(this.ondata||I(5),this.s)this.s.push(t,r);else{if(this.p&&this.p.length){var i=new n(this.p.length+t.length);i.set(this.p),i.set(t,this.p.length)}else this.p=t;this.p.length>2&&(this.s=31==this.p[0]&&139==this.p[1]&&8==this.p[2]?new this.G(this.o):8!=(15&this.p[0])||this.p[0]>>4>7||(this.p[0]<<8|this.p[1])%31?new this.I(this.o):new this.Z(this.o),this.i(),this.s.push(this.p,r),this.p=null)}},t}();_e.Decompress=Vt;var Yt=function(){function t(t,n){Vt.call(this,t,n),this.queuedSize=0,this.G=Et,this.I=St,this.Z=jt}return t.prototype.i=function(){var t=this;this.s.ondata=function(n,r,i){t.ondata(n,r,i)},this.s.ondrain=function(n){t.queuedSize-=n,t.ondrain&&t.ondrain(n)}},t.prototype.push=function(t,n){this.queuedSize+=t.length,Vt.prototype.push.call(this,t,n)},t}();function Jt(t,n,r){return r||(r=n,n={}),"function"!=typeof r&&I(7),31==t[0]&&139==t[1]&&8==t[2]?Zt(t,n,r):8!=(15&t[0])||t[0]>>4>7||(t[0]<<8|t[1])%31?At(t,n,r):Nt(t,n,r)}function Kt(t,n){return 31==t[0]&&139==t[1]&&8==t[2]?qt(t,n):8!=(15&t[0])||t[0]>>4>7||(t[0]<<8|t[1])%31?Tt(t,n):Pt(t,n)}_e.AsyncDecompress=Yt;var Qt=function(t,r,i,e){for(var o in t){var s=t[o],a=r+o,u=e;Array.isArray(s)&&(u=K(e,s[1]),s=s[0]),ArrayBuffer.isView(s)?i[a]=[s,u]:(i[a+="/"]=[new n(0),u],Qt(s,a,i,e))}},Rt="undefined"!=typeof TextEncoder&&new TextEncoder,Wt="undefined"!=typeof TextDecoder&&new TextDecoder,Xt=0;try{Wt.decode(j,{stream:!0}),Xt=1}catch(t){}var $t=function(t){for(var n="",r=0;;){var i=t[r++],e=(i>127)+(i>223)+(i>239);if(r+e>t.length)return{s:n,r:D(t,r-1)};e?3==e?(i=((15&i)<<18|(63&t[r++])<<12|(63&t[r++])<<6|63&t[r++])-65536,n+=String.fromCharCode(55296|i>>10,56320|1023&i)):n+=String.fromCharCode(1&e?(31&i)<<6|63&t[r++]:(15&i)<<12|(63&t[r++])<<6|63&t[r++]):n+=String.fromCharCode(i)}},_t=function(){function t(t){this.ondata=t,Xt?this.t=new TextDecoder:this.p=j}return t.prototype.push=function(t,r){if(this.ondata||I(5),r=!!r,this.t)return this.ondata(this.t.decode(t,{stream:!0}),r),void(r&&(this.t.decode().length&&I(8),this.t=null));this.p||I(4);var i=new n(this.p.length+t.length);i.set(this.p),i.set(t,this.p.length);var e=$t(i),o=e.s,s=e.r;r?(s.length&&I(8),this.p=null):this.p=s,this.ondata(o,r)},t}();_e.DecodeUTF8=_t;var tn=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||I(5),this.d&&I(4),this.ondata(nn(t),this.d=n||!1)},t}();function nn(t,r){if(r){for(var i=new n(t.length),e=0;e>1)),a=0,u=function(t){s[a++]=t};for(e=0;es.length){var h=new n(a+8+(o-e<<1));h.set(s),s=h}var f=t.charCodeAt(e);f<128||r?u(f):f<2048?(u(192|f>>6),u(128|63&f)):f>55295&&f<57344?(u(240|(f=65536+(1047552&f)|1023&t.charCodeAt(++e))>>18),u(128|f>>12&63),u(128|f>>6&63),u(128|63&f)):(u(224|f>>12),u(128|f>>6&63),u(128|63&f))}return D(s,0,a)}function rn(t,n){if(n){for(var r="",i=0;i65535&&I(9),n+=i+4}return n},hn=function(t,n,r,i,e,o,s,a){var u=i.length,h=r.extra,f=a&&a.length,c=un(h);lt(t,n,null!=s?33639248:67324752),n+=4,null!=s&&(t[n++]=20,t[n++]=r.os),t[n]=20,n+=2,t[n++]=r.flag<<1|(o<0&&8),t[n++]=e&&8,t[n++]=255&r.compression,t[n++]=r.compression>>8;var l=new Date(null==r.mtime?Date.now():r.mtime),p=l.getFullYear()-1980;if((p<0||p>119)&&I(10),lt(t,n,p<<25|l.getMonth()+1<<21|l.getDate()<<16|l.getHours()<<11|l.getMinutes()<<5|l.getSeconds()>>1),n+=4,-1!=o&&(lt(t,n,r.crc),lt(t,n+4,o<0?-o-2:o),lt(t,n+8,r.size)),lt(t,n+12,u),lt(t,n+14,c),n+=16,null!=s&&(lt(t,n,f),lt(t,n+6,r.attrs),lt(t,n+10,s),n+=14),t.set(i,n),n+=u,c)for(var v in h){var d=h[v],g=d.length;lt(t,n,+v),lt(t,n+2,g),t.set(d,n+4),n+=4+g}return f&&(t.set(a,n),n+=f),n},fn=function(t,n,r,i,e){lt(t,n,101010256),lt(t,n+8,r),lt(t,n+10,r),lt(t,n+12,i),lt(t,n+16,e)},cn=function(){function t(t){this.filename=t,this.c=V(),this.size=0,this.compression=0}return t.prototype.process=function(t,n){this.ondata(null,t,n)},t.prototype.push=function(t,n){this.ondata||I(5),this.c.p(t),this.size+=t.length,n&&(this.crc=this.c.d()),this.process(t,n||!1)},t}();_e.ZipPassThrough=cn;var ln=function(){function t(t,n){var r=this;n||(n={}),cn.call(this,t),this.d=new wt(n,function(t,n){r.ondata(null,t,n)}),this.compression=8,this.flag=en(n.level)}return t.prototype.process=function(t,n){try{this.d.push(t,n)}catch(t){this.ondata(t,null,n)}},t.prototype.push=function(t,n){cn.prototype.push.call(this,t,n)},t}();_e.ZipDeflate=ln;var pn=function(){function t(t,n){var r=this;n||(n={}),cn.call(this,t),this.d=new xt(n,function(t,n,i){r.ondata(t,n,i)}),this.compression=8,this.flag=en(n.level),this.terminate=this.d.terminate}return t.prototype.process=function(t,n){this.d.push(t,n)},t.prototype.push=function(t,n){cn.prototype.push.call(this,t,n)},t}();_e.AsyncZipDeflate=pn;var vn=function(){function t(t){this.ondata=t,this.u=[],this.d=1}return t.prototype.add=function(t){var r=this;if(this.ondata||I(5),2&this.d)this.ondata(I(4+8*(1&this.d),0,1),null,!1);else{var i=nn(t.filename),e=i.length,o=t.comment,s=o&&nn(o),a=e!=t.filename.length||s&&o.length!=s.length,u=e+un(t.extra)+30;e>65535&&this.ondata(I(11,0,1),null,!1);var h=new n(u);hn(h,0,t,i,a,-1);var f=[h],c=function(){for(var t=0,n=f;t65535&&M(I(11,0,1),null),k)if(g<16e4)try{M(null,kt(i,h))}catch(t){M(t,null)}else c.push(zt(i,h,M));else M(null,i)},g=0;g65535&&I(11);var y=c?kt(h,f):h,m=y.length,b=V();b.p(h),e.push(K(f,{size:h.length,crc:b.d(),c:y,f:M,m:v,u:l!=a.length||v&&p.length!=d,o:o,compression:c})),o+=30+l+g+m,s+=76+2*(l+g)+(d||0)+m}for(var w=new n(s+22),x=o,z=s-o,k=0;k0){var e=Math.min(this.c,t.length),o=t.subarray(0,e);if(this.c-=e,this.d?this.d.push(o,!this.c):this.k[0].push(o),(t=t.subarray(e)).length)return this.push(t,r)}else{var s=0,a=0,u=void 0,h=void 0;this.p.length?t.length?((h=new n(this.p.length+t.length)).set(this.p),h.set(t,this.p.length)):h=this.p:h=t;for(var f=h.length,c=this.c,l=c&&this.d,p=function(){var t=ft(h,a);if(67324752==t){s=1,u=a,v.d=null,v.c=0;var n=ht(h,a+6),r=ht(h,a+8),e=2048&n,o=8&n,l=ht(h,a+26),p=ht(h,a+28);if(f>a+30+l+p){var d=[];v.k.unshift(d),s=2;var g,y=ft(h,a+18),m=ft(h,a+22),b=rn(h.subarray(a+30,a+=30+l),!e),w=an(h,a,p,2,y,m,0),x=w[0],z=w[1];o&&(x=-1-w[3]),a+=p,v.c=x;var k={name:b,compression:r,start:function(){if(k.ondata||I(5),x){var t=i.o[r];t||k.ondata(I(14,"unknown compression type "+r,1),null,!1),(g=x<0?new t(b):new t(b,x,z)).ondata=function(t,n,r){k.ondata(t,n,r)};for(var n=0,e=d;n=0&&(k.size=x,k.originalSize=z),v.onfile(k)}return"break"}if(c){if(134695760==t)return u=a+=12+(-2==c&&8),s=3,v.c=0,"break";if(33639248==t)return u=a-=4,s=3,v.c=0,"break"}},v=this;a65558)return a(I(13,0,1),null),o;var h=ht(t,u+8);if(h){var f=h,c=ft(t,u+16),l=117853008==ft(t,u-20);if(l){var p=ft(t,u-12);(l=101075792==ft(t,p))&&(f=h=ft(t,p+32),c=ft(t,p+48))}for(var v=r&&r.filter,d=function(r){var i=sn(t,c,l),u=i[0],f=i[1],p=i[2],d=i[3],g=i[4],y=on(t,i[5]);c=g;var m=function(t,n){t?(o(),a(t,null)):(n&&(s[d]=n),--h||a(null,s))};if(!v||v({name:d,size:f,originalSize:p,compression:u}))if(u)if(8==u){var b=t.subarray(y,y+f);if(p<524288||f>.8*p)try{m(null,Tt(b,{out:new n(p)}))}catch(t){m(t,null)}else e.push(At(b,{size:p},m))}else m(I(14,"unknown compression type "+u,1),null);else m(null,D(t,y,y+f));else m(null,null)},g=0;g65558)&&I(13);var o=ht(t,e+8);if(!o)return{};var s=ft(t,e+16),a=117853008==ft(t,e-20);if(a){var u=ft(t,e-12);(a=101075792==ft(t,u))&&(o=ft(t,u+32),s=ft(t,u+48))}for(var h=r&&r.filter,f=0;f Super simple cache for file metadata, useful for process that work on a given series of files +> and that only need to repeat the job on the changed ones since the previous run of the process — Edit + +[![NPM Version](https://img.shields.io/npm/v/file-entry-cache.svg?style=flat)](https://npmjs.org/package/file-entry-cache) +[![tests](https://github.com/jaredwray/file-entry-cache/actions/workflows/tests.yaml/badge.svg?branch=master)](https://github.com/jaredwray/file-entry-cache/actions/workflows/tests.yaml) +[![codecov](https://codecov.io/github/jaredwray/file-entry-cache/graph/badge.svg?token=37tZMQE0Sy)](https://codecov.io/github/jaredwray/file-entry-cache) +[![npm](https://img.shields.io/npm/dm/file-entry-cache)](https://npmjs.com/package/file-entry-cache) + + +## install + +```bash +npm i --save file-entry-cache +``` + +## Usage + +The module exposes two functions `create` and `createFromFile`. + +## `create(cacheName, [directory, useCheckSum])` +- **cacheName**: the name of the cache to be created +- **directory**: Optional the directory to load the cache from +- **usecheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. + +## `createFromFile(pathToCache, [useCheckSum])` +- **pathToCache**: the path to the cache file (this combines the cache name and directory) +- **useCheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. + +```js +// loads the cache, if one does not exists for the given +// Id a new one will be prepared to be created +var fileEntryCache = require('file-entry-cache'); + +var cache = fileEntryCache.create('testCache'); + +var files = expand('../fixtures/*.txt'); + +// the first time this method is called, will return all the files +var oFiles = cache.getUpdatedFiles(files); + +// this will persist this to disk checking each file stats and +// updating the meta attributes `size` and `mtime`. +// custom fields could also be added to the meta object and will be persisted +// in order to retrieve them later +cache.reconcile(); + +// use this if you want the non visited file entries to be kept in the cache +// for more than one execution +// +// cache.reconcile( true /* noPrune */) + +// on a second run +var cache2 = fileEntryCache.create('testCache'); + +// will return now only the files that were modified or none +// if no files were modified previous to the execution of this function +var oFiles = cache.getUpdatedFiles(files); + +// if you want to prevent a file from being considered non modified +// something useful if a file failed some sort of validation +// you can then remove the entry from the cache doing +cache.removeEntry('path/to/file'); // path to file should be the same path of the file received on `getUpdatedFiles` +// that will effectively make the file to appear again as modified until the validation is passed. In that +// case you should not remove it from the cache + +// if you need all the files, so you can determine what to do with the changed ones +// you can call +var oFiles = cache.normalizeEntries(files); + +// oFiles will be an array of objects like the following +entry = { + key: 'some/name/file', the path to the file + changed: true, // if the file was changed since previous run + meta: { + size: 3242, // the size of the file + mtime: 231231231, // the modification time of the file + data: {} // some extra field stored for this file (useful to save the result of a transformation on the file + } +} + +``` + +## Motivation for this module + +I needed a super simple and dumb **in-memory cache** with optional disk persistence (write-back cache) in order to make +a script that will beautify files with `esformatter` to execute only on the files that were changed since the last run. + +In doing so the process of beautifying files was reduced from several seconds to a small fraction of a second. + +This module uses [flat-cache](https://www.npmjs.com/package/flat-cache) a super simple `key/value` cache storage with +optional file persistance. + +The main idea is to read the files when the task begins, apply the transforms required, and if the process succeed, +then store the new state of the files. The next time this module request for `getChangedFiles` will return only +the files that were modified. Making the process to end faster. + +This module could also be used by processes that modify the files applying a transform, in that case the result of the +transform could be stored in the `meta` field, of the entries. Anything added to the meta field will be persisted. +Those processes won't need to call `getChangedFiles` they will instead call `normalizeEntries` that will return the +entries with a `changed` field that can be used to determine if the file was changed or not. If it was not changed +the transformed stored data could be used instead of actually applying the transformation, saving time in case of only +a few files changed. + +In the worst case scenario all the files will be processed. In the best case scenario only a few of them will be processed. + +## Important notes +- The values set on the meta attribute of the entries should be `stringify-able` ones if possible, flat-cache uses `circular-json` to try to persist circular structures, but this should be considered experimental. The best results are always obtained with non circular values +- All the changes to the cache state are done to memory first and only persisted after reconcile. + +## License + +MIT + + diff --git a/node_modules/file-entry-cache/cache.js b/node_modules/file-entry-cache/cache.js new file mode 100644 index 0000000000000000000000000000000000000000..6b15767e164f4e8c3e6d6685daf42cd75130e485 --- /dev/null +++ b/node_modules/file-entry-cache/cache.js @@ -0,0 +1,291 @@ +var path = require('path'); +var crypto = require('crypto'); + +module.exports = { + createFromFile: function (filePath, useChecksum) { + var fname = path.basename(filePath); + var dir = path.dirname(filePath); + return this.create(fname, dir, useChecksum); + }, + + create: function (cacheId, _path, useChecksum) { + var fs = require('fs'); + var flatCache = require('flat-cache'); + var cache = flatCache.load(cacheId, _path); + var normalizedEntries = {}; + + var removeNotFoundFiles = function removeNotFoundFiles() { + const cachedEntries = cache.keys(); + // remove not found entries + cachedEntries.forEach(function remover(fPath) { + try { + fs.statSync(fPath); + } catch (err) { + if (err.code === 'ENOENT') { + cache.removeKey(fPath); + } + } + }); + }; + + removeNotFoundFiles(); + + return { + /** + * the flat cache storage used to persist the metadata of the `files + * @type {Object} + */ + cache: cache, + + /** + * Given a buffer, calculate md5 hash of its content. + * @method getHash + * @param {Buffer} buffer buffer to calculate hash on + * @return {String} content hash digest + */ + getHash: function (buffer) { + return crypto.createHash('md5').update(buffer).digest('hex'); + }, + + /** + * Return whether or not a file has changed since last time reconcile was called. + * @method hasFileChanged + * @param {String} file the filepath to check + * @return {Boolean} wheter or not the file has changed + */ + hasFileChanged: function (file) { + return this.getFileDescriptor(file).changed; + }, + + /** + * given an array of file paths it return and object with three arrays: + * - changedFiles: Files that changed since previous run + * - notChangedFiles: Files that haven't change + * - notFoundFiles: Files that were not found, probably deleted + * + * @param {Array} files the files to analyze and compare to the previous seen files + * @return {[type]} [description] + */ + analyzeFiles: function (files) { + var me = this; + files = files || []; + + var res = { + changedFiles: [], + notFoundFiles: [], + notChangedFiles: [], + }; + + me.normalizeEntries(files).forEach(function (entry) { + if (entry.changed) { + res.changedFiles.push(entry.key); + return; + } + if (entry.notFound) { + res.notFoundFiles.push(entry.key); + return; + } + res.notChangedFiles.push(entry.key); + }); + return res; + }, + + getFileDescriptor: function (file) { + var fstat; + + try { + fstat = fs.statSync(file); + } catch (ex) { + this.removeEntry(file); + return { key: file, notFound: true, err: ex }; + } + + if (useChecksum) { + return this._getFileDescriptorUsingChecksum(file); + } + + return this._getFileDescriptorUsingMtimeAndSize(file, fstat); + }, + + _getFileDescriptorUsingMtimeAndSize: function (file, fstat) { + var meta = cache.getKey(file); + var cacheExists = !!meta; + + var cSize = fstat.size; + var cTime = fstat.mtime.getTime(); + + var isDifferentDate; + var isDifferentSize; + + if (!meta) { + meta = { size: cSize, mtime: cTime }; + } else { + isDifferentDate = cTime !== meta.mtime; + isDifferentSize = cSize !== meta.size; + } + + var nEntry = (normalizedEntries[file] = { + key: file, + changed: !cacheExists || isDifferentDate || isDifferentSize, + meta: meta, + }); + + return nEntry; + }, + + _getFileDescriptorUsingChecksum: function (file) { + var meta = cache.getKey(file); + var cacheExists = !!meta; + + var contentBuffer; + try { + contentBuffer = fs.readFileSync(file); + } catch (ex) { + contentBuffer = ''; + } + + var isDifferent = true; + var hash = this.getHash(contentBuffer); + + if (!meta) { + meta = { hash: hash }; + } else { + isDifferent = hash !== meta.hash; + } + + var nEntry = (normalizedEntries[file] = { + key: file, + changed: !cacheExists || isDifferent, + meta: meta, + }); + + return nEntry; + }, + + /** + * Return the list o the files that changed compared + * against the ones stored in the cache + * + * @method getUpdated + * @param files {Array} the array of files to compare against the ones in the cache + * @returns {Array} + */ + getUpdatedFiles: function (files) { + var me = this; + files = files || []; + + return me + .normalizeEntries(files) + .filter(function (entry) { + return entry.changed; + }) + .map(function (entry) { + return entry.key; + }); + }, + + /** + * return the list of files + * @method normalizeEntries + * @param files + * @returns {*} + */ + normalizeEntries: function (files) { + files = files || []; + + var me = this; + var nEntries = files.map(function (file) { + return me.getFileDescriptor(file); + }); + + //normalizeEntries = nEntries; + return nEntries; + }, + + /** + * Remove an entry from the file-entry-cache. Useful to force the file to still be considered + * modified the next time the process is run + * + * @method removeEntry + * @param entryName + */ + removeEntry: function (entryName) { + delete normalizedEntries[entryName]; + cache.removeKey(entryName); + }, + + /** + * Delete the cache file from the disk + * @method deleteCacheFile + */ + deleteCacheFile: function () { + cache.removeCacheFile(); + }, + + /** + * remove the cache from the file and clear the memory cache + */ + destroy: function () { + normalizedEntries = {}; + cache.destroy(); + }, + + _getMetaForFileUsingCheckSum: function (cacheEntry) { + var contentBuffer = fs.readFileSync(cacheEntry.key); + var hash = this.getHash(contentBuffer); + var meta = Object.assign(cacheEntry.meta, { hash: hash }); + delete meta.size; + delete meta.mtime; + return meta; + }, + + _getMetaForFileUsingMtimeAndSize: function (cacheEntry) { + var stat = fs.statSync(cacheEntry.key); + var meta = Object.assign(cacheEntry.meta, { + size: stat.size, + mtime: stat.mtime.getTime(), + }); + delete meta.hash; + return meta; + }, + + /** + * Sync the files and persist them to the cache + * @method reconcile + */ + reconcile: function (noPrune) { + removeNotFoundFiles(); + + noPrune = typeof noPrune === 'undefined' ? true : noPrune; + + var entries = normalizedEntries; + var keys = Object.keys(entries); + + if (keys.length === 0) { + return; + } + + var me = this; + + keys.forEach(function (entryName) { + var cacheEntry = entries[entryName]; + + try { + var meta = useChecksum + ? me._getMetaForFileUsingCheckSum(cacheEntry) + : me._getMetaForFileUsingMtimeAndSize(cacheEntry); + cache.setKey(entryName, meta); + } catch (err) { + // if the file does not exists we don't save it + // other errors are just thrown + if (err.code !== 'ENOENT') { + throw err; + } + } + }); + + cache.save(noPrune); + }, + }; + }, +}; diff --git a/node_modules/file-entry-cache/package.json b/node_modules/file-entry-cache/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ef63b6ff8711357d96f4c356bae8e83f19c5c9a5 --- /dev/null +++ b/node_modules/file-entry-cache/package.json @@ -0,0 +1,56 @@ +{ + "name": "file-entry-cache", + "version": "8.0.0", + "description": "Super simple cache for file metadata, useful for process that work o a given series of files and that only need to repeat the job on the changed ones since the previous run of the process", + "repository": "jaredwray/file-entry-cache", + "license": "MIT", + "author": { + "name": "Jared Wray", + "url": "https://jaredwray.com" + }, + "main": "cache.js", + "files": [ + "cache.js" + ], + "engines": { + "node": ">=16.0.0" + }, + "scripts": { + "eslint": "eslint --cache --cache-location=node_modules/.cache/ 'cache.js' 'test/**/*.js' 'perf.js'", + "autofix": "npm run eslint -- --fix", + "clean": "rimraf ./node_modules ./package-lock.json ./yarn.lock", + "test": "npm run eslint --silent && c8 mocha -R spec test/specs", + "test:ci": "npm run eslint --silent && c8 --reporter=lcov mocha -R spec test/specs", + "perf": "node perf.js" + }, + "prepush": [ + "npm run eslint --silent" + ], + "precommit": [ + "npm run eslint --silent" + ], + "keywords": [ + "file cache", + "task cache files", + "file cache", + "key par", + "key value", + "cache" + ], + "devDependencies": { + "c8": "^8.0.1", + "chai": "^4.3.10", + "eslint": "^8.56.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-mocha": "^10.2.0", + "eslint-plugin-prettier": "^5.0.1", + "glob-expand": "^0.2.1", + "mocha": "^10.2.0", + "prettier": "^3.1.1", + "rimraf": "^5.0.5", + "write": "^2.0.0" + }, + "dependencies": { + "flat-cache": "^4.0.0" + } +} diff --git a/node_modules/file-selector/LICENSE b/node_modules/file-selector/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eda448f49ab578340a778877613836af779382a3 --- /dev/null +++ b/node_modules/file-selector/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Roland Groza + +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. diff --git a/node_modules/file-selector/README.md b/node_modules/file-selector/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c5bf8a76020b4407849d487e8e5aa00864665607 --- /dev/null +++ b/node_modules/file-selector/README.md @@ -0,0 +1,144 @@ +# file-selector + +> A small package for converting a [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent) or [file input](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file) to a list of File objects. + +[![npm](https://img.shields.io/npm/v/file-selector.svg?style=flat-square)](https://www.npmjs.com/package/file-selector) +![Tests](https://img.shields.io/github/actions/workflow/status/react-dropzone/file-selector/test.yml?branch=master&style=flat-square&label=tests) +[![codecov](https://img.shields.io/coveralls/github/react-dropzone/file-selector/master?style=flat-square)](https://coveralls.io/github/react-dropzone/file-selector?branch=master) +[![Open Collective Backers](https://img.shields.io/opencollective/backers/react-dropzone.svg?style=flat-square)](#backers) +[![Open Collective Sponsors](https://img.shields.io/opencollective/sponsors/react-dropzone.svg?style=flat-square)](#sponsors) +[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg?style=flat-square)](https://github.com/react-dropzone/.github/blob/main/CODE_OF_CONDUCT.md) + +# Table of Contents + +* [Installation](#installation) +* [Usage](#usage) +* [Browser Support](#browser-support) +* [Contribute](#contribute) +* [Credits](#credits) +* [Support](#support) +* [License](#license) + + +## Installation +You can install this package from [NPM](https://www.npmjs.com): +```bash +npm add file-selector +``` + +### CDN +For CDN, you can use [unpkg](https://unpkg.com): + +[https://unpkg.com/file-selector/dist/bundles/file-selector.umd.min.js](https://unpkg.com/file-selector/dist/bundles/file-selector.umd.min.js) + +The global namespace for file-selector is `fileSelector`: +```js +const {fromEvent} = fileSelector; +document.addEventListener('drop', async evt => { + const files = await fromEvent(evt); + console.log(files); +}); +``` + + +## Usage + +### ES6 +Convert a [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent) to File objects: +```ts +import {fromEvent} from 'file-selector'; +document.addEventListener('drop', async evt => { + const files = await fromEvent(evt); + console.log(files); +}); +``` + +Convert a [change event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) for an input type file to File objects: +```ts +import {fromEvent} from 'file-selector'; +const input = document.getElementById('myInput'); +input.addEventListener('change', async evt => { + const files = await fromEvent(evt); + console.log(files); +}); +``` + +Convert [FileSystemFileHandle](https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle) items to File objects: +```ts +import {fromEvent} from 'file-selector'; + +// Open file picker +const handles = await window.showOpenFilePicker({multiple: true}); +// Get the files +const files = await fromEvent(handles); +console.log(files); +``` +**NOTE** The above is experimental and subject to change. + +### CommonJS +Convert a `DragEvent` to File objects: +```ts +const {fromEvent} = require('file-selector'); +document.addEventListener('drop', async evt => { + const files = await fromEvent(evt); + console.log(files); +}); +``` + + +## Browser Support +Most browser support basic File selection with drag 'n' drop or file input: +* [File API](https://developer.mozilla.org/en-US/docs/Web/API/File#Browser_compatibility) +* [Drag Event](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent#Browser_compatibility) +* [DataTransfer](https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer#Browser_compatibility) +* [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Browser_compatibility) + +For folder drop we use the [FileSystem API](https://developer.mozilla.org/en-US/docs/Web/API/FileSystem) which has very limited support: +* [DataTransferItem.getAsFile()](https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/getAsFile#Browser_compatibility) +* [DataTransferItem.webkitGetAsEntry()](https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/webkitGetAsEntry#Browser_compatibility) +* [FileSystemEntry](https://developer.mozilla.org/en-US/docs/Web/API/FileSystemEntry#Browser_compatibility) +* [FileSystemFileEntry.file()](https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileEntry/file#Browser_compatibility) +* [FileSystemDirectoryEntry.createReader()](https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry/createReader#Browser_compatibility) +* [FileSystemDirectoryReader.readEntries()](https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryReader/readEntries#Browser_compatibility) + + +## Contribute +Checkout the organization [CONTRIBUTING.md](https://github.com/react-dropzone/.github/blob/main/CONTRIBUTING.md). + +## Credits +* [html5-file-selector](https://github.com/quarklemotion/html5-file-selector) + +## Support + +### Backers +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/react-dropzone#backer)] + + + + + + + + + + + + + +### Sponsors +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/react-dropzone#sponsor)] + + + + + + + + + + + + + +## License +MIT diff --git a/node_modules/file-selector/package.json b/node_modules/file-selector/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8b7cd55b324654b4dfe1f371d7f94f2815685d65 --- /dev/null +++ b/node_modules/file-selector/package.json @@ -0,0 +1,69 @@ +{ + "name": "file-selector", + "version": "2.1.2", + "description": "Convert DataTransfer object to a list of File objects", + "main": "./dist/index.js", + "module": "./dist/es2015/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist/**/*", + "src/*", + "!*.spec.*" + ], + "keywords": [ + "drag-and-drop", + "html5", + "file-api", + "DataTransfer", + "File" + ], + "homepage": "https://github.com/react-dropzone/file-selector", + "license": "MIT", + "author": { + "name": "Roland Groza", + "email": "rolandjitsu@gmail.com" + }, + "repository": { + "type": "git", + "url": "https://github.com/react-dropzone/file-selector.git" + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "prebuild": "npm run clean", + "build": "npm-run-all -s compile build:umd", + "build:umd": "rollup -c ./rollup.config.mjs", + "compile": "npm-run-all -p compile:es2015 compile:cjs compile:types", + "compile:es2015": "tsc -p ./tsconfig.es2015.json", + "compile:cjs": "tsc -p ./tsconfig.cjs.json", + "compile:types": "tsc -p ./tsconfig.types.json", + "clean": "rm -rf dist/*", + "lint": "tslint -c tslint.json -p ./tsconfig.spec.json -t stylish", + "lint:fix": "npm run lint -- --fix", + "pretest:cov": "npm run lint", + "test:cov": "jest --coverage", + "test": "jest --watch" + }, + "dependencies": { + "tslib": "^2.7.0" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^28.0.0", + "@rollup/plugin-node-resolve": "^15.3.0", + "@rollup/plugin-terser": "^0.4.4", + "@types/jest": "^29.5.13", + "@types/node": "^22.7.5", + "camelcase": "^8.0.0", + "jest": "^29.7.0", + "jest-environment-jsdom": "^29.7.0", + "npm-run-all": "^4.1.5", + "rollup": "^4.24.0", + "ts-jest": "^29.2.5", + "tslint": "^6.1.3", + "typescript": "^5.6.2" + }, + "engines": { + "node": ">= 12" + } +} diff --git a/node_modules/file-selector/src/file-selector.ts b/node_modules/file-selector/src/file-selector.ts new file mode 100644 index 0000000000000000000000000000000000000000..33717d76bc22244056eee584008a60f348a628a0 --- /dev/null +++ b/node_modules/file-selector/src/file-selector.ts @@ -0,0 +1,207 @@ +import {FileWithPath, toFileWithPath} from './file'; + + +const FILES_TO_IGNORE = [ + // Thumbnail cache files for macOS and Windows + '.DS_Store', // macOs + 'Thumbs.db' // Windows +]; + + +/** + * Convert a DragEvent's DataTrasfer object to a list of File objects + * NOTE: If some of the items are folders, + * everything will be flattened and placed in the same list but the paths will be kept as a {path} property. + * + * EXPERIMENTAL: A list of https://developer.mozilla.org/en-US/docs/Web/API/FileSystemHandle objects can also be passed as an arg + * and a list of File objects will be returned. + * + * @param evt + */ +export async function fromEvent(evt: Event | any): Promise<(FileWithPath | DataTransferItem)[]> { + if (isObject(evt) && isDataTransfer(evt.dataTransfer)) { + return getDataTransferFiles(evt.dataTransfer, evt.type); + } else if (isChangeEvt(evt)) { + return getInputFiles(evt); + } else if (Array.isArray(evt) && evt.every(item => 'getFile' in item && typeof item.getFile === 'function')) { + return getFsHandleFiles(evt) + } + return []; +} + +function isDataTransfer(value: any): value is DataTransfer { + return isObject(value); +} + +function isChangeEvt(value: any): value is Event { + return isObject(value) && isObject(value.target); +} + +function isObject(v: any): v is T { + return typeof v === 'object' && v !== null +} + +function getInputFiles(evt: Event) { + return fromList((evt.target as HTMLInputElement).files).map(file => toFileWithPath(file)); +} + +// Ee expect each handle to be https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle +async function getFsHandleFiles(handles: any[]) { + const files = await Promise.all(handles.map(h => h.getFile())); + return files.map(file => toFileWithPath(file)); +} + + +async function getDataTransferFiles(dt: DataTransfer, type: string) { + // IE11 does not support dataTransfer.items + // See https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/items#Browser_compatibility + if (dt.items) { + const items = fromList(dt.items) + .filter(item => item.kind === 'file'); + // According to https://html.spec.whatwg.org/multipage/dnd.html#dndevents, + // only 'dragstart' and 'drop' has access to the data (source node) + if (type !== 'drop') { + return items; + } + const files = await Promise.all(items.map(toFilePromises)); + return noIgnoredFiles(flatten(files)); + } + + return noIgnoredFiles(fromList(dt.files) + .map(file => toFileWithPath(file))); +} + +function noIgnoredFiles(files: FileWithPath[]) { + return files.filter(file => FILES_TO_IGNORE.indexOf(file.name) === -1); +} + +// IE11 does not support Array.from() +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Browser_compatibility +// https://developer.mozilla.org/en-US/docs/Web/API/FileList +// https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList +function fromList(items: DataTransferItemList | FileList | null): T[] { + if (items === null) { + return []; + } + + const files = []; + + // tslint:disable: prefer-for-of + for (let i = 0; i < items.length; i++) { + const file = items[i]; + files.push(file); + } + + return files as any; +} + +// https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem +function toFilePromises(item: DataTransferItem) { + if (typeof item.webkitGetAsEntry !== 'function') { + return fromDataTransferItem(item); + } + + const entry = item.webkitGetAsEntry(); + + // Safari supports dropping an image node from a different window and can be retrieved using + // the DataTransferItem.getAsFile() API + // NOTE: FileSystemEntry.file() throws if trying to get the file + if (entry && entry.isDirectory) { + return fromDirEntry(entry) as any; + } + + return fromDataTransferItem(item, entry); +} + +function flatten(items: any[]): T[] { + return items.reduce((acc, files) => [ + ...acc, + ...(Array.isArray(files) ? flatten(files) : [files]) + ], []); +} + +async function fromDataTransferItem(item: DataTransferItem, entry?: FileSystemEntry | null) { + // Check if we're in a secure context; due to a bug in Chrome (as far as we know) + // the browser crashes when calling this API (yet to be confirmed as a consistent behaviour). + // + // See: + // - https://issues.chromium.org/issues/40186242 + // - https://github.com/react-dropzone/react-dropzone/issues/1397 + if (globalThis.isSecureContext && typeof (item as any).getAsFileSystemHandle === 'function') { + const h = await (item as any).getAsFileSystemHandle(); + if (h === null) { + throw new Error(`${item} is not a File`); + } + // It seems that the handle can be `undefined` (see https://github.com/react-dropzone/file-selector/issues/120), + // so we check if it isn't; if it is, the code path continues to the next API (`getAsFile`). + if (h !== undefined) { + const file = await h.getFile(); + file.handle = h; + return toFileWithPath(file); + } + } + const file = item.getAsFile(); + if (!file) { + throw new Error(`${item} is not a File`); + } + const fwp = toFileWithPath(file, entry?.fullPath ?? undefined); + return fwp; +} + +// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemEntry +async function fromEntry(entry: any) { + return entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry); +} + +// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry +function fromDirEntry(entry: any) { + const reader = entry.createReader(); + + return new Promise((resolve, reject) => { + const entries: Promise[] = []; + + function readEntries() { + // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry/createReader + // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryReader/readEntries + reader.readEntries(async (batch: any[]) => { + if (!batch.length) { + // Done reading directory + try { + const files = await Promise.all(entries); + resolve(files); + } catch (err) { + reject(err); + } + } else { + const items = Promise.all(batch.map(fromEntry)); + entries.push(items); + + // Continue reading + readEntries(); + } + }, (err: any) => { + reject(err); + }); + } + + readEntries(); + }); +} + +// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileEntry +async function fromFileEntry(entry: any) { + return new Promise((resolve, reject) => { + entry.file((file: FileWithPath) => { + const fwp = toFileWithPath(file, entry.fullPath); + resolve(fwp); + }, (err: any) => { + reject(err); + }); + }); +} + +// Infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +interface FileArray extends Array {} +type FileValue = FileWithPath + | FileArray[]; diff --git a/node_modules/file-selector/src/file.ts b/node_modules/file-selector/src/file.ts new file mode 100644 index 0000000000000000000000000000000000000000..c33a201c74f1a80f2a69cde5ef81e262edd3741f --- /dev/null +++ b/node_modules/file-selector/src/file.ts @@ -0,0 +1,1267 @@ +export const COMMON_MIME_TYPES = new Map([ + // https://github.com/guzzle/psr7/blob/2d9260799e713f1c475d3c5fdc3d6561ff7441b2/src/MimeType.php + ['1km', 'application/vnd.1000minds.decision-model+xml'], + ['3dml', 'text/vnd.in3d.3dml'], + ['3ds', 'image/x-3ds'], + ['3g2', 'video/3gpp2'], + ['3gp', 'video/3gp'], + ['3gpp', 'video/3gpp'], + ['3mf', 'model/3mf'], + ['7z', 'application/x-7z-compressed'], + ['7zip', 'application/x-7z-compressed'], + ['123', 'application/vnd.lotus-1-2-3'], + ['aab', 'application/x-authorware-bin'], + ['aac', 'audio/x-acc'], + ['aam', 'application/x-authorware-map'], + ['aas', 'application/x-authorware-seg'], + ['abw', 'application/x-abiword'], + ['ac', 'application/vnd.nokia.n-gage.ac+xml'], + ['ac3', 'audio/ac3'], + ['acc', 'application/vnd.americandynamics.acc'], + ['ace', 'application/x-ace-compressed'], + ['acu', 'application/vnd.acucobol'], + ['acutc', 'application/vnd.acucorp'], + ['adp', 'audio/adpcm'], + ['aep', 'application/vnd.audiograph'], + ['afm', 'application/x-font-type1'], + ['afp', 'application/vnd.ibm.modcap'], + ['ahead', 'application/vnd.ahead.space'], + ['ai', 'application/pdf'], + ['aif', 'audio/x-aiff'], + ['aifc', 'audio/x-aiff'], + ['aiff', 'audio/x-aiff'], + ['air', 'application/vnd.adobe.air-application-installer-package+zip'], + ['ait', 'application/vnd.dvb.ait'], + ['ami', 'application/vnd.amiga.ami'], + ['amr', 'audio/amr'], + ['apk', 'application/vnd.android.package-archive'], + ['apng', 'image/apng'], + ['appcache', 'text/cache-manifest'], + ['application', 'application/x-ms-application'], + ['apr', 'application/vnd.lotus-approach'], + ['arc', 'application/x-freearc'], + ['arj', 'application/x-arj'], + ['asc', 'application/pgp-signature'], + ['asf', 'video/x-ms-asf'], + ['asm', 'text/x-asm'], + ['aso', 'application/vnd.accpac.simply.aso'], + ['asx', 'video/x-ms-asf'], + ['atc', 'application/vnd.acucorp'], + ['atom', 'application/atom+xml'], + ['atomcat', 'application/atomcat+xml'], + ['atomdeleted', 'application/atomdeleted+xml'], + ['atomsvc', 'application/atomsvc+xml'], + ['atx', 'application/vnd.antix.game-component'], + ['au', 'audio/x-au'], + ['avi', 'video/x-msvideo'], + ['avif', 'image/avif'], + ['aw', 'application/applixware'], + ['azf', 'application/vnd.airzip.filesecure.azf'], + ['azs', 'application/vnd.airzip.filesecure.azs'], + ['azv', 'image/vnd.airzip.accelerator.azv'], + ['azw', 'application/vnd.amazon.ebook'], + ['b16', 'image/vnd.pco.b16'], + ['bat', 'application/x-msdownload'], + ['bcpio', 'application/x-bcpio'], + ['bdf', 'application/x-font-bdf'], + ['bdm', 'application/vnd.syncml.dm+wbxml'], + ['bdoc', 'application/x-bdoc'], + ['bed', 'application/vnd.realvnc.bed'], + ['bh2', 'application/vnd.fujitsu.oasysprs'], + ['bin', 'application/octet-stream'], + ['blb', 'application/x-blorb'], + ['blorb', 'application/x-blorb'], + ['bmi', 'application/vnd.bmi'], + ['bmml', 'application/vnd.balsamiq.bmml+xml'], + ['bmp', 'image/bmp'], + ['book', 'application/vnd.framemaker'], + ['box', 'application/vnd.previewsystems.box'], + ['boz', 'application/x-bzip2'], + ['bpk', 'application/octet-stream'], + ['bpmn', 'application/octet-stream'], + ['bsp', 'model/vnd.valve.source.compiled-map'], + ['btif', 'image/prs.btif'], + ['buffer', 'application/octet-stream'], + ['bz', 'application/x-bzip'], + ['bz2', 'application/x-bzip2'], + ['c', 'text/x-c'], + ['c4d', 'application/vnd.clonk.c4group'], + ['c4f', 'application/vnd.clonk.c4group'], + ['c4g', 'application/vnd.clonk.c4group'], + ['c4p', 'application/vnd.clonk.c4group'], + ['c4u', 'application/vnd.clonk.c4group'], + ['c11amc', 'application/vnd.cluetrust.cartomobile-config'], + ['c11amz', 'application/vnd.cluetrust.cartomobile-config-pkg'], + ['cab', 'application/vnd.ms-cab-compressed'], + ['caf', 'audio/x-caf'], + ['cap', 'application/vnd.tcpdump.pcap'], + ['car', 'application/vnd.curl.car'], + ['cat', 'application/vnd.ms-pki.seccat'], + ['cb7', 'application/x-cbr'], + ['cba', 'application/x-cbr'], + ['cbr', 'application/x-cbr'], + ['cbt', 'application/x-cbr'], + ['cbz', 'application/x-cbr'], + ['cc', 'text/x-c'], + ['cco', 'application/x-cocoa'], + ['cct', 'application/x-director'], + ['ccxml', 'application/ccxml+xml'], + ['cdbcmsg', 'application/vnd.contact.cmsg'], + ['cda', 'application/x-cdf'], + ['cdf', 'application/x-netcdf'], + ['cdfx', 'application/cdfx+xml'], + ['cdkey', 'application/vnd.mediastation.cdkey'], + ['cdmia', 'application/cdmi-capability'], + ['cdmic', 'application/cdmi-container'], + ['cdmid', 'application/cdmi-domain'], + ['cdmio', 'application/cdmi-object'], + ['cdmiq', 'application/cdmi-queue'], + ['cdr', 'application/cdr'], + ['cdx', 'chemical/x-cdx'], + ['cdxml', 'application/vnd.chemdraw+xml'], + ['cdy', 'application/vnd.cinderella'], + ['cer', 'application/pkix-cert'], + ['cfs', 'application/x-cfs-compressed'], + ['cgm', 'image/cgm'], + ['chat', 'application/x-chat'], + ['chm', 'application/vnd.ms-htmlhelp'], + ['chrt', 'application/vnd.kde.kchart'], + ['cif', 'chemical/x-cif'], + ['cii', 'application/vnd.anser-web-certificate-issue-initiation'], + ['cil', 'application/vnd.ms-artgalry'], + ['cjs', 'application/node'], + ['cla', 'application/vnd.claymore'], + ['class', 'application/octet-stream'], + ['clkk', 'application/vnd.crick.clicker.keyboard'], + ['clkp', 'application/vnd.crick.clicker.palette'], + ['clkt', 'application/vnd.crick.clicker.template'], + ['clkw', 'application/vnd.crick.clicker.wordbank'], + ['clkx', 'application/vnd.crick.clicker'], + ['clp', 'application/x-msclip'], + ['cmc', 'application/vnd.cosmocaller'], + ['cmdf', 'chemical/x-cmdf'], + ['cml', 'chemical/x-cml'], + ['cmp', 'application/vnd.yellowriver-custom-menu'], + ['cmx', 'image/x-cmx'], + ['cod', 'application/vnd.rim.cod'], + ['coffee', 'text/coffeescript'], + ['com', 'application/x-msdownload'], + ['conf', 'text/plain'], + ['cpio', 'application/x-cpio'], + ['cpp', 'text/x-c'], + ['cpt', 'application/mac-compactpro'], + ['crd', 'application/x-mscardfile'], + ['crl', 'application/pkix-crl'], + ['crt', 'application/x-x509-ca-cert'], + ['crx', 'application/x-chrome-extension'], + ['cryptonote', 'application/vnd.rig.cryptonote'], + ['csh', 'application/x-csh'], + ['csl', 'application/vnd.citationstyles.style+xml'], + ['csml', 'chemical/x-csml'], + ['csp', 'application/vnd.commonspace'], + ['csr', 'application/octet-stream'], + ['css', 'text/css'], + ['cst', 'application/x-director'], + ['csv', 'text/csv'], + ['cu', 'application/cu-seeme'], + ['curl', 'text/vnd.curl'], + ['cww', 'application/prs.cww'], + ['cxt', 'application/x-director'], + ['cxx', 'text/x-c'], + ['dae', 'model/vnd.collada+xml'], + ['daf', 'application/vnd.mobius.daf'], + ['dart', 'application/vnd.dart'], + ['dataless', 'application/vnd.fdsn.seed'], + ['davmount', 'application/davmount+xml'], + ['dbf', 'application/vnd.dbf'], + ['dbk', 'application/docbook+xml'], + ['dcr', 'application/x-director'], + ['dcurl', 'text/vnd.curl.dcurl'], + ['dd2', 'application/vnd.oma.dd2+xml'], + ['ddd', 'application/vnd.fujixerox.ddd'], + ['ddf', 'application/vnd.syncml.dmddf+xml'], + ['dds', 'image/vnd.ms-dds'], + ['deb', 'application/x-debian-package'], + ['def', 'text/plain'], + ['deploy', 'application/octet-stream'], + ['der', 'application/x-x509-ca-cert'], + ['dfac', 'application/vnd.dreamfactory'], + ['dgc', 'application/x-dgc-compressed'], + ['dic', 'text/x-c'], + ['dir', 'application/x-director'], + ['dis', 'application/vnd.mobius.dis'], + ['disposition-notification', 'message/disposition-notification'], + ['dist', 'application/octet-stream'], + ['distz', 'application/octet-stream'], + ['djv', 'image/vnd.djvu'], + ['djvu', 'image/vnd.djvu'], + ['dll', 'application/octet-stream'], + ['dmg', 'application/x-apple-diskimage'], + ['dmn', 'application/octet-stream'], + ['dmp', 'application/vnd.tcpdump.pcap'], + ['dms', 'application/octet-stream'], + ['dna', 'application/vnd.dna'], + ['doc', 'application/msword'], + ['docm', 'application/vnd.ms-word.template.macroEnabled.12'], + ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'], + ['dot', 'application/msword'], + ['dotm', 'application/vnd.ms-word.template.macroEnabled.12'], + ['dotx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'], + ['dp', 'application/vnd.osgi.dp'], + ['dpg', 'application/vnd.dpgraph'], + ['dra', 'audio/vnd.dra'], + ['drle', 'image/dicom-rle'], + ['dsc', 'text/prs.lines.tag'], + ['dssc', 'application/dssc+der'], + ['dtb', 'application/x-dtbook+xml'], + ['dtd', 'application/xml-dtd'], + ['dts', 'audio/vnd.dts'], + ['dtshd', 'audio/vnd.dts.hd'], + ['dump', 'application/octet-stream'], + ['dvb', 'video/vnd.dvb.file'], + ['dvi', 'application/x-dvi'], + ['dwd', 'application/atsc-dwd+xml'], + ['dwf', 'model/vnd.dwf'], + ['dwg', 'image/vnd.dwg'], + ['dxf', 'image/vnd.dxf'], + ['dxp', 'application/vnd.spotfire.dxp'], + ['dxr', 'application/x-director'], + ['ear', 'application/java-archive'], + ['ecelp4800', 'audio/vnd.nuera.ecelp4800'], + ['ecelp7470', 'audio/vnd.nuera.ecelp7470'], + ['ecelp9600', 'audio/vnd.nuera.ecelp9600'], + ['ecma', 'application/ecmascript'], + ['edm', 'application/vnd.novadigm.edm'], + ['edx', 'application/vnd.novadigm.edx'], + ['efif', 'application/vnd.picsel'], + ['ei6', 'application/vnd.pg.osasli'], + ['elc', 'application/octet-stream'], + ['emf', 'image/emf'], + ['eml', 'message/rfc822'], + ['emma', 'application/emma+xml'], + ['emotionml', 'application/emotionml+xml'], + ['emz', 'application/x-msmetafile'], + ['eol', 'audio/vnd.digital-winds'], + ['eot', 'application/vnd.ms-fontobject'], + ['eps', 'application/postscript'], + ['epub', 'application/epub+zip'], + ['es', 'application/ecmascript'], + ['es3', 'application/vnd.eszigno3+xml'], + ['esa', 'application/vnd.osgi.subsystem'], + ['esf', 'application/vnd.epson.esf'], + ['et3', 'application/vnd.eszigno3+xml'], + ['etx', 'text/x-setext'], + ['eva', 'application/x-eva'], + ['evy', 'application/x-envoy'], + ['exe', 'application/octet-stream'], + ['exi', 'application/exi'], + ['exp', 'application/express'], + ['exr', 'image/aces'], + ['ext', 'application/vnd.novadigm.ext'], + ['ez', 'application/andrew-inset'], + ['ez2', 'application/vnd.ezpix-album'], + ['ez3', 'application/vnd.ezpix-package'], + ['f', 'text/x-fortran'], + ['f4v', 'video/mp4'], + ['f77', 'text/x-fortran'], + ['f90', 'text/x-fortran'], + ['fbs', 'image/vnd.fastbidsheet'], + ['fcdt', 'application/vnd.adobe.formscentral.fcdt'], + ['fcs', 'application/vnd.isac.fcs'], + ['fdf', 'application/vnd.fdf'], + ['fdt', 'application/fdt+xml'], + ['fe_launch', 'application/vnd.denovo.fcselayout-link'], + ['fg5', 'application/vnd.fujitsu.oasysgp'], + ['fgd', 'application/x-director'], + ['fh', 'image/x-freehand'], + ['fh4', 'image/x-freehand'], + ['fh5', 'image/x-freehand'], + ['fh7', 'image/x-freehand'], + ['fhc', 'image/x-freehand'], + ['fig', 'application/x-xfig'], + ['fits', 'image/fits'], + ['flac', 'audio/x-flac'], + ['fli', 'video/x-fli'], + ['flo', 'application/vnd.micrografx.flo'], + ['flv', 'video/x-flv'], + ['flw', 'application/vnd.kde.kivio'], + ['flx', 'text/vnd.fmi.flexstor'], + ['fly', 'text/vnd.fly'], + ['fm', 'application/vnd.framemaker'], + ['fnc', 'application/vnd.frogans.fnc'], + ['fo', 'application/vnd.software602.filler.form+xml'], + ['for', 'text/x-fortran'], + ['fpx', 'image/vnd.fpx'], + ['frame', 'application/vnd.framemaker'], + ['fsc', 'application/vnd.fsc.weblaunch'], + ['fst', 'image/vnd.fst'], + ['ftc', 'application/vnd.fluxtime.clip'], + ['fti', 'application/vnd.anser-web-funds-transfer-initiation'], + ['fvt', 'video/vnd.fvt'], + ['fxp', 'application/vnd.adobe.fxp'], + ['fxpl', 'application/vnd.adobe.fxp'], + ['fzs', 'application/vnd.fuzzysheet'], + ['g2w', 'application/vnd.geoplan'], + ['g3', 'image/g3fax'], + ['g3w', 'application/vnd.geospace'], + ['gac', 'application/vnd.groove-account'], + ['gam', 'application/x-tads'], + ['gbr', 'application/rpki-ghostbusters'], + ['gca', 'application/x-gca-compressed'], + ['gdl', 'model/vnd.gdl'], + ['gdoc', 'application/vnd.google-apps.document'], + ['geo', 'application/vnd.dynageo'], + ['geojson', 'application/geo+json'], + ['gex', 'application/vnd.geometry-explorer'], + ['ggb', 'application/vnd.geogebra.file'], + ['ggt', 'application/vnd.geogebra.tool'], + ['ghf', 'application/vnd.groove-help'], + ['gif', 'image/gif'], + ['gim', 'application/vnd.groove-identity-message'], + ['glb', 'model/gltf-binary'], + ['gltf', 'model/gltf+json'], + ['gml', 'application/gml+xml'], + ['gmx', 'application/vnd.gmx'], + ['gnumeric', 'application/x-gnumeric'], + ['gpg', 'application/gpg-keys'], + ['gph', 'application/vnd.flographit'], + ['gpx', 'application/gpx+xml'], + ['gqf', 'application/vnd.grafeq'], + ['gqs', 'application/vnd.grafeq'], + ['gram', 'application/srgs'], + ['gramps', 'application/x-gramps-xml'], + ['gre', 'application/vnd.geometry-explorer'], + ['grv', 'application/vnd.groove-injector'], + ['grxml', 'application/srgs+xml'], + ['gsf', 'application/x-font-ghostscript'], + ['gsheet', 'application/vnd.google-apps.spreadsheet'], + ['gslides', 'application/vnd.google-apps.presentation'], + ['gtar', 'application/x-gtar'], + ['gtm', 'application/vnd.groove-tool-message'], + ['gtw', 'model/vnd.gtw'], + ['gv', 'text/vnd.graphviz'], + ['gxf', 'application/gxf'], + ['gxt', 'application/vnd.geonext'], + ['gz', 'application/gzip'], + ['gzip', 'application/gzip'], + ['h', 'text/x-c'], + ['h261', 'video/h261'], + ['h263', 'video/h263'], + ['h264', 'video/h264'], + ['hal', 'application/vnd.hal+xml'], + ['hbci', 'application/vnd.hbci'], + ['hbs', 'text/x-handlebars-template'], + ['hdd', 'application/x-virtualbox-hdd'], + ['hdf', 'application/x-hdf'], + ['heic', 'image/heic'], + ['heics', 'image/heic-sequence'], + ['heif', 'image/heif'], + ['heifs', 'image/heif-sequence'], + ['hej2', 'image/hej2k'], + ['held', 'application/atsc-held+xml'], + ['hh', 'text/x-c'], + ['hjson', 'application/hjson'], + ['hlp', 'application/winhlp'], + ['hpgl', 'application/vnd.hp-hpgl'], + ['hpid', 'application/vnd.hp-hpid'], + ['hps', 'application/vnd.hp-hps'], + ['hqx', 'application/mac-binhex40'], + ['hsj2', 'image/hsj2'], + ['htc', 'text/x-component'], + ['htke', 'application/vnd.kenameaapp'], + ['htm', 'text/html'], + ['html', 'text/html'], + ['hvd', 'application/vnd.yamaha.hv-dic'], + ['hvp', 'application/vnd.yamaha.hv-voice'], + ['hvs', 'application/vnd.yamaha.hv-script'], + ['i2g', 'application/vnd.intergeo'], + ['icc', 'application/vnd.iccprofile'], + ['ice', 'x-conference/x-cooltalk'], + ['icm', 'application/vnd.iccprofile'], + ['ico', 'image/x-icon'], + ['ics', 'text/calendar'], + ['ief', 'image/ief'], + ['ifb', 'text/calendar'], + ['ifm', 'application/vnd.shana.informed.formdata'], + ['iges', 'model/iges'], + ['igl', 'application/vnd.igloader'], + ['igm', 'application/vnd.insors.igm'], + ['igs', 'model/iges'], + ['igx', 'application/vnd.micrografx.igx'], + ['iif', 'application/vnd.shana.informed.interchange'], + ['img', 'application/octet-stream'], + ['imp', 'application/vnd.accpac.simply.imp'], + ['ims', 'application/vnd.ms-ims'], + ['in', 'text/plain'], + ['ini', 'text/plain'], + ['ink', 'application/inkml+xml'], + ['inkml', 'application/inkml+xml'], + ['install', 'application/x-install-instructions'], + ['iota', 'application/vnd.astraea-software.iota'], + ['ipfix', 'application/ipfix'], + ['ipk', 'application/vnd.shana.informed.package'], + ['irm', 'application/vnd.ibm.rights-management'], + ['irp', 'application/vnd.irepository.package+xml'], + ['iso', 'application/x-iso9660-image'], + ['itp', 'application/vnd.shana.informed.formtemplate'], + ['its', 'application/its+xml'], + ['ivp', 'application/vnd.immervision-ivp'], + ['ivu', 'application/vnd.immervision-ivu'], + ['jad', 'text/vnd.sun.j2me.app-descriptor'], + ['jade', 'text/jade'], + ['jam', 'application/vnd.jam'], + ['jar', 'application/java-archive'], + ['jardiff', 'application/x-java-archive-diff'], + ['java', 'text/x-java-source'], + ['jhc', 'image/jphc'], + ['jisp', 'application/vnd.jisp'], + ['jls', 'image/jls'], + ['jlt', 'application/vnd.hp-jlyt'], + ['jng', 'image/x-jng'], + ['jnlp', 'application/x-java-jnlp-file'], + ['joda', 'application/vnd.joost.joda-archive'], + ['jp2', 'image/jp2'], + ['jpe', 'image/jpeg'], + ['jpeg', 'image/jpeg'], + ['jpf', 'image/jpx'], + ['jpg', 'image/jpeg'], + ['jpg2', 'image/jp2'], + ['jpgm', 'video/jpm'], + ['jpgv', 'video/jpeg'], + ['jph', 'image/jph'], + ['jpm', 'video/jpm'], + ['jpx', 'image/jpx'], + ['js', 'application/javascript'], + ['json', 'application/json'], + ['json5', 'application/json5'], + ['jsonld', 'application/ld+json'], + // https://jsonlines.org/ + ['jsonl', 'application/jsonl'], + ['jsonml', 'application/jsonml+json'], + ['jsx', 'text/jsx'], + ['jxr', 'image/jxr'], + ['jxra', 'image/jxra'], + ['jxrs', 'image/jxrs'], + ['jxs', 'image/jxs'], + ['jxsc', 'image/jxsc'], + ['jxsi', 'image/jxsi'], + ['jxss', 'image/jxss'], + ['kar', 'audio/midi'], + ['karbon', 'application/vnd.kde.karbon'], + ['kdb', 'application/octet-stream'], + ['kdbx', 'application/x-keepass2'], + ['key', 'application/x-iwork-keynote-sffkey'], + ['kfo', 'application/vnd.kde.kformula'], + ['kia', 'application/vnd.kidspiration'], + ['kml', 'application/vnd.google-earth.kml+xml'], + ['kmz', 'application/vnd.google-earth.kmz'], + ['kne', 'application/vnd.kinar'], + ['knp', 'application/vnd.kinar'], + ['kon', 'application/vnd.kde.kontour'], + ['kpr', 'application/vnd.kde.kpresenter'], + ['kpt', 'application/vnd.kde.kpresenter'], + ['kpxx', 'application/vnd.ds-keypoint'], + ['ksp', 'application/vnd.kde.kspread'], + ['ktr', 'application/vnd.kahootz'], + ['ktx', 'image/ktx'], + ['ktx2', 'image/ktx2'], + ['ktz', 'application/vnd.kahootz'], + ['kwd', 'application/vnd.kde.kword'], + ['kwt', 'application/vnd.kde.kword'], + ['lasxml', 'application/vnd.las.las+xml'], + ['latex', 'application/x-latex'], + ['lbd', 'application/vnd.llamagraphics.life-balance.desktop'], + ['lbe', 'application/vnd.llamagraphics.life-balance.exchange+xml'], + ['les', 'application/vnd.hhe.lesson-player'], + ['less', 'text/less'], + ['lgr', 'application/lgr+xml'], + ['lha', 'application/octet-stream'], + ['link66', 'application/vnd.route66.link66+xml'], + ['list', 'text/plain'], + ['list3820', 'application/vnd.ibm.modcap'], + ['listafp', 'application/vnd.ibm.modcap'], + ['litcoffee', 'text/coffeescript'], + ['lnk', 'application/x-ms-shortcut'], + ['log', 'text/plain'], + ['lostxml', 'application/lost+xml'], + ['lrf', 'application/octet-stream'], + ['lrm', 'application/vnd.ms-lrm'], + ['ltf', 'application/vnd.frogans.ltf'], + ['lua', 'text/x-lua'], + ['luac', 'application/x-lua-bytecode'], + ['lvp', 'audio/vnd.lucent.voice'], + ['lwp', 'application/vnd.lotus-wordpro'], + ['lzh', 'application/octet-stream'], + ['m1v', 'video/mpeg'], + ['m2a', 'audio/mpeg'], + ['m2v', 'video/mpeg'], + ['m3a', 'audio/mpeg'], + ['m3u', 'text/plain'], + ['m3u8', 'application/vnd.apple.mpegurl'], + ['m4a', 'audio/x-m4a'], + ['m4p', 'application/mp4'], + ['m4s', 'video/iso.segment'], + ['m4u', 'application/vnd.mpegurl'], + ['m4v', 'video/x-m4v'], + ['m13', 'application/x-msmediaview'], + ['m14', 'application/x-msmediaview'], + ['m21', 'application/mp21'], + ['ma', 'application/mathematica'], + ['mads', 'application/mads+xml'], + ['maei', 'application/mmt-aei+xml'], + ['mag', 'application/vnd.ecowin.chart'], + ['maker', 'application/vnd.framemaker'], + ['man', 'text/troff'], + ['manifest', 'text/cache-manifest'], + ['map', 'application/json'], + ['mar', 'application/octet-stream'], + ['markdown', 'text/markdown'], + ['mathml', 'application/mathml+xml'], + ['mb', 'application/mathematica'], + ['mbk', 'application/vnd.mobius.mbk'], + ['mbox', 'application/mbox'], + ['mc1', 'application/vnd.medcalcdata'], + ['mcd', 'application/vnd.mcd'], + ['mcurl', 'text/vnd.curl.mcurl'], + ['md', 'text/markdown'], + ['mdb', 'application/x-msaccess'], + ['mdi', 'image/vnd.ms-modi'], + ['mdx', 'text/mdx'], + ['me', 'text/troff'], + ['mesh', 'model/mesh'], + ['meta4', 'application/metalink4+xml'], + ['metalink', 'application/metalink+xml'], + ['mets', 'application/mets+xml'], + ['mfm', 'application/vnd.mfmp'], + ['mft', 'application/rpki-manifest'], + ['mgp', 'application/vnd.osgeo.mapguide.package'], + ['mgz', 'application/vnd.proteus.magazine'], + ['mid', 'audio/midi'], + ['midi', 'audio/midi'], + ['mie', 'application/x-mie'], + ['mif', 'application/vnd.mif'], + ['mime', 'message/rfc822'], + ['mj2', 'video/mj2'], + ['mjp2', 'video/mj2'], + ['mjs', 'application/javascript'], + ['mk3d', 'video/x-matroska'], + ['mka', 'audio/x-matroska'], + ['mkd', 'text/x-markdown'], + ['mks', 'video/x-matroska'], + ['mkv', 'video/x-matroska'], + ['mlp', 'application/vnd.dolby.mlp'], + ['mmd', 'application/vnd.chipnuts.karaoke-mmd'], + ['mmf', 'application/vnd.smaf'], + ['mml', 'text/mathml'], + ['mmr', 'image/vnd.fujixerox.edmics-mmr'], + ['mng', 'video/x-mng'], + ['mny', 'application/x-msmoney'], + ['mobi', 'application/x-mobipocket-ebook'], + ['mods', 'application/mods+xml'], + ['mov', 'video/quicktime'], + ['movie', 'video/x-sgi-movie'], + ['mp2', 'audio/mpeg'], + ['mp2a', 'audio/mpeg'], + ['mp3', 'audio/mpeg'], + ['mp4', 'video/mp4'], + ['mp4a', 'audio/mp4'], + ['mp4s', 'application/mp4'], + ['mp4v', 'video/mp4'], + ['mp21', 'application/mp21'], + ['mpc', 'application/vnd.mophun.certificate'], + ['mpd', 'application/dash+xml'], + ['mpe', 'video/mpeg'], + ['mpeg', 'video/mpeg'], + ['mpg', 'video/mpeg'], + ['mpg4', 'video/mp4'], + ['mpga', 'audio/mpeg'], + ['mpkg', 'application/vnd.apple.installer+xml'], + ['mpm', 'application/vnd.blueice.multipass'], + ['mpn', 'application/vnd.mophun.application'], + ['mpp', 'application/vnd.ms-project'], + ['mpt', 'application/vnd.ms-project'], + ['mpy', 'application/vnd.ibm.minipay'], + ['mqy', 'application/vnd.mobius.mqy'], + ['mrc', 'application/marc'], + ['mrcx', 'application/marcxml+xml'], + ['ms', 'text/troff'], + ['mscml', 'application/mediaservercontrol+xml'], + ['mseed', 'application/vnd.fdsn.mseed'], + ['mseq', 'application/vnd.mseq'], + ['msf', 'application/vnd.epson.msf'], + ['msg', 'application/vnd.ms-outlook'], + ['msh', 'model/mesh'], + ['msi', 'application/x-msdownload'], + ['msl', 'application/vnd.mobius.msl'], + ['msm', 'application/octet-stream'], + ['msp', 'application/octet-stream'], + ['msty', 'application/vnd.muvee.style'], + ['mtl', 'model/mtl'], + ['mts', 'model/vnd.mts'], + ['mus', 'application/vnd.musician'], + ['musd', 'application/mmt-usd+xml'], + ['musicxml', 'application/vnd.recordare.musicxml+xml'], + ['mvb', 'application/x-msmediaview'], + ['mvt', 'application/vnd.mapbox-vector-tile'], + ['mwf', 'application/vnd.mfer'], + ['mxf', 'application/mxf'], + ['mxl', 'application/vnd.recordare.musicxml'], + ['mxmf', 'audio/mobile-xmf'], + ['mxml', 'application/xv+xml'], + ['mxs', 'application/vnd.triscape.mxs'], + ['mxu', 'video/vnd.mpegurl'], + ['n-gage', 'application/vnd.nokia.n-gage.symbian.install'], + ['n3', 'text/n3'], + ['nb', 'application/mathematica'], + ['nbp', 'application/vnd.wolfram.player'], + ['nc', 'application/x-netcdf'], + ['ncx', 'application/x-dtbncx+xml'], + ['nfo', 'text/x-nfo'], + ['ngdat', 'application/vnd.nokia.n-gage.data'], + ['nitf', 'application/vnd.nitf'], + ['nlu', 'application/vnd.neurolanguage.nlu'], + ['nml', 'application/vnd.enliven'], + ['nnd', 'application/vnd.noblenet-directory'], + ['nns', 'application/vnd.noblenet-sealer'], + ['nnw', 'application/vnd.noblenet-web'], + ['npx', 'image/vnd.net-fpx'], + ['nq', 'application/n-quads'], + ['nsc', 'application/x-conference'], + ['nsf', 'application/vnd.lotus-notes'], + ['nt', 'application/n-triples'], + ['ntf', 'application/vnd.nitf'], + ['numbers', 'application/x-iwork-numbers-sffnumbers'], + ['nzb', 'application/x-nzb'], + ['oa2', 'application/vnd.fujitsu.oasys2'], + ['oa3', 'application/vnd.fujitsu.oasys3'], + ['oas', 'application/vnd.fujitsu.oasys'], + ['obd', 'application/x-msbinder'], + ['obgx', 'application/vnd.openblox.game+xml'], + ['obj', 'model/obj'], + ['oda', 'application/oda'], + ['odb', 'application/vnd.oasis.opendocument.database'], + ['odc', 'application/vnd.oasis.opendocument.chart'], + ['odf', 'application/vnd.oasis.opendocument.formula'], + ['odft', 'application/vnd.oasis.opendocument.formula-template'], + ['odg', 'application/vnd.oasis.opendocument.graphics'], + ['odi', 'application/vnd.oasis.opendocument.image'], + ['odm', 'application/vnd.oasis.opendocument.text-master'], + ['odp', 'application/vnd.oasis.opendocument.presentation'], + ['ods', 'application/vnd.oasis.opendocument.spreadsheet'], + ['odt', 'application/vnd.oasis.opendocument.text'], + ['oga', 'audio/ogg'], + ['ogex', 'model/vnd.opengex'], + ['ogg', 'audio/ogg'], + ['ogv', 'video/ogg'], + ['ogx', 'application/ogg'], + ['omdoc', 'application/omdoc+xml'], + ['onepkg', 'application/onenote'], + ['onetmp', 'application/onenote'], + ['onetoc', 'application/onenote'], + ['onetoc2', 'application/onenote'], + ['opf', 'application/oebps-package+xml'], + ['opml', 'text/x-opml'], + ['oprc', 'application/vnd.palm'], + ['opus', 'audio/ogg'], + ['org', 'text/x-org'], + ['osf', 'application/vnd.yamaha.openscoreformat'], + ['osfpvg', 'application/vnd.yamaha.openscoreformat.osfpvg+xml'], + ['osm', 'application/vnd.openstreetmap.data+xml'], + ['otc', 'application/vnd.oasis.opendocument.chart-template'], + ['otf', 'font/otf'], + ['otg', 'application/vnd.oasis.opendocument.graphics-template'], + ['oth', 'application/vnd.oasis.opendocument.text-web'], + ['oti', 'application/vnd.oasis.opendocument.image-template'], + ['otp', 'application/vnd.oasis.opendocument.presentation-template'], + ['ots', 'application/vnd.oasis.opendocument.spreadsheet-template'], + ['ott', 'application/vnd.oasis.opendocument.text-template'], + ['ova', 'application/x-virtualbox-ova'], + ['ovf', 'application/x-virtualbox-ovf'], + ['owl', 'application/rdf+xml'], + ['oxps', 'application/oxps'], + ['oxt', 'application/vnd.openofficeorg.extension'], + ['p', 'text/x-pascal'], + ['p7a', 'application/x-pkcs7-signature'], + ['p7b', 'application/x-pkcs7-certificates'], + ['p7c', 'application/pkcs7-mime'], + ['p7m', 'application/pkcs7-mime'], + ['p7r', 'application/x-pkcs7-certreqresp'], + ['p7s', 'application/pkcs7-signature'], + ['p8', 'application/pkcs8'], + ['p10', 'application/x-pkcs10'], + ['p12', 'application/x-pkcs12'], + ['pac', 'application/x-ns-proxy-autoconfig'], + ['pages', 'application/x-iwork-pages-sffpages'], + ['pas', 'text/x-pascal'], + ['paw', 'application/vnd.pawaafile'], + ['pbd', 'application/vnd.powerbuilder6'], + ['pbm', 'image/x-portable-bitmap'], + ['pcap', 'application/vnd.tcpdump.pcap'], + ['pcf', 'application/x-font-pcf'], + ['pcl', 'application/vnd.hp-pcl'], + ['pclxl', 'application/vnd.hp-pclxl'], + ['pct', 'image/x-pict'], + ['pcurl', 'application/vnd.curl.pcurl'], + ['pcx', 'image/x-pcx'], + ['pdb', 'application/x-pilot'], + ['pde', 'text/x-processing'], + ['pdf', 'application/pdf'], + ['pem', 'application/x-x509-user-cert'], + ['pfa', 'application/x-font-type1'], + ['pfb', 'application/x-font-type1'], + ['pfm', 'application/x-font-type1'], + ['pfr', 'application/font-tdpfr'], + ['pfx', 'application/x-pkcs12'], + ['pgm', 'image/x-portable-graymap'], + ['pgn', 'application/x-chess-pgn'], + ['pgp', 'application/pgp'], + ['php', 'application/x-httpd-php'], + ['php3', 'application/x-httpd-php'], + ['php4', 'application/x-httpd-php'], + ['phps', 'application/x-httpd-php-source'], + ['phtml', 'application/x-httpd-php'], + ['pic', 'image/x-pict'], + ['pkg', 'application/octet-stream'], + ['pki', 'application/pkixcmp'], + ['pkipath', 'application/pkix-pkipath'], + ['pkpass', 'application/vnd.apple.pkpass'], + ['pl', 'application/x-perl'], + ['plb', 'application/vnd.3gpp.pic-bw-large'], + ['plc', 'application/vnd.mobius.plc'], + ['plf', 'application/vnd.pocketlearn'], + ['pls', 'application/pls+xml'], + ['pm', 'application/x-perl'], + ['pml', 'application/vnd.ctc-posml'], + ['png', 'image/png'], + ['pnm', 'image/x-portable-anymap'], + ['portpkg', 'application/vnd.macports.portpkg'], + ['pot', 'application/vnd.ms-powerpoint'], + ['potm', 'application/vnd.ms-powerpoint.presentation.macroEnabled.12'], + ['potx', 'application/vnd.openxmlformats-officedocument.presentationml.template'], + ['ppa', 'application/vnd.ms-powerpoint'], + ['ppam', 'application/vnd.ms-powerpoint.addin.macroEnabled.12'], + ['ppd', 'application/vnd.cups-ppd'], + ['ppm', 'image/x-portable-pixmap'], + ['pps', 'application/vnd.ms-powerpoint'], + ['ppsm', 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12'], + ['ppsx', 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'], + ['ppt', 'application/powerpoint'], + ['pptm', 'application/vnd.ms-powerpoint.presentation.macroEnabled.12'], + ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'], + ['pqa', 'application/vnd.palm'], + ['prc', 'application/x-pilot'], + ['pre', 'application/vnd.lotus-freelance'], + ['prf', 'application/pics-rules'], + ['provx', 'application/provenance+xml'], + ['ps', 'application/postscript'], + ['psb', 'application/vnd.3gpp.pic-bw-small'], + ['psd', 'application/x-photoshop'], + ['psf', 'application/x-font-linux-psf'], + ['pskcxml', 'application/pskc+xml'], + ['pti', 'image/prs.pti'], + ['ptid', 'application/vnd.pvi.ptid1'], + ['pub', 'application/x-mspublisher'], + ['pvb', 'application/vnd.3gpp.pic-bw-var'], + ['pwn', 'application/vnd.3m.post-it-notes'], + ['pya', 'audio/vnd.ms-playready.media.pya'], + ['pyv', 'video/vnd.ms-playready.media.pyv'], + ['qam', 'application/vnd.epson.quickanime'], + ['qbo', 'application/vnd.intu.qbo'], + ['qfx', 'application/vnd.intu.qfx'], + ['qps', 'application/vnd.publishare-delta-tree'], + ['qt', 'video/quicktime'], + ['qwd', 'application/vnd.quark.quarkxpress'], + ['qwt', 'application/vnd.quark.quarkxpress'], + ['qxb', 'application/vnd.quark.quarkxpress'], + ['qxd', 'application/vnd.quark.quarkxpress'], + ['qxl', 'application/vnd.quark.quarkxpress'], + ['qxt', 'application/vnd.quark.quarkxpress'], + ['ra', 'audio/x-realaudio'], + ['ram', 'audio/x-pn-realaudio'], + ['raml', 'application/raml+yaml'], + ['rapd', 'application/route-apd+xml'], + ['rar', 'application/x-rar'], + ['ras', 'image/x-cmu-raster'], + ['rcprofile', 'application/vnd.ipunplugged.rcprofile'], + ['rdf', 'application/rdf+xml'], + ['rdz', 'application/vnd.data-vision.rdz'], + ['relo', 'application/p2p-overlay+xml'], + ['rep', 'application/vnd.businessobjects'], + ['res', 'application/x-dtbresource+xml'], + ['rgb', 'image/x-rgb'], + ['rif', 'application/reginfo+xml'], + ['rip', 'audio/vnd.rip'], + ['ris', 'application/x-research-info-systems'], + ['rl', 'application/resource-lists+xml'], + ['rlc', 'image/vnd.fujixerox.edmics-rlc'], + ['rld', 'application/resource-lists-diff+xml'], + ['rm', 'audio/x-pn-realaudio'], + ['rmi', 'audio/midi'], + ['rmp', 'audio/x-pn-realaudio-plugin'], + ['rms', 'application/vnd.jcp.javame.midlet-rms'], + ['rmvb', 'application/vnd.rn-realmedia-vbr'], + ['rnc', 'application/relax-ng-compact-syntax'], + ['rng', 'application/xml'], + ['roa', 'application/rpki-roa'], + ['roff', 'text/troff'], + ['rp9', 'application/vnd.cloanto.rp9'], + ['rpm', 'audio/x-pn-realaudio-plugin'], + ['rpss', 'application/vnd.nokia.radio-presets'], + ['rpst', 'application/vnd.nokia.radio-preset'], + ['rq', 'application/sparql-query'], + ['rs', 'application/rls-services+xml'], + ['rsa', 'application/x-pkcs7'], + ['rsat', 'application/atsc-rsat+xml'], + ['rsd', 'application/rsd+xml'], + ['rsheet', 'application/urc-ressheet+xml'], + ['rss', 'application/rss+xml'], + ['rtf', 'text/rtf'], + ['rtx', 'text/richtext'], + ['run', 'application/x-makeself'], + ['rusd', 'application/route-usd+xml'], + ['rv', 'video/vnd.rn-realvideo'], + ['s', 'text/x-asm'], + ['s3m', 'audio/s3m'], + ['saf', 'application/vnd.yamaha.smaf-audio'], + ['sass', 'text/x-sass'], + ['sbml', 'application/sbml+xml'], + ['sc', 'application/vnd.ibm.secure-container'], + ['scd', 'application/x-msschedule'], + ['scm', 'application/vnd.lotus-screencam'], + ['scq', 'application/scvp-cv-request'], + ['scs', 'application/scvp-cv-response'], + ['scss', 'text/x-scss'], + ['scurl', 'text/vnd.curl.scurl'], + ['sda', 'application/vnd.stardivision.draw'], + ['sdc', 'application/vnd.stardivision.calc'], + ['sdd', 'application/vnd.stardivision.impress'], + ['sdkd', 'application/vnd.solent.sdkm+xml'], + ['sdkm', 'application/vnd.solent.sdkm+xml'], + ['sdp', 'application/sdp'], + ['sdw', 'application/vnd.stardivision.writer'], + ['sea', 'application/octet-stream'], + ['see', 'application/vnd.seemail'], + ['seed', 'application/vnd.fdsn.seed'], + ['sema', 'application/vnd.sema'], + ['semd', 'application/vnd.semd'], + ['semf', 'application/vnd.semf'], + ['senmlx', 'application/senml+xml'], + ['sensmlx', 'application/sensml+xml'], + ['ser', 'application/java-serialized-object'], + ['setpay', 'application/set-payment-initiation'], + ['setreg', 'application/set-registration-initiation'], + ['sfd-hdstx', 'application/vnd.hydrostatix.sof-data'], + ['sfs', 'application/vnd.spotfire.sfs'], + ['sfv', 'text/x-sfv'], + ['sgi', 'image/sgi'], + ['sgl', 'application/vnd.stardivision.writer-global'], + ['sgm', 'text/sgml'], + ['sgml', 'text/sgml'], + ['sh', 'application/x-sh'], + ['shar', 'application/x-shar'], + ['shex', 'text/shex'], + ['shf', 'application/shf+xml'], + ['shtml', 'text/html'], + ['sid', 'image/x-mrsid-image'], + ['sieve', 'application/sieve'], + ['sig', 'application/pgp-signature'], + ['sil', 'audio/silk'], + ['silo', 'model/mesh'], + ['sis', 'application/vnd.symbian.install'], + ['sisx', 'application/vnd.symbian.install'], + ['sit', 'application/x-stuffit'], + ['sitx', 'application/x-stuffitx'], + ['siv', 'application/sieve'], + ['skd', 'application/vnd.koan'], + ['skm', 'application/vnd.koan'], + ['skp', 'application/vnd.koan'], + ['skt', 'application/vnd.koan'], + ['sldm', 'application/vnd.ms-powerpoint.slide.macroenabled.12'], + ['sldx', 'application/vnd.openxmlformats-officedocument.presentationml.slide'], + ['slim', 'text/slim'], + ['slm', 'text/slim'], + ['sls', 'application/route-s-tsid+xml'], + ['slt', 'application/vnd.epson.salt'], + ['sm', 'application/vnd.stepmania.stepchart'], + ['smf', 'application/vnd.stardivision.math'], + ['smi', 'application/smil'], + ['smil', 'application/smil'], + ['smv', 'video/x-smv'], + ['smzip', 'application/vnd.stepmania.package'], + ['snd', 'audio/basic'], + ['snf', 'application/x-font-snf'], + ['so', 'application/octet-stream'], + ['spc', 'application/x-pkcs7-certificates'], + ['spdx', 'text/spdx'], + ['spf', 'application/vnd.yamaha.smaf-phrase'], + ['spl', 'application/x-futuresplash'], + ['spot', 'text/vnd.in3d.spot'], + ['spp', 'application/scvp-vp-response'], + ['spq', 'application/scvp-vp-request'], + ['spx', 'audio/ogg'], + ['sql', 'application/x-sql'], + ['src', 'application/x-wais-source'], + ['srt', 'application/x-subrip'], + ['sru', 'application/sru+xml'], + ['srx', 'application/sparql-results+xml'], + ['ssdl', 'application/ssdl+xml'], + ['sse', 'application/vnd.kodak-descriptor'], + ['ssf', 'application/vnd.epson.ssf'], + ['ssml', 'application/ssml+xml'], + ['sst', 'application/octet-stream'], + ['st', 'application/vnd.sailingtracker.track'], + ['stc', 'application/vnd.sun.xml.calc.template'], + ['std', 'application/vnd.sun.xml.draw.template'], + ['stf', 'application/vnd.wt.stf'], + ['sti', 'application/vnd.sun.xml.impress.template'], + ['stk', 'application/hyperstudio'], + ['stl', 'model/stl'], + ['stpx', 'model/step+xml'], + ['stpxz', 'model/step-xml+zip'], + ['stpz', 'model/step+zip'], + ['str', 'application/vnd.pg.format'], + ['stw', 'application/vnd.sun.xml.writer.template'], + ['styl', 'text/stylus'], + ['stylus', 'text/stylus'], + ['sub', 'text/vnd.dvb.subtitle'], + ['sus', 'application/vnd.sus-calendar'], + ['susp', 'application/vnd.sus-calendar'], + ['sv4cpio', 'application/x-sv4cpio'], + ['sv4crc', 'application/x-sv4crc'], + ['svc', 'application/vnd.dvb.service'], + ['svd', 'application/vnd.svd'], + ['svg', 'image/svg+xml'], + ['svgz', 'image/svg+xml'], + ['swa', 'application/x-director'], + ['swf', 'application/x-shockwave-flash'], + ['swi', 'application/vnd.aristanetworks.swi'], + ['swidtag', 'application/swid+xml'], + ['sxc', 'application/vnd.sun.xml.calc'], + ['sxd', 'application/vnd.sun.xml.draw'], + ['sxg', 'application/vnd.sun.xml.writer.global'], + ['sxi', 'application/vnd.sun.xml.impress'], + ['sxm', 'application/vnd.sun.xml.math'], + ['sxw', 'application/vnd.sun.xml.writer'], + ['t', 'text/troff'], + ['t3', 'application/x-t3vm-image'], + ['t38', 'image/t38'], + ['taglet', 'application/vnd.mynfc'], + ['tao', 'application/vnd.tao.intent-module-archive'], + ['tap', 'image/vnd.tencent.tap'], + ['tar', 'application/x-tar'], + ['tcap', 'application/vnd.3gpp2.tcap'], + ['tcl', 'application/x-tcl'], + ['td', 'application/urc-targetdesc+xml'], + ['teacher', 'application/vnd.smart.teacher'], + ['tei', 'application/tei+xml'], + ['teicorpus', 'application/tei+xml'], + ['tex', 'application/x-tex'], + ['texi', 'application/x-texinfo'], + ['texinfo', 'application/x-texinfo'], + ['text', 'text/plain'], + ['tfi', 'application/thraud+xml'], + ['tfm', 'application/x-tex-tfm'], + ['tfx', 'image/tiff-fx'], + ['tga', 'image/x-tga'], + ['tgz', 'application/x-tar'], + ['thmx', 'application/vnd.ms-officetheme'], + ['tif', 'image/tiff'], + ['tiff', 'image/tiff'], + ['tk', 'application/x-tcl'], + ['tmo', 'application/vnd.tmobile-livetv'], + ['toml', 'application/toml'], + ['torrent', 'application/x-bittorrent'], + ['tpl', 'application/vnd.groove-tool-template'], + ['tpt', 'application/vnd.trid.tpt'], + ['tr', 'text/troff'], + ['tra', 'application/vnd.trueapp'], + ['trig', 'application/trig'], + ['trm', 'application/x-msterminal'], + ['ts', 'video/mp2t'], + ['tsd', 'application/timestamped-data'], + ['tsv', 'text/tab-separated-values'], + ['ttc', 'font/collection'], + ['ttf', 'font/ttf'], + ['ttl', 'text/turtle'], + ['ttml', 'application/ttml+xml'], + ['twd', 'application/vnd.simtech-mindmapper'], + ['twds', 'application/vnd.simtech-mindmapper'], + ['txd', 'application/vnd.genomatix.tuxedo'], + ['txf', 'application/vnd.mobius.txf'], + ['txt', 'text/plain'], + ['u8dsn', 'message/global-delivery-status'], + ['u8hdr', 'message/global-headers'], + ['u8mdn', 'message/global-disposition-notification'], + ['u8msg', 'message/global'], + ['u32', 'application/x-authorware-bin'], + ['ubj', 'application/ubjson'], + ['udeb', 'application/x-debian-package'], + ['ufd', 'application/vnd.ufdl'], + ['ufdl', 'application/vnd.ufdl'], + ['ulx', 'application/x-glulx'], + ['umj', 'application/vnd.umajin'], + ['unityweb', 'application/vnd.unity'], + ['uoml', 'application/vnd.uoml+xml'], + ['uri', 'text/uri-list'], + ['uris', 'text/uri-list'], + ['urls', 'text/uri-list'], + ['usdz', 'model/vnd.usdz+zip'], + ['ustar', 'application/x-ustar'], + ['utz', 'application/vnd.uiq.theme'], + ['uu', 'text/x-uuencode'], + ['uva', 'audio/vnd.dece.audio'], + ['uvd', 'application/vnd.dece.data'], + ['uvf', 'application/vnd.dece.data'], + ['uvg', 'image/vnd.dece.graphic'], + ['uvh', 'video/vnd.dece.hd'], + ['uvi', 'image/vnd.dece.graphic'], + ['uvm', 'video/vnd.dece.mobile'], + ['uvp', 'video/vnd.dece.pd'], + ['uvs', 'video/vnd.dece.sd'], + ['uvt', 'application/vnd.dece.ttml+xml'], + ['uvu', 'video/vnd.uvvu.mp4'], + ['uvv', 'video/vnd.dece.video'], + ['uvva', 'audio/vnd.dece.audio'], + ['uvvd', 'application/vnd.dece.data'], + ['uvvf', 'application/vnd.dece.data'], + ['uvvg', 'image/vnd.dece.graphic'], + ['uvvh', 'video/vnd.dece.hd'], + ['uvvi', 'image/vnd.dece.graphic'], + ['uvvm', 'video/vnd.dece.mobile'], + ['uvvp', 'video/vnd.dece.pd'], + ['uvvs', 'video/vnd.dece.sd'], + ['uvvt', 'application/vnd.dece.ttml+xml'], + ['uvvu', 'video/vnd.uvvu.mp4'], + ['uvvv', 'video/vnd.dece.video'], + ['uvvx', 'application/vnd.dece.unspecified'], + ['uvvz', 'application/vnd.dece.zip'], + ['uvx', 'application/vnd.dece.unspecified'], + ['uvz', 'application/vnd.dece.zip'], + ['vbox', 'application/x-virtualbox-vbox'], + ['vbox-extpack', 'application/x-virtualbox-vbox-extpack'], + ['vcard', 'text/vcard'], + ['vcd', 'application/x-cdlink'], + ['vcf', 'text/x-vcard'], + ['vcg', 'application/vnd.groove-vcard'], + ['vcs', 'text/x-vcalendar'], + ['vcx', 'application/vnd.vcx'], + ['vdi', 'application/x-virtualbox-vdi'], + ['vds', 'model/vnd.sap.vds'], + ['vhd', 'application/x-virtualbox-vhd'], + ['vis', 'application/vnd.visionary'], + ['viv', 'video/vnd.vivo'], + ['vlc', 'application/videolan'], + ['vmdk', 'application/x-virtualbox-vmdk'], + ['vob', 'video/x-ms-vob'], + ['vor', 'application/vnd.stardivision.writer'], + ['vox', 'application/x-authorware-bin'], + ['vrml', 'model/vrml'], + ['vsd', 'application/vnd.visio'], + ['vsf', 'application/vnd.vsf'], + ['vss', 'application/vnd.visio'], + ['vst', 'application/vnd.visio'], + ['vsw', 'application/vnd.visio'], + ['vtf', 'image/vnd.valve.source.texture'], + ['vtt', 'text/vtt'], + ['vtu', 'model/vnd.vtu'], + ['vxml', 'application/voicexml+xml'], + ['w3d', 'application/x-director'], + ['wad', 'application/x-doom'], + ['wadl', 'application/vnd.sun.wadl+xml'], + ['war', 'application/java-archive'], + ['wasm', 'application/wasm'], + ['wav', 'audio/x-wav'], + ['wax', 'audio/x-ms-wax'], + ['wbmp', 'image/vnd.wap.wbmp'], + ['wbs', 'application/vnd.criticaltools.wbs+xml'], + ['wbxml', 'application/wbxml'], + ['wcm', 'application/vnd.ms-works'], + ['wdb', 'application/vnd.ms-works'], + ['wdp', 'image/vnd.ms-photo'], + ['weba', 'audio/webm'], + ['webapp', 'application/x-web-app-manifest+json'], + ['webm', 'video/webm'], + ['webmanifest', 'application/manifest+json'], + ['webp', 'image/webp'], + ['wg', 'application/vnd.pmi.widget'], + ['wgt', 'application/widget'], + ['wks', 'application/vnd.ms-works'], + ['wm', 'video/x-ms-wm'], + ['wma', 'audio/x-ms-wma'], + ['wmd', 'application/x-ms-wmd'], + ['wmf', 'image/wmf'], + ['wml', 'text/vnd.wap.wml'], + ['wmlc', 'application/wmlc'], + ['wmls', 'text/vnd.wap.wmlscript'], + ['wmlsc', 'application/vnd.wap.wmlscriptc'], + ['wmv', 'video/x-ms-wmv'], + ['wmx', 'video/x-ms-wmx'], + ['wmz', 'application/x-msmetafile'], + ['woff', 'font/woff'], + ['woff2', 'font/woff2'], + ['word', 'application/msword'], + ['wpd', 'application/vnd.wordperfect'], + ['wpl', 'application/vnd.ms-wpl'], + ['wps', 'application/vnd.ms-works'], + ['wqd', 'application/vnd.wqd'], + ['wri', 'application/x-mswrite'], + ['wrl', 'model/vrml'], + ['wsc', 'message/vnd.wfa.wsc'], + ['wsdl', 'application/wsdl+xml'], + ['wspolicy', 'application/wspolicy+xml'], + ['wtb', 'application/vnd.webturbo'], + ['wvx', 'video/x-ms-wvx'], + ['x3d', 'model/x3d+xml'], + ['x3db', 'model/x3d+fastinfoset'], + ['x3dbz', 'model/x3d+binary'], + ['x3dv', 'model/x3d-vrml'], + ['x3dvz', 'model/x3d+vrml'], + ['x3dz', 'model/x3d+xml'], + ['x32', 'application/x-authorware-bin'], + ['x_b', 'model/vnd.parasolid.transmit.binary'], + ['x_t', 'model/vnd.parasolid.transmit.text'], + ['xaml', 'application/xaml+xml'], + ['xap', 'application/x-silverlight-app'], + ['xar', 'application/vnd.xara'], + ['xav', 'application/xcap-att+xml'], + ['xbap', 'application/x-ms-xbap'], + ['xbd', 'application/vnd.fujixerox.docuworks.binder'], + ['xbm', 'image/x-xbitmap'], + ['xca', 'application/xcap-caps+xml'], + ['xcs', 'application/calendar+xml'], + ['xdf', 'application/xcap-diff+xml'], + ['xdm', 'application/vnd.syncml.dm+xml'], + ['xdp', 'application/vnd.adobe.xdp+xml'], + ['xdssc', 'application/dssc+xml'], + ['xdw', 'application/vnd.fujixerox.docuworks'], + ['xel', 'application/xcap-el+xml'], + ['xenc', 'application/xenc+xml'], + ['xer', 'application/patch-ops-error+xml'], + ['xfdf', 'application/vnd.adobe.xfdf'], + ['xfdl', 'application/vnd.xfdl'], + ['xht', 'application/xhtml+xml'], + ['xhtml', 'application/xhtml+xml'], + ['xhvml', 'application/xv+xml'], + ['xif', 'image/vnd.xiff'], + ['xl', 'application/excel'], + ['xla', 'application/vnd.ms-excel'], + ['xlam', 'application/vnd.ms-excel.addin.macroEnabled.12'], + ['xlc', 'application/vnd.ms-excel'], + ['xlf', 'application/xliff+xml'], + ['xlm', 'application/vnd.ms-excel'], + ['xls', 'application/vnd.ms-excel'], + ['xlsb', 'application/vnd.ms-excel.sheet.binary.macroEnabled.12'], + ['xlsm', 'application/vnd.ms-excel.sheet.macroEnabled.12'], + ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'], + ['xlt', 'application/vnd.ms-excel'], + ['xltm', 'application/vnd.ms-excel.template.macroEnabled.12'], + ['xltx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.template'], + ['xlw', 'application/vnd.ms-excel'], + ['xm', 'audio/xm'], + ['xml', 'application/xml'], + ['xns', 'application/xcap-ns+xml'], + ['xo', 'application/vnd.olpc-sugar'], + ['xop', 'application/xop+xml'], + ['xpi', 'application/x-xpinstall'], + ['xpl', 'application/xproc+xml'], + ['xpm', 'image/x-xpixmap'], + ['xpr', 'application/vnd.is-xpr'], + ['xps', 'application/vnd.ms-xpsdocument'], + ['xpw', 'application/vnd.intercon.formnet'], + ['xpx', 'application/vnd.intercon.formnet'], + ['xsd', 'application/xml'], + ['xsl', 'application/xml'], + ['xslt', 'application/xslt+xml'], + ['xsm', 'application/vnd.syncml+xml'], + ['xspf', 'application/xspf+xml'], + ['xul', 'application/vnd.mozilla.xul+xml'], + ['xvm', 'application/xv+xml'], + ['xvml', 'application/xv+xml'], + ['xwd', 'image/x-xwindowdump'], + ['xyz', 'chemical/x-xyz'], + ['xz', 'application/x-xz'], + ['yaml', 'text/yaml'], + ['yang', 'application/yang'], + ['yin', 'application/yin+xml'], + ['yml', 'text/yaml'], + ['ymp', 'text/x-suse-ymp'], + ['z', 'application/x-compress'], + ['z1', 'application/x-zmachine'], + ['z2', 'application/x-zmachine'], + ['z3', 'application/x-zmachine'], + ['z4', 'application/x-zmachine'], + ['z5', 'application/x-zmachine'], + ['z6', 'application/x-zmachine'], + ['z7', 'application/x-zmachine'], + ['z8', 'application/x-zmachine'], + ['zaz', 'application/vnd.zzazz.deck+xml'], + ['zip', 'application/zip'], + ['zir', 'application/vnd.zul'], + ['zirz', 'application/vnd.zul'], + ['zmm', 'application/vnd.handheld-entertainment+xml'], + ['zsh', 'text/x-scriptzsh'] +]); + + +export function toFileWithPath(file: FileWithPath, path?: string, h?: FileSystemHandle): FileWithPath { + const f = withMimeType(file); + const {webkitRelativePath} = file; + const p = typeof path === 'string' + ? path + // If is set, + // the File will have a {webkitRelativePath} property + // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory + : typeof webkitRelativePath === 'string' && webkitRelativePath.length > 0 + ? webkitRelativePath + : `./${file.name}`; + if (typeof f.path !== 'string') { // on electron, path is already set to the absolute path + setObjProp(f, 'path', p); + } + if (h !== undefined) { + Object.defineProperty(f, 'handle', { + value: h, + writable: false, + configurable: false, + enumerable: true + }); + } + // Always populate a relative path so that even electron apps have access to a relativePath value + setObjProp(f, 'relativePath', p); + return f; +} + +export interface FileWithPath extends File { + readonly path?: string; + readonly handle?: FileSystemFileHandle; + readonly relativePath?: string; +} + +function withMimeType(file: FileWithPath) { + const {name} = file; + const hasExtension = name && name.lastIndexOf('.') !== -1; + + if (hasExtension && !file.type) { + const ext = name.split('.') + .pop()!.toLowerCase(); + const type = COMMON_MIME_TYPES.get(ext); + if (type) { + Object.defineProperty(file, 'type', { + value: type, + writable: false, + configurable: false, + enumerable: true + }); + } + } + + return file; +} + +function setObjProp(f: FileWithPath, key: string, value: string) { + Object.defineProperty(f, key, { + value, + writable: false, + configurable: false, + enumerable: true + }) +} diff --git a/node_modules/file-selector/src/index.ts b/node_modules/file-selector/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3f81f41567f433407159442fc04d2cab39e191c --- /dev/null +++ b/node_modules/file-selector/src/index.ts @@ -0,0 +1,2 @@ +export {fromEvent} from './file-selector'; +export {FileWithPath} from './file'; diff --git a/node_modules/file-type/core.d.ts b/node_modules/file-type/core.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8cd9c68658c05629d553ae329b03770075301d72 --- /dev/null +++ b/node_modules/file-type/core.d.ts @@ -0,0 +1,253 @@ +/** +Typings for primary entry point, Node.js specific typings can be found in index.d.ts +*/ + +import type {ReadableStream as WebReadableStream} from 'node:stream/web'; +import type {ITokenizer, AnyWebByteStream} from 'strtok3'; + +/** +Either the Node.js ReadableStream or the `lib.dom.d.ts` ReadableStream. +Related issue: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/60377 +*/ +export type AnyWebReadableStream = WebReadableStream | ReadableStream; + +export type FileTypeResult = { + /** + One of the supported [file types](https://github.com/sindresorhus/file-type#supported-file-types). + */ + readonly ext: string; + + /** + The detected [MIME type](https://en.wikipedia.org/wiki/Internet_media_type). + */ + readonly mime: string; +}; + +/** +Detect the file type of a `Uint8Array` or `ArrayBuffer`. + +The file type is detected by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer. + +If file access is available, it is recommended to use `.fromFile()` instead. + +@param buffer - An Uint8Array or ArrayBuffer representing file data. It works best if the buffer contains the entire file. It may work with a smaller portion as well. +@param options - Options to override default behavior. +@returns The detected file type, or `undefined` when there is no match. +*/ +export function fileTypeFromBuffer(buffer: Uint8Array | ArrayBuffer, options?: FileTypeOptions): Promise; + +/** +Detect the file type of a [web `ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream). + +The file type is detected by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer. + +@param stream - A [web `ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) streaming a file to examine. +@param options - Options to override default behavior. +@returns A `Promise` for an object with the detected file type, or `undefined` when there is no match. +*/ +export function fileTypeFromStream(stream: AnyWebByteStream, options?: FileTypeOptions): Promise; + +/** +Detect the file type from an [`ITokenizer`](https://github.com/Borewit/strtok3#tokenizer) source. + +This method is used internally, but can also be used for a special "tokenizer" reader. + +A tokenizer propagates the internal read functions, allowing alternative transport mechanisms, to access files, to be implemented and used. + +@param tokenizer - File source implementing the tokenizer interface. +@param options - Options to override default behavior. +@returns The detected file type, or `undefined` when there is no match. + +An example is [`@tokenizer/http`](https://github.com/Borewit/tokenizer-http), which requests data using [HTTP-range-requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests). A difference with a conventional stream and the [*tokenizer*](https://github.com/Borewit/strtok3#tokenizer), is that it is able to *ignore* (seek, fast-forward) in the stream. For example, you may only need and read the first 6 bytes, and the last 128 bytes, which may be an advantage in case reading the entire file would take longer. + +@example +``` +import {makeTokenizer} from '@tokenizer/http'; +import {fileTypeFromTokenizer} from 'file-type'; + +const audioTrackUrl = 'https://test-audio.netlify.com/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/01%20-%20Diablo%20Swing%20Orchestra%20-%20Heroines.mp3'; + +const httpTokenizer = await makeTokenizer(audioTrackUrl); +const fileType = await fileTypeFromTokenizer(httpTokenizer); + +console.log(fileType); +//=> {ext: 'mp3', mime: 'audio/mpeg'} +``` +*/ +export function fileTypeFromTokenizer(tokenizer: ITokenizer, options?: FileTypeOptions): Promise; + +/** +Supported file extensions. +*/ +export const supportedExtensions: ReadonlySet; + +/** +Supported MIME types. +*/ +export const supportedMimeTypes: ReadonlySet; + +export type StreamOptions = { + /** + The default sample size in bytes. + + @default 4100 + */ + readonly sampleSize?: number; +}; + +/** +Detect the file type of a [`Blob`](https://nodejs.org/api/buffer.html#class-blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). + +@param blob - The [`Blob`](https://nodejs.org/api/buffer.html#class-blob) used for file detection. +@param options - Options to override default behavior. +@returns The detected file type, or `undefined` when there is no match. + +@example +``` +import {fileTypeFromBlob} from 'file-type'; + +const blob = new Blob([''], { + type: 'text/plain', + endings: 'native' +}); + +console.log(await fileTypeFromBlob(blob)); +//=> {ext: 'txt', mime: 'text/plain'} +``` +*/ +export declare function fileTypeFromBlob(blob: Blob, options?: FileTypeOptions): Promise; + +/** +A custom file type detector. + +Custom file type detectors are plugins designed to extend the default detection capabilities. +They allow support for uncommon file types, non-binary formats, or customized detection behavior. + +Detectors can be added via the constructor options or by modifying `FileTypeParser#detectors` directly. +Detectors provided through the constructor are executed before the default ones. + +Detectors can be added via the constructor options or by directly modifying `FileTypeParser#detectors`. + +### Example adding a detector + +```js +import {FileTypeParser} from 'file-type'; +import {detectXml} from '@file-type/xml'; + +const parser = new FileTypeParser({customDetectors: [detectXml]}); +const fileType = await parser.fromFile('sample.kml'); +console.log(fileType); +``` + +### Available-third party file-type detectors + +- [@file-type/xml](https://github.com/Borewit/file-type-xml): Detects common XML file types, such as GLM, KML, MusicXML, RSS, SVG, and XHTML + +### Detector execution flow + +If a detector returns `undefined`, the following rules apply: + +1. **No Tokenizer Interaction**: If the detector does not modify the tokenizer's position, the next detector in the sequence is executed. +2. **Tokenizer Interaction**: If the detector modifies the tokenizer's position (`tokenizer.position` is advanced), no further detectors are executed. In this case, the file type remains `undefined`, as subsequent detectors cannot evaluate the content. This is an exceptional scenario, as it prevents any other detectors from determining the file type. + +### Example writing a custom detector + +Below is an example of a custom detector array. This can be passed to the `FileTypeParser` via the `fileTypeOptions` argument. + +``` +import {FileTypeParser} from 'file-type'; + +const customDetectors = [ + async tokenizer => { + const unicornHeader = [85, 78, 73, 67, 79, 82, 78]; // "UNICORN" in ASCII decimal + + const buffer = new Uint8Array(unicornHeader.length); + await tokenizer.peekBuffer(buffer, {length: unicornHeader.length, mayBeLess: true}); + if (unicornHeader.every((value, index) => value === buffer[index])) { + return {ext: 'unicorn', mime: 'application/unicorn'}; + } + + return undefined; + }, +]; + +const buffer = new Uint8Array([85, 78, 73, 67, 79, 82, 78]); +const parser = new FileTypeParser({customDetectors}); +const fileType = await parser.fromBuffer(buffer); +console.log(fileType); // {ext: 'unicorn', mime: 'application/unicorn'} +``` + +@param tokenizer - The [tokenizer](https://github.com/Borewit/strtok3#tokenizer) used to read file content. +@param fileType - The file type detected by standard or previous custom detectors, or `undefined` if no match is found. +@returns The detected file type, or `undefined` if no match is found. +*/ +export type Detector = { + id: string; + detect: (tokenizer: ITokenizer, fileType?: FileTypeResult) => Promise; +}; + +export type FileTypeOptions = { + customDetectors?: Iterable; + + /** + Specifies the byte tolerance for locating the first MPEG audio frame (e.g. `.mp1`, `.mp2`, `.mp3`, `.aac`). + + Allows detection to handle slight sync offsets between the expected and actual frame start. Common in malformed or incorrectly muxed files, which, while technically invalid, do occur in the wild. + + A tolerance of 10 bytes covers most cases. + + @default 0 + */ + mpegOffsetTolerance?: number; +}; + +export declare class TokenizerPositionError extends Error { + constructor(message?: string); +} + +export type AnyWebReadableByteStreamWithFileType = AnyWebReadableStream & { + readonly fileType?: FileTypeResult; +}; + +/** +Workaround for using `bundler` as the module-resolution in TypeScript. +*/ +export function fileTypeFromFile(filePath: string, options?: {customDetectors?: Iterable}): Promise; + +/** +Returns a `Promise` which resolves to the original readable stream argument, but with an added `fileType` property, which is an object like the one returned from `fileTypeFromFile()`. + +This method can be handy to put in a stream pipeline, but it comes with a price. Internally `stream()` builds up a buffer of `sampleSize` bytes, used as a sample, to determine the file type. The sample size impacts the file detection resolution. A smaller sample size will result in lower probability of the best file type detection. +*/ +export function fileTypeStream(webStream: AnyWebReadableStream, options?: StreamOptions): Promise; + +export declare class FileTypeParser { + /** + File type detectors. + + Initialized with a single entry holding the built-in detector function. + */ + detectors: Detector[]; + + constructor(options?: {customDetectors?: Iterable; signal?: AbortSignal}); + + /** + Works the same way as {@link fileTypeFromBuffer}, additionally taking into account custom detectors (if any were provided to the constructor). + */ + fromBuffer(buffer: Uint8Array | ArrayBuffer): Promise; + + /** + Works the same way as {@link fileTypeFromTokenizer}, additionally taking into account custom detectors (if any were provided to the constructor). + */ + fromTokenizer(tokenizer: ITokenizer): Promise; + + /** + Works the same way as {@link fileTypeFromBlob}, additionally taking into account custom detectors (if any were provided to the constructor). + */ + fromBlob(blob: Blob): Promise; + + /** + Works the same way as {@link fileTypeStream}, additionally taking into account custom detectors (if any were provided to the constructor). + */ + toDetectionStream(webStream: AnyWebReadableStream, options?: StreamOptions): Promise; +} diff --git a/node_modules/file-type/core.js b/node_modules/file-type/core.js new file mode 100644 index 0000000000000000000000000000000000000000..1a28e8b413f594a9f28353851d47fef908d70df3 --- /dev/null +++ b/node_modules/file-type/core.js @@ -0,0 +1,2899 @@ +/** +Primary entry point, Node.js specific entry point is index.js +*/ + +import * as Token from 'token-types'; +import * as strtok3 from 'strtok3/core'; +import {ZipHandler, GzipHandler} from '@tokenizer/inflate'; +import {getUintBE} from 'uint8array-extras'; +import { + stringToBytes, + tarHeaderChecksumMatches, + uint32SyncSafeToken, +} from './util.js'; +import {extensions, mimeTypes} from './supported.js'; + +export const reasonableDetectionSizeInBytes = 4100; // A fair amount of file-types are detectable within this range. +// Keep defensive limits small enough to avoid accidental memory spikes from untrusted inputs. +const maximumMpegOffsetTolerance = reasonableDetectionSizeInBytes - 2; +const maximumZipEntrySizeInBytes = 1024 * 1024; +const maximumZipEntryCount = 1024; +const maximumZipBufferedReadSizeInBytes = (2 ** 31) - 1; +const maximumUntrustedSkipSizeInBytes = 16 * 1024 * 1024; +const maximumUnknownSizePayloadProbeSizeInBytes = maximumZipEntrySizeInBytes; +const maximumZipTextEntrySizeInBytes = maximumZipEntrySizeInBytes; +const maximumNestedGzipDetectionSizeInBytes = maximumUntrustedSkipSizeInBytes; +const maximumNestedGzipProbeDepth = 1; +const unknownSizeGzipProbeTimeoutInMilliseconds = 100; +const maximumId3HeaderSizeInBytes = maximumUntrustedSkipSizeInBytes; +const maximumEbmlDocumentTypeSizeInBytes = 64; +const maximumEbmlElementPayloadSizeInBytes = maximumUnknownSizePayloadProbeSizeInBytes; +const maximumEbmlElementCount = 256; +const maximumPngChunkCount = 512; +const maximumPngStreamScanBudgetInBytes = maximumUntrustedSkipSizeInBytes; +const maximumAsfHeaderObjectCount = 512; +const maximumTiffTagCount = 512; +const maximumDetectionReentryCount = 256; +const maximumPngChunkSizeInBytes = maximumUnknownSizePayloadProbeSizeInBytes; +const maximumAsfHeaderPayloadSizeInBytes = maximumUnknownSizePayloadProbeSizeInBytes; +const maximumTiffStreamIfdOffsetInBytes = maximumUnknownSizePayloadProbeSizeInBytes; +const maximumTiffIfdOffsetInBytes = maximumUntrustedSkipSizeInBytes; +const recoverableZipErrorMessages = new Set([ + 'Unexpected signature', + 'Encrypted ZIP', + 'Expected Central-File-Header signature', +]); +const recoverableZipErrorMessagePrefixes = [ + 'ZIP entry count exceeds ', + 'Unsupported ZIP compression method:', + 'ZIP entry compressed data exceeds ', + 'ZIP entry decompressed data exceeds ', + 'Expected data-descriptor-signature at position ', +]; +const recoverableZipErrorCodes = new Set([ + 'Z_BUF_ERROR', + 'Z_DATA_ERROR', + 'ERR_INVALID_STATE', +]); + +class ParserHardLimitError extends Error {} + +function patchWebByobTokenizerClose(tokenizer) { + const streamReader = tokenizer?.streamReader; + if (streamReader?.constructor?.name !== 'WebStreamByobReader') { + return tokenizer; + } + + const {reader} = streamReader; + const cancelAndRelease = async () => { + await reader.cancel(); + reader.releaseLock(); + }; + + streamReader.close = cancelAndRelease; + streamReader.abort = async () => { + streamReader.interrupted = true; + await cancelAndRelease(); + }; + + return tokenizer; +} + +function getSafeBound(value, maximum, reason) { + if ( + !Number.isFinite(value) + || value < 0 + || value > maximum + ) { + throw new ParserHardLimitError(`${reason} has invalid size ${value} (maximum ${maximum} bytes)`); + } + + return value; +} + +async function safeIgnore(tokenizer, length, {maximumLength = maximumUntrustedSkipSizeInBytes, reason = 'skip'} = {}) { + const safeLength = getSafeBound(length, maximumLength, reason); + await tokenizer.ignore(safeLength); +} + +async function safeReadBuffer(tokenizer, buffer, options, {maximumLength = buffer.length, reason = 'read'} = {}) { + const length = options?.length ?? buffer.length; + const safeLength = getSafeBound(length, maximumLength, reason); + return tokenizer.readBuffer(buffer, { + ...options, + length: safeLength, + }); +} + +async function decompressDeflateRawWithLimit(data, {maximumLength = maximumZipEntrySizeInBytes} = {}) { + const input = new ReadableStream({ + start(controller) { + controller.enqueue(data); + controller.close(); + }, + }); + const output = input.pipeThrough(new DecompressionStream('deflate-raw')); + const reader = output.getReader(); + const chunks = []; + let totalLength = 0; + + try { + for (;;) { + const {done, value} = await reader.read(); + if (done) { + break; + } + + totalLength += value.length; + if (totalLength > maximumLength) { + await reader.cancel(); + throw new Error(`ZIP entry decompressed data exceeds ${maximumLength} bytes`); + } + + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + + const uncompressedData = new Uint8Array(totalLength); + let offset = 0; + for (const chunk of chunks) { + uncompressedData.set(chunk, offset); + offset += chunk.length; + } + + return uncompressedData; +} + +const zipDataDescriptorSignature = 0x08_07_4B_50; +const zipDataDescriptorLengthInBytes = 16; +const zipDataDescriptorOverlapLengthInBytes = zipDataDescriptorLengthInBytes - 1; + +function findZipDataDescriptorOffset(buffer, bytesConsumed) { + if (buffer.length < zipDataDescriptorLengthInBytes) { + return -1; + } + + const lastPossibleDescriptorOffset = buffer.length - zipDataDescriptorLengthInBytes; + for (let index = 0; index <= lastPossibleDescriptorOffset; index++) { + if ( + Token.UINT32_LE.get(buffer, index) === zipDataDescriptorSignature + && Token.UINT32_LE.get(buffer, index + 8) === bytesConsumed + index + ) { + return index; + } + } + + return -1; +} + +function isPngAncillaryChunk(type) { + return (type.codePointAt(0) & 0x20) !== 0; +} + +function mergeByteChunks(chunks, totalLength) { + const merged = new Uint8Array(totalLength); + let offset = 0; + + for (const chunk of chunks) { + merged.set(chunk, offset); + offset += chunk.length; + } + + return merged; +} + +async function readZipDataDescriptorEntryWithLimit(zipHandler, {shouldBuffer, maximumLength = maximumZipEntrySizeInBytes} = {}) { + const {syncBuffer} = zipHandler; + const {length: syncBufferLength} = syncBuffer; + const chunks = []; + let bytesConsumed = 0; + + for (;;) { + const length = await zipHandler.tokenizer.peekBuffer(syncBuffer, {mayBeLess: true}); + const dataDescriptorOffset = findZipDataDescriptorOffset(syncBuffer.subarray(0, length), bytesConsumed); + const retainedLength = dataDescriptorOffset >= 0 + ? 0 + : ( + length === syncBufferLength + ? Math.min(zipDataDescriptorOverlapLengthInBytes, length - 1) + : 0 + ); + const chunkLength = dataDescriptorOffset >= 0 ? dataDescriptorOffset : length - retainedLength; + + if (chunkLength === 0) { + break; + } + + bytesConsumed += chunkLength; + if (bytesConsumed > maximumLength) { + throw new Error(`ZIP entry compressed data exceeds ${maximumLength} bytes`); + } + + if (shouldBuffer) { + const data = new Uint8Array(chunkLength); + await zipHandler.tokenizer.readBuffer(data); + chunks.push(data); + } else { + await zipHandler.tokenizer.ignore(chunkLength); + } + + if (dataDescriptorOffset >= 0) { + break; + } + } + + if (!hasUnknownFileSize(zipHandler.tokenizer)) { + zipHandler.knownSizeDescriptorScannedBytes += bytesConsumed; + } + + if (!shouldBuffer) { + return; + } + + return mergeByteChunks(chunks, bytesConsumed); +} + +function getRemainingZipScanBudget(zipHandler, startOffset) { + if (hasUnknownFileSize(zipHandler.tokenizer)) { + return Math.max(0, maximumUntrustedSkipSizeInBytes - (zipHandler.tokenizer.position - startOffset)); + } + + return Math.max(0, maximumZipEntrySizeInBytes - zipHandler.knownSizeDescriptorScannedBytes); +} + +async function readZipEntryData(zipHandler, zipHeader, {shouldBuffer, maximumDescriptorLength = maximumZipEntrySizeInBytes} = {}) { + if ( + zipHeader.dataDescriptor + && zipHeader.compressedSize === 0 + ) { + return readZipDataDescriptorEntryWithLimit(zipHandler, { + shouldBuffer, + maximumLength: maximumDescriptorLength, + }); + } + + if (!shouldBuffer) { + await safeIgnore(zipHandler.tokenizer, zipHeader.compressedSize, { + maximumLength: hasUnknownFileSize(zipHandler.tokenizer) ? maximumZipEntrySizeInBytes : zipHandler.tokenizer.fileInfo.size, + reason: 'ZIP entry compressed data', + }); + return; + } + + const maximumLength = getMaximumZipBufferedReadLength(zipHandler.tokenizer); + if ( + !Number.isFinite(zipHeader.compressedSize) + || zipHeader.compressedSize < 0 + || zipHeader.compressedSize > maximumLength + ) { + throw new Error(`ZIP entry compressed data exceeds ${maximumLength} bytes`); + } + + const fileData = new Uint8Array(zipHeader.compressedSize); + await zipHandler.tokenizer.readBuffer(fileData); + return fileData; +} + +// Override the default inflate to enforce decompression size limits, since @tokenizer/inflate does not expose a configuration hook for this. +ZipHandler.prototype.inflate = async function (zipHeader, fileData, callback) { + if (zipHeader.compressedMethod === 0) { + return callback(fileData); + } + + if (zipHeader.compressedMethod !== 8) { + throw new Error(`Unsupported ZIP compression method: ${zipHeader.compressedMethod}`); + } + + const uncompressedData = await decompressDeflateRawWithLimit(fileData, {maximumLength: maximumZipEntrySizeInBytes}); + return callback(uncompressedData); +}; + +ZipHandler.prototype.unzip = async function (fileCallback) { + let stop = false; + let zipEntryCount = 0; + const zipScanStart = this.tokenizer.position; + this.knownSizeDescriptorScannedBytes = 0; + do { + if (hasExceededUnknownSizeScanBudget(this.tokenizer, zipScanStart, maximumUntrustedSkipSizeInBytes)) { + throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`); + } + + const zipHeader = await this.readLocalFileHeader(); + if (!zipHeader) { + break; + } + + zipEntryCount++; + if (zipEntryCount > maximumZipEntryCount) { + throw new Error(`ZIP entry count exceeds ${maximumZipEntryCount}`); + } + + const next = fileCallback(zipHeader); + stop = Boolean(next.stop); + await this.tokenizer.ignore(zipHeader.extraFieldLength); + const fileData = await readZipEntryData(this, zipHeader, { + shouldBuffer: Boolean(next.handler), + maximumDescriptorLength: Math.min(maximumZipEntrySizeInBytes, getRemainingZipScanBudget(this, zipScanStart)), + }); + + if (next.handler) { + await this.inflate(zipHeader, fileData, next.handler); + } + + if (zipHeader.dataDescriptor) { + const dataDescriptor = new Uint8Array(zipDataDescriptorLengthInBytes); + await this.tokenizer.readBuffer(dataDescriptor); + if (Token.UINT32_LE.get(dataDescriptor, 0) !== zipDataDescriptorSignature) { + throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position - dataDescriptor.length}`); + } + } + + if (hasExceededUnknownSizeScanBudget(this.tokenizer, zipScanStart, maximumUntrustedSkipSizeInBytes)) { + throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`); + } + } while (!stop); +}; + +function createByteLimitedReadableStream(stream, maximumBytes) { + const reader = stream.getReader(); + let emittedBytes = 0; + let sourceDone = false; + let sourceCanceled = false; + + const cancelSource = async reason => { + if ( + sourceDone + || sourceCanceled + ) { + return; + } + + sourceCanceled = true; + await reader.cancel(reason); + }; + + return new ReadableStream({ + async pull(controller) { + if (emittedBytes >= maximumBytes) { + controller.close(); + await cancelSource(); + return; + } + + const {done, value} = await reader.read(); + if ( + done + || !value + ) { + sourceDone = true; + controller.close(); + return; + } + + const remainingBytes = maximumBytes - emittedBytes; + if (value.length > remainingBytes) { + controller.enqueue(value.subarray(0, remainingBytes)); + emittedBytes += remainingBytes; + controller.close(); + await cancelSource(); + return; + } + + controller.enqueue(value); + emittedBytes += value.length; + }, + async cancel(reason) { + await cancelSource(reason); + }, + }); +} + +export async function fileTypeFromStream(stream, options) { + return new FileTypeParser(options).fromStream(stream); +} + +export async function fileTypeFromBuffer(input, options) { + return new FileTypeParser(options).fromBuffer(input); +} + +export async function fileTypeFromBlob(blob, options) { + return new FileTypeParser(options).fromBlob(blob); +} + +function getFileTypeFromMimeType(mimeType) { + mimeType = mimeType.toLowerCase(); + switch (mimeType) { + case 'application/epub+zip': + return { + ext: 'epub', + mime: mimeType, + }; + case 'application/vnd.oasis.opendocument.text': + return { + ext: 'odt', + mime: mimeType, + }; + case 'application/vnd.oasis.opendocument.text-template': + return { + ext: 'ott', + mime: mimeType, + }; + case 'application/vnd.oasis.opendocument.spreadsheet': + return { + ext: 'ods', + mime: mimeType, + }; + case 'application/vnd.oasis.opendocument.spreadsheet-template': + return { + ext: 'ots', + mime: mimeType, + }; + case 'application/vnd.oasis.opendocument.presentation': + return { + ext: 'odp', + mime: mimeType, + }; + case 'application/vnd.oasis.opendocument.presentation-template': + return { + ext: 'otp', + mime: mimeType, + }; + case 'application/vnd.oasis.opendocument.graphics': + return { + ext: 'odg', + mime: mimeType, + }; + case 'application/vnd.oasis.opendocument.graphics-template': + return { + ext: 'otg', + mime: mimeType, + }; + case 'application/vnd.openxmlformats-officedocument.presentationml.slideshow': + return { + ext: 'ppsx', + mime: mimeType, + }; + case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': + return { + ext: 'xlsx', + mime: mimeType, + }; + case 'application/vnd.ms-excel.sheet.macroenabled': + return { + ext: 'xlsm', + mime: 'application/vnd.ms-excel.sheet.macroenabled.12', + }; + case 'application/vnd.openxmlformats-officedocument.spreadsheetml.template': + return { + ext: 'xltx', + mime: mimeType, + }; + case 'application/vnd.ms-excel.template.macroenabled': + return { + ext: 'xltm', + mime: 'application/vnd.ms-excel.template.macroenabled.12', + }; + case 'application/vnd.ms-powerpoint.slideshow.macroenabled': + return { + ext: 'ppsm', + mime: 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', + }; + case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': + return { + ext: 'docx', + mime: mimeType, + }; + case 'application/vnd.ms-word.document.macroenabled': + return { + ext: 'docm', + mime: 'application/vnd.ms-word.document.macroenabled.12', + }; + case 'application/vnd.openxmlformats-officedocument.wordprocessingml.template': + return { + ext: 'dotx', + mime: mimeType, + }; + case 'application/vnd.ms-word.template.macroenabledtemplate': + return { + ext: 'dotm', + mime: 'application/vnd.ms-word.template.macroenabled.12', + }; + case 'application/vnd.openxmlformats-officedocument.presentationml.template': + return { + ext: 'potx', + mime: mimeType, + }; + case 'application/vnd.ms-powerpoint.template.macroenabled': + return { + ext: 'potm', + mime: 'application/vnd.ms-powerpoint.template.macroenabled.12', + }; + case 'application/vnd.openxmlformats-officedocument.presentationml.presentation': + return { + ext: 'pptx', + mime: mimeType, + }; + case 'application/vnd.ms-powerpoint.presentation.macroenabled': + return { + ext: 'pptm', + mime: 'application/vnd.ms-powerpoint.presentation.macroenabled.12', + }; + case 'application/vnd.ms-visio.drawing': + return { + ext: 'vsdx', + mime: 'application/vnd.visio', + }; + case 'application/vnd.ms-package.3dmanufacturing-3dmodel+xml': + return { + ext: '3mf', + mime: 'model/3mf', + }; + default: + } +} + +function _check(buffer, headers, options) { + options = { + offset: 0, + ...options, + }; + + for (const [index, header] of headers.entries()) { + // If a bitmask is set + if (options.mask) { + // If header doesn't equal `buf` with bits masked off + if (header !== (options.mask[index] & buffer[index + options.offset])) { + return false; + } + } else if (header !== buffer[index + options.offset]) { + return false; + } + } + + return true; +} + +export function normalizeSampleSize(sampleSize) { + // `sampleSize` is an explicit caller-controlled tuning knob, not untrusted file input. + // Preserve valid caller-requested probe depth here; applications must bound attacker-derived option values themselves. + if (!Number.isFinite(sampleSize)) { + return reasonableDetectionSizeInBytes; + } + + return Math.max(1, Math.trunc(sampleSize)); +} + +function readByobReaderWithSignal(reader, buffer, signal) { + if (signal === undefined) { + return reader.read(buffer); + } + + signal.throwIfAborted(); + + return new Promise((resolve, reject) => { + const cleanup = () => { + signal.removeEventListener('abort', onAbort); + }; + + const onAbort = () => { + const abortReason = signal.reason; + cleanup(); + + (async () => { + try { + await reader.cancel(abortReason); + } catch {} + })(); + + reject(abortReason); + }; + + signal.addEventListener('abort', onAbort, {once: true}); + (async () => { + try { + const result = await reader.read(buffer); + cleanup(); + resolve(result); + } catch (error) { + cleanup(); + reject(error); + } + })(); + }); +} + +function normalizeMpegOffsetTolerance(mpegOffsetTolerance) { + // This value controls scan depth and therefore worst-case CPU work. + if (!Number.isFinite(mpegOffsetTolerance)) { + return 0; + } + + return Math.max(0, Math.min(maximumMpegOffsetTolerance, Math.trunc(mpegOffsetTolerance))); +} + +function getKnownFileSizeOrMaximum(fileSize) { + if (!Number.isFinite(fileSize)) { + return Number.MAX_SAFE_INTEGER; + } + + return Math.max(0, fileSize); +} + +function hasUnknownFileSize(tokenizer) { + const fileSize = tokenizer.fileInfo.size; + return ( + !Number.isFinite(fileSize) + || fileSize === Number.MAX_SAFE_INTEGER + ); +} + +function hasExceededUnknownSizeScanBudget(tokenizer, startOffset, maximumBytes) { + return ( + hasUnknownFileSize(tokenizer) + && tokenizer.position - startOffset > maximumBytes + ); +} + +function getMaximumZipBufferedReadLength(tokenizer) { + const fileSize = tokenizer.fileInfo.size; + const remainingBytes = Number.isFinite(fileSize) + ? Math.max(0, fileSize - tokenizer.position) + : Number.MAX_SAFE_INTEGER; + + return Math.min(remainingBytes, maximumZipBufferedReadSizeInBytes); +} + +function isRecoverableZipError(error) { + if (error instanceof strtok3.EndOfStreamError) { + return true; + } + + if (error instanceof ParserHardLimitError) { + return true; + } + + if (!(error instanceof Error)) { + return false; + } + + if (recoverableZipErrorMessages.has(error.message)) { + return true; + } + + if (recoverableZipErrorCodes.has(error.code)) { + return true; + } + + for (const prefix of recoverableZipErrorMessagePrefixes) { + if (error.message.startsWith(prefix)) { + return true; + } + } + + return false; +} + +function canReadZipEntryForDetection(zipHeader, maximumSize = maximumZipEntrySizeInBytes) { + const sizes = [zipHeader.compressedSize, zipHeader.uncompressedSize]; + for (const size of sizes) { + if ( + !Number.isFinite(size) + || size < 0 + || size > maximumSize + ) { + return false; + } + } + + return true; +} + +function createOpenXmlZipDetectionState() { + return { + hasContentTypesEntry: false, + hasParsedContentTypesEntry: false, + isParsingContentTypes: false, + hasUnparseableContentTypes: false, + hasWordDirectory: false, + hasPresentationDirectory: false, + hasSpreadsheetDirectory: false, + hasThreeDimensionalModelEntry: false, + }; +} + +function updateOpenXmlZipDetectionStateFromFilename(openXmlState, filename) { + if (filename.startsWith('word/')) { + openXmlState.hasWordDirectory = true; + } + + if (filename.startsWith('ppt/')) { + openXmlState.hasPresentationDirectory = true; + } + + if (filename.startsWith('xl/')) { + openXmlState.hasSpreadsheetDirectory = true; + } + + if ( + filename.startsWith('3D/') + && filename.endsWith('.model') + ) { + openXmlState.hasThreeDimensionalModelEntry = true; + } +} + +function getOpenXmlFileTypeFromZipEntries(openXmlState) { + // Only use directory-name heuristic when [Content_Types].xml was present in the archive + // but its handler was skipped (not invoked, not currently running, and not already resolved). + // This avoids guessing from directory names when content-type parsing already gave a definitive answer or failed. + if ( + !openXmlState.hasContentTypesEntry + || openXmlState.hasUnparseableContentTypes + || openXmlState.isParsingContentTypes + || openXmlState.hasParsedContentTypesEntry + ) { + return; + } + + if (openXmlState.hasWordDirectory) { + return { + ext: 'docx', + mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + }; + } + + if (openXmlState.hasPresentationDirectory) { + return { + ext: 'pptx', + mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + }; + } + + if (openXmlState.hasSpreadsheetDirectory) { + return { + ext: 'xlsx', + mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }; + } + + if (openXmlState.hasThreeDimensionalModelEntry) { + return { + ext: '3mf', + mime: 'model/3mf', + }; + } +} + +function getOpenXmlMimeTypeFromContentTypesXml(xmlContent) { + // We only need the `ContentType="...main+xml"` value, so a small string scan is enough and avoids full XML parsing. + const endPosition = xmlContent.indexOf('.main+xml"'); + if (endPosition === -1) { + const mimeType = 'application/vnd.ms-package.3dmanufacturing-3dmodel+xml'; + if (xmlContent.includes(`ContentType="${mimeType}"`)) { + return mimeType; + } + + return; + } + + const truncatedContent = xmlContent.slice(0, endPosition); + const firstQuotePosition = truncatedContent.lastIndexOf('"'); + // If no quote is found, `lastIndexOf` returns -1 and this intentionally falls back to the full truncated prefix. + return truncatedContent.slice(firstQuotePosition + 1); +} + +export async function fileTypeFromTokenizer(tokenizer, options) { + return new FileTypeParser(options).fromTokenizer(tokenizer); +} + +export async function fileTypeStream(webStream, options) { + return new FileTypeParser(options).toDetectionStream(webStream, options); +} + +export class FileTypeParser { + constructor(options) { + const normalizedMpegOffsetTolerance = normalizeMpegOffsetTolerance(options?.mpegOffsetTolerance); + this.options = { + ...options, + mpegOffsetTolerance: normalizedMpegOffsetTolerance, + }; + + this.detectors = [...(this.options.customDetectors ?? []), + {id: 'core', detect: this.detectConfident}, + {id: 'core.imprecise', detect: this.detectImprecise}]; + this.tokenizerOptions = { + abortSignal: this.options.signal, + }; + this.gzipProbeDepth = 0; + } + + getTokenizerOptions() { + return { + ...this.tokenizerOptions, + }; + } + + createTokenizerFromWebStream(stream) { + return patchWebByobTokenizerClose(strtok3.fromWebStream(stream, this.getTokenizerOptions())); + } + + async parseTokenizer(tokenizer, detectionReentryCount = 0) { + this.detectionReentryCount = detectionReentryCount; + const initialPosition = tokenizer.position; + // Iterate through all file-type detectors + for (const detector of this.detectors) { + let fileType; + try { + fileType = await detector.detect(tokenizer); + } catch (error) { + if (error instanceof strtok3.EndOfStreamError) { + return; + } + + if (error instanceof ParserHardLimitError) { + return; + } + + throw error; + } + + if (fileType) { + return fileType; + } + + if (initialPosition !== tokenizer.position) { + return undefined; // Cannot proceed scanning of the tokenizer is at an arbitrary position + } + } + } + + async fromTokenizer(tokenizer) { + try { + return await this.parseTokenizer(tokenizer); + } finally { + await tokenizer.close(); + } + } + + async fromBuffer(input) { + if (!(input instanceof Uint8Array || input instanceof ArrayBuffer)) { + throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof input}\``); + } + + const buffer = input instanceof Uint8Array ? input : new Uint8Array(input); + + if (!(buffer?.length > 1)) { + return; + } + + return this.fromTokenizer(strtok3.fromBuffer(buffer, this.getTokenizerOptions())); + } + + async fromBlob(blob) { + this.options.signal?.throwIfAborted(); + const tokenizer = strtok3.fromBlob(blob, this.getTokenizerOptions()); + return this.fromTokenizer(tokenizer); + } + + async fromStream(stream) { + this.options.signal?.throwIfAborted(); + const tokenizer = this.createTokenizerFromWebStream(stream); + return this.fromTokenizer(tokenizer); + } + + async toDetectionStream(stream, options) { + const sampleSize = normalizeSampleSize(options?.sampleSize ?? reasonableDetectionSizeInBytes); + let detectedFileType; + let firstChunk; + + const reader = stream.getReader({mode: 'byob'}); + try { + // Read the first chunk from the stream + const {value: chunk, done} = await readByobReaderWithSignal(reader, new Uint8Array(sampleSize), this.options.signal); + firstChunk = chunk; + if (!done && chunk) { + try { + // Attempt to detect the file type from the chunk + detectedFileType = await this.fromBuffer(chunk.subarray(0, sampleSize)); + } catch (error) { + if (!(error instanceof strtok3.EndOfStreamError)) { + throw error; // Re-throw non-EndOfStreamError + } + + detectedFileType = undefined; + } + } + + firstChunk = chunk; + } finally { + reader.releaseLock(); // Ensure the reader is released + } + + // Create a new ReadableStream to manage locking issues + const transformStream = new TransformStream({ + async start(controller) { + controller.enqueue(firstChunk); // Enqueue the initial chunk + }, + transform(chunk, controller) { + // Pass through the chunks without modification + controller.enqueue(chunk); + }, + }); + + const newStream = stream.pipeThrough(transformStream); + newStream.fileType = detectedFileType; + + return newStream; + } + + async detectGzip(tokenizer) { + if (this.gzipProbeDepth >= maximumNestedGzipProbeDepth) { + return { + ext: 'gz', + mime: 'application/gzip', + }; + } + + const gzipHandler = new GzipHandler(tokenizer); + const limitedInflatedStream = createByteLimitedReadableStream(gzipHandler.inflate(), maximumNestedGzipDetectionSizeInBytes); + const hasUnknownSize = hasUnknownFileSize(tokenizer); + let timeout; + let probeSignal; + let probeParser; + let compressedFileType; + + if (hasUnknownSize) { + const timeoutController = new AbortController(); + timeout = setTimeout(() => { + timeoutController.abort(new DOMException(`Operation timed out after ${unknownSizeGzipProbeTimeoutInMilliseconds} ms`, 'TimeoutError')); + }, unknownSizeGzipProbeTimeoutInMilliseconds); + probeSignal = this.options.signal === undefined + ? timeoutController.signal + // eslint-disable-next-line n/no-unsupported-features/node-builtins + : AbortSignal.any([this.options.signal, timeoutController.signal]); + probeParser = new FileTypeParser({ + ...this.options, + signal: probeSignal, + }); + probeParser.gzipProbeDepth = this.gzipProbeDepth + 1; + } else { + this.gzipProbeDepth++; + } + + try { + compressedFileType = await (probeParser ?? this).fromStream(limitedInflatedStream); + } catch (error) { + if ( + error?.name === 'AbortError' + && probeSignal?.reason?.name !== 'TimeoutError' + ) { + throw error; + } + + // Timeout, decompression, or inner-detection failures are expected for non-tar gzip files. + } finally { + clearTimeout(timeout); + if (!hasUnknownSize) { + this.gzipProbeDepth--; + } + } + + if (compressedFileType?.ext === 'tar') { + return { + ext: 'tar.gz', + mime: 'application/gzip', + }; + } + + return { + ext: 'gz', + mime: 'application/gzip', + }; + } + + check(header, options) { + return _check(this.buffer, header, options); + } + + checkString(header, options) { + return this.check(stringToBytes(header, options?.encoding), options); + } + + // Detections with a high degree of certainty in identifying the correct file type + detectConfident = async tokenizer => { + this.buffer = new Uint8Array(reasonableDetectionSizeInBytes); + + // Keep reading until EOF if the file size is unknown. + if (tokenizer.fileInfo.size === undefined) { + tokenizer.fileInfo.size = Number.MAX_SAFE_INTEGER; + } + + this.tokenizer = tokenizer; + + if (hasUnknownFileSize(tokenizer)) { + await tokenizer.peekBuffer(this.buffer, {length: 3, mayBeLess: true}); + if (this.check([0x1F, 0x8B, 0x8])) { + return this.detectGzip(tokenizer); + } + } + + await tokenizer.peekBuffer(this.buffer, {length: 32, mayBeLess: true}); + + // -- 2-byte signatures -- + + if (this.check([0x42, 0x4D])) { + return { + ext: 'bmp', + mime: 'image/bmp', + }; + } + + if (this.check([0x0B, 0x77])) { + return { + ext: 'ac3', + mime: 'audio/vnd.dolby.dd-raw', + }; + } + + if (this.check([0x78, 0x01])) { + return { + ext: 'dmg', + mime: 'application/x-apple-diskimage', + }; + } + + if (this.check([0x4D, 0x5A])) { + return { + ext: 'exe', + mime: 'application/x-msdownload', + }; + } + + if (this.check([0x25, 0x21])) { + await tokenizer.peekBuffer(this.buffer, {length: 24, mayBeLess: true}); + + if ( + this.checkString('PS-Adobe-', {offset: 2}) + && this.checkString(' EPSF-', {offset: 14}) + ) { + return { + ext: 'eps', + mime: 'application/eps', + }; + } + + return { + ext: 'ps', + mime: 'application/postscript', + }; + } + + if ( + this.check([0x1F, 0xA0]) + || this.check([0x1F, 0x9D]) + ) { + return { + ext: 'Z', + mime: 'application/x-compress', + }; + } + + if (this.check([0xC7, 0x71])) { + return { + ext: 'cpio', + mime: 'application/x-cpio', + }; + } + + if (this.check([0x60, 0xEA])) { + return { + ext: 'arj', + mime: 'application/x-arj', + }; + } + + // -- 3-byte signatures -- + + if (this.check([0xEF, 0xBB, 0xBF])) { // UTF-8-BOM + if (this.detectionReentryCount >= maximumDetectionReentryCount) { + return; + } + + this.detectionReentryCount++; + // Strip off UTF-8-BOM + await this.tokenizer.ignore(3); + return this.detectConfident(tokenizer); + } + + if (this.check([0x47, 0x49, 0x46])) { + return { + ext: 'gif', + mime: 'image/gif', + }; + } + + if (this.check([0x49, 0x49, 0xBC])) { + return { + ext: 'jxr', + mime: 'image/vnd.ms-photo', + }; + } + + if (this.check([0x1F, 0x8B, 0x8])) { + return this.detectGzip(tokenizer); + } + + if (this.check([0x42, 0x5A, 0x68])) { + return { + ext: 'bz2', + mime: 'application/x-bzip2', + }; + } + + if (this.checkString('ID3')) { + await safeIgnore(tokenizer, 6, { + maximumLength: 6, + reason: 'ID3 header prefix', + }); // Skip ID3 header until the header size + const id3HeaderLength = await tokenizer.readToken(uint32SyncSafeToken); + const isUnknownFileSize = hasUnknownFileSize(tokenizer); + if ( + !Number.isFinite(id3HeaderLength) + || id3HeaderLength < 0 + // Keep ID3 probing bounded for unknown-size streams to avoid attacker-controlled large skips. + || ( + isUnknownFileSize + && ( + id3HeaderLength > maximumId3HeaderSizeInBytes + || (tokenizer.position + id3HeaderLength) > maximumId3HeaderSizeInBytes + ) + ) + ) { + return; + } + + if (tokenizer.position + id3HeaderLength > tokenizer.fileInfo.size) { + if (isUnknownFileSize) { + return; + } + + return { + ext: 'mp3', + mime: 'audio/mpeg', + }; + } + + try { + await safeIgnore(tokenizer, id3HeaderLength, { + maximumLength: isUnknownFileSize ? maximumId3HeaderSizeInBytes : tokenizer.fileInfo.size, + reason: 'ID3 payload', + }); + } catch (error) { + if (error instanceof strtok3.EndOfStreamError) { + return; + } + + throw error; + } + + if (this.detectionReentryCount >= maximumDetectionReentryCount) { + return; + } + + this.detectionReentryCount++; + return this.parseTokenizer(tokenizer, this.detectionReentryCount); // Skip ID3 header, recursion + } + + // Musepack, SV7 + if (this.checkString('MP+')) { + return { + ext: 'mpc', + mime: 'audio/x-musepack', + }; + } + + if ( + (this.buffer[0] === 0x43 || this.buffer[0] === 0x46) + && this.check([0x57, 0x53], {offset: 1}) + ) { + return { + ext: 'swf', + mime: 'application/x-shockwave-flash', + }; + } + + // -- 4-byte signatures -- + + // Requires a sample size of 4 bytes + if (this.check([0xFF, 0xD8, 0xFF])) { + if (this.check([0xF7], {offset: 3})) { // JPG7/SOF55, indicating a ISO/IEC 14495 / JPEG-LS file + return { + ext: 'jls', + mime: 'image/jls', + }; + } + + return { + ext: 'jpg', + mime: 'image/jpeg', + }; + } + + if (this.check([0x4F, 0x62, 0x6A, 0x01])) { + return { + ext: 'avro', + mime: 'application/avro', + }; + } + + if (this.checkString('FLIF')) { + return { + ext: 'flif', + mime: 'image/flif', + }; + } + + if (this.checkString('8BPS')) { + return { + ext: 'psd', + mime: 'image/vnd.adobe.photoshop', + }; + } + + // Musepack, SV8 + if (this.checkString('MPCK')) { + return { + ext: 'mpc', + mime: 'audio/x-musepack', + }; + } + + if (this.checkString('FORM')) { + return { + ext: 'aif', + mime: 'audio/aiff', + }; + } + + if (this.checkString('icns', {offset: 0})) { + return { + ext: 'icns', + mime: 'image/icns', + }; + } + + // Zip-based file formats + // Need to be before the `zip` check + if (this.check([0x50, 0x4B, 0x3, 0x4])) { // Local file header signature + let fileType; + const openXmlState = createOpenXmlZipDetectionState(); + + try { + await new ZipHandler(tokenizer).unzip(zipHeader => { + updateOpenXmlZipDetectionStateFromFilename(openXmlState, zipHeader.filename); + + const isOpenXmlContentTypesEntry = zipHeader.filename === '[Content_Types].xml'; + const openXmlFileTypeFromEntries = getOpenXmlFileTypeFromZipEntries(openXmlState); + if ( + !isOpenXmlContentTypesEntry + && openXmlFileTypeFromEntries + ) { + fileType = openXmlFileTypeFromEntries; + return { + stop: true, + }; + } + + switch (zipHeader.filename) { + case 'META-INF/mozilla.rsa': + fileType = { + ext: 'xpi', + mime: 'application/x-xpinstall', + }; + return { + stop: true, + }; + case 'META-INF/MANIFEST.MF': + fileType = { + ext: 'jar', + mime: 'application/java-archive', + }; + return { + stop: true, + }; + case 'mimetype': + if (!canReadZipEntryForDetection(zipHeader, maximumZipTextEntrySizeInBytes)) { + return {}; + } + + return { + async handler(fileData) { + // Use TextDecoder to decode the UTF-8 encoded data + const mimeType = new TextDecoder('utf-8').decode(fileData).trim(); + fileType = getFileTypeFromMimeType(mimeType); + }, + stop: true, + }; + + case '[Content_Types].xml': { + openXmlState.hasContentTypesEntry = true; + + if (!canReadZipEntryForDetection(zipHeader, maximumZipTextEntrySizeInBytes)) { + openXmlState.hasUnparseableContentTypes = true; + return {}; + } + + openXmlState.isParsingContentTypes = true; + return { + async handler(fileData) { + // Use TextDecoder to decode the UTF-8 encoded data + const xmlContent = new TextDecoder('utf-8').decode(fileData); + const mimeType = getOpenXmlMimeTypeFromContentTypesXml(xmlContent); + if (mimeType) { + fileType = getFileTypeFromMimeType(mimeType); + } + + openXmlState.hasParsedContentTypesEntry = true; + openXmlState.isParsingContentTypes = false; + }, + stop: true, + }; + } + + default: + if (/classes\d*\.dex/.test(zipHeader.filename)) { + fileType = { + ext: 'apk', + mime: 'application/vnd.android.package-archive', + }; + return {stop: true}; + } + + return {}; + } + }); + } catch (error) { + if (!isRecoverableZipError(error)) { + throw error; + } + + if (openXmlState.isParsingContentTypes) { + openXmlState.isParsingContentTypes = false; + openXmlState.hasUnparseableContentTypes = true; + } + } + + return fileType ?? getOpenXmlFileTypeFromZipEntries(openXmlState) ?? { + ext: 'zip', + mime: 'application/zip', + }; + } + + if (this.checkString('OggS')) { + // This is an OGG container + await tokenizer.ignore(28); + const type = new Uint8Array(8); + await tokenizer.readBuffer(type); + + // Needs to be before `ogg` check + if (_check(type, [0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64])) { + return { + ext: 'opus', + mime: 'audio/ogg; codecs=opus', + }; + } + + // If ' theora' in header. + if (_check(type, [0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61])) { + return { + ext: 'ogv', + mime: 'video/ogg', + }; + } + + // If '\x01video' in header. + if (_check(type, [0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00])) { + return { + ext: 'ogm', + mime: 'video/ogg', + }; + } + + // If ' FLAC' in header https://xiph.org/flac/faq.html + if (_check(type, [0x7F, 0x46, 0x4C, 0x41, 0x43])) { + return { + ext: 'oga', + mime: 'audio/ogg', + }; + } + + // 'Speex ' in header https://en.wikipedia.org/wiki/Speex + if (_check(type, [0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20])) { + return { + ext: 'spx', + mime: 'audio/ogg', + }; + } + + // If '\x01vorbis' in header + if (_check(type, [0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73])) { + return { + ext: 'ogg', + mime: 'audio/ogg', + }; + } + + // Default OGG container https://www.iana.org/assignments/media-types/application/ogg + return { + ext: 'ogx', + mime: 'application/ogg', + }; + } + + if ( + this.check([0x50, 0x4B]) + && (this.buffer[2] === 0x3 || this.buffer[2] === 0x5 || this.buffer[2] === 0x7) + && (this.buffer[3] === 0x4 || this.buffer[3] === 0x6 || this.buffer[3] === 0x8) + ) { + return { + ext: 'zip', + mime: 'application/zip', + }; + } + + if (this.checkString('MThd')) { + return { + ext: 'mid', + mime: 'audio/midi', + }; + } + + if ( + this.checkString('wOFF') + && ( + this.check([0x00, 0x01, 0x00, 0x00], {offset: 4}) + || this.checkString('OTTO', {offset: 4}) + ) + ) { + return { + ext: 'woff', + mime: 'font/woff', + }; + } + + if ( + this.checkString('wOF2') + && ( + this.check([0x00, 0x01, 0x00, 0x00], {offset: 4}) + || this.checkString('OTTO', {offset: 4}) + ) + ) { + return { + ext: 'woff2', + mime: 'font/woff2', + }; + } + + if (this.check([0xD4, 0xC3, 0xB2, 0xA1]) || this.check([0xA1, 0xB2, 0xC3, 0xD4])) { + return { + ext: 'pcap', + mime: 'application/vnd.tcpdump.pcap', + }; + } + + // Sony DSD Stream File (DSF) + if (this.checkString('DSD ')) { + return { + ext: 'dsf', + mime: 'audio/x-dsf', // Non-standard + }; + } + + if (this.checkString('LZIP')) { + return { + ext: 'lz', + mime: 'application/x-lzip', + }; + } + + if (this.checkString('fLaC')) { + return { + ext: 'flac', + mime: 'audio/flac', + }; + } + + if (this.check([0x42, 0x50, 0x47, 0xFB])) { + return { + ext: 'bpg', + mime: 'image/bpg', + }; + } + + if (this.checkString('wvpk')) { + return { + ext: 'wv', + mime: 'audio/wavpack', + }; + } + + if (this.checkString('%PDF')) { + // Assume this is just a normal PDF + return { + ext: 'pdf', + mime: 'application/pdf', + }; + } + + if (this.check([0x00, 0x61, 0x73, 0x6D])) { + return { + ext: 'wasm', + mime: 'application/wasm', + }; + } + + // TIFF, little-endian type + if (this.check([0x49, 0x49])) { + const fileType = await this.readTiffHeader(false); + if (fileType) { + return fileType; + } + } + + // TIFF, big-endian type + if (this.check([0x4D, 0x4D])) { + const fileType = await this.readTiffHeader(true); + if (fileType) { + return fileType; + } + } + + if (this.checkString('MAC ')) { + return { + ext: 'ape', + mime: 'audio/ape', + }; + } + + // https://github.com/file/file/blob/master/magic/Magdir/matroska + if (this.check([0x1A, 0x45, 0xDF, 0xA3])) { // Root element: EBML + async function readField() { + const msb = await tokenizer.peekNumber(Token.UINT8); + let mask = 0x80; + let ic = 0; // 0 = A, 1 = B, 2 = C, 3 = D + + while ((msb & mask) === 0 && mask !== 0) { + ++ic; + mask >>= 1; + } + + const id = new Uint8Array(ic + 1); + await safeReadBuffer(tokenizer, id, undefined, { + maximumLength: id.length, + reason: 'EBML field', + }); + return id; + } + + async function readElement() { + const idField = await readField(); + const lengthField = await readField(); + + lengthField[0] ^= 0x80 >> (lengthField.length - 1); + const nrLength = Math.min(6, lengthField.length); // JavaScript can max read 6 bytes integer + + const idView = new DataView(idField.buffer); + const lengthView = new DataView(lengthField.buffer, lengthField.length - nrLength, nrLength); + + return { + id: getUintBE(idView), + len: getUintBE(lengthView), + }; + } + + async function readChildren(children) { + let ebmlElementCount = 0; + while (children > 0) { + ebmlElementCount++; + if (ebmlElementCount > maximumEbmlElementCount) { + return; + } + + if (hasExceededUnknownSizeScanBudget(tokenizer, ebmlScanStart, maximumUntrustedSkipSizeInBytes)) { + return; + } + + const previousPosition = tokenizer.position; + const element = await readElement(); + + if (element.id === 0x42_82) { + // `DocType` is a short string ("webm", "matroska", ...), reject implausible lengths to avoid large allocations. + if (element.len > maximumEbmlDocumentTypeSizeInBytes) { + return; + } + + const documentTypeLength = getSafeBound(element.len, maximumEbmlDocumentTypeSizeInBytes, 'EBML DocType'); + const rawValue = await tokenizer.readToken(new Token.StringType(documentTypeLength)); + return rawValue.replaceAll(/\00.*$/g, ''); // Return DocType + } + + if ( + hasUnknownFileSize(tokenizer) + && ( + !Number.isFinite(element.len) + || element.len < 0 + || element.len > maximumEbmlElementPayloadSizeInBytes + ) + ) { + return; + } + + await safeIgnore(tokenizer, element.len, { + maximumLength: hasUnknownFileSize(tokenizer) ? maximumEbmlElementPayloadSizeInBytes : tokenizer.fileInfo.size, + reason: 'EBML payload', + }); // ignore payload + --children; + + // Safeguard against malformed files: bail if the position did not advance. + if (tokenizer.position <= previousPosition) { + return; + } + } + } + + const rootElement = await readElement(); + const ebmlScanStart = tokenizer.position; + const documentType = await readChildren(rootElement.len); + + switch (documentType) { + case 'webm': + return { + ext: 'webm', + mime: 'video/webm', + }; + + case 'matroska': + return { + ext: 'mkv', + mime: 'video/matroska', + }; + + default: + return; + } + } + + if (this.checkString('SQLi')) { + return { + ext: 'sqlite', + mime: 'application/x-sqlite3', + }; + } + + if (this.check([0x4E, 0x45, 0x53, 0x1A])) { + return { + ext: 'nes', + mime: 'application/x-nintendo-nes-rom', + }; + } + + if (this.checkString('Cr24')) { + return { + ext: 'crx', + mime: 'application/x-google-chrome-extension', + }; + } + + if ( + this.checkString('MSCF') + || this.checkString('ISc(') + ) { + return { + ext: 'cab', + mime: 'application/vnd.ms-cab-compressed', + }; + } + + if (this.check([0xED, 0xAB, 0xEE, 0xDB])) { + return { + ext: 'rpm', + mime: 'application/x-rpm', + }; + } + + if (this.check([0xC5, 0xD0, 0xD3, 0xC6])) { + return { + ext: 'eps', + mime: 'application/eps', + }; + } + + if (this.check([0x28, 0xB5, 0x2F, 0xFD])) { + return { + ext: 'zst', + mime: 'application/zstd', + }; + } + + if (this.check([0x7F, 0x45, 0x4C, 0x46])) { + return { + ext: 'elf', + mime: 'application/x-elf', + }; + } + + if (this.check([0x21, 0x42, 0x44, 0x4E])) { + return { + ext: 'pst', + mime: 'application/vnd.ms-outlook', + }; + } + + if (this.checkString('PAR1') || this.checkString('PARE')) { + return { + ext: 'parquet', + mime: 'application/vnd.apache.parquet', + }; + } + + if (this.checkString('ttcf')) { + return { + ext: 'ttc', + mime: 'font/collection', + }; + } + + if ( + this.check([0xFE, 0xED, 0xFA, 0xCE]) // 32-bit, big-endian + || this.check([0xFE, 0xED, 0xFA, 0xCF]) // 64-bit, big-endian + || this.check([0xCE, 0xFA, 0xED, 0xFE]) // 32-bit, little-endian + || this.check([0xCF, 0xFA, 0xED, 0xFE]) // 64-bit, little-endian + ) { + return { + ext: 'macho', + mime: 'application/x-mach-binary', + }; + } + + if (this.check([0x04, 0x22, 0x4D, 0x18])) { + return { + ext: 'lz4', + mime: 'application/x-lz4', // Invented by us + }; + } + + if (this.checkString('regf')) { + return { + ext: 'dat', + mime: 'application/x-ft-windows-registry-hive', + }; + } + + // SPSS Statistical Data File + if (this.checkString('$FL2') || this.checkString('$FL3')) { + return { + ext: 'sav', + mime: 'application/x-spss-sav', + }; + } + + // -- 5-byte signatures -- + + if (this.check([0x4F, 0x54, 0x54, 0x4F, 0x00])) { + return { + ext: 'otf', + mime: 'font/otf', + }; + } + + if (this.checkString('#!AMR')) { + return { + ext: 'amr', + mime: 'audio/amr', + }; + } + + if (this.checkString('{\\rtf')) { + return { + ext: 'rtf', + mime: 'application/rtf', + }; + } + + if (this.check([0x46, 0x4C, 0x56, 0x01])) { + return { + ext: 'flv', + mime: 'video/x-flv', + }; + } + + if (this.checkString('IMPM')) { + return { + ext: 'it', + mime: 'audio/x-it', + }; + } + + if ( + this.checkString('-lh0-', {offset: 2}) + || this.checkString('-lh1-', {offset: 2}) + || this.checkString('-lh2-', {offset: 2}) + || this.checkString('-lh3-', {offset: 2}) + || this.checkString('-lh4-', {offset: 2}) + || this.checkString('-lh5-', {offset: 2}) + || this.checkString('-lh6-', {offset: 2}) + || this.checkString('-lh7-', {offset: 2}) + || this.checkString('-lzs-', {offset: 2}) + || this.checkString('-lz4-', {offset: 2}) + || this.checkString('-lz5-', {offset: 2}) + || this.checkString('-lhd-', {offset: 2}) + ) { + return { + ext: 'lzh', + mime: 'application/x-lzh-compressed', + }; + } + + // MPEG program stream (PS or MPEG-PS) + if (this.check([0x00, 0x00, 0x01, 0xBA])) { + // MPEG-PS, MPEG-1 Part 1 + if (this.check([0x21], {offset: 4, mask: [0xF1]})) { + return { + ext: 'mpg', // May also be .ps, .mpeg + mime: 'video/MP1S', + }; + } + + // MPEG-PS, MPEG-2 Part 1 + if (this.check([0x44], {offset: 4, mask: [0xC4]})) { + return { + ext: 'mpg', // May also be .mpg, .m2p, .vob or .sub + mime: 'video/MP2P', + }; + } + } + + if (this.checkString('ITSF')) { + return { + ext: 'chm', + mime: 'application/vnd.ms-htmlhelp', + }; + } + + if (this.check([0xCA, 0xFE, 0xBA, 0xBE])) { + // Java bytecode and Mach-O universal binaries have the same magic number. + // We disambiguate based on the next 4 bytes, as done by `file`. + // See https://github.com/file/file/blob/master/magic/Magdir/cafebabe + const machOArchitectureCount = Token.UINT32_BE.get(this.buffer, 4); + const javaClassFileMajorVersion = Token.UINT16_BE.get(this.buffer, 6); + + if (machOArchitectureCount > 0 && machOArchitectureCount <= 30) { + return { + ext: 'macho', + mime: 'application/x-mach-binary', + }; + } + + if (javaClassFileMajorVersion > 30) { + return { + ext: 'class', + mime: 'application/java-vm', + }; + } + } + + if (this.checkString('.RMF')) { + return { + ext: 'rm', + mime: 'application/vnd.rn-realmedia', + }; + } + + // -- 5-byte signatures -- + + if (this.checkString('DRACO')) { + return { + ext: 'drc', + mime: 'application/vnd.google.draco', // Invented by us + }; + } + + // -- 6-byte signatures -- + + if (this.check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) { + return { + ext: 'xz', + mime: 'application/x-xz', + }; + } + + if (this.checkString('= 1000 && version <= 1050) { + return { + ext: 'dwg', + mime: 'image/vnd.dwg', + }; + } + } + + if (this.checkString('070707')) { + return { + ext: 'cpio', + mime: 'application/x-cpio', + }; + } + + // -- 7-byte signatures -- + + if (this.checkString('BLENDER')) { + return { + ext: 'blend', + mime: 'application/x-blender', + }; + } + + if (this.checkString('!')) { + await tokenizer.ignore(8); + const string = await tokenizer.readToken(new Token.StringType(13, 'ascii')); + if (string === 'debian-binary') { + return { + ext: 'deb', + mime: 'application/x-deb', + }; + } + + return { + ext: 'ar', + mime: 'application/x-unix-archive', + }; + } + + if ( + this.checkString('WEBVTT') + && ( + // One of LF, CR, tab, space, or end of file must follow "WEBVTT" per the spec (see `fixture/fixture-vtt-*.vtt` for examples). Note that `\0` is technically the null character (there is no such thing as an EOF character). However, checking for `\0` gives us the same result as checking for the end of the stream. + (['\n', '\r', '\t', ' ', '\0'].some(char7 => this.checkString(char7, {offset: 6})))) + ) { + return { + ext: 'vtt', + mime: 'text/vtt', + }; + } + + // -- 8-byte signatures -- + + if (this.check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) { + const pngFileType = { + ext: 'png', + mime: 'image/png', + }; + + const apngFileType = { + ext: 'apng', + mime: 'image/apng', + }; + + // APNG format (https://wiki.mozilla.org/APNG_Specification) + // 1. Find the first IDAT (image data) chunk (49 44 41 54) + // 2. Check if there is an "acTL" chunk before the IDAT one (61 63 54 4C) + + // Offset calculated as follows: + // - 8 bytes: PNG signature + // - 4 (length) + 4 (chunk type) + 13 (chunk data) + 4 (CRC): IHDR chunk + + await tokenizer.ignore(8); // ignore PNG signature + + async function readChunkHeader() { + return { + length: await tokenizer.readToken(Token.INT32_BE), + type: await tokenizer.readToken(new Token.StringType(4, 'latin1')), + }; + } + + const isUnknownPngStream = hasUnknownFileSize(tokenizer); + const pngScanStart = tokenizer.position; + let pngChunkCount = 0; + let hasSeenImageHeader = false; + do { + pngChunkCount++; + if (pngChunkCount > maximumPngChunkCount) { + break; + } + + if (hasExceededUnknownSizeScanBudget(tokenizer, pngScanStart, maximumPngStreamScanBudgetInBytes)) { + break; + } + + const previousPosition = tokenizer.position; + const chunk = await readChunkHeader(); + if (chunk.length < 0) { + return; // Invalid chunk length + } + + if (chunk.type === 'IHDR') { + // PNG requires the first real image header to be a 13-byte IHDR chunk. + if (chunk.length !== 13) { + return; + } + + hasSeenImageHeader = true; + } + + switch (chunk.type) { + case 'IDAT': + return pngFileType; + case 'acTL': + return apngFileType; + default: + if ( + !hasSeenImageHeader + && chunk.type !== 'CgBI' + ) { + return; + } + + if ( + isUnknownPngStream + && chunk.length > maximumPngChunkSizeInBytes + ) { + // Avoid huge attacker-controlled skips when probing unknown-size streams. + return hasSeenImageHeader && isPngAncillaryChunk(chunk.type) ? pngFileType : undefined; + } + + try { + await safeIgnore(tokenizer, chunk.length + 4, { + maximumLength: isUnknownPngStream ? maximumPngChunkSizeInBytes + 4 : tokenizer.fileInfo.size, + reason: 'PNG chunk payload', + }); // Ignore chunk-data + CRC + } catch (error) { + if ( + !isUnknownPngStream + && ( + error instanceof ParserHardLimitError + || error instanceof strtok3.EndOfStreamError + ) + ) { + return pngFileType; + } + + throw error; + } + } + + // Safeguard against malformed files: bail if the position did not advance. + if (tokenizer.position <= previousPosition) { + break; + } + } while (tokenizer.position + 8 < tokenizer.fileInfo.size); + + return pngFileType; + } + + if (this.check([0x41, 0x52, 0x52, 0x4F, 0x57, 0x31, 0x00, 0x00])) { + return { + ext: 'arrow', + mime: 'application/vnd.apache.arrow.file', + }; + } + + if (this.check([0x67, 0x6C, 0x54, 0x46, 0x02, 0x00, 0x00, 0x00])) { + return { + ext: 'glb', + mime: 'model/gltf-binary', + }; + } + + // `mov` format variants + if ( + this.check([0x66, 0x72, 0x65, 0x65], {offset: 4}) // `free` + || this.check([0x6D, 0x64, 0x61, 0x74], {offset: 4}) // `mdat` MJPEG + || this.check([0x6D, 0x6F, 0x6F, 0x76], {offset: 4}) // `moov` + || this.check([0x77, 0x69, 0x64, 0x65], {offset: 4}) // `wide` + ) { + return { + ext: 'mov', + mime: 'video/quicktime', + }; + } + + // -- 9-byte signatures -- + + if (this.check([0x49, 0x49, 0x52, 0x4F, 0x08, 0x00, 0x00, 0x00, 0x18])) { + return { + ext: 'orf', + mime: 'image/x-olympus-orf', + }; + } + + if (this.checkString('gimp xcf ')) { + return { + ext: 'xcf', + mime: 'image/x-xcf', + }; + } + + // File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format) + // It's not required to be first, but it's recommended to be. Almost all ISO base media files start with `ftyp` box. + // `ftyp` box must contain a brand major identifier, which must consist of ISO 8859-1 printable characters. + // Here we check for 8859-1 printable characters (for simplicity, it's a mask which also catches one non-printable character). + if ( + this.checkString('ftyp', {offset: 4}) + && (this.buffer[8] & 0x60) !== 0x00 // Brand major, first character ASCII? + ) { + // They all can have MIME `video/mp4` except `application/mp4` special-case which is hard to detect. + // For some cases, we're specific, everything else falls to `video/mp4` with `mp4` extension. + const brandMajor = new Token.StringType(4, 'latin1').get(this.buffer, 8).replace('\0', ' ').trim(); + switch (brandMajor) { + case 'avif': + case 'avis': + return {ext: 'avif', mime: 'image/avif'}; + case 'mif1': + return {ext: 'heic', mime: 'image/heif'}; + case 'msf1': + return {ext: 'heic', mime: 'image/heif-sequence'}; + case 'heic': + case 'heix': + return {ext: 'heic', mime: 'image/heic'}; + case 'hevc': + case 'hevx': + return {ext: 'heic', mime: 'image/heic-sequence'}; + case 'qt': + return {ext: 'mov', mime: 'video/quicktime'}; + case 'M4V': + case 'M4VH': + case 'M4VP': + return {ext: 'm4v', mime: 'video/x-m4v'}; + case 'M4P': + return {ext: 'm4p', mime: 'video/mp4'}; + case 'M4B': + return {ext: 'm4b', mime: 'audio/mp4'}; + case 'M4A': + return {ext: 'm4a', mime: 'audio/x-m4a'}; + case 'F4V': + return {ext: 'f4v', mime: 'video/mp4'}; + case 'F4P': + return {ext: 'f4p', mime: 'video/mp4'}; + case 'F4A': + return {ext: 'f4a', mime: 'audio/mp4'}; + case 'F4B': + return {ext: 'f4b', mime: 'audio/mp4'}; + case 'crx': + return {ext: 'cr3', mime: 'image/x-canon-cr3'}; + default: + if (brandMajor.startsWith('3g')) { + if (brandMajor.startsWith('3g2')) { + return {ext: '3g2', mime: 'video/3gpp2'}; + } + + return {ext: '3gp', mime: 'video/3gpp'}; + } + + return {ext: 'mp4', mime: 'video/mp4'}; + } + } + + // -- 10-byte signatures -- + + if (this.checkString('REGEDIT4\r\n')) { + return { + ext: 'reg', + mime: 'application/x-ms-regedit', + }; + } + + // -- 12-byte signatures -- + + // RIFF file format which might be AVI, WAV, QCP, etc + if (this.check([0x52, 0x49, 0x46, 0x46])) { + if (this.checkString('WEBP', {offset: 8})) { + return { + ext: 'webp', + mime: 'image/webp', + }; + } + + if (this.check([0x41, 0x56, 0x49], {offset: 8})) { + return { + ext: 'avi', + mime: 'video/vnd.avi', + }; + } + + if (this.check([0x57, 0x41, 0x56, 0x45], {offset: 8})) { + return { + ext: 'wav', + mime: 'audio/wav', + }; + } + + // QLCM, QCP file + if (this.check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) { + return { + ext: 'qcp', + mime: 'audio/qcelp', + }; + } + } + + if (this.check([0x49, 0x49, 0x55, 0x00, 0x18, 0x00, 0x00, 0x00, 0x88, 0xE7, 0x74, 0xD8])) { + return { + ext: 'rw2', + mime: 'image/x-panasonic-rw2', + }; + } + + // ASF_Header_Object first 80 bytes + if (this.check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) { + let isMalformedAsf = false; + try { + async function readHeader() { + const guid = new Uint8Array(16); + await safeReadBuffer(tokenizer, guid, undefined, { + maximumLength: guid.length, + reason: 'ASF header GUID', + }); + return { + id: guid, + size: Number(await tokenizer.readToken(Token.UINT64_LE)), + }; + } + + await safeIgnore(tokenizer, 30, { + maximumLength: 30, + reason: 'ASF header prelude', + }); + const isUnknownFileSize = hasUnknownFileSize(tokenizer); + const asfHeaderScanStart = tokenizer.position; + let asfHeaderObjectCount = 0; + while (tokenizer.position + 24 < tokenizer.fileInfo.size) { + asfHeaderObjectCount++; + if (asfHeaderObjectCount > maximumAsfHeaderObjectCount) { + break; + } + + if (hasExceededUnknownSizeScanBudget(tokenizer, asfHeaderScanStart, maximumUntrustedSkipSizeInBytes)) { + break; + } + + const previousPosition = tokenizer.position; + const header = await readHeader(); + let payload = header.size - 24; + if ( + !Number.isFinite(payload) + || payload < 0 + ) { + isMalformedAsf = true; + break; + } + + if (_check(header.id, [0x91, 0x07, 0xDC, 0xB7, 0xB7, 0xA9, 0xCF, 0x11, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65])) { + // Sync on Stream-Properties-Object (B7DC0791-A9B7-11CF-8EE6-00C00C205365) + const typeId = new Uint8Array(16); + payload -= await safeReadBuffer(tokenizer, typeId, undefined, { + maximumLength: typeId.length, + reason: 'ASF stream type GUID', + }); + + if (_check(typeId, [0x40, 0x9E, 0x69, 0xF8, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) { + // Found audio: + return { + ext: 'asf', + mime: 'audio/x-ms-asf', + }; + } + + if (_check(typeId, [0xC0, 0xEF, 0x19, 0xBC, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) { + // Found video: + return { + ext: 'asf', + mime: 'video/x-ms-asf', + }; + } + + break; + } + + if ( + isUnknownFileSize + && payload > maximumAsfHeaderPayloadSizeInBytes + ) { + isMalformedAsf = true; + break; + } + + await safeIgnore(tokenizer, payload, { + maximumLength: isUnknownFileSize ? maximumAsfHeaderPayloadSizeInBytes : tokenizer.fileInfo.size, + reason: 'ASF header payload', + }); + + // Safeguard against malformed files: break if the position did not advance. + if (tokenizer.position <= previousPosition) { + isMalformedAsf = true; + break; + } + } + } catch (error) { + if ( + error instanceof strtok3.EndOfStreamError + || error instanceof ParserHardLimitError + ) { + if (hasUnknownFileSize(tokenizer)) { + isMalformedAsf = true; + } + } else { + throw error; + } + } + + if (isMalformedAsf) { + return; + } + + // Default to ASF generic extension + return { + ext: 'asf', + mime: 'application/vnd.ms-asf', + }; + } + + if (this.check([0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A])) { + return { + ext: 'ktx', + mime: 'image/ktx', + }; + } + + if ((this.check([0x7E, 0x10, 0x04]) || this.check([0x7E, 0x18, 0x04])) && this.check([0x30, 0x4D, 0x49, 0x45], {offset: 4})) { + return { + ext: 'mie', + mime: 'application/x-mie', + }; + } + + if (this.check([0x27, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], {offset: 2})) { + return { + ext: 'shp', + mime: 'application/x-esri-shape', + }; + } + + if (this.check([0xFF, 0x4F, 0xFF, 0x51])) { + return { + ext: 'j2c', + mime: 'image/j2c', + }; + } + + if (this.check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) { + // JPEG-2000 family + + await tokenizer.ignore(20); + const type = await tokenizer.readToken(new Token.StringType(4, 'ascii')); + switch (type) { + case 'jp2 ': + return { + ext: 'jp2', + mime: 'image/jp2', + }; + case 'jpx ': + return { + ext: 'jpx', + mime: 'image/jpx', + }; + case 'jpm ': + return { + ext: 'jpm', + mime: 'image/jpm', + }; + case 'mjp2': + return { + ext: 'mj2', + mime: 'image/mj2', + }; + default: + return; + } + } + + if ( + this.check([0xFF, 0x0A]) + || this.check([0x00, 0x00, 0x00, 0x0C, 0x4A, 0x58, 0x4C, 0x20, 0x0D, 0x0A, 0x87, 0x0A]) + ) { + return { + ext: 'jxl', + mime: 'image/jxl', + }; + } + + if (this.check([0xFE, 0xFF])) { // UTF-16-BOM-BE + if (this.checkString('= 16) { // Rough & quick check Pickle/ASAR + const jsonSize = new DataView(this.buffer.buffer).getUint32(12, true); + + if (jsonSize > 12 && this.buffer.length >= jsonSize + 16) { + try { + const header = new TextDecoder().decode(this.buffer.subarray(16, jsonSize + 16)); + const json = JSON.parse(header); + // Check if Pickle is ASAR + if (json.files) { // Final check, assuring Pickle/ASAR format + return { + ext: 'asar', + mime: 'application/x-asar', + }; + } + } catch {} + } + } + + if (this.check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) { + return { + ext: 'mxf', + mime: 'application/mxf', + }; + } + + if (this.checkString('SCRM', {offset: 44})) { + return { + ext: 's3m', + mime: 'audio/x-s3m', + }; + } + + // Raw MPEG-2 transport stream (188-byte packets) + if (this.check([0x47]) && this.check([0x47], {offset: 188})) { + return { + ext: 'mts', + mime: 'video/mp2t', + }; + } + + // Blu-ray Disc Audio-Video (BDAV) MPEG-2 transport stream has 4-byte TP_extra_header before each 188-byte packet + if (this.check([0x47], {offset: 4}) && this.check([0x47], {offset: 196})) { + return { + ext: 'mts', + mime: 'video/mp2t', + }; + } + + if (this.check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {offset: 60})) { + return { + ext: 'mobi', + mime: 'application/x-mobipocket-ebook', + }; + } + + if (this.check([0x44, 0x49, 0x43, 0x4D], {offset: 128})) { + return { + ext: 'dcm', + mime: 'application/dicom', + }; + } + + if (this.check([0x4C, 0x00, 0x00, 0x00, 0x01, 0x14, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46])) { + return { + ext: 'lnk', + mime: 'application/x.ms.shortcut', // Invented by us + }; + } + + if (this.check([0x62, 0x6F, 0x6F, 0x6B, 0x00, 0x00, 0x00, 0x00, 0x6D, 0x61, 0x72, 0x6B, 0x00, 0x00, 0x00, 0x00])) { + return { + ext: 'alias', + mime: 'application/x.apple.alias', // Invented by us + }; + } + + if (this.checkString('Kaydara FBX Binary \u0000')) { + return { + ext: 'fbx', + mime: 'application/x.autodesk.fbx', // Invented by us + }; + } + + if ( + this.check([0x4C, 0x50], {offset: 34}) + && ( + this.check([0x00, 0x00, 0x01], {offset: 8}) + || this.check([0x01, 0x00, 0x02], {offset: 8}) + || this.check([0x02, 0x00, 0x02], {offset: 8}) + ) + ) { + return { + ext: 'eot', + mime: 'application/vnd.ms-fontobject', + }; + } + + if (this.check([0x06, 0x06, 0xED, 0xF5, 0xD8, 0x1D, 0x46, 0xE5, 0xBD, 0x31, 0xEF, 0xE7, 0xFE, 0x74, 0xB7, 0x1D])) { + return { + ext: 'indd', + mime: 'application/x-indesign', + }; + } + + // -- 16-byte signatures -- + + // JMP files - check for both Little Endian and Big Endian signatures + if (this.check([0xFF, 0xFF, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00]) + || this.check([0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x01])) { + return { + ext: 'jmp', + mime: 'application/x-jmp-data', + }; + } + + // Increase sample size from 256 to 512 + await tokenizer.peekBuffer(this.buffer, {length: Math.min(512, tokenizer.fileInfo.size), mayBeLess: true}); + + // Requires a buffer size of 512 bytes + if ((this.checkString('ustar', {offset: 257}) && (this.checkString('\0', {offset: 262}) || this.checkString(' ', {offset: 262}))) + || (this.check([0, 0, 0, 0, 0, 0], {offset: 257}) && tarHeaderChecksumMatches(this.buffer))) { + return { + ext: 'tar', + mime: 'application/x-tar', + }; + } + + if (this.check([0xFF, 0xFE])) { // UTF-16-BOM-LE + const encoding = 'utf-16le'; + if (this.checkString(' { + this.buffer = new Uint8Array(reasonableDetectionSizeInBytes); + const fileSize = getKnownFileSizeOrMaximum(tokenizer.fileInfo.size); + + // Read initial sample size of 8 bytes + await tokenizer.peekBuffer(this.buffer, {length: Math.min(8, fileSize), mayBeLess: true}); + + if ( + this.check([0x0, 0x0, 0x1, 0xBA]) + || this.check([0x0, 0x0, 0x1, 0xB3]) + ) { + return { + ext: 'mpg', + mime: 'video/mpeg', + }; + } + + if (this.check([0x00, 0x01, 0x00, 0x00, 0x00])) { + return { + ext: 'ttf', + mime: 'font/ttf', + }; + } + + if (this.check([0x00, 0x00, 0x01, 0x00])) { + return { + ext: 'ico', + mime: 'image/x-icon', + }; + } + + if (this.check([0x00, 0x00, 0x02, 0x00])) { + return { + ext: 'cur', + mime: 'image/x-icon', + }; + } + + // Adjust buffer to `mpegOffsetTolerance` + await tokenizer.peekBuffer(this.buffer, {length: Math.min(2 + this.options.mpegOffsetTolerance, fileSize), mayBeLess: true}); + + // Check MPEG 1 or 2 Layer 3 header, or 'layer 0' for ADTS (MPEG sync-word 0xFFE) + if (this.buffer.length >= (2 + this.options.mpegOffsetTolerance)) { + for (let depth = 0; depth <= this.options.mpegOffsetTolerance; ++depth) { + const type = this.scanMpeg(depth); + if (type) { + return type; + } + } + } + }; + + async readTiffTag(bigEndian) { + const tagId = await this.tokenizer.readToken(bigEndian ? Token.UINT16_BE : Token.UINT16_LE); + await this.tokenizer.ignore(10); + switch (tagId) { + case 50_341: + return { + ext: 'arw', + mime: 'image/x-sony-arw', + }; + case 50_706: + return { + ext: 'dng', + mime: 'image/x-adobe-dng', + }; + default: + } + } + + async readTiffIFD(bigEndian) { + const numberOfTags = await this.tokenizer.readToken(bigEndian ? Token.UINT16_BE : Token.UINT16_LE); + if (numberOfTags > maximumTiffTagCount) { + return; + } + + if ( + hasUnknownFileSize(this.tokenizer) + && (2 + (numberOfTags * 12)) > maximumTiffIfdOffsetInBytes + ) { + return; + } + + for (let n = 0; n < numberOfTags; ++n) { + const fileType = await this.readTiffTag(bigEndian); + if (fileType) { + return fileType; + } + } + } + + async readTiffHeader(bigEndian) { + const tiffFileType = { + ext: 'tif', + mime: 'image/tiff', + }; + + const version = (bigEndian ? Token.UINT16_BE : Token.UINT16_LE).get(this.buffer, 2); + const ifdOffset = (bigEndian ? Token.UINT32_BE : Token.UINT32_LE).get(this.buffer, 4); + + if (version === 42) { + // TIFF file header + if (ifdOffset >= 6) { + if (this.checkString('CR', {offset: 8})) { + return { + ext: 'cr2', + mime: 'image/x-canon-cr2', + }; + } + + if (ifdOffset >= 8) { + const someId1 = (bigEndian ? Token.UINT16_BE : Token.UINT16_LE).get(this.buffer, 8); + const someId2 = (bigEndian ? Token.UINT16_BE : Token.UINT16_LE).get(this.buffer, 10); + + if ( + (someId1 === 0x1C && someId2 === 0xFE) + || (someId1 === 0x1F && someId2 === 0x0B)) { + return { + ext: 'nef', + mime: 'image/x-nikon-nef', + }; + } + } + } + + if ( + hasUnknownFileSize(this.tokenizer) + && ifdOffset > maximumTiffStreamIfdOffsetInBytes + ) { + return tiffFileType; + } + + const maximumTiffOffset = hasUnknownFileSize(this.tokenizer) ? maximumTiffIfdOffsetInBytes : this.tokenizer.fileInfo.size; + + try { + await safeIgnore(this.tokenizer, ifdOffset, { + maximumLength: maximumTiffOffset, + reason: 'TIFF IFD offset', + }); + } catch (error) { + if (error instanceof strtok3.EndOfStreamError) { + return; + } + + throw error; + } + + let fileType; + try { + fileType = await this.readTiffIFD(bigEndian); + } catch (error) { + if (error instanceof strtok3.EndOfStreamError) { + return; + } + + throw error; + } + + return fileType ?? tiffFileType; + } + + if (version === 43) { // Big TIFF file header + return tiffFileType; + } + } + + /** + Scan check MPEG 1 or 2 Layer 3 header, or 'layer 0' for ADTS (MPEG sync-word 0xFFE). + + @param offset - Offset to scan for sync-preamble. + @returns {{ext: string, mime: string}} + */ + scanMpeg(offset) { + if (this.check([0xFF, 0xE0], {offset, mask: [0xFF, 0xE0]})) { + if (this.check([0x10], {offset: offset + 1, mask: [0x16]})) { + // Check for (ADTS) MPEG-2 + if (this.check([0x08], {offset: offset + 1, mask: [0x08]})) { + return { + ext: 'aac', + mime: 'audio/aac', + }; + } + + // Must be (ADTS) MPEG-4 + return { + ext: 'aac', + mime: 'audio/aac', + }; + } + + // MPEG 1 or 2 Layer 3 header + // Check for MPEG layer 3 + if (this.check([0x02], {offset: offset + 1, mask: [0x06]})) { + return { + ext: 'mp3', + mime: 'audio/mpeg', + }; + } + + // Check for MPEG layer 2 + if (this.check([0x04], {offset: offset + 1, mask: [0x06]})) { + return { + ext: 'mp2', + mime: 'audio/mpeg', + }; + } + + // Check for MPEG layer 1 + if (this.check([0x06], {offset: offset + 1, mask: [0x06]})) { + return { + ext: 'mp1', + mime: 'audio/mpeg', + }; + } + } + } +} + +export const supportedExtensions = new Set(extensions); +export const supportedMimeTypes = new Set(mimeTypes); diff --git a/node_modules/file-type/index.d.ts b/node_modules/file-type/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2b7432ccbc087a2945994010a1d8a0acf47b54b --- /dev/null +++ b/node_modules/file-type/index.d.ts @@ -0,0 +1,98 @@ +/** +Typings for Node.js specific entry point. +*/ + +import type {Readable as NodeReadableStream} from 'node:stream'; +import type {AnyWebByteStream} from 'strtok3'; +import { + type FileTypeResult, + type StreamOptions, + type AnyWebReadableStream, + type AnyWebReadableByteStreamWithFileType, + type FileTypeOptions, + FileTypeParser as DefaultFileTypeParser, +} from './core.js'; + +export type ReadableStreamWithFileType = NodeReadableStream & { + readonly fileType?: FileTypeResult; +}; + +/** +Extending `FileTypeParser` with Node.js engine specific functions. +*/ +export declare class FileTypeParser extends DefaultFileTypeParser { + /** + @param stream - Node.js `stream.Readable` or web `ReadableStream`. + */ + fromStream(stream: AnyWebReadableStream | NodeReadableStream): Promise; + + fromFile(filePath: string): Promise; + + /** + Works the same way as {@link fileTypeStream}, additionally taking into account custom detectors (if any were provided to the constructor). + */ + toDetectionStream(readableStream: NodeReadableStream, options?: FileTypeOptions & StreamOptions): Promise; + toDetectionStream(webStream: AnyWebReadableStream, options?: FileTypeOptions & StreamOptions): Promise; +} + +/** +Detect the file type of a file path. + +The file type is detected by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the file. + +This is for Node.js only. + +To read from a [`File`](https://developer.mozilla.org/docs/Web/API/File), see `fileTypeFromBlob()`. + +The file type is detected by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer. + +@returns The detected file type and MIME type or `undefined` when there is no match. +*/ +export function fileTypeFromFile(filePath: string, options?: FileTypeOptions): Promise; + +/** +Detect the file type of a [web `ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream). + +If the engine is Node.js, this may also be a [Node.js `stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +Direct support for Node.js streams will be dropped in the future, when Node.js streams can be converted to Web streams (see [`toWeb()`](https://nodejs.org/api/stream.html#streamreadabletowebstreamreadable-options)). + +The file type is detected by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer. + +@param stream - A [web `ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) or [Node.js `stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable) streaming a file to examine. +@param options - Options to override default behaviour. + @returns A `Promise` for an object with the detected file type, or `undefined` when there is no match. +*/ +export function fileTypeFromStream(stream: AnyWebReadableStream | NodeReadableStream, options?: FileTypeOptions): Promise; + +/** +Returns a `Promise` which resolves to the original readable stream argument, but with an added `fileType` property, which is an object like the one returned from `fileTypeFromFile()`. + +This method can be handy to put in between a stream, but it comes with a price. +Internally `stream()` builds up a buffer of `sampleSize` bytes, used as a sample, to determine the file type. +The sample size impacts the file detection resolution. +A smaller sample size will result in lower probability of the best file type detection. + +@param readableStream - A [web `ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) or [Node.js `stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable), streaming a file to examine. +@param options - May be used to override the default sample size. +@returns A `Promise` which resolves to the original readable stream argument, but with an added `fileType` property, which is an object like the one returned from `fileTypeFromFile()`. + +@example +``` +import got from 'got'; +import {fileTypeStream} from 'file-type'; + +const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg'; + +const stream1 = got.stream(url); +const stream2 = await fileTypeStream(stream1, {sampleSize: 1024}); + +if (stream2.fileType?.mime === 'image/jpeg') { + // stream2 can be used to stream the JPEG image (from the very beginning of the stream) +} +``` +*/ +export function fileTypeStream(readableStream: NodeReadableStream, options?: FileTypeOptions & StreamOptions): Promise; +export function fileTypeStream(webStream: AnyWebByteStream, options?: FileTypeOptions & StreamOptions): Promise; + +export * from './core.js'; diff --git a/node_modules/file-type/index.js b/node_modules/file-type/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3198142bdc3ee9199e410509d025caf857e8a3ff --- /dev/null +++ b/node_modules/file-type/index.js @@ -0,0 +1,163 @@ +/** +Node.js specific entry point. +*/ + +import {ReadableStream as WebReadableStream} from 'node:stream/web'; +import {pipeline, PassThrough, Readable} from 'node:stream'; +import fs from 'node:fs/promises'; +import {constants as fileSystemConstants} from 'node:fs'; +import * as strtok3 from 'strtok3'; +import { + FileTypeParser as DefaultFileTypeParser, + reasonableDetectionSizeInBytes, + normalizeSampleSize, +} from './core.js'; + +function isTokenizerStreamBoundsError(error) { + if ( + !(error instanceof RangeError) + || error.message !== 'offset is out of bounds' + || typeof error.stack !== 'string' + ) { + return false; + } + + // Some malformed or non-byte Node.js streams can surface this tokenizer-internal range error. + // Note: This stack-trace check is fragile and may break if strtok3 restructures its internals. + return /strtok3[/\\]lib[/\\]stream[/\\]/.test(error.stack); +} + +export class FileTypeParser extends DefaultFileTypeParser { + async fromStream(stream) { + this.options.signal?.throwIfAborted(); + const tokenizer = await (stream instanceof WebReadableStream ? this.createTokenizerFromWebStream(stream) : strtok3.fromStream(stream, this.getTokenizerOptions())); + try { + return await super.fromTokenizer(tokenizer); + } catch (error) { + if (isTokenizerStreamBoundsError(error)) { + return; + } + + throw error; + } finally { + // TODO: Remove this when `strtok3.fromStream()` closes the underlying Readable instead of only aborting tokenizer reads. + if ( + stream instanceof Readable + && !stream.destroyed + ) { + stream.destroy(); + } + } + } + + async fromFile(path) { + this.options.signal?.throwIfAborted(); + // TODO: Remove this when `strtok3.fromFile()` safely rejects non-regular filesystem objects without a pathname race. + const fileHandle = await fs.open(path, fileSystemConstants.O_RDONLY | fileSystemConstants.O_NONBLOCK); + const fileStat = await fileHandle.stat(); + if (!fileStat.isFile()) { + await fileHandle.close(); + return; + } + + const tokenizer = new strtok3.FileTokenizer(fileHandle, { + ...this.getTokenizerOptions(), + fileInfo: { + path, + size: fileStat.size, + }, + }); + return super.fromTokenizer(tokenizer); + } + + async toDetectionStream(readableStream, options = {}) { + if (!(readableStream instanceof Readable)) { + return super.toDetectionStream(readableStream, options); + } + + const {sampleSize = reasonableDetectionSizeInBytes} = options; + const {signal} = this.options; + const normalizedSampleSize = normalizeSampleSize(sampleSize); + + signal?.throwIfAborted(); + + return new Promise((resolve, reject) => { + let isSettled = false; + + const cleanup = () => { + readableStream.off('error', onError); + readableStream.off('readable', onReadable); + signal?.removeEventListener('abort', onAbort); + }; + + const settle = (callback, value) => { + if (isSettled) { + return; + } + + isSettled = true; + cleanup(); + callback(value); + }; + + const onError = error => { + settle(reject, error); + }; + + const onAbort = () => { + if (!readableStream.destroyed) { + readableStream.destroy(); + } + + settle(reject, signal.reason); + }; + + const onReadable = () => { + (async () => { + try { + const pass = new PassThrough(); + const outputStream = pipeline ? pipeline(readableStream, pass, () => {}) : readableStream.pipe(pass); + const chunk = readableStream.read(normalizedSampleSize) ?? readableStream.read() ?? new Uint8Array(0); + try { + pass.fileType = await this.fromBuffer(chunk); + } catch (error) { + if (error instanceof strtok3.EndOfStreamError) { + pass.fileType = undefined; + } else { + settle(reject, error); + } + } + + settle(resolve, outputStream); + } catch (error) { + settle(reject, error); + } + })(); + }; + + readableStream.on('error', onError); + readableStream.once('readable', onReadable); + signal?.addEventListener('abort', onAbort, {once: true}); + }); + } +} + +export async function fileTypeFromFile(path, options) { + return (new FileTypeParser(options)).fromFile(path, options); +} + +export async function fileTypeFromStream(stream, options) { + return (new FileTypeParser(options)).fromStream(stream); +} + +export async function fileTypeStream(readableStream, options = {}) { + return new FileTypeParser(options).toDetectionStream(readableStream, options); +} + +export { + fileTypeFromTokenizer, + fileTypeFromBuffer, + fileTypeFromBlob, + supportedMimeTypes, + supportedExtensions, +} from './core.js'; diff --git a/node_modules/file-type/license b/node_modules/file-type/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/file-type/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.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. diff --git a/node_modules/file-type/package.json b/node_modules/file-type/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ff46381ae8b7614df8847ffd10c993cfa132a540 --- /dev/null +++ b/node_modules/file-type/package.json @@ -0,0 +1,290 @@ +{ + "name": "file-type", + "version": "21.3.4", + "description": "Detect the file type of a file, stream, or data", + "license": "MIT", + "repository": "sindresorhus/file-type", + "funding": "https://github.com/sindresorhus/file-type?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": { + ".": { + "node": { + "types": "./index.d.ts", + "import": "./index.js", + "module-sync": "./index.js" + }, + "default": { + "types": "./core.d.ts", + "import": "./core.js", + "module-sync": "./core.js" + } + }, + "./core": { + "types": "./core.d.ts", + "default": "./core.js" + }, + "./node": { + "types": "./index.d.ts", + "default": "./index.js" + } + }, + "sideEffects": false, + "engines": { + "node": ">=20" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts", + "core.js", + "core.d.ts", + "supported.js", + "util.js" + ], + "keywords": [ + "mime", + "file", + "type", + "magic", + "archive", + "image", + "img", + "pic", + "picture", + "flash", + "photo", + "video", + "detect", + "check", + "is", + "exif", + "elf", + "macho", + "exe", + "binary", + "buffer", + "uint8array", + "jpg", + "png", + "apng", + "gif", + "webp", + "flif", + "xcf", + "cr2", + "cr3", + "orf", + "arw", + "dng", + "nef", + "rw2", + "raf", + "tif", + "bmp", + "icns", + "jxr", + "psd", + "indd", + "zip", + "tar", + "rar", + "gz", + "bz2", + "7z", + "dmg", + "mp4", + "mid", + "mkv", + "webm", + "mov", + "avi", + "mpg", + "mp2", + "mp3", + "m4a", + "ogg", + "opus", + "flac", + "wav", + "amr", + "pdf", + "epub", + "mobi", + "swf", + "rtf", + "woff", + "woff2", + "eot", + "ttf", + "otf", + "ttc", + "ico", + "flv", + "ps", + "xz", + "sqlite", + "xpi", + "cab", + "deb", + "ar", + "rpm", + "Z", + "lz", + "cfb", + "mxf", + "mts", + "wasm", + "webassembly", + "blend", + "bpg", + "docx", + "pptx", + "xlsx", + "3gp", + "j2c", + "jp2", + "jpm", + "jpx", + "mj2", + "aif", + "odt", + "ods", + "odp", + "xml", + "heic", + "ics", + "glb", + "pcap", + "dsf", + "lnk", + "alias", + "voc", + "ac3", + "3g2", + "m4b", + "m4p", + "m4v", + "f4a", + "f4b", + "f4p", + "f4v", + "mie", + "qcp", + "asf", + "ogv", + "ogm", + "oga", + "spx", + "ogx", + "ape", + "wv", + "cur", + "nes", + "crx", + "ktx", + "dcm", + "mpc", + "arrow", + "shp", + "aac", + "mp1", + "it", + "s3m", + "xm", + "skp", + "avif", + "eps", + "lzh", + "pgp", + "asar", + "stl", + "chm", + "3mf", + "zst", + "jxl", + "vcf", + "jls", + "pst", + "dwg", + "parquet", + "class", + "arj", + "cpio", + "ace", + "avro", + "icc", + "fbx", + "vsdx", + "vtt", + "apk", + "drc", + "lz4", + "potx", + "xltx", + "dotx", + "xltm", + "ots", + "odg", + "otg", + "otp", + "ott", + "xlsm", + "docm", + "dotm", + "potm", + "pptm", + "jar", + "jmp", + "rm", + "sav", + "ppsm", + "ppsx", + "tar.gz", + "reg", + "dat" + ], + "dependencies": { + "@tokenizer/inflate": "^0.4.1", + "strtok3": "^10.3.4", + "token-types": "^6.1.1", + "uint8array-extras": "^1.4.0" + }, + "devDependencies": { + "@tokenizer/token": "^0.3.0", + "@types/node": "^25.3.3", + "ava": "^7.0.0", + "commonmark": "^0.31.2", + "get-stream": "^9.0.1", + "noop-stream": "^1.0.0", + "tsd": "^0.33.0", + "xo": "^0.60.0" + }, + "xo": { + "envs": [ + "node", + "browser" + ], + "ignores": [ + "fixture" + ], + "rules": { + "no-inner-declarations": "warn", + "no-await-in-loop": "warn", + "no-bitwise": "off", + "@typescript-eslint/no-unsafe-assignment": "off", + "unicorn/text-encoding-identifier-case": "off", + "unicorn/switch-case-braces": "off", + "unicorn/prefer-top-level-await": "off" + } + }, + "ava": { + "serial": true + } +} diff --git a/node_modules/file-type/readme.md b/node_modules/file-type/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..49e130e6bf622148eca48d5f86e2f140c8084a1a --- /dev/null +++ b/node_modules/file-type/readme.md @@ -0,0 +1,667 @@ +

+ file-type logo +

+ +> Detect the file type of a file, stream, or data + +The file type is detected by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer. + +This package is for detecting binary-based file formats, not text-based formats like `.txt`, `.csv`, `.svg`, etc. + +We accept contributions for commonly used modern file formats, not historical or obscure ones. Open an issue first for discussion. + +> [!IMPORTANT] +> NO SECURITY REPORTS WILL BE ACCEPTED RIGHT NOW. I'm currently hardening the parser and all the low-quality AI-generated security reports is just a huge waste of time. + +## Install + +```sh +npm install file-type +``` + +**This package is an ESM package. Your project needs to be ESM too. [Read more](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). For TypeScript + CommonJS, see [`load-esm`](https://github.com/Borewit/load-esm).** If you use it with Webpack, you need the latest Webpack version and ensure you configure it correctly for ESM. + +> [!IMPORTANT] +> File type detection is based on binary signatures (magic numbers) and is a best-effort hint. It does not guarantee the file is actually of that type or that the file is valid/not malformed. +> +> Robustness against malformed input is best-effort. When processing untrusted files on a server, enforce a reasonable file size limit and use a worker thread with a timeout (e.g., [`make-asynchronous`](https://github.com/sindresorhus/make-asynchronous)). These are not considered security issues in this package. + +## Usage + +### Node.js + +Determine file type from a file: + +```js +import {fileTypeFromFile} from 'file-type'; + +console.log(await fileTypeFromFile('Unicorn.png')); +//=> {ext: 'png', mime: 'image/png'} +``` + +Determine file type from a Uint8Array/ArrayBuffer, which may be a portion of the beginning of a file: + +```js +import {fileTypeFromBuffer} from 'file-type'; +import {readChunk} from 'read-chunk'; + +const buffer = await readChunk('Unicorn.png', {length: 4100}); + +console.log(await fileTypeFromBuffer(buffer)); +//=> {ext: 'png', mime: 'image/png'} +``` + +Determine file type from a stream: + +```js +import fs from 'node:fs'; +import {fileTypeFromStream} from 'file-type'; + +const stream = fs.createReadStream('Unicorn.mp4'); + +console.log(await fileTypeFromStream(stream)); +//=> {ext: 'mp4', mime: 'video/mp4'} +``` + +The stream method can also be used to read from a remote location: + +```js +import got from 'got'; +import {fileTypeFromStream} from 'file-type'; + +const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg'; + +const stream = got.stream(url); + +console.log(await fileTypeFromStream(stream)); +//=> {ext: 'jpg', mime: 'image/jpeg'} +``` + +Another stream example: + +```js +import stream from 'node:stream'; +import fs from 'node:fs'; +import crypto from 'node:crypto'; +import {fileTypeStream} from 'file-type'; + +const read = fs.createReadStream('encrypted.enc'); +const decipher = crypto.createDecipheriv(alg, key, iv); + +const streamWithFileType = await fileTypeStream(stream.pipeline(read, decipher)); + +console.log(streamWithFileType.fileType); +//=> {ext: 'mov', mime: 'video/quicktime'} + +const write = fs.createWriteStream(`decrypted.${streamWithFileType.fileType.ext}`); +streamWithFileType.pipe(write); +``` + +### Browser + +```js +import {fileTypeFromStream} from 'file-type'; + +const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg'; + +const response = await fetch(url); +const fileType = await fileTypeFromStream(response.body); + +console.log(fileType); +//=> {ext: 'jpg', mime: 'image/jpeg'} +``` + +## API + +### fileTypeFromBuffer(buffer, options) + +Detect the file type of a `Uint8Array`, or `ArrayBuffer`. + +The file type is detected by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer. + +If file access is available, it is recommended to use `fileTypeFromFile()` instead. + +Returns a `Promise` for an object with the detected file type: + +- `ext` - One of the [supported file types](#supported-file-types) +- `mime` - The [MIME type](https://en.wikipedia.org/wiki/Internet_media_type) + +Or `undefined` when there is no match. + +#### buffer + +Type: `Uint8Array | ArrayBuffer` + +A buffer representing file data. It works best if the buffer contains the entire file. It may work with a smaller portion as well. + +### fileTypeFromFile(filePath, options) + +Detect the file type of a file path. + +This is for Node.js only. + +To read from a [`File`](https://developer.mozilla.org/docs/Web/API/File), see [`fileTypeFromBlob()`](#filetypefromblobblob-options). + +The file type is detected by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer. + +Returns a `Promise` for an object with the detected file type: + +- `ext` - One of the [supported file types](#supported-file-types) +- `mime` - The [MIME type](https://en.wikipedia.org/wiki/Internet_media_type) + +Or `undefined` when there is no match. + +#### filePath + +Type: `string` + +The file path to parse. + +### fileTypeFromStream(stream) + +Detect the file type of a [web `ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream). + +If the engine is Node.js, this may also be a [Node.js `stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +Direct support for Node.js streams will be dropped in the future, when Node.js streams can be converted to Web streams (see [`toWeb()`](https://nodejs.org/api/stream.html#streamreadabletowebstreamreadable-options)). + +The file type is detected by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer. + +Returns a `Promise` for an object with the detected file type: + +- `ext` - One of the [supported file types](#supported-file-types) +- `mime` - The [MIME type](https://en.wikipedia.org/wiki/Internet_media_type) + +Or `undefined` when there is no match. + +#### stream + +Type: [Web `ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) or [Node.js `stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable) + +A readable stream representing file data. + +### fileTypeFromBlob(blob, options) + +Detect the file type of a [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob), + +> [!TIP] +> A [`File` object](https://developer.mozilla.org/docs/Web/API/File) is a `Blob` and can be passed in here. + +It will **stream** the underlying Blob. + +The file type is detected by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the blob. + +Returns a `Promise` for an object with the detected file type: + +- `ext` - One of the [supported file types](#supported-file-types) +- `mime` - The [MIME type](https://en.wikipedia.org/wiki/Internet_media_type) + +Or `undefined` when there is no match. + +```js +import {fileTypeFromBlob} from 'file-type'; + +const blob = new Blob([''], { + type: 'text/plain', + endings: 'native' +}); + +console.log(await fileTypeFromBlob(blob)); +//=> {ext: 'txt', mime: 'text/plain'} +``` + +#### blob + +Type: [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + +### fileTypeFromTokenizer(tokenizer, options) + +Detect the file type from an `ITokenizer` source. + +This method is used internally, but can also be used for a special "tokenizer" reader. + +A tokenizer propagates the internal read functions, allowing alternative transport mechanisms, to access files, to be implemented and used. + +Returns a `Promise` for an object with the detected file type: + +- `ext` - One of the [supported file types](#supported-file-types) +- `mime` - The [MIME type](https://en.wikipedia.org/wiki/Internet_media_type) + +Or `undefined` when there is no match. + +An example is [`@tokenizer/http`](https://github.com/Borewit/tokenizer-http), which requests data using [HTTP-range-requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests). A difference with a conventional stream and the [*tokenizer*](https://github.com/Borewit/strtok3#tokenizer), is that it can *ignore* (seek, fast-forward) in the stream. For example, you may only need and read the first 6 bytes, and the last 128 bytes, which may be an advantage in case reading the entire file would take longer. + +```js +import {makeTokenizer} from '@tokenizer/http'; +import {fileTypeFromTokenizer} from 'file-type'; + +const audioTrackUrl = 'https://test-audio.netlify.com/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/01%20-%20Diablo%20Swing%20Orchestra%20-%20Heroines.mp3'; + +const httpTokenizer = await makeTokenizer(audioTrackUrl); +const fileType = await fileTypeFromTokenizer(httpTokenizer); + +console.log(fileType); +//=> {ext: 'mp3', mime: 'audio/mpeg'} +``` + +Or use [`@tokenizer/s3`](https://github.com/Borewit/tokenizer-s3) to determine the file type of a file stored on [Amazon S3](https://aws.amazon.com/s3): + +```js +import {S3Client} from '@aws-sdk/client-s3'; +import {makeChunkedTokenizerFromS3} from '@tokenizer/s3'; +import {fileTypeFromTokenizer} from 'file-type'; + +// Initialize the S3 client +// Initialize S3 client +const s3 = new S3Client(); + +// Initialize the S3 tokenizer. +const s3Tokenizer = await makeChunkedTokenizerFromS3(s3, { + Bucket: 'affectlab', + Key: '1min_35sec.mp4' +}); + +// Figure out what kind of file it is. +const fileType = await fileTypeFromTokenizer(s3Tokenizer); +console.log(fileType); +``` + +Note that only the minimum amount of data required to determine the file type is read (okay, just a bit extra to prevent too many fragmented reads). + +#### tokenizer + +Type: [`ITokenizer`](https://github.com/Borewit/strtok3#tokenizer) + +A file source implementing the [tokenizer interface](https://github.com/Borewit/strtok3#tokenizer). + +### fileTypeStream(webStream, options?) + +Returns a `Promise` which resolves to the original readable stream argument, but with an added `fileType` property, which is an object like the one returned from `fileTypeFromFile()`. + +This method can be handy to put in between a stream, but it comes with a price. +Internally `stream()` builds up a buffer of `sampleSize` bytes, used as a sample, to determine the file type. +The sample size impacts the file detection resolution. +A smaller sample size will result in lower probability of the best file type detection. + +**Note:** When using Node.js, a `stream.Readable` may be provided as well. + +#### readableStream + +Type: [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable) + +#### options + +Type: `object` + +Supports the following options in addition to the [general options](#options): + +##### sampleSize + +Type: `number`\ +Default: `4100` + +The sample size in bytes. + +#### Example + +```js +import got from 'got'; +import {fileTypeStream} from 'file-type'; + +const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg'; + +const stream1 = got.stream(url); +const stream2 = await fileTypeStream(stream1, {sampleSize: 1024}); + +if (stream2.fileType?.mime === 'image/jpeg') { + // stream2 can be used to stream the JPEG image (from the very beginning of the stream) +} +``` + +#### readableStream + +Type: [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable) + +The input stream. + +### supportedExtensions + +Returns a `Set` of supported file extensions. + +### supportedMimeTypes + +Returns a `Set` of supported MIME types. + +### Options + +#### customDetectors + +Array of custom file type detectors to run before default detectors. + +For example: + +```js +import {fileTypeFromFile} from 'file-type'; +import {detectXml} from '@file-type/xml'; + +const fileType = await fileTypeFromFile('sample.kml', {customDetectors: [detectXml]}); +console.log(fileType); +``` + +#### mpegOffsetTolerance + +Default: `0` + +Specifies the byte tolerance for locating the first MPEG audio frame (e.g. `.mp1`, `.mp2`, `.mp3`, `.aac`). + +Allows detection to handle slight sync offsets between the expected and actual frame start. Common in malformed or incorrectly muxed files, which, while technically invalid, do occur in the wild. + +A tolerance of 10 bytes covers most cases. + +## Custom detectors + +Custom file type detectors are plugins designed to extend the default detection capabilities. +They allow support for uncommon file types, non-binary formats, or customized detection behavior. + +Detectors can be added via the constructor options or by modifying `FileTypeParser#detectors` directly. +Detectors provided through the constructor are executed before the default ones. + +Detectors can be added via the constructor options or by directly modifying `FileTypeParser#detectors`. + +### Example adding a detector + +For example: + +```js +import {FileTypeParser} from 'file-type'; +import {detectXml} from '@file-type/xml'; + +const parser = new FileTypeParser({customDetectors: [detectXml]}); +const fileType = await parser.fromFile('sample.kml'); +console.log(fileType); +``` + +### Available third-party file-type detectors + +- [@file-type/av](https://github.com/Borewit/file-type-av): Improves detection of audio and video file formats, with accurate differentiation between the two +- [@file-type/cfbf](https://github.com/Borewit/file-type-cfbf): Detects Compound File Binary Format (CFBF) based formats, such as Office 97–2003 documents and `.msi`. +- [@file-type/pdf](https://github.com/Borewit/file-type-pdf): Detects PDF based file types, such as Adobe Illustrator +- [@file-type/xml](https://github.com/Borewit/file-type-xml): Detects common XML file types, such as GLM, KML, MusicXML, RSS, SVG, and XHTML + +### Detector execution flow + +If a detector returns `undefined`, the following rules apply: + +1. **No Tokenizer Interaction**: If the detector does not modify the tokenizer's position, the next detector in the sequence is executed. +2. **Tokenizer Interaction**: If the detector modifies the tokenizer's position (`tokenizer.position` is advanced), no further detectors are executed. In this case, the file type remains `undefined`, as subsequent detectors cannot evaluate the content. This is an exceptional scenario, as it prevents any other detectors from determining the file type. + +### Writing your own custom detector + +Below is an example of a custom detector array. This can be passed to the `FileTypeParser` via the `fileTypeOptions` argument. + +```js +import {FileTypeParser} from 'file-type'; + +const unicornDetector = { + id: 'unicorn', // May be used to recognize the detector in the detector list + async detect(tokenizer) { + const unicornHeader = [85, 78, 73, 67, 79, 82, 78]; // "UNICORN" in ASCII decimal + + const buffer = new Uint8Array(unicornHeader.length); + await tokenizer.peekBuffer(buffer, {length: unicornHeader.length, mayBeLess: true}); + if (unicornHeader.every((value, index) => value === buffer[index])) { + return {ext: 'unicorn', mime: 'application/unicorn'}; + } + + return undefined; + } +} + +const buffer = new Uint8Array([85, 78, 73, 67, 79, 82, 78]); +const parser = new FileTypeParser({customDetectors: [unicornDetector]}); +const fileType = await parser.fromBuffer(buffer); +console.log(fileType); // {ext: 'unicorn', mime: 'application/unicorn'} +``` + +```ts +/** +@param tokenizer - The [tokenizer](https://github.com/Borewit/strtok3#tokenizer) used to read file content. +@param fileType - The file type detected by standard or previous custom detectors, or `undefined` if no match is found. +@returns The detected file type, or `undefined` if no match is found. +*/ +export type Detector = (tokenizer: ITokenizer, fileType?: FileTypeResult) => Promise; +``` + +## Abort signal + +Some async operations can be aborted by passing an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to the `FileTypeParser` constructor. + +```js +import {FileTypeParser} from 'file-type'; + +const abortController = new AbortController() + +const parser = new FileTypeParser({signal: abortController.signal}); + +const promise = parser.fromStream(blob.stream()); + +abortController.abort(); // Abort file-type reading from the Blob stream. +``` + +## Supported file types + +- [`3g2`](https://en.wikipedia.org/wiki/3GP_and_3G2#3G2) - Multimedia container format defined by the 3GPP2 for 3G CDMA2000 multimedia services +- [`3gp`](https://en.wikipedia.org/wiki/3GP_and_3G2#3GP) - Multimedia container format defined by the Third Generation Partnership Project (3GPP) for 3G UMTS multimedia services +- [`3mf`](https://en.wikipedia.org/wiki/3D_Manufacturing_Format) - 3D Manufacturing Format +- [`7z`](https://en.wikipedia.org/wiki/7z) - 7-Zip archive +- [`Z`](https://fileinfo.com/extension/z) - Unix Compressed File +- [`aac`](https://en.wikipedia.org/wiki/Advanced_Audio_Coding) - Advanced Audio Coding +- [`ac3`](https://www.atsc.org/standard/a522012-digital-audio-compression-ac-3-e-ac-3-standard-12172012/) - ATSC A/52 Audio File +- [`ace`](https://en.wikipedia.org/wiki/ACE_(compressed_file_format)) - ACE archive +- [`aif`](https://en.wikipedia.org/wiki/Audio_Interchange_File_Format) - Audio Interchange file +- [`alias`](https://en.wikipedia.org/wiki/Alias_%28Mac_OS%29) - macOS Alias file +- [`amr`](https://en.wikipedia.org/wiki/Adaptive_Multi-Rate_audio_codec) - Adaptive Multi-Rate audio codec +- [`ape`](https://en.wikipedia.org/wiki/Monkey%27s_Audio) - Monkey's Audio +- [`apk`](https://en.wikipedia.org/wiki/Apk_(file_format)) - Android package format +- [`apng`](https://en.wikipedia.org/wiki/APNG) - Animated Portable Network Graphics +- [`ar`](https://en.wikipedia.org/wiki/Ar_(Unix)) - Archive file +- [`arj`](https://en.wikipedia.org/wiki/ARJ) - Archive file +- [`arrow`](https://arrow.apache.org) - Columnar format for tables of data +- [`arw`](https://en.wikipedia.org/wiki/Raw_image_format#ARW) - Sony Alpha Raw image file +- [`asar`](https://github.com/electron/asar#format) - Archive format primarily used to enclose Electron applications +- [`asf`](https://en.wikipedia.org/wiki/Advanced_Systems_Format) - Advanced Systems Format +- [`avi`](https://en.wikipedia.org/wiki/Audio_Video_Interleave) - Audio Video Interleave file +- [`avif`](https://en.wikipedia.org/wiki/AV1#AV1_Image_File_Format_(AVIF)) - AV1 Image File Format +- [`avro`](https://en.wikipedia.org/wiki/Apache_Avro#Avro_Object_Container_File) - Object container file developed by Apache Avro +- [`blend`](https://wiki.blender.org/index.php/Dev:Source/Architecture/File_Format) - Blender project +- [`bmp`](https://en.wikipedia.org/wiki/BMP_file_format) - Bitmap image file +- [`bpg`](https://bellard.org/bpg/) - Better Portable Graphics file +- [`bz2`](https://en.wikipedia.org/wiki/Bzip2) - Archive file +- [`cab`](https://en.wikipedia.org/wiki/Cabinet_(file_format)) - Cabinet file +- [`cfb`](https://en.wikipedia.org/wiki/Compound_File_Binary_Format) - Compound File Binary Format +- [`chm`](https://en.wikipedia.org/wiki/Microsoft_Compiled_HTML_Help) - Microsoft Compiled HTML Help +- [`class`](https://en.wikipedia.org/wiki/Java_class_file) - Java class file +- [`cpio`](https://en.wikipedia.org/wiki/Cpio) - Cpio archive +- [`cr2`](https://fileinfo.com/extension/cr2) - Canon Raw image file (v2) +- [`cr3`](https://fileinfo.com/extension/cr3) - Canon Raw image file (v3) +- [`crx`](https://developer.chrome.com/extensions/crx) - Google Chrome extension +- [`cur`](https://en.wikipedia.org/wiki/ICO_(file_format)) - Icon file +- [`dat`](https://en.wikipedia.org/wiki/Windows_Registry) - Windows registry hive file +- [`dcm`](https://en.wikipedia.org/wiki/DICOM#Data_format) - DICOM Image File +- [`deb`](https://en.wikipedia.org/wiki/Deb_(file_format)) - Debian package +- [`dmg`](https://en.wikipedia.org/wiki/Apple_Disk_Image) - Apple Disk Image +- [`dng`](https://en.wikipedia.org/wiki/Digital_Negative) - Adobe Digital Negative image file +- [`docm`](https://en.wikipedia.org/wiki/List_of_Microsoft_Office_filename_extensions) - Microsoft Word macro-enabled document +- [`docx`](https://en.wikipedia.org/wiki/Office_Open_XML) - Microsoft Word document +- [`dotm`](https://en.wikipedia.org/wiki/List_of_Microsoft_Office_filename_extensions) - Microsoft Word macro-enabled template +- [`dotx`](https://en.wikipedia.org/wiki/List_of_Microsoft_Office_filename_extensions) - Microsoft Word template +- [`drc`](https://en.wikipedia.org/wiki/Zstandard) - Google's Draco 3D Data Compression +- [`dsf`](https://dsd-guide.com/sites/default/files/white-papers/DSFFileFormatSpec_E.pdf) - Sony DSD Stream File (DSF) +- [`dwg`](https://en.wikipedia.org/wiki/.dwg) - Autodesk CAD file +- [`elf`](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format) - Unix Executable and Linkable Format +- [`eot`](https://en.wikipedia.org/wiki/Embedded_OpenType) - Embedded OpenType font +- [`eps`](https://en.wikipedia.org/wiki/Encapsulated_PostScript) - Encapsulated PostScript +- [`epub`](https://en.wikipedia.org/wiki/EPUB) - E-book file +- [`exe`](https://en.wikipedia.org/wiki/.exe) - Executable file +- [`f4a`](https://en.wikipedia.org/wiki/Flash_Video) - Audio-only ISO base media file format used by Adobe Flash Player +- [`f4b`](https://en.wikipedia.org/wiki/Flash_Video) - Audiobook and podcast ISO base media file format used by Adobe Flash Player +- [`f4p`](https://en.wikipedia.org/wiki/Flash_Video) - ISO base media file format protected by Adobe Access DRM used by Adobe Flash Player +- [`f4v`](https://en.wikipedia.org/wiki/Flash_Video) - ISO base media file format used by Adobe Flash Player +- [`fbx`](https://en.wikipedia.org/wiki/FBX) - Filmbox is a proprietary file format used to provide interoperability between digital content creation apps. +- [`flac`](https://en.wikipedia.org/wiki/FLAC) - Free Lossless Audio Codec +- [`flif`](https://en.wikipedia.org/wiki/Free_Lossless_Image_Format) - Free Lossless Image Format +- [`flv`](https://en.wikipedia.org/wiki/Flash_Video) - Flash video +- [`gif`](https://en.wikipedia.org/wiki/GIF) - Graphics Interchange Format +- [`glb`](https://github.com/KhronosGroup/glTF) - GL Transmission Format +- [`gz`](https://en.wikipedia.org/wiki/Gzip) - Archive file +- [`heic`](https://nokiatech.github.io/heif/technical.html) - High Efficiency Image File Format +- [`icc`](https://en.wikipedia.org/wiki/ICC_profile) - ICC Profile +- [`icns`](https://en.wikipedia.org/wiki/Apple_Icon_Image_format) - Apple Icon image +- [`ico`](https://en.wikipedia.org/wiki/ICO_(file_format)) - Windows icon file +- [`ics`](https://en.wikipedia.org/wiki/ICalendar#Data_format) - iCalendar +- [`indd`](https://en.wikipedia.org/wiki/Adobe_InDesign#File_format) - Adobe InDesign document +- [`it`](https://wiki.openmpt.org/Manual:_Module_formats#The_Impulse_Tracker_format_.28.it.29) - Audio module format: Impulse Tracker +- [`j2c`](https://en.wikipedia.org/wiki/JPEG_2000) - JPEG 2000 +- [`jar`](https://en.wikipedia.org/wiki/JAR_(file_format)) - Java archive +- [`jls`](https://en.wikipedia.org/wiki/Lossless_JPEG#JPEG-LS) - Lossless/near-lossless compression standard for continuous-tone images +- [`jmp`](https://en.wikipedia.org/wiki/JMP_(statistical_software)) - JMP data file format by SAS Institute +- [`jp2`](https://en.wikipedia.org/wiki/JPEG_2000) - JPEG 2000 +- [`jpg`](https://en.wikipedia.org/wiki/JPEG) - Joint Photographic Experts Group image +- [`jpm`](https://en.wikipedia.org/wiki/JPEG_2000) - JPEG 2000 +- [`jpx`](https://en.wikipedia.org/wiki/JPEG_2000) - JPEG 2000 +- [`jxl`](https://en.wikipedia.org/wiki/JPEG_XL) - JPEG XL image format +- [`jxr`](https://en.wikipedia.org/wiki/JPEG_XR) - Joint Photographic Experts Group extended range +- [`ktx`](https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/) - OpenGL and OpenGL ES textures +- [`lnk`](https://en.wikipedia.org/wiki/Shortcut_%28computing%29#Microsoft_Windows) - Microsoft Windows file shortcut +- [`lz`](https://en.wikipedia.org/wiki/Lzip) - Archive file +- [`lz4`](https://en.wikipedia.org/wiki/LZ4_(compression_algorithm)) - Compressed archive created by one of a variety of LZ4 compression utilities +- [`lzh`](https://en.wikipedia.org/wiki/LHA_(file_format)) - LZH archive +- [`m4a`](https://en.wikipedia.org/wiki/M4A) - Audio-only MPEG-4 files +- [`m4b`](https://en.wikipedia.org/wiki/M4B) - Audiobook and podcast MPEG-4 files, which also contain metadata including chapter markers, images, and hyperlinks +- [`m4p`](https://en.wikipedia.org/wiki/MPEG-4_Part_14#Filename_extensions) - MPEG-4 files with audio streams encrypted by FairPlay Digital Rights Management as were sold through the iTunes Store +- [`m4v`](https://en.wikipedia.org/wiki/M4V) - Video container format developed by Apple, which is very similar to the MP4 format +- [`macho`](https://en.wikipedia.org/wiki/Mach-O) - Mach-O binary format +- [`mid`](https://en.wikipedia.org/wiki/MIDI) - Musical Instrument Digital Interface file +- [`mie`](https://en.wikipedia.org/wiki/Sidecar_file) - Dedicated meta information format which supports storage of binary as well as textual meta information +- [`mj2`](https://en.wikipedia.org/wiki/Motion_JPEG_2000) - Motion JPEG 2000 +- [`mkv`](https://en.wikipedia.org/wiki/Matroska) - Matroska video file +- [`mobi`](https://en.wikipedia.org/wiki/Mobipocket) - Mobipocket +- [`mov`](https://en.wikipedia.org/wiki/QuickTime_File_Format) - QuickTime video file +- [`mp1`](https://en.wikipedia.org/wiki/MPEG-1_Audio_Layer_I) - MPEG-1 Audio Layer I +- [`mp2`](https://en.wikipedia.org/wiki/MPEG-1_Audio_Layer_II) - MPEG-1 Audio Layer II +- [`mp3`](https://en.wikipedia.org/wiki/MP3) - Audio file +- [`mp4`](https://en.wikipedia.org/wiki/MPEG-4_Part_14#Filename_extensions) - MPEG-4 Part 14 video file +- [`mpc`](https://en.wikipedia.org/wiki/Musepack) - Musepack (SV7 & SV8) +- [`mpg`](https://en.wikipedia.org/wiki/MPEG-1) - MPEG-1 file +- [`mts`](https://en.wikipedia.org/wiki/.m2ts) - MPEG-2 Transport Stream, both raw and Blu-ray Disc Audio-Video (BDAV) versions +- [`mxf`](https://en.wikipedia.org/wiki/Material_Exchange_Format) - Material Exchange Format +- [`nef`](https://www.nikonusa.com/en/learn-and-explore/a/products-and-innovation/nikon-electronic-format-nef.html) - Nikon Electronic Format image file +- [`nes`](https://fileinfo.com/extension/nes) - Nintendo NES ROM +- [`odg`](https://en.wikipedia.org/wiki/OpenDocument) - OpenDocument for drawing +- [`odp`](https://en.wikipedia.org/wiki/OpenDocument) - OpenDocument for presentations +- [`ods`](https://en.wikipedia.org/wiki/OpenDocument) - OpenDocument for spreadsheets +- [`odt`](https://en.wikipedia.org/wiki/OpenDocument) - OpenDocument for word processing +- [`oga`](https://en.wikipedia.org/wiki/Ogg) - Audio file +- [`ogg`](https://en.wikipedia.org/wiki/Ogg) - Audio file +- [`ogm`](https://en.wikipedia.org/wiki/Ogg) - Audio file +- [`ogv`](https://en.wikipedia.org/wiki/Ogg) - Audio file +- [`ogx`](https://en.wikipedia.org/wiki/Ogg) - Audio file +- [`opus`](https://en.wikipedia.org/wiki/Opus_(audio_format)) - Audio file +- [`orf`](https://en.wikipedia.org/wiki/ORF_format) - Olympus Raw image file +- [`otf`](https://en.wikipedia.org/wiki/OpenType) - OpenType font +- [`otg`](https://en.wikipedia.org/wiki/OpenDocument_technical_specification#Templates) - OpenDocument template for drawing +- [`otp`](https://en.wikipedia.org/wiki/OpenDocument_technical_specification#Templates) - OpenDocument template for presentations +- [`ots`](https://en.wikipedia.org/wiki/OpenDocument_technical_specification#Templates) - OpenDocument template for spreadsheets +- [`ott`](https://en.wikipedia.org/wiki/OpenDocument_technical_specification#Templates) - OpenDocument template for word processing +- [`parquet`](https://en.wikipedia.org/wiki/Apache_Parquet) - Apache Parquet +- [`pcap`](https://wiki.wireshark.org/Development/LibpcapFileFormat) - Libpcap File Format +- [`pdf`](https://en.wikipedia.org/wiki/Portable_Document_Format) - Portable Document Format +- [`pgp`](https://en.wikipedia.org/wiki/Pretty_Good_Privacy) - Pretty Good Privacy +- [`png`](https://en.wikipedia.org/wiki/Portable_Network_Graphics) - Portable Network Graphics +- [`potm`](https://en.wikipedia.org/wiki/List_of_Microsoft_Office_filename_extensions) - Microsoft PowerPoint macro-enabled template +- [`potx`](https://en.wikipedia.org/wiki/List_of_Microsoft_Office_filename_extensions) - Microsoft PowerPoint template +- [`ppsm`](https://en.wikipedia.org/wiki/List_of_Microsoft_Office_filename_extensions#PowerPoint) - Office PowerPoint 2007 macro-enabled slide show +- [`ppsx`](https://en.wikipedia.org/wiki/List_of_Microsoft_Office_filename_extensions#PowerPoint) - Office PowerPoint 2007 slide show +- [`pptm`](https://en.wikipedia.org/wiki/List_of_Microsoft_Office_filename_extensions) - Microsoft PowerPoint macro-enabled document +- [`pptx`](https://en.wikipedia.org/wiki/Office_Open_XML) - Microsoft PowerPoint document +- [`ps`](https://en.wikipedia.org/wiki/Postscript) - Postscript +- [`psd`](https://en.wikipedia.org/wiki/Adobe_Photoshop#File_format) - Adobe Photoshop document +- [`pst`](https://en.wikipedia.org/wiki/Personal_Storage_Table) - Personal Storage Table file +- [`qcp`](https://en.wikipedia.org/wiki/QCP) - Tagged and chunked data +- [`raf`](https://en.wikipedia.org/wiki/Raw_image_format) - Fujifilm RAW image file +- [`rar`](https://en.wikipedia.org/wiki/RAR_(file_format)) - Archive file +- [`reg`](https://en.wikipedia.org/wiki/Windows_Registry) - Windows registry (entries) file format +- [`rm`](https://en.wikipedia.org/wiki/RealMedia) - RealMedia +- [`rpm`](https://fileinfo.com/extension/rpm) - Red Hat Package Manager file +- [`rtf`](https://en.wikipedia.org/wiki/Rich_Text_Format) - Rich Text Format +- [`rw2`](https://en.wikipedia.org/wiki/Raw_image_format) - Panasonic RAW image file +- [`s3m`](https://wiki.openmpt.org/Manual:_Module_formats#The_ScreamTracker_3_format_.28.s3m.29) - Audio module format: ScreamTracker 3 +- [`sav`](https://en.wikipedia.org/wiki/SPSS) - SPSS Statistical Data File +- [`shp`](https://en.wikipedia.org/wiki/Shapefile) - Geospatial vector data format +- [`skp`](https://en.wikipedia.org/wiki/SketchUp) - SketchUp +- [`spx`](https://en.wikipedia.org/wiki/Ogg) - Audio file +- [`sqlite`](https://www.sqlite.org/fileformat2.html) - SQLite file +- [`stl`](https://en.wikipedia.org/wiki/STL_(file_format)) - Standard Tesselated Geometry File Format (ASCII only) +- [`swf`](https://en.wikipedia.org/wiki/SWF) - Adobe Flash Player file +- [`tar`](https://en.wikipedia.org/wiki/Tar_(computing)#File_format) - Tape archive or tarball +- [`tar.gz`](https://en.wikipedia.org/wiki/Gzip) - Gzipped tape archive (tarball) +- [`tif`](https://en.wikipedia.org/wiki/Tagged_Image_File_Format) - Tagged Image file +- [`ttc`](https://en.wikipedia.org/wiki/TrueType#TrueType_Collection) - TrueType Collection font +- [`ttf`](https://en.wikipedia.org/wiki/TrueType) - TrueType font +- [`vcf`](https://en.wikipedia.org/wiki/VCard) - vCard +- [`voc`](https://wiki.multimedia.cx/index.php/Creative_Voice) - Creative Voice File +- [`vsdx`](https://en.wikipedia.org/wiki/Microsoft_Visio) - Microsoft Visio File +- [`vtt`](https://en.wikipedia.org/wiki/WebVTT) - WebVTT File (for video captions) +- [`wasm`](https://en.wikipedia.org/wiki/WebAssembly) - WebAssembly intermediate compiled format +- [`wav`](https://en.wikipedia.org/wiki/WAV) - Waveform Audio file +- [`webm`](https://en.wikipedia.org/wiki/WebM) - Web video file +- [`webp`](https://en.wikipedia.org/wiki/WebP) - Web Picture format +- [`woff`](https://en.wikipedia.org/wiki/Web_Open_Font_Format) - Web Open Font Format +- [`woff2`](https://en.wikipedia.org/wiki/Web_Open_Font_Format) - Web Open Font Format +- [`wv`](https://en.wikipedia.org/wiki/WavPack) - WavPack +- [`xcf`](https://en.wikipedia.org/wiki/XCF_(file_format)) - eXperimental Computing Facility +- [`xlsm`](https://en.wikipedia.org/wiki/List_of_Microsoft_Office_filename_extensions) - Microsoft Excel macro-enabled document +- [`xlsx`](https://en.wikipedia.org/wiki/Office_Open_XML) - Microsoft Excel document +- [`xltm`](https://en.wikipedia.org/wiki/List_of_Microsoft_Office_filename_extensions) - Microsoft Excel macro-enabled template +- [`xltx`](https://en.wikipedia.org/wiki/List_of_Microsoft_Office_filename_extensions) - Microsoft Excel template +- [`xm`](https://wiki.openmpt.org/Manual:_Module_formats#The_FastTracker_2_format_.28.xm.29) - Audio module format: FastTracker 2 +- [`xml`](https://en.wikipedia.org/wiki/XML) - eXtensible Markup Language +- [`xpi`](https://en.wikipedia.org/wiki/XPInstall) - XPInstall file +- [`xz`](https://en.wikipedia.org/wiki/Xz) - Compressed file +- [`zip`](https://en.wikipedia.org/wiki/Zip_(file_format)) - Archive file +- [`zst`](https://en.wikipedia.org/wiki/Zstandard) - Archive file + +*[Pull requests](.github/pull_request_template.md) are welcome for additional commonly used file types.* + +The following file types will not be accepted, but most of them are supported by [third-party detector](#available-third-party-file-type-detectors) +- [MS-CFB: Microsoft Compound File Binary File Format based formats](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cfb/53989ce4-7b05-4f8d-829b-d08d6148375b) + - `.doc` - Microsoft Word 97-2003 Document + - `.xls` - Microsoft Excel 97-2003 Document + - `.ppt` - Microsoft PowerPoint97-2003 Document + - `.msi` - Microsoft Windows Installer +- `.csv` - [Reason.](https://github.com/sindresorhus/file-type/issues/264#issuecomment-568439196) +- `.svg` + +#### tokenizer + +Type: [`ITokenizer`](https://github.com/Borewit/strtok3#tokenizer) + +Usable as source of the examined file. + +#### fileType + +Type: `FileTypeResult` + +An object having an `ext` (extension) and `mime` (mime type) property. + +Detected by the standard detections or a previous custom detection. Undefined if no matching fileTypeResult could be found. + +## Related + +- [file-type-cli](https://github.com/sindresorhus/file-type-cli) - CLI for this module +- [image-dimensions](https://github.com/sindresorhus/image-dimensions) - Get the dimensions of an image + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Borewit](https://github.com/Borewit) diff --git a/node_modules/file-type/supported.js b/node_modules/file-type/supported.js new file mode 100644 index 0000000000000000000000000000000000000000..c916afe0f3342f009679bea69911b93e95db6961 --- /dev/null +++ b/node_modules/file-type/supported.js @@ -0,0 +1,360 @@ +export const extensions = [ + 'jpg', + 'png', + 'apng', + 'gif', + 'webp', + 'flif', + 'xcf', + 'cr2', + 'cr3', + 'orf', + 'arw', + 'dng', + 'nef', + 'rw2', + 'raf', + 'tif', + 'bmp', + 'icns', + 'jxr', + 'psd', + 'indd', + 'zip', + 'tar', + 'rar', + 'gz', + 'bz2', + '7z', + 'dmg', + 'mp4', + 'mid', + 'mkv', + 'webm', + 'mov', + 'avi', + 'mpg', + 'mp2', + 'mp3', + 'm4a', + 'oga', + 'ogg', + 'ogv', + 'opus', + 'flac', + 'wav', + 'spx', + 'amr', + 'pdf', + 'epub', + 'elf', + 'macho', + 'exe', + 'swf', + 'rtf', + 'wasm', + 'woff', + 'woff2', + 'eot', + 'ttf', + 'otf', + 'ttc', + 'ico', + 'flv', + 'ps', + 'xz', + 'sqlite', + 'nes', + 'crx', + 'xpi', + 'cab', + 'deb', + 'ar', + 'rpm', + 'Z', + 'lz', + 'cfb', + 'mxf', + 'mts', + 'blend', + 'bpg', + 'docx', + 'pptx', + 'xlsx', + '3gp', + '3g2', + 'j2c', + 'jp2', + 'jpm', + 'jpx', + 'mj2', + 'aif', + 'qcp', + 'odt', + 'ods', + 'odp', + 'xml', + 'mobi', + 'heic', + 'cur', + 'ktx', + 'ape', + 'wv', + 'dcm', + 'ics', + 'glb', + 'pcap', + 'dsf', + 'lnk', + 'alias', + 'voc', + 'ac3', + 'm4v', + 'm4p', + 'm4b', + 'f4v', + 'f4p', + 'f4b', + 'f4a', + 'mie', + 'asf', + 'ogm', + 'ogx', + 'mpc', + 'arrow', + 'shp', + 'aac', + 'mp1', + 'it', + 's3m', + 'xm', + 'skp', + 'avif', + 'eps', + 'lzh', + 'pgp', + 'asar', + 'stl', + 'chm', + '3mf', + 'zst', + 'jxl', + 'vcf', + 'jls', + 'pst', + 'dwg', + 'parquet', + 'class', + 'arj', + 'cpio', + 'ace', + 'avro', + 'icc', + 'fbx', + 'vsdx', + 'vtt', + 'apk', + 'drc', + 'lz4', + 'potx', + 'xltx', + 'dotx', + 'xltm', + 'ott', + 'ots', + 'otp', + 'odg', + 'otg', + 'xlsm', + 'docm', + 'dotm', + 'potm', + 'pptm', + 'jar', + 'jmp', + 'rm', + 'sav', + 'ppsm', + 'ppsx', + 'tar.gz', + 'reg', + 'dat', +]; + +export const mimeTypes = [ + 'image/jpeg', + 'image/png', + 'image/gif', + 'image/webp', + 'image/flif', + 'image/x-xcf', + 'image/x-canon-cr2', + 'image/x-canon-cr3', + 'image/tiff', + 'image/bmp', + 'image/vnd.ms-photo', + 'image/vnd.adobe.photoshop', + 'application/x-indesign', + 'application/epub+zip', + 'application/x-xpinstall', + 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', + 'application/vnd.oasis.opendocument.text', + 'application/vnd.oasis.opendocument.spreadsheet', + 'application/vnd.oasis.opendocument.presentation', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'application/zip', + 'application/x-tar', + 'application/x-rar-compressed', + 'application/gzip', + 'application/x-bzip2', + 'application/x-7z-compressed', + 'application/x-apple-diskimage', + 'application/vnd.apache.arrow.file', + 'video/mp4', + 'audio/midi', + 'video/matroska', + 'video/webm', + 'video/quicktime', + 'video/vnd.avi', + 'audio/wav', + 'audio/qcelp', + 'audio/x-ms-asf', + 'video/x-ms-asf', + 'application/vnd.ms-asf', + 'video/mpeg', + 'video/3gpp', + 'audio/mpeg', + 'audio/mp4', // RFC 4337 + 'video/ogg', + 'audio/ogg', + 'audio/ogg; codecs=opus', + 'application/ogg', + 'audio/flac', + 'audio/ape', + 'audio/wavpack', + 'audio/amr', + 'application/pdf', + 'application/x-elf', + 'application/x-mach-binary', + 'application/x-msdownload', + 'application/x-shockwave-flash', + 'application/rtf', + 'application/wasm', + 'font/woff', + 'font/woff2', + 'application/vnd.ms-fontobject', + 'font/ttf', + 'font/otf', + 'font/collection', + 'image/x-icon', + 'video/x-flv', + 'application/postscript', + 'application/eps', + 'application/x-xz', + 'application/x-sqlite3', + 'application/x-nintendo-nes-rom', + 'application/x-google-chrome-extension', + 'application/vnd.ms-cab-compressed', + 'application/x-deb', + 'application/x-unix-archive', + 'application/x-rpm', + 'application/x-compress', + 'application/x-lzip', + 'application/x-cfb', + 'application/x-mie', + 'application/mxf', + 'video/mp2t', + 'application/x-blender', + 'image/bpg', + 'image/j2c', + 'image/jp2', + 'image/jpx', + 'image/jpm', + 'image/mj2', + 'audio/aiff', + 'application/xml', + 'application/x-mobipocket-ebook', + 'image/heif', + 'image/heif-sequence', + 'image/heic', + 'image/heic-sequence', + 'image/icns', + 'image/ktx', + 'application/dicom', + 'audio/x-musepack', + 'text/calendar', + 'text/vcard', + 'text/vtt', + 'model/gltf-binary', + 'application/vnd.tcpdump.pcap', + 'audio/x-dsf', // Non-standard + 'application/x.ms.shortcut', // Invented by us + 'application/x.apple.alias', // Invented by us + 'audio/x-voc', + 'audio/vnd.dolby.dd-raw', + 'audio/x-m4a', + 'image/apng', + 'image/x-olympus-orf', + 'image/x-sony-arw', + 'image/x-adobe-dng', + 'image/x-nikon-nef', + 'image/x-panasonic-rw2', + 'image/x-fujifilm-raf', + 'video/x-m4v', + 'video/3gpp2', + 'application/x-esri-shape', + 'audio/aac', + 'audio/x-it', + 'audio/x-s3m', + 'audio/x-xm', + 'video/MP1S', + 'video/MP2P', + 'application/vnd.sketchup.skp', + 'image/avif', + 'application/x-lzh-compressed', + 'application/pgp-encrypted', + 'application/x-asar', + 'model/stl', + 'application/vnd.ms-htmlhelp', + 'model/3mf', + 'image/jxl', + 'application/zstd', + 'image/jls', + 'application/vnd.ms-outlook', + 'image/vnd.dwg', + 'application/vnd.apache.parquet', + 'application/java-vm', + 'application/x-arj', + 'application/x-cpio', + 'application/x-ace-compressed', + 'application/avro', + 'application/vnd.iccprofile', + 'application/x.autodesk.fbx', // Invented by us + 'application/vnd.visio', + 'application/vnd.android.package-archive', + 'application/vnd.google.draco', // Invented by us + 'application/x-lz4', // Invented by us + 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'application/vnd.ms-excel.template.macroenabled.12', + 'application/vnd.oasis.opendocument.text-template', + 'application/vnd.oasis.opendocument.spreadsheet-template', + 'application/vnd.oasis.opendocument.presentation-template', + 'application/vnd.oasis.opendocument.graphics', + 'application/vnd.oasis.opendocument.graphics-template', + 'application/vnd.ms-excel.sheet.macroenabled.12', + 'application/vnd.ms-word.document.macroenabled.12', + 'application/vnd.ms-word.template.macroenabled.12', + 'application/vnd.ms-powerpoint.template.macroenabled.12', + 'application/vnd.ms-powerpoint.presentation.macroenabled.12', + 'application/java-archive', + 'application/vnd.rn-realmedia', + 'application/x-spss-sav', + 'application/x-ms-regedit', + 'application/x-ft-windows-registry-hive', + 'application/x-jmp-data', +]; diff --git a/node_modules/file-type/util.js b/node_modules/file-type/util.js new file mode 100644 index 0000000000000000000000000000000000000000..1635f20c29fb868f44eb64eba09fc95962d0dc4c --- /dev/null +++ b/node_modules/file-type/util.js @@ -0,0 +1,60 @@ +import {StringType} from 'token-types'; + +export function stringToBytes(string, encoding) { + if (encoding === 'utf-16le') { + const bytes = []; + for (let index = 0; index < string.length; index++) { + const code = string.charCodeAt(index); // eslint-disable-line unicorn/prefer-code-point + bytes.push(code & 0xFF, (code >> 8) & 0xFF); // High byte + } + + return bytes; + } + + if (encoding === 'utf-16be') { + const bytes = []; + for (let index = 0; index < string.length; index++) { + const code = string.charCodeAt(index); // eslint-disable-line unicorn/prefer-code-point + bytes.push((code >> 8) & 0xFF, code & 0xFF); // Low byte + } + + return bytes; + } + + return [...string].map(character => character.charCodeAt(0)); // eslint-disable-line unicorn/prefer-code-point +} + +/** +Checks whether the TAR checksum is valid. + +@param {Uint8Array} arrayBuffer - The TAR header `[offset ... offset + 512]`. +@param {number} offset - TAR header offset. +@returns {boolean} `true` if the TAR checksum is valid, otherwise `false`. +*/ +export function tarHeaderChecksumMatches(arrayBuffer, offset = 0) { + const readSum = Number.parseInt(new StringType(6).get(arrayBuffer, 148).replace(/\0.*$/, '').trim(), 8); // Read sum in header + if (Number.isNaN(readSum)) { + return false; + } + + let sum = 8 * 0x20; // Initialize signed bit sum + + for (let index = offset; index < offset + 148; index++) { + sum += arrayBuffer[index]; + } + + for (let index = offset + 156; index < offset + 512; index++) { + sum += arrayBuffer[index]; + } + + return readSum === sum; +} + +/** +ID3 UINT32 sync-safe tokenizer token. +28 bits (representing up to 256MB) integer, the msb is 0 to avoid "false syncsignals". +*/ +export const uint32SyncSafeToken = { + get: (buffer, offset) => (buffer[offset + 3] & 0x7F) | ((buffer[offset + 2]) << 7) | ((buffer[offset + 1]) << 14) | ((buffer[offset]) << 21), + len: 4, +}; diff --git a/node_modules/file-uri-to-path/.npmignore b/node_modules/file-uri-to-path/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..07e6e472cc75fafa944e2a6d4b0f101bc476c060 --- /dev/null +++ b/node_modules/file-uri-to-path/.npmignore @@ -0,0 +1 @@ +/node_modules diff --git a/node_modules/file-uri-to-path/.travis.yml b/node_modules/file-uri-to-path/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..016bb6e7ce4c538e596c8c6ab226b029848f6faa --- /dev/null +++ b/node_modules/file-uri-to-path/.travis.yml @@ -0,0 +1,30 @@ +sudo: false + +language: node_js + +node_js: + - "0.8" + - "0.10" + - "0.12" + - "1" + - "2" + - "3" + - "4" + - "5" + - "6" + - "7" + - "8" + +install: + - PATH="`npm bin`:`npm bin -g`:$PATH" + # Node 0.8 comes with a too obsolete npm + - if [[ "`node --version`" =~ ^v0\.8\. ]]; then npm install -g npm@1.4.28 ; fi + # Install dependencies and build + - npm install + +script: + # Output useful info for debugging + - node --version + - npm --version + # Run tests + - npm test diff --git a/node_modules/file-uri-to-path/History.md b/node_modules/file-uri-to-path/History.md new file mode 100644 index 0000000000000000000000000000000000000000..c8682be48228cd42c14d5a05b6199f536301bc29 --- /dev/null +++ b/node_modules/file-uri-to-path/History.md @@ -0,0 +1,21 @@ + +1.0.0 / 2017-07-06 +================== + + * update "mocha" to v3 + * fixed unicode URI decoding (#6) + * add typings for Typescript + * README: use SVG Travis-CI badge + * add LICENSE file (MIT) + * add .travis.yml file (testing Node.js 0.8 through 8 currently) + * add README.md file + +0.0.2 / 2014-01-27 +================== + + * index: invert the path separators on Windows + +0.0.1 / 2014-01-27 +================== + + * initial commit diff --git a/node_modules/file-uri-to-path/LICENSE b/node_modules/file-uri-to-path/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e1af78389b2250b3a587fa5a0bd1d15d38002e3e --- /dev/null +++ b/node_modules/file-uri-to-path/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2014 Nathan Rajlich + +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. diff --git a/node_modules/file-uri-to-path/README.md b/node_modules/file-uri-to-path/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ab30be8f326d0da390a4c3063d59c9f90c91140c --- /dev/null +++ b/node_modules/file-uri-to-path/README.md @@ -0,0 +1,74 @@ +file-uri-to-path +================ +### Convert a `file:` URI to a file path +[![Build Status](https://travis-ci.org/TooTallNate/file-uri-to-path.svg?branch=master)](https://travis-ci.org/TooTallNate/file-uri-to-path) + +Accepts a `file:` URI and returns a regular file path suitable for use with the +`fs` module functions. + + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install file-uri-to-path +``` + + +Example +------- + +``` js +var uri2path = require('file-uri-to-path'); + +uri2path('file://localhost/c|/WINDOWS/clock.avi'); +// "c:\\WINDOWS\\clock.avi" + +uri2path('file:///c|/WINDOWS/clock.avi'); +// "c:\\WINDOWS\\clock.avi" + +uri2path('file://localhost/c:/WINDOWS/clock.avi'); +// "c:\\WINDOWS\\clock.avi" + +uri2path('file://hostname/path/to/the%20file.txt'); +// "\\\\hostname\\path\\to\\the file.txt" + +uri2path('file:///c:/path/to/the%20file.txt'); +// "c:\\path\\to\\the file.txt" +``` + + +API +--- + +### fileUriToPath(String uri) → String + + + +License +------- + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich <nathan@tootallnate.net> + +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. diff --git a/node_modules/file-uri-to-path/index.d.ts b/node_modules/file-uri-to-path/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..99dc3f966bce204ee0e05cfcf3af43b5437e2db4 --- /dev/null +++ b/node_modules/file-uri-to-path/index.d.ts @@ -0,0 +1,2 @@ +declare function fileUriToPath(uri: string): string; +export = fileUriToPath; diff --git a/node_modules/file-uri-to-path/index.js b/node_modules/file-uri-to-path/index.js new file mode 100644 index 0000000000000000000000000000000000000000..48cb280c04c3ae94fea36b5a54c757fbd3a91637 --- /dev/null +++ b/node_modules/file-uri-to-path/index.js @@ -0,0 +1,66 @@ + +/** + * Module dependencies. + */ + +var sep = require('path').sep || '/'; + +/** + * Module exports. + */ + +module.exports = fileUriToPath; + +/** + * File URI to Path function. + * + * @param {String} uri + * @return {String} path + * @api public + */ + +function fileUriToPath (uri) { + if ('string' != typeof uri || + uri.length <= 7 || + 'file://' != uri.substring(0, 7)) { + throw new TypeError('must pass in a file:// URI to convert to a file path'); + } + + var rest = decodeURI(uri.substring(7)); + var firstSlash = rest.indexOf('/'); + var host = rest.substring(0, firstSlash); + var path = rest.substring(firstSlash + 1); + + // 2. Scheme Definition + // As a special case, can be the string "localhost" or the empty + // string; this is interpreted as "the machine from which the URL is + // being interpreted". + if ('localhost' == host) host = ''; + + if (host) { + host = sep + sep + host; + } + + // 3.2 Drives, drive letters, mount points, file system root + // Drive letters are mapped into the top of a file URI in various ways, + // depending on the implementation; some applications substitute + // vertical bar ("|") for the colon after the drive letter, yielding + // "file:///c|/tmp/test.txt". In some cases, the colon is left + // unchanged, as in "file:///c:/tmp/test.txt". In other cases, the + // colon is simply omitted, as in "file:///c/tmp/test.txt". + path = path.replace(/^(.+)\|/, '$1:'); + + // for Windows, we need to invert the path separators from what a URI uses + if (sep == '\\') { + path = path.replace(/\//g, '\\'); + } + + if (/^.+\:/.test(path)) { + // has Windows drive at beginning of path + } else { + // unix path… + path = sep + path; + } + + return host + path; +} diff --git a/node_modules/file-uri-to-path/package.json b/node_modules/file-uri-to-path/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b6a4a0752ec3603d52d11c4daa2a4ae0cf0a7ad7 --- /dev/null +++ b/node_modules/file-uri-to-path/package.json @@ -0,0 +1,32 @@ +{ + "name": "file-uri-to-path", + "version": "1.0.0", + "description": "Convert a file: URI to a file path", + "main": "index.js", + "types": "index.d.ts", + "directories": { + "test": "test" + }, + "scripts": { + "test": "mocha --reporter spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/file-uri-to-path.git" + }, + "keywords": [ + "file", + "uri", + "convert", + "path" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/file-uri-to-path/issues" + }, + "homepage": "https://github.com/TooTallNate/file-uri-to-path", + "devDependencies": { + "mocha": "3" + } +} diff --git a/node_modules/file-uri-to-path/test/test.js b/node_modules/file-uri-to-path/test/test.js new file mode 100644 index 0000000000000000000000000000000000000000..79305dcae2492e76f0cefc8fe1ff566eb878b7b6 --- /dev/null +++ b/node_modules/file-uri-to-path/test/test.js @@ -0,0 +1,24 @@ + +var sep = require('path').sep || '/'; +var assert = require('assert'); +var uri2path = require('../'); +var tests = require('./tests.json'); + +describe('file-uri-to-path', function () { + + Object.keys(tests).forEach(function (uri) { + + // the test cases were generated from Windows' PathCreateFromUrlA() function. + // On Unix, we have to replace the path separator with the Unix one instead of + // the Windows one. + var expected = tests[uri].replace(/\\/g, sep); + + it('should convert ' + JSON.stringify(uri) + ' to ' + JSON.stringify(expected), + function () { + var actual = uri2path(uri); + assert.equal(actual, expected); + }); + + }); + +}); diff --git a/node_modules/file-uri-to-path/test/tests.json b/node_modules/file-uri-to-path/test/tests.json new file mode 100644 index 0000000000000000000000000000000000000000..b935a639a30e60b43b9648d42febe2f4ed8854e0 --- /dev/null +++ b/node_modules/file-uri-to-path/test/tests.json @@ -0,0 +1,13 @@ +{ + "file://host/path": "\\\\host\\path", + "file://localhost/etc/fstab": "\\etc\\fstab", + "file:///etc/fstab": "\\etc\\fstab", + "file:///c:/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi", + "file://localhost/c|/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi", + "file:///c|/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi", + "file://localhost/c:/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi", + "file://hostname/path/to/the%20file.txt": "\\\\hostname\\path\\to\\the file.txt", + "file:///c:/path/to/the%20file.txt": "c:\\path\\to\\the file.txt", + "file:///C:/Documents%20and%20Settings/davris/FileSchemeURIs.doc": "C:\\Documents and Settings\\davris\\FileSchemeURIs.doc", + "file:///C:/caf%C3%A9/%C3%A5r/d%C3%BCnn/%E7%89%9B%E9%93%83/Ph%E1%BB%9F/%F0%9F%98%B5.exe": "C:\\café\\år\\dünn\\牛铃\\Phở\\😵.exe" +} diff --git a/node_modules/filelist/README.md b/node_modules/filelist/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b52ebe7c5a7069864565b774426d021ec65e5fe2 --- /dev/null +++ b/node_modules/filelist/README.md @@ -0,0 +1,84 @@ +## FileList + +A FileList is a lazy-evaluated list of files. When given a list +of glob patterns for possible files to be included in the file +list, instead of searching the file structures to find the files, +a FileList holds the pattern for latter use. + +This allows you to define a FileList to match any number of +files, but only search out the actual files when then FileList +itself is actually used. The key is that the first time an +element of the FileList/Array is requested, the pending patterns +are resolved into a real list of file names. + +### Usage + +Add files to the list with the `include` method. You can add glob +patterns, individual files, or RegExp objects. When the Array +methods are invoked on the FileList, these items are resolved to +an actual list of files. + +```javascript +var fl = new FileList(); +fl.include('test/*.js'); +fl.exclude('test/helpers.js'); +``` + +Use the `exclude` method to override inclusions. You can use this +when your inclusions are too broad. + +### Array methods + +FileList has lazy-evaluated versions of most of the array +methods, including the following: + +* join +* pop +* push +* concat +* reverse +* shift +* unshift +* slice +* splice +* sort +* filter +* forEach +* some +* every +* map +* indexOf +* lastIndexOf +* reduce +* reduceRight + +When you call one of these methods, the items in the FileList +will be resolved to the full list of files, and the method will +be invoked on that result. + +### Special `length` method + +`length`: FileList includes a length *method* (instead of a +property) which returns the number of actual files in the list +once it's been resolved. + +### FileList-specific methods + +`include`: Add a filename/glob/regex to the list + +`exclude`: Override inclusions by excluding a filename/glob/regex + +`resolve`: Resolve the items in the FileList to the full list of +files. This method is invoked automatically when one of the array +methods is called. + +`toArray`: Immediately resolves the list of items, and returns an +actual array of filepaths. + +`clearInclusions`: Clears any pending items -- must be used +before resolving the list. + +`clearExclusions`: Clears the list of exclusions rules. + + + diff --git a/node_modules/filelist/index.d.ts b/node_modules/filelist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a6addf28ca0b05e613a4ee0c34adf4131ed3b46b --- /dev/null +++ b/node_modules/filelist/index.d.ts @@ -0,0 +1,110 @@ +// IncludeOptions definitions copied from minimatch (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/minimatch/index.d.ts) +interface IncludeOptions { + /** + * Dump a ton of stuff to stderr. + * + * @default false + */ + debug?: boolean; + + /** + * Do not expand {a,b} and {1..3} brace sets. + * + * @default false + */ + nobrace?: boolean; + + /** + * Disable ** matching against multiple folder names. + * + * @default false + */ + noglobstar?: boolean; + + /** + * Allow patterns to match filenames starting with a period, + * even if the pattern does not explicitly have a period in that spot. + * + * @default false + */ + dot?: boolean; + + /** + * Disable "extglob" style patterns like +(a|b). + * + * @default false + */ + noext?: boolean; + + /** + * Perform a case-insensitive match. + * + * @default false + */ + nocase?: boolean; + + /** + * When a match is not found by minimatch.match, + * return a list containing the pattern itself if this option is set. + * Otherwise, an empty list is returned if there are no matches. + * + * @default false + */ + nonull?: boolean; + + /** + * If set, then patterns without slashes will be matched against + * the basename of the path if it contains slashes. + * + * @default false + */ + matchBase?: boolean; + + /** + * Suppress the behavior of treating # + * at the start of a pattern as a comment. + * + * @default false + */ + nocomment?: boolean; + + /** + * Suppress the behavior of treating a leading ! character as negation. + * + * @default false + */ + nonegate?: boolean; + + /** + * Returns from negate expressions the same as if they were not negated. + * (Ie, true on a hit, false on a miss.) + * + * @default false + */ + flipNegate?: boolean; +} + +export class FileList { + static clone(): FileList + static verbose: boolean +} + +export interface FileList extends Omit, "length"> { + pendingAdd: string[] + pending: boolean + excludes: { + pats: RegExp[], + funcs: Function[], + regex: null | RegExp + } + items: string[] + toArray(): string[] + include(...items: string[]): this + include(...items: (IncludeOptions | string)[]): this + exclude(...items: string[]): this + shouldExclude(item: string): boolean + resolve(): this + clearInclusions(): this + clearExclusions(): this + length(): number +} \ No newline at end of file diff --git a/node_modules/filelist/index.js b/node_modules/filelist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..34ca389745f6b1548d2f4a8102aa6bf0fc843eab --- /dev/null +++ b/node_modules/filelist/index.js @@ -0,0 +1,495 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +var fs = require('fs') +, path = require('path') +, minimatch = require('minimatch') +, escapeRegExpChars +, merge +, basedir +, _readDir +, readdirR +, globSync; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var hasOwn = function (obj, key) { return hasOwnProperty.apply(obj, [key]); }; + + /** + @name escapeRegExpChars + @function + @return {String} A string of escaped characters + @description Escapes regex control-characters in strings + used to build regexes dynamically + @param {String} string The string of chars to escape + */ + escapeRegExpChars = (function () { + var specials = [ '^', '$', '/', '.', '*', '+', '?', '|', '(', ')', + '[', ']', '{', '}', '\\' ]; + var sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); + return function (string) { + var str = string || ''; + str = String(str); + return str.replace(sRE, '\\$1'); + }; + })(); + + /** + @name merge + @function + @return {Object} Returns the merged object + @description Merge merges `otherObject` into `object` and takes care of deep + merging of objects + @param {Object} object Object to merge into + @param {Object} otherObject Object to read from + */ + merge = function (object, otherObject) { + var obj = object || {} + , otherObj = otherObject || {} + , key, value; + + for (key in otherObj) { + + if (!hasOwn(otherObj, key)) { + continue; + } + if (key === '__proto__' || key === 'constructor') { + continue; + } + + value = otherObj[key]; + // Check if a value is an Object, if so recursively add it's key/values + if (typeof value === 'object' && !(value instanceof Array)) { + // Update value of object to the one from otherObj + obj[key] = merge(obj[key], value); + } + // Value is anything other than an Object, so just add it + else { + obj[key] = value; + } + } + + return obj; + }; + /** + Given a patern, return the base directory of it (ie. the folder + that will contain all the files matching the path). + eg. file.basedir('/test/**') => '/test/' + Path ending by '/' are considerd as folder while other are considerd + as files, eg.: + file.basedir('/test/a/') => '/test/a' + file.basedir('/test/a') => '/test' + The returned path always end with a '/' so we have: + file.basedir(file.basedir(x)) == file.basedir(x) + */ + basedir = function (pathParam) { + var bd = '' + , parts + , part + , pos = 0 + , p = pathParam || ''; + + // If the path has a leading asterisk, basedir is the current dir + if (p.indexOf('*') == 0 || p.indexOf('**') == 0) { + return '.'; + } + + // always consider .. at the end as a folder and not a filename + if (/(?:^|\/|\\)\.\.$/.test(p.slice(-3))) { + p += '/'; + } + + parts = p.split(/\\|\//); + for (var i = 0, l = parts.length - 1; i < l; i++) { + part = parts[i]; + if (part.indexOf('*') > -1 || part.indexOf('**') > -1) { + break; + } + pos += part.length + 1; + bd += part + p[pos - 1]; + } + if (!bd) { + bd = '.'; + } + // Strip trailing slashes + if (!(bd == '\\' || bd == '/')) { + bd = bd.replace(/\\$|\/$/, ''); + } + return bd; + + }; + + // Return the contents of a given directory + _readDir = function (dirPath) { + var dir = path.normalize(dirPath) + , paths = [] + , ret = [dir] + , msg; + + try { + paths = fs.readdirSync(dir); + } + catch (e) { + msg = 'Could not read path ' + dir + '\n'; + if (e.stack) { + msg += e.stack; + } + throw new Error(msg); + } + + paths.forEach(function (p) { + var curr = path.join(dir, p); + var stat = fs.statSync(curr); + if (stat.isDirectory()) { + ret = ret.concat(_readDir(curr)); + } + else { + ret.push(curr); + } + }); + + return ret; + }; + + /** + @name file#readdirR + @function + @return {Array} Returns the contents as an Array, can be configured via opts.format + @description Reads the given directory returning it's contents + @param {String} dir The directory to read + @param {Object} opts Options to use + @param {String} [opts.format] Set the format to return(Default: Array) + */ + readdirR = function (dir, opts) { + var options = opts || {} + , format = options.format || 'array' + , ret; + ret = _readDir(dir); + return format == 'string' ? ret.join('\n') : ret; + }; + + +globSync = function (pat, opts) { + var dirname = basedir(pat) + , files + , matches; + + try { + files = readdirR(dirname).map(function(file){ + return file.replace(/\\/g, '/'); + }); + } + // Bail if path doesn't exist -- assume no files + catch(e) { + if (FileList.verbose) console.error(e.message); + } + + if (files) { + pat = path.normalize(pat); + matches = minimatch.match(files, pat, opts || {}); + } + return matches || []; +}; + +// Constants +// --------------- +// List of all the builtin Array methods we want to override +var ARRAY_METHODS = Object.getOwnPropertyNames(Array.prototype) +// Array methods that return a copy instead of affecting the original + , SPECIAL_RETURN = { + 'concat': true + , 'slice': true + , 'filter': true + , 'map': true + } +// Default file-patterns we want to ignore + , DEFAULT_IGNORE_PATTERNS = [ + /(^|[\/\\])CVS([\/\\]|$)/ + , /(^|[\/\\])\.svn([\/\\]|$)/ + , /(^|[\/\\])\.git([\/\\]|$)/ + , /\.bak$/ + , /~$/ + ] +// Ignore core files + , DEFAULT_IGNORE_FUNCS = [ + function (name) { + var isDir = false + , stats; + try { + stats = fs.statSync(name); + isDir = stats.isDirectory(); + } + catch(e) {} + return (/(^|[\/\\])core$/).test(name) && !isDir; + } + ]; + +var FileList = function () { + var self = this + , wrap; + + // List of glob-patterns or specific filenames + this.pendingAdd = []; + // Switched to false after lazy-eval of files + this.pending = true; + // Used to calculate exclusions from the list of files + this.excludes = { + pats: DEFAULT_IGNORE_PATTERNS.slice() + , funcs: DEFAULT_IGNORE_FUNCS.slice() + , regex: null + }; + this.items = []; + + // Wrap the array methods with the delegates + wrap = function (prop) { + var arr; + self[prop] = function () { + if (self.pending) { + self.resolve(); + } + if (typeof self.items[prop] == 'function') { + // Special method that return a copy + if (SPECIAL_RETURN[prop]) { + arr = self.items[prop].apply(self.items, arguments); + return FileList.clone(self, arr); + } + else { + return self.items[prop].apply(self.items, arguments); + } + } + else { + return self.items[prop]; + } + }; + }; + for (var i = 0, ii = ARRAY_METHODS.length; i < ii; i++) { + wrap(ARRAY_METHODS[i]); + } + + // Include whatever files got passed to the constructor + this.include.apply(this, arguments); + + // Fix constructor linkage + this.constructor = FileList; +}; + +FileList.prototype = new (function () { + var globPattern = /[*?\[\{]/; + + var _addMatching = function (item) { + var matches = globSync(item.path, item.options); + this.items = this.items.concat(matches); + } + + , _resolveAdd = function (item) { + if (globPattern.test(item.path)) { + _addMatching.call(this, item); + } + else { + this.push(item.path); + } + } + + , _calculateExcludeRe = function () { + var pats = this.excludes.pats + , pat + , excl = [] + , matches = []; + + for (var i = 0, ii = pats.length; i < ii; i++) { + pat = pats[i]; + if (typeof pat == 'string') { + // Glob, look up files + if (/[*?]/.test(pat)) { + matches = globSync(pat); + matches = matches.map(function (m) { + return escapeRegExpChars(m); + }); + excl = excl.concat(matches); + } + // String for regex + else { + excl.push(escapeRegExpChars(pat)); + } + } + // Regex, grab the string-representation + else if (pat instanceof RegExp) { + excl.push(pat.toString().replace(/^\/|\/$/g, '')); + } + } + if (excl.length) { + this.excludes.regex = new RegExp('(' + excl.join(')|(') + ')'); + } + else { + this.excludes.regex = /^$/; + } + } + + , _resolveExclude = function () { + var self = this; + _calculateExcludeRe.call(this); + // No `reject` method, so use reverse-filter + this.items = this.items.filter(function (name) { + return !self.shouldExclude(name); + }); + }; + + /** + * Includes file-patterns in the FileList. Should be called with one or more + * pattern for finding file to include in the list. Arguments should be strings + * for either a glob-pattern or a specific file-name, or an array of them + */ + this.include = function () { + var args = Array.prototype.slice.call(arguments) + , arg + , includes = { items: [], options: {} }; + + for (var i = 0, ilen = args.length; i < ilen; i++) { + arg = args[i]; + + if (typeof arg === 'object' && !Array.isArray(arg)) { + merge(includes.options, arg); + } else { + includes.items = includes.items.concat(arg).filter(function (item) { + return !!item; + }); + } + } + + var items = includes.items.map(function(item) { + return { path: item, options: includes.options }; + }); + + this.pendingAdd = this.pendingAdd.concat(items); + + return this; + }; + + /** + * Indicates whether a particular file would be filtered out by the current + * exclusion rules for this FileList. + * @param {String} name The filename to check + * @return {Boolean} Whether or not the file should be excluded + */ + this.shouldExclude = function (name) { + if (!this.excludes.regex) { + _calculateExcludeRe.call(this); + } + var excl = this.excludes; + return excl.regex.test(name) || excl.funcs.some(function (f) { + return !!f(name); + }); + }; + + /** + * Excludes file-patterns from the FileList. Should be called with one or more + * pattern for finding file to include in the list. Arguments can be: + * 1. Strings for either a glob-pattern or a specific file-name + * 2. Regular expression literals + * 3. Functions to be run on the filename that return a true/false + */ + this.exclude = function () { + var args = Array.isArray(arguments[0]) ? arguments[0] : arguments + , arg; + for (var i = 0, ii = args.length; i < ii; i++) { + arg = args[i]; + if (typeof arg == 'function' && !(arg instanceof RegExp)) { + this.excludes.funcs.push(arg); + } + else { + this.excludes.pats.push(arg); + } + } + if (!this.pending) { + _resolveExclude.call(this); + } + return this; + }; + + /** + * Populates the FileList from the include/exclude rules with a list of + * actual files + */ + this.resolve = function () { + var item + , uniqueFunc = function (p, c) { + if (p.indexOf(c) < 0) { + p.push(c); + } + return p; + }; + if (this.pending) { + this.pending = false; + while ((item = this.pendingAdd.shift())) { + _resolveAdd.call(this, item); + } + // Reduce to a unique list + this.items = this.items.reduce(uniqueFunc, []); + // Remove exclusions + _resolveExclude.call(this); + } + return this; + }; + + /** + * Convert to a plain-jane array + */ + this.toArray = function () { + // Call slice to ensure lazy-resolution before slicing items + var ret = this.slice().items.slice(); + return ret; + }; + + /** + * Clear any pending items -- only useful before + * calling `resolve` + */ + this.clearInclusions = function () { + this.pendingAdd = []; + return this; + }; + + /** + * Clear any current exclusion rules + */ + this.clearExclusions = function () { + this.excludes = { + pats: [] + , funcs: [] + , regex: null + }; + return this; + }; + +})(); + +// Static method, used to create copy returned by special +// array methods +FileList.clone = function (list, items) { + var clone = new FileList(); + if (items) { + clone.items = items; + } + clone.pendingAdd = list.pendingAdd; + clone.pending = list.pending; + for (var p in list.excludes) { + clone.excludes[p] = list.excludes[p]; + } + return clone; +}; + +FileList.verbose = true + +exports.FileList = FileList; diff --git a/node_modules/filelist/jakefile.js b/node_modules/filelist/jakefile.js new file mode 100644 index 0000000000000000000000000000000000000000..18d4d7df09a3cdf3d4c428331369a1f274025053 --- /dev/null +++ b/node_modules/filelist/jakefile.js @@ -0,0 +1,15 @@ +testTask('FileList', function () { + this.testFiles.include('test/*.js'); +}); + +publishTask('FileList', function () { + this.packageFiles.include([ + 'jakefile.js', + 'README.md', + 'package.json', + 'index.js', + 'index.d.ts' + ]); +}); + + diff --git a/node_modules/filelist/package.json b/node_modules/filelist/package.json new file mode 100644 index 0000000000000000000000000000000000000000..940b57db80048daaa25cf0500e8edd6d074ef2ee --- /dev/null +++ b/node_modules/filelist/package.json @@ -0,0 +1,28 @@ +{ + "name": "filelist", + "version": "1.0.6", + "description": "Lazy-evaluating list of files, based on globs or regex patterns", + "main": "index.js", + "types": "index.d.ts", + "scripts": { + "test": "jake test" + }, + "repository": { + "type": "git", + "url": "git://github.com/mde/filelist.git" + }, + "keywords": [ + "file", + "utility", + "glob" + ], + "author": "Matthew Eernisse (http://fleegix.org)", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/mde/filelist/issues" + }, + "homepage": "https://github.com/mde/filelist", + "dependencies": { + "minimatch": "^5.0.1" + } +} diff --git a/node_modules/fill-range/LICENSE b/node_modules/fill-range/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9af4a67d206f24ecdbb5fdff2839041ca0bbd346 --- /dev/null +++ b/node_modules/fill-range/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +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. diff --git a/node_modules/fill-range/README.md b/node_modules/fill-range/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8d756fe9016aec005378ea1b61e599d944ffa4d3 --- /dev/null +++ b/node_modules/fill-range/README.md @@ -0,0 +1,237 @@ +# fill-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/fill-range.svg?style=flat)](https://www.npmjs.com/package/fill-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![NPM total downloads](https://img.shields.io/npm/dt/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/fill-range.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/fill-range) + +> Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex` + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save fill-range +``` + +## Usage + +Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_. + +```js +const fill = require('fill-range'); +// fill(from, to[, step, options]); + +console.log(fill('1', '10')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] +console.log(fill('1', '10', { toRegex: true })); //=> [1-9]|10 +``` + +**Params** + +* `from`: **{String|Number}** the number or letter to start with +* `to`: **{String|Number}** the number or letter to end with +* `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use. +* `options`: **{Object|Function}**: See all available [options](#options) + +## Examples + +By default, an array of values is returned. + +**Alphabetical ranges** + +```js +console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e'] +console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ] +``` + +**Numerical ranges** + +Numbers can be defined as actual numbers or strings. + +```js +console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] +console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ] +``` + +**Negative ranges** + +Numbers can be defined as actual numbers or strings. + +```js +console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ] +console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ] +``` + +**Steps (increments)** + +```js +// numerical ranges with increments +console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ] +console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ] +console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ] + +// alphabetical ranges with increments +console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ] +console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] +console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ] +``` + +## Options + +### options.step + +**Type**: `number` (formatted as a string or number) + +**Default**: `undefined` + +**Description**: The increment to use for the range. Can be used with letters or numbers. + +**Example(s)** + +```js +// numbers +console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ] +console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ] +console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ] + +// letters +console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] +console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ] +console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ] +``` + +### options.strictRanges + +**Type**: `boolean` + +**Default**: `false` + +**Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges. + +**Example(s)** + +The following are all invalid: + +```js +fill('1.1', '2'); // decimals not supported in ranges +fill('a', '2'); // incompatible range values +fill(1, 10, 'foo'); // invalid "step" argument +``` + +### options.stringify + +**Type**: `boolean` + +**Default**: `undefined` + +**Description**: Cast all returned values to strings. By default, integers are returned as numbers. + +**Example(s)** + +```js +console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] +console.log(fill(1, 5, { stringify: true })); //=> [ '1', '2', '3', '4', '5' ] +``` + +### options.toRegex + +**Type**: `boolean` + +**Default**: `undefined` + +**Description**: Create a regex-compatible source string, instead of expanding values to an array. + +**Example(s)** + +```js +// alphabetical range +console.log(fill('a', 'e', { toRegex: true })); //=> '[a-e]' +// alphabetical with step +console.log(fill('a', 'z', 3, { toRegex: true })); //=> 'a|d|g|j|m|p|s|v|y' +// numerical range +console.log(fill('1', '100', { toRegex: true })); //=> '[1-9]|[1-9][0-9]|100' +// numerical range with zero padding +console.log(fill('000001', '100000', { toRegex: true })); +//=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000' +``` + +### options.transform + +**Type**: `function` + +**Default**: `undefined` + +**Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_. + +**Example(s)** + +```js +// add zero padding +console.log(fill(1, 5, value => String(value).padStart(4, '0'))); +//=> ['0001', '0002', '0003', '0004', '0005'] +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 116 | [jonschlinkert](https://github.com/jonschlinkert) | +| 4 | [paulmillr](https://github.com/paulmillr) | +| 2 | [realityking](https://github.com/realityking) | +| 2 | [bluelovers](https://github.com/bluelovers) | +| 1 | [edorivai](https://github.com/edorivai) | +| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! + + + + + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ \ No newline at end of file diff --git a/node_modules/fill-range/index.js b/node_modules/fill-range/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ddb212ee2873d7c13624c47265c56f38fbb4ed1c --- /dev/null +++ b/node_modules/fill-range/index.js @@ -0,0 +1,248 @@ +/*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. + */ + +'use strict'; + +const util = require('util'); +const toRegexRange = require('to-regex-range'); + +const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); + +const transform = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; + +const isValidValue = value => { + return typeof value === 'number' || (typeof value === 'string' && value !== ''); +}; + +const isNumber = num => Number.isInteger(+num); + +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + while (value[++index] === '0'); + return index > 0; +}; + +const stringify = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + return options.stringify === true; +}; + +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); + } + if (toNumber === false) { + return String(input); + } + return input; +}; + +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) input = '0' + input; + return negative ? ('-' + input) : input; +}; + +const toSequence = (parts, options, maxLen) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; + + if (parts.positives.length) { + positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); + } + + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; + } + + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + + if (options.wrap) { + return `(${prefix}${result})`; + } + + return result; +}; + +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange(a, b, { wrap: false, ...options }); + } + + let start = String.fromCharCode(a); + if (a === b) return start; + + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; + +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + return toRegexRange(start, end, options); +}; + +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util.inspect(...args)); +}; + +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; + +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; +}; + +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } + + // fix negative zero + if (a === 0) a = 0; + if (b === 0) b = 0; + + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify(start, end, options) === false; + let format = options.transform || transform(toNumber); + + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + + let parts = { negatives: [], positives: [] }; + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return step > 1 + ? toSequence(parts, options, maxLen) + : toRegex(range, null, { wrap: false, ...options }); + } + + return range; +}; + +const fillLetters = (start, end, step = 1, options = {}) => { + if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { + return invalidRange(start, end, options); + } + + let format = options.transform || (val => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); + } + + return range; +}; + +const fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } + + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } + + if (typeof step === 'function') { + return fill(start, end, 1, { transform: step }); + } + + if (isObject(step)) { + return fill(start, end, 0, step); + } + + let opts = { ...options }; + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; + + if (!isNumber(step)) { + if (step != null && !isObject(step)) return invalidStep(step, opts); + return fill(start, end, 1, step); + } + + if (isNumber(start) && isNumber(end)) { + return fillNumbers(start, end, step, opts); + } + + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; + +module.exports = fill; diff --git a/node_modules/fill-range/package.json b/node_modules/fill-range/package.json new file mode 100644 index 0000000000000000000000000000000000000000..582357fb50baf6d7ceb473732ae6f2179ab4ff7b --- /dev/null +++ b/node_modules/fill-range/package.json @@ -0,0 +1,74 @@ +{ + "name": "fill-range", + "description": "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`", + "version": "7.1.1", + "homepage": "https://github.com/jonschlinkert/fill-range", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Edo Rivai (edo.rivai.nl)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Paul Miller (paulmillr.com)", + "Rouven Weßling (www.rouvenwessling.de)", + "(https://github.com/wtgtybhertgeghgtwtg)" + ], + "repository": "jonschlinkert/fill-range", + "bugs": { + "url": "https://github.com/jonschlinkert/fill-range/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=8" + }, + "scripts": { + "lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .", + "mocha": "mocha --reporter dot", + "test": "npm run lint && npm run mocha", + "test:ci": "npm run test:cover", + "test:cover": "nyc npm run mocha" + }, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "devDependencies": { + "gulp-format-md": "^2.0.0", + "mocha": "^6.1.1", + "nyc": "^15.1.0" + }, + "keywords": [ + "alpha", + "alphabetical", + "array", + "bash", + "brace", + "expand", + "expansion", + "fill", + "glob", + "match", + "matches", + "matching", + "number", + "numerical", + "range", + "ranges", + "regex", + "sh" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/finalhandler/HISTORY.md b/node_modules/finalhandler/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..77ce54d15f4dcb44d751c7d27c44af29eb8e8fa4 --- /dev/null +++ b/node_modules/finalhandler/HISTORY.md @@ -0,0 +1,216 @@ +v1.3.2 / 2025-12-01 +================== + + * deps: use tilde notation for dependencies + * deps: statuses@~2.0.2 + +v1.3.1 / 2024-09-11 +================== + + * deps: encodeurl@~2.0.0 + +v1.3.0 / 2024-09-03 +================== + + * ignore status message for HTTP/2 (#53) + +v1.2.1 / 2024-09-02 +================== + + * Gracefully handle when handling an error and socket is null + +1.2.0 / 2022-03-22 +================== + + * Remove set content headers that break response + * deps: on-finished@2.4.1 + * deps: statuses@2.0.1 + - Rename `425 Unordered Collection` to standard `425 Too Early` + +1.1.2 / 2019-05-09 +================== + + * Set stricter `Content-Security-Policy` header + * deps: parseurl@~1.3.3 + * deps: statuses@~1.5.0 + +1.1.1 / 2018-03-06 +================== + + * Fix 404 output for bad / missing pathnames + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +1.1.0 / 2017-09-24 +================== + + * Use `res.headersSent` when available + +1.0.6 / 2017-09-22 +================== + + * deps: debug@2.6.9 + +1.0.5 / 2017-09-15 +================== + + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + +1.0.4 / 2017-08-03 +================== + + * deps: debug@2.6.8 + +1.0.3 / 2017-05-16 +================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + +1.0.2 / 2017-04-22 +================== + + * deps: debug@2.6.4 + - deps: ms@0.7.3 + +1.0.1 / 2017-03-21 +================== + + * Fix missing `` in HTML document + * deps: debug@2.6.3 + - Fix: `DEBUG_MAX_ARRAY_LENGTH` + +1.0.0 / 2017-02-15 +================== + + * Fix exception when `err` cannot be converted to a string + * Fully URL-encode the pathname in the 404 message + * Only include the pathname in the 404 message + * Send complete HTML document + * Set `Content-Security-Policy: default-src 'self'` header + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + +0.5.1 / 2016-11-12 +================== + + * Fix exception when `err.headers` is not an object + * deps: statuses@~1.3.1 + * perf: hoist regular expressions + * perf: remove duplicate validation path + +0.5.0 / 2016-06-15 +================== + + * Change invalid or non-numeric status code to 500 + * Overwrite status message to match set status code + * Prefer `err.statusCode` if `err.status` is invalid + * Set response headers from `err.headers` object + * Use `statuses` instead of `http` module for status messages + - Includes all defined status messages + +0.4.1 / 2015-12-02 +================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + +0.4.0 / 2015-06-14 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + * Support `statusCode` property on `Error` objects + * Use `unpipe` module for unpiping requests + * deps: escape-html@1.0.2 + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove argument reassignment + +0.3.6 / 2015-05-11 +================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + +0.3.5 / 2015-04-22 +================== + + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + +0.3.4 / 2015-03-15 +================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.3.3 / 2015-01-01 +================== + + * deps: debug@~2.1.1 + * deps: on-finished@~2.2.0 + +0.3.2 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.3.1 / 2014-10-16 +================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + +0.3.0 / 2014-09-17 +================== + + * Terminate in progress response only on error + * Use `on-finished` to determine request status + +0.2.0 / 2014-09-03 +================== + + * Set `X-Content-Type-Options: nosniff` header + * deps: debug@~2.0.0 + +0.1.0 / 2014-07-16 +================== + + * Respond after request fully read + - prevents hung responses and socket hang ups + * deps: debug@1.0.4 + +0.0.3 / 2014-07-11 +================== + + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.0.2 / 2014-06-19 +================== + + * Handle invalid status codes + +0.0.1 / 2014-06-05 +================== + + * deps: debug@1.0.2 + +0.0.0 / 2014-06-05 +================== + + * Extracted from connect/express diff --git a/node_modules/finalhandler/LICENSE b/node_modules/finalhandler/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..60221067c4d591554407b4700033aab9669a9b0e --- /dev/null +++ b/node_modules/finalhandler/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2022 Douglas Christopher Wilson + +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. diff --git a/node_modules/finalhandler/README.md b/node_modules/finalhandler/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6244a13eb656346f2ff668c4742aee06bed35a62 --- /dev/null +++ b/node_modules/finalhandler/README.md @@ -0,0 +1,147 @@ +# finalhandler + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js function to invoke as the final step to respond to HTTP request. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install finalhandler +``` + +## API + +```js +var finalhandler = require('finalhandler') +``` + +### finalhandler(req, res, [options]) + +Returns function to be invoked as the final step for the given `req` and `res`. +This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will +write out a 404 response to the `res`. If it is truthy, an error response will +be written out to the `res` or `res` will be terminated if a response has already +started. + +When an error is written, the following information is added to the response: + + * The `res.statusCode` is set from `err.status` (or `err.statusCode`). If + this value is outside the 4xx or 5xx range, it will be set to 500. + * The `res.statusMessage` is set according to the status code. + * The body will be the HTML of the status code message if `env` is + `'production'`, otherwise will be `err.stack`. + * Any headers specified in an `err.headers` object. + +The final handler will also unpipe anything from `req` when it is invoked. + +#### options.env + +By default, the environment is determined by `NODE_ENV` variable, but it can be +overridden by this option. + +#### options.onerror + +Provide a function to be called with the `err` when it exists. Can be used for +writing errors to a central location without excessive function generation. Called +as `onerror(err, req, res)`. + +## Examples + +### always 404 + +```js +var finalhandler = require('finalhandler') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + done() +}) + +server.listen(3000) +``` + +### perform simple action + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) +``` + +### use with middleware-style functions + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +var serve = serveStatic('public') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + serve(req, res, done) +}) + +server.listen(3000) +``` + +### keep log of all errors + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res, { onerror: logerror }) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) + +function logerror (err) { + console.error(err.stack || err.toString()) +} +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/finalhandler.svg +[npm-url]: https://npmjs.org/package/finalhandler +[node-image]: https://img.shields.io/node/v/finalhandler.svg +[node-url]: https://nodejs.org/en/download +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master +[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg +[downloads-url]: https://npmjs.org/package/finalhandler +[github-actions-ci-image]: https://github.com/pillarjs/finalhandler/actions/workflows/ci.yml/badge.svg +[github-actions-ci-url]: https://github.com/pillarjs/finalhandler/actions/workflows/ci.yml diff --git a/node_modules/finalhandler/SECURITY.md b/node_modules/finalhandler/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..6e23249f5f93bb2bbe1cc15990d1f9c8975da269 --- /dev/null +++ b/node_modules/finalhandler/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `finalhandler` team and community take all security bugs seriously. Thank +you for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `finalhandler`. This +information can be found in the npm registry using the command +`npm owner ls finalhandler`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/pillarjs/finalhandler/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/node_modules/finalhandler/index.js b/node_modules/finalhandler/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ec34be90d153051156a8558c90f1564b84857d06 --- /dev/null +++ b/node_modules/finalhandler/index.js @@ -0,0 +1,341 @@ +/*! + * finalhandler + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('finalhandler') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var onFinished = require('on-finished') +var parseUrl = require('parseurl') +var statuses = require('statuses') +var unpipe = require('unpipe') + +/** + * Module variables. + * @private + */ + +var DOUBLE_SPACE_REGEXP = /\x20{2}/g +var NEWLINE_REGEXP = /\n/g + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished + +/** + * Create a minimal HTML document. + * + * @param {string} message + * @private + */ + +function createHtmlDocument (message) { + var body = escapeHtml(message) + .replace(NEWLINE_REGEXP, '
') + .replace(DOUBLE_SPACE_REGEXP, '  ') + + return '\n' + + '\n' + + '\n' + + '\n' + + 'Error\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Module exports. + * @public + */ + +module.exports = finalhandler + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler (req, res, options) { + var opts = options || {} + + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' + + // get error callback + var onerror = opts.onerror + + return function (err) { + var headers + var msg + var status + + // ignore 404 on in-flight response + if (!err && headersSent(res)) { + debug('cannot 404 after headers sent') + return + } + + // unhandled error + if (err) { + // respect status code from error + status = getErrorStatusCode(err) + + if (status === undefined) { + // fallback to status code on response + status = getResponseStatusCode(res) + } else { + // respect headers from error + headers = getErrorHeaders(err) + } + + // get error message + msg = getErrorMessage(err, status, env) + } else { + // not found + status = 404 + msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) + } + + debug('default %s', status) + + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } + + // cannot actually respond + if (headersSent(res)) { + debug('cannot %d after headers sent', status) + if (req.socket) { + req.socket.destroy() + } + return + } + + // send response + send(req, res, status, headers, msg) + } +} + +/** + * Get headers from Error object. + * + * @param {Error} err + * @return {object} + * @private + */ + +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined + } + + var headers = Object.create(null) + var keys = Object.keys(err.headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + headers[key] = err.headers[key] + } + + return headers +} + +/** + * Get message from Error object, fallback to status message. + * + * @param {Error} err + * @param {number} status + * @param {string} env + * @return {string} + * @private + */ + +function getErrorMessage (err, status, env) { + var msg + + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack + + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString() + } + } + + return msg || statuses.message[status] +} + +/** + * Get status code from Error object. + * + * @param {Error} err + * @return {number} + * @private + */ + +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status + } + + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode + } + + return undefined +} + +/** + * Get resource name for the request. + * + * This is typically just the original pathname of the request + * but will fallback to "resource" is that cannot be determined. + * + * @param {IncomingMessage} req + * @return {string} + * @private + */ + +function getResourceName (req) { + try { + return parseUrl.original(req).pathname + } catch (e) { + return 'resource' + } +} + +/** + * Get status code from response. + * + * @param {OutgoingMessage} res + * @return {number} + * @private + */ + +function getResponseStatusCode (res) { + var status = res.statusCode + + // default status code to 500 if outside valid range + if (typeof status !== 'number' || status < 400 || status > 599) { + status = 500 + } + + return status +} + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private + */ + +function send (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message) + + // response status + res.statusCode = status + + if (req.httpVersionMajor < 2) { + res.statusMessage = statuses.message[status] + } + + // remove any content headers + res.removeHeader('Content-Encoding') + res.removeHeader('Content-Language') + res.removeHeader('Content-Range') + + // response headers + setHeaders(res, headers) + + // security headers + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return + } + + res.end(body, 'utf8') + } + + if (isFinished(req)) { + write() + return + } + + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() +} + +/** + * Set response headers from an object. + * + * @param {OutgoingMessage} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + if (!headers) { + return + } + + var keys = Object.keys(headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} diff --git a/node_modules/finalhandler/package.json b/node_modules/finalhandler/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ce618dc4476519ea557622a1144a5406a8bc10cd --- /dev/null +++ b/node_modules/finalhandler/package.json @@ -0,0 +1,47 @@ +{ + "name": "finalhandler", + "description": "Node.js final http responder", + "version": "1.3.2", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "pillarjs/finalhandler", + "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" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.26.0", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "10.0.0", + "nyc": "15.1.0", + "readable-stream": "2.3.6", + "safe-buffer": "5.2.1", + "supertest": "6.2.4" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "SECURITY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-inspect": "mocha --reporter spec --inspect --inspect-brk test/" + } +} diff --git a/node_modules/find-up/index.d.ts b/node_modules/find-up/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6746bb72914a50141a945dea03ace0b5fc8ecd29 --- /dev/null +++ b/node_modules/find-up/index.d.ts @@ -0,0 +1,138 @@ +/* eslint-disable @typescript-eslint/unified-signatures */ +import {Options as LocatePathOptions} from 'locate-path'; + +declare const stop: unique symbol; + +declare namespace findUp { + interface Options extends LocatePathOptions {} + + type StopSymbol = typeof stop; + + type Match = string | StopSymbol | undefined; +} + +declare const findUp: { + sync: { + /** + Synchronously check if a path exists. + + @param path - Path to the file or directory. + @returns Whether the path exists. + + @example + ``` + import findUp = require('find-up'); + + console.log(findUp.sync.exists('/Users/sindresorhus/unicorn.png')); + //=> true + ``` + */ + exists: (path: string) => boolean; + + /** + Synchronously find a file or directory by walking up parent directories. + + @param name - Name of the file or directory to find. Can be multiple. + @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. + */ + (name: string | readonly string[], options?: findUp.Options): string | undefined; + + /** + Synchronously find a file or directory by walking up parent directories. + + @param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search. + @returns The first path found or `undefined` if none could be found. + + @example + ``` + import path = require('path'); + import findUp = require('find-up'); + + console.log(findUp.sync(directory => { + const hasUnicorns = findUp.sync.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' + ``` + */ + (matcher: (directory: string) => findUp.Match, options?: findUp.Options): string | undefined; + }; + + /** + Check if a path exists. + + @param path - Path to a file or directory. + @returns Whether the path exists. + + @example + ``` + import findUp = require('find-up'); + + (async () => { + console.log(await findUp.exists('/Users/sindresorhus/unicorn.png')); + //=> true + })(); + ``` + */ + exists: (path: string) => Promise; + + /** + Return this in a `matcher` function to stop the search and force `findUp` to immediately return `undefined`. + */ + readonly stop: findUp.StopSymbol; + + /** + Find a file or directory by walking up parent directories. + + @param name - Name of the file or directory to find. Can be multiple. + @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. + + @example + ``` + // / + // └── Users + // └── sindresorhus + // ├── unicorn.png + // └── foo + // └── bar + // ├── baz + // └── example.js + + // example.js + import findUp = require('find-up'); + + (async () => { + console.log(await findUp('unicorn.png')); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(['rainbow.png', 'unicorn.png'])); + //=> '/Users/sindresorhus/unicorn.png' + })(); + ``` + */ + (name: string | readonly string[], options?: findUp.Options): Promise; + + /** + Find a file or directory by walking up parent directories. + + @param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search. + @returns The first path found or `undefined` if none could be found. + + @example + ``` + import path = require('path'); + import findUp = require('find-up'); + + (async () => { + console.log(await findUp(async directory => { + const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' + })(); + ``` + */ + (matcher: (directory: string) => (findUp.Match | Promise), options?: findUp.Options): Promise; +}; + +export = findUp; diff --git a/node_modules/find-up/index.js b/node_modules/find-up/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ce564e5d322847ed088eba6d0973c19da3b4426d --- /dev/null +++ b/node_modules/find-up/index.js @@ -0,0 +1,89 @@ +'use strict'; +const path = require('path'); +const locatePath = require('locate-path'); +const pathExists = require('path-exists'); + +const stop = Symbol('findUp.stop'); + +module.exports = async (name, options = {}) => { + let directory = path.resolve(options.cwd || ''); + const {root} = path.parse(directory); + const paths = [].concat(name); + + const runMatcher = async locateOptions => { + if (typeof name !== 'function') { + return locatePath(paths, locateOptions); + } + + const foundPath = await name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath([foundPath], locateOptions); + } + + return foundPath; + }; + + // eslint-disable-next-line no-constant-condition + while (true) { + // eslint-disable-next-line no-await-in-loop + const foundPath = await runMatcher({...options, cwd: directory}); + + if (foundPath === stop) { + return; + } + + if (foundPath) { + return path.resolve(directory, foundPath); + } + + if (directory === root) { + return; + } + + directory = path.dirname(directory); + } +}; + +module.exports.sync = (name, options = {}) => { + let directory = path.resolve(options.cwd || ''); + const {root} = path.parse(directory); + const paths = [].concat(name); + + const runMatcher = locateOptions => { + if (typeof name !== 'function') { + return locatePath.sync(paths, locateOptions); + } + + const foundPath = name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath.sync([foundPath], locateOptions); + } + + return foundPath; + }; + + // eslint-disable-next-line no-constant-condition + while (true) { + const foundPath = runMatcher({...options, cwd: directory}); + + if (foundPath === stop) { + return; + } + + if (foundPath) { + return path.resolve(directory, foundPath); + } + + if (directory === root) { + return; + } + + directory = path.dirname(directory); + } +}; + +module.exports.exists = pathExists; + +module.exports.sync.exists = pathExists.sync; + +module.exports.stop = stop; diff --git a/node_modules/find-up/license b/node_modules/find-up/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/find-up/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.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. diff --git a/node_modules/find-up/package.json b/node_modules/find-up/package.json new file mode 100644 index 0000000000000000000000000000000000000000..56db6dd80a8e93d03c0f4e2ed4c34926c513b051 --- /dev/null +++ b/node_modules/find-up/package.json @@ -0,0 +1,54 @@ +{ + "name": "find-up", + "version": "5.0.0", + "description": "Find a file or directory by walking up parent directories", + "license": "MIT", + "repository": "sindresorhus/find-up", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "find", + "up", + "find-up", + "findup", + "look-up", + "look", + "file", + "search", + "match", + "package", + "resolve", + "parent", + "parents", + "folder", + "directory", + "walk", + "walking", + "path" + ], + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "devDependencies": { + "ava": "^2.1.0", + "is-path-inside": "^2.1.0", + "tempy": "^0.6.0", + "tsd": "^0.13.1", + "xo": "^0.33.0" + } +} diff --git a/node_modules/find-up/readme.md b/node_modules/find-up/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..7ad908a7ce31b6f95fc7f2fbd6e959d118f79943 --- /dev/null +++ b/node_modules/find-up/readme.md @@ -0,0 +1,151 @@ +# find-up [![Build Status](https://travis-ci.com/sindresorhus/find-up.svg?branch=master)](https://travis-ci.com/github/sindresorhus/find-up) + +> Find a file or directory by walking up parent directories + +## Install + +``` +$ npm install find-up +``` + +## Usage + +``` +/ +└── Users + └── sindresorhus + ├── unicorn.png + └── foo + └── bar + ├── baz + └── example.js +``` + +`example.js` + +```js +const path = require('path'); +const findUp = require('find-up'); + +(async () => { + console.log(await findUp('unicorn.png')); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(['rainbow.png', 'unicorn.png'])); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(async directory => { + const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' +})(); +``` + +## API + +### findUp(name, options?) +### findUp(matcher, options?) + +Returns a `Promise` for either the path or `undefined` if it couldn't be found. + +### findUp([...name], options?) + +Returns a `Promise` for either the first path found (by respecting the order of the array) or `undefined` if none could be found. + +### findUp.sync(name, options?) +### findUp.sync(matcher, options?) + +Returns a path or `undefined` if it couldn't be found. + +### findUp.sync([...name], options?) + +Returns the first path found (by respecting the order of the array) or `undefined` if none could be found. + +#### name + +Type: `string` + +Name of the file or directory to find. + +#### matcher + +Type: `Function` + +A function that will be called with each directory until it returns a `string` with the path, which stops the search, or the root directory has been reached and nothing was found. Useful if you want to match files with certain patterns, set of permissions, or other advanced use-cases. + +When using async mode, the `matcher` may optionally be an async or promise-returning function that returns the path. + +#### options + +Type: `object` + +##### cwd + +Type: `string`\ +Default: `process.cwd()` + +Directory to start from. + +##### type + +Type: `string`\ +Default: `'file'`\ +Values: `'file'` `'directory'` + +The type of paths that can match. + +##### allowSymlinks + +Type: `boolean`\ +Default: `true` + +Allow symbolic links to match if they point to the chosen path type. + +### findUp.exists(path) + +Returns a `Promise` of whether the path exists. + +### findUp.sync.exists(path) + +Returns a `boolean` of whether the path exists. + +#### path + +Type: `string` + +Path to a file or directory. + +### findUp.stop + +A [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) that can be returned by a `matcher` function to stop the search and cause `findUp` to immediately return `undefined`. Useful as a performance optimization in case the current working directory is deeply nested in the filesystem. + +```js +const path = require('path'); +const findUp = require('find-up'); + +(async () => { + await findUp(directory => { + return path.basename(directory) === 'work' ? findUp.stop : 'logo.png'; + }); +})(); +``` + +## Related + +- [find-up-cli](https://github.com/sindresorhus/find-up-cli) - CLI for this module +- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file +- [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package +- [resolve-from](https://github.com/sindresorhus/resolve-from) - Resolve the path of a module like `require.resolve()` but from a given path + +--- + +
+ + Get professional support for 'find-up' with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/flat-cache/LICENSE b/node_modules/flat-cache/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7383a47e9c2c9d80083dae619d00f2de025d3135 --- /dev/null +++ b/node_modules/flat-cache/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) Roy Riojas and Jared Wray + +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. + diff --git a/node_modules/flat-cache/README.md b/node_modules/flat-cache/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3d7793aac1aca3f4026d031ec851cfd89e56fd93 --- /dev/null +++ b/node_modules/flat-cache/README.md @@ -0,0 +1,77 @@ +# flat-cache + +> A stupidly simple key/value storage using files to persist the data + +[![NPM Version](https://img.shields.io/npm/v/flat-cache.svg?style=flat)](https://npmjs.org/package/flat-cache) +[![tests](https://github.com/jaredwray/flat-cache/actions/workflows/tests.yaml/badge.svg?branch=master)](https://github.com/jaredwray/flat-cache/actions/workflows/tests.yaml) +[![codecov](https://codecov.io/github/jaredwray/flat-cache/branch/master/graph/badge.svg?token=KxR95XT3NF)](https://codecov.io/github/jaredwray/flat-cache) +[![npm](https://img.shields.io/npm/dm/flat-cache)](https://npmjs.com/package/flat-cache) + +## install + +```bash +npm i --save flat-cache +``` + +## Usage + +```js +const flatCache = require('flat-cache'); +// loads the cache, if one does not exists for the given +// Id a new one will be prepared to be created +const cache = flatCache.load('cacheId'); + +// sets a key on the cache +cache.setKey('key', { foo: 'var' }); + +// get a key from the cache +cache.getKey('key'); // { foo: 'var' } + +// fetch the entire persisted object +cache.all(); // { 'key': { foo: 'var' } } + +// remove a key +cache.removeKey('key'); // removes a key from the cache + +// save it to disk +cache.save(); // very important, if you don't save no changes will be persisted. +// cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys + +// loads the cache from a given directory, if one does +// not exists for the given Id a new one will be prepared to be created +const cache = flatCache.load('cacheId', path.resolve('./path/to/folder')); + +// The following methods are useful to clear the cache +// delete a given cache +flatCache.clearCacheById('cacheId'); // removes the cacheId document if one exists. + +// delete all cache +flatCache.clearAll(); // remove the cache directory +``` + +## Motivation for this module + +I needed a super simple and dumb **in-memory cache** with optional disk persistance in order to make +a script that will beutify files with `esformatter` only execute on the files that were changed since the last run. +To make that possible we need to store the `fileSize` and `modificationTime` of the files. So a simple `key/value` +storage was needed and Bam! this module was born. + +## Important notes + +- If no directory is especified when the `load` method is called, a folder named `.cache` will be created + inside the module directory when `cache.save` is called. If you're committing your `node_modules` to any vcs, you + might want to ignore the default `.cache` folder, or specify a custom directory. +- The values set on the keys of the cache should be `stringify-able` ones, meaning no circular references +- All the changes to the cache state are done to memory +- I could have used a timer or `Object.observe` to deliver the changes to disk, but I wanted to keep this module + intentionally dumb and simple +- Non visited keys are removed when `cache.save()` is called. If this is not desired, you can pass `true` to the save call + like: `cache.save( true /* noPrune */ )`. + +## License + +MIT + +## Changelog + +[changelog](./changelog.md) diff --git a/node_modules/flat-cache/changelog.md b/node_modules/flat-cache/changelog.md new file mode 100644 index 0000000000000000000000000000000000000000..866f9501d96b9320914016c85ce3bc1c57d4f11b --- /dev/null +++ b/node_modules/flat-cache/changelog.md @@ -0,0 +1,278 @@ +# flat-cache - Changelog + +## v3.0.4 + +- **Refactoring** + - add files by name to the list of exported files - [89a2698](https://github.com/royriojas/flat-cache/commit/89a2698), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 02:35:39 + +## v3.0.3 + +- **Bug Fixes** + - Fix wrong eslint command - [f268e42](https://github.com/royriojas/flat-cache/commit/f268e42), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 02:15:04 + +## v3.0.2 + +- **Refactoring** + + - Update the files paths - [6983a80](https://github.com/royriojas/flat-cache/commit/6983a80), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:58:39 + - Move code to src/ - [18ed6e8](https://github.com/royriojas/flat-cache/commit/18ed6e8), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:57:17 + - Change eslint-cache location - [beed74c](https://github.com/royriojas/flat-cache/commit/beed74c), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:48:32 + +## v3.0.1 + +- **Refactoring** + - Remove unused deps - [8c6d9dc](https://github.com/royriojas/flat-cache/commit/8c6d9dc), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:43:29 + +## v3.0.0 + +- **Refactoring** + - Fix engines - [52b824c](https://github.com/royriojas/flat-cache/commit/52b824c), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:01:52 +- **Other changes** + + - Replace write with combination of mkdir and writeFile ([#49](https://github.com/royriojas/flat-cache/issues/49)) - [ef48276](https://github.com/royriojas/flat-cache/commit/ef48276), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 08/11/2020 00:17:15 + + Node v10 introduced a great "recursive" option for mkdir which allows to + get rid from mkdirp package and easily rewrite "write" package usage + with two function calls. + + https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback + + - Added a testcase for clearAll ([#48](https://github.com/royriojas/flat-cache/issues/48)) - [45b51ca](https://github.com/royriojas/flat-cache/commit/45b51ca), [Aaron Chen](https://github.com/Aaron Chen), 21/05/2020 08:40:03 + - requet node>=10 - [a5c482c](https://github.com/royriojas/flat-cache/commit/a5c482c), [yumetodo](https://github.com/yumetodo), 10/04/2020 23:14:53 + + thanks @SuperITMan + + - Update README.md - [29fe40b](https://github.com/royriojas/flat-cache/commit/29fe40b), [Roy Riojas](https://github.com/Roy Riojas), 10/04/2020 20:08:05 + - reduce vulnerability to 1 - [e9db1b2](https://github.com/royriojas/flat-cache/commit/e9db1b2), [yumetodo](https://github.com/yumetodo), 30/03/2020 11:10:43 + - reduce vulnerabilities dependencies to 8 - [b58d196](https://github.com/royriojas/flat-cache/commit/b58d196), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:54:56 + - use prettier instead of esbeautifier - [03b1db7](https://github.com/royriojas/flat-cache/commit/03b1db7), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:27:14 + - update proxyquire - [c2f048d](https://github.com/royriojas/flat-cache/commit/c2f048d), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:16:16 + - update flatted and mocha - [a0e56da](https://github.com/royriojas/flat-cache/commit/a0e56da), [yumetodo](https://github.com/yumetodo), 30/03/2020 09:46:45 + + mocha > mkdirp is updated + istanble >>> optimist > minimist is not updated + + - drop support node.js < 10 in develop - [beba691](https://github.com/royriojas/flat-cache/commit/beba691), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:31:09 + + see mkdirp + + - npm aufit fix(still remains) - [ce166cb](https://github.com/royriojas/flat-cache/commit/ce166cb), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:18:08 + + 37 vulnerabilities required manual review and could not be updated + + - updtate sinon - [9f2d1b6](https://github.com/royriojas/flat-cache/commit/9f2d1b6), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:17:51 + - apply eslint-plugin-mocha - [07343b5](https://github.com/royriojas/flat-cache/commit/07343b5), [yumetodo](https://github.com/yumetodo), 13/03/2020 22:17:21 + - Less strint version check ([#44](https://github.com/royriojas/flat-cache/issues/44)) - [92aca1c](https://github.com/royriojas/flat-cache/commit/92aca1c), [Wojciech Maj](https://github.com/Wojciech Maj), 13/11/2019 16:18:25 + + - Use ^ version matching for production dependencies + - Run npm audit fix + +- **Bug Fixes** + - update dependencies and use eslint directly - [73fbed2](https://github.com/royriojas/flat-cache/commit/73fbed2), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:17:27 + +## v2.0.1 + +- **Refactoring** + - upgrade node modules to latest versions - [6402ed3](https://github.com/royriojas/flat-cache/commit/6402ed3), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 18:47:05 + +## v2.0.0 + +- **Bug Fixes** + + - upgrade package.json lock file - [8d21c7b](https://github.com/royriojas/flat-cache/commit/8d21c7b), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 17:03:13 + - Use the same versions of node_js that eslint use - [8d23379](https://github.com/royriojas/flat-cache/commit/8d23379), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 16:25:11 + +- **Other changes** + + - Replace circular-json with flatted ([#36](https://github.com/royriojas/flat-cache/issues/36)) - [b93aced](https://github.com/royriojas/flat-cache/commit/b93aced), [C. K. Tang](https://github.com/C. K. Tang), 08/01/2019 17:03:01 + - Change JSON parser from circular-json to flatted & 1 more changes ([#37](https://github.com/royriojas/flat-cache/issues/37)) - [745e65a](https://github.com/royriojas/flat-cache/commit/745e65a), [Andy Chen](https://github.com/Andy Chen), 08/01/2019 16:17:20 + + - Change JSON parser from circular-json to flatted & 1 more changes + - Change JSON parser from circular-json + - Audited 2 vulnerabilities + - Update package.json + - Update Engine require + - There's a bunch of dependencies in this pkg requires node >=4, so I changed it to 4 + - Remove and add node versions + - I have seen this pkg is not available with node 0.12 so I removed it + - I have added a popular used LTS version of node - 10 + +## v1.3.4 + +- **Refactoring** + - Add del.js and utils.js to the list of files to be beautified - [9d0ca9b](https://github.com/royriojas/flat-cache/commit/9d0ca9b), [Roy Riojas](https://github.com/Roy Riojas), 14/11/2018 12:19:02 + +## v1.3.3 + +- **Refactoring** + - Make sure package-lock.json is up to date - [a7d2598](https://github.com/royriojas/flat-cache/commit/a7d2598), [Roy Riojas](https://github.com/Roy Riojas), 14/11/2018 11:36:08 +- **Other changes** + + - Removed the need for del ([#33](https://github.com/royriojas/flat-cache/issues/33)) - [c429012](https://github.com/royriojas/flat-cache/commit/c429012), [S. Gilroy](https://github.com/S. Gilroy), 13/11/2018 13:56:37 + + - Removed the need for del + + Removed the need for del as newer versions have broken backwards + compatibility. del mainly uses rimraf for deleting folders + and files, replaceing it with rimraf only is a minimal change. + + - Disable glob on rimraf calls + - Added glob disable to wrong call + - Wrapped rimraf to simplify solution + +## v1.3.2 + +- **Refactoring** + - remove yarn.lock file - [704c6c4](https://github.com/royriojas/flat-cache/commit/704c6c4), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 15:41:08 +- **Other changes** + + - replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23))" - [db12d74](https://github.com/royriojas/flat-cache/commit/db12d74), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 15:40:39 + + This reverts commit 00f689277a75e85fef28e6a048fad227afc525e6. + +## v1.3.1 + +- **Refactoring** + - upgrade deps to remove some security warnings - [f405719](https://github.com/royriojas/flat-cache/commit/f405719), [Roy Riojas](https://github.com/Roy Riojas), 06/11/2018 12:07:31 +- **Bug Fixes** + - replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23)) - [00f6892](https://github.com/royriojas/flat-cache/commit/00f6892), [Terry](https://github.com/Terry), 05/11/2018 18:44:16 +- **Other changes** + + - update del to v3.0.0 ([#26](https://github.com/royriojas/flat-cache/issues/26)) - [d42883f](https://github.com/royriojas/flat-cache/commit/d42883f), [Patrick Silva](https://github.com/Patrick Silva), 03/11/2018 01:00:44 + + Closes #25 + +## v1.3.0 + +- **Other changes** + + - Added #all method ([#16](https://github.com/royriojas/flat-cache/issues/16)) - [12293be](https://github.com/royriojas/flat-cache/commit/12293be), [Ozair Patel](https://github.com/Ozair Patel), 25/09/2017 14:46:38 + + - Added #all method + - Added #all method test + - Updated readme + - Added yarn.lock + - Added more keys for #all test + - Beautified file + + - fix changelog title style ([#14](https://github.com/royriojas/flat-cache/issues/14)) - [af8338a](https://github.com/royriojas/flat-cache/commit/af8338a), [前端小武](https://github.com/前端小武), 19/12/2016 20:34:48 + +## v1.2.2 + +- **Bug Fixes** + + - Do not crash if cache file is invalid JSON. ([#13](https://github.com/royriojas/flat-cache/issues/13)) - [87beaa6](https://github.com/royriojas/flat-cache/commit/87beaa6), [Roy Riojas](https://github.com/Roy Riojas), 19/12/2016 18:03:35 + + Fixes #12 + + Not sure under which situations a cache file might exist that does + not contain a valid JSON structure, but just in case to cover + the possibility of this happening a try catch block has been added + + If the cache is somehow not valid the cache will be discarded an a + a new cache will be stored instead + +- **Other changes** + + - Added travis ci support for modern node versions ([#11](https://github.com/royriojas/flat-cache/issues/11)) - [1c2b1f7](https://github.com/royriojas/flat-cache/commit/1c2b1f7), [Amila Welihinda](https://github.com/Amila Welihinda), 10/11/2016 23:47:52 + - Bumping `circular-son` version ([#10](https://github.com/royriojas/flat-cache/issues/10)) - [4d5e861](https://github.com/royriojas/flat-cache/commit/4d5e861), [Andrea Giammarchi](https://github.com/Andrea Giammarchi), 02/08/2016 07:13:52 + + As mentioned in https://github.com/WebReflection/circular-json/issues/25 `circular-json` wan't rightly implementing the license field. + + Latest version bump changed only that bit so that ESLint should now be happy. + +## v1.2.1 + +- **Bug Fixes** + - Add missing utils.js file to the package. closes [#8](https://github.com/royriojas/flat-cache/issues/8) - [ec10cf2](https://github.com/royriojas/flat-cache/commit/ec10cf2), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:18:57 + +## v1.2.0 + +- **Documentation** + - Add documentation about noPrune option - [23e11f9](https://github.com/royriojas/flat-cache/commit/23e11f9), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:06:49 + +## v1.0.11 + +- **Features** + + - Add noPrune option to cache.save() method. closes [#7](https://github.com/royriojas/flat-cache/issues/7) - [2c8016a](https://github.com/royriojas/flat-cache/commit/2c8016a), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:00:29 + - Add json read and write utility based on circular-json - [c31081e](https://github.com/royriojas/flat-cache/commit/c31081e), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:58:17 + +- **Bug Fixes** + + - Remove UTF16 BOM stripping - [4a41e22](https://github.com/royriojas/flat-cache/commit/4a41e22), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:18:06 + + Since we control both writing and reading of JSON stream, there no needs + to handle unicode BOM. + + - Use circular-json to handle circular references (fix [#5](https://github.com/royriojas/flat-cache/issues/5)) - [cd7aeed](https://github.com/royriojas/flat-cache/commit/cd7aeed), [Jean Ponchon](https://github.com/Jean Ponchon), 25/07/2016 11:11:59 + +- **Tests Related fixes** + + - Add missing file from eslint test - [d6fa3c3](https://github.com/royriojas/flat-cache/commit/d6fa3c3), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:15:51 + - Add test for circular json serialization / deserialization - [07d2ddd](https://github.com/royriojas/flat-cache/commit/07d2ddd), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:36 + +- **Refactoring** + - Remove unused read-json-sync - [2be1c24](https://github.com/royriojas/flat-cache/commit/2be1c24), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:18 +- **Build Scripts Changes** + - travis tests on 0.12 and 4x - [3a613fd](https://github.com/royriojas/flat-cache/commit/3a613fd), [royriojas](https://github.com/royriojas), 15/11/2015 14:34:40 + +## v1.0.10 + +- **Build Scripts Changes** + + - add eslint-fix task - [fd29e52](https://github.com/royriojas/flat-cache/commit/fd29e52), [royriojas](https://github.com/royriojas), 01/11/2015 15:04:08 + - make sure the test script also verify beautification and linting of files before running tests - [e94e176](https://github.com/royriojas/flat-cache/commit/e94e176), [royriojas](https://github.com/royriojas), 01/11/2015 11:54:48 + +- **Other changes** + - add clearAll for cacheDir - [97383d9](https://github.com/royriojas/flat-cache/commit/97383d9), [xieyaowu](https://github.com/xieyaowu), 31/10/2015 21:02:18 + +## v1.0.9 + +- **Bug Fixes** + - wrong default values for changelogx user repo name - [7bb52d1](https://github.com/royriojas/flat-cache/commit/7bb52d1), [royriojas](https://github.com/royriojas), 11/09/2015 15:59:30 + +## v1.0.8 + +- **Build Scripts Changes** + - test against node 4 - [c395b66](https://github.com/royriojas/flat-cache/commit/c395b66), [royriojas](https://github.com/royriojas), 11/09/2015 15:51:39 + +## v1.0.7 + +- **Other changes** + - Move dependencies into devDep - [7e47099](https://github.com/royriojas/flat-cache/commit/7e47099), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 15:10:57 +- **Documentation** + - Add missing changelog link - [f51197a](https://github.com/royriojas/flat-cache/commit/f51197a), [royriojas](https://github.com/royriojas), 11/09/2015 14:48:05 + +## v1.0.6 + +- **Build Scripts Changes** + - Add helpers/code check scripts - [bdb82f3](https://github.com/royriojas/flat-cache/commit/bdb82f3), [royriojas](https://github.com/royriojas), 11/09/2015 14:44:31 + +## v1.0.5 + +- **Documentation** + - better description for the module - [436817f](https://github.com/royriojas/flat-cache/commit/436817f), [royriojas](https://github.com/royriojas), 11/09/2015 14:35:33 +- **Other changes** + - Update dependencies - [be88aa3](https://github.com/royriojas/flat-cache/commit/be88aa3), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 13:47:41 + +## v1.0.4 + +- **Refactoring** + - load a cache file using the full filepath - [b8f68c2](https://github.com/royriojas/flat-cache/commit/b8f68c2), [Roy Riojas](https://github.com/Roy Riojas), 30/08/2015 04:19:14 +- **Documentation** + - Add documentation about `clearAll` and `clearCacheById` - [13947c1](https://github.com/royriojas/flat-cache/commit/13947c1), [Roy Riojas](https://github.com/Roy Riojas), 01/03/2015 23:44:05 +- **Features** + - Add methods to remove the cache documents created - [af40443](https://github.com/royriojas/flat-cache/commit/af40443), [Roy Riojas](https://github.com/Roy Riojas), 01/03/2015 23:39:27 + +## v1.0.1 + +- **Other changes** + - Update README.md - [c2b6805](https://github.com/royriojas/flat-cache/commit/c2b6805), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 04:28:07 + +## v1.0.0 + +- **Refactoring** + - flat-cache v.1.0.0 - [c984274](https://github.com/royriojas/flat-cache/commit/c984274), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 04:11:50 +- **Other changes** + - Initial commit - [d43cccf](https://github.com/royriojas/flat-cache/commit/d43cccf), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 01:12:16 diff --git a/node_modules/flat-cache/package.json b/node_modules/flat-cache/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b1248837543472d0048b3eb98e07647912ee62ec --- /dev/null +++ b/node_modules/flat-cache/package.json @@ -0,0 +1,63 @@ +{ + "name": "flat-cache", + "version": "4.0.1", + "description": "A stupidly simple key/value storage using files to persist some data", + "repository": "jaredwray/flat-cache", + "license": "MIT", + "author": { + "name": "Jared Wray", + "url": "https://jaredwray.com" + }, + "main": "src/cache.js", + "files": [ + "src/cache.js", + "src/del.js", + "src/utils.js" + ], + "engines": { + "node": ">=16" + }, + "precommit": [ + "npm run verify --silent" + ], + "prepush": [ + "npm run verify --silent" + ], + "scripts": { + "eslint": "eslint --cache --cache-location=node_modules/.cache/ ./src/**/*.js ./test/**/*.js", + "clean": "rimraf ./node_modules ./package-lock.json ./yarn.lock ./coverage", + "eslint-fix": "npm run eslint -- --fix", + "autofix": "npm run eslint-fix", + "check": "npm run eslint", + "verify": "npm run eslint && npm run test:cache", + "test:cache": "c8 mocha -R spec test/specs", + "test:ci:cache": "c8 --reporter=lcov mocha -R spec test/specs", + "test": "npm run verify --silent", + "format": "prettier --write ." + }, + "keywords": [ + "json cache", + "simple cache", + "file cache", + "key par", + "key value", + "cache" + ], + "devDependencies": { + "c8": "^9.1.0", + "chai": "^4.3.10", + "eslint": "^8.56.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-mocha": "^10.2.0", + "glob-expand": "^0.2.1", + "mocha": "^10.3.0", + "prettier": "^3.2.4", + "rimraf": "^5.0.5", + "sinon": "^17.0.1", + "write": "^2.0.0" + }, + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + } +} diff --git a/node_modules/flat-cache/src/cache.js b/node_modules/flat-cache/src/cache.js new file mode 100644 index 0000000000000000000000000000000000000000..b1fdf6d88c1ebd338ff2519755fa4863915166b6 --- /dev/null +++ b/node_modules/flat-cache/src/cache.js @@ -0,0 +1,214 @@ +const path = require('path'); +const fs = require('fs'); +const Keyv = require('keyv'); +const { writeJSON, tryParse } = require('./utils'); +const { del } = require('./del'); + +const cache = { + /** + * Load a cache identified by the given Id. If the element does not exists, then initialize an empty + * cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted + * then the cache module directory `./cache` will be used instead + * + * @method load + * @param docId {String} the id of the cache, would also be used as the name of the file cache + * @param [cacheDir] {String} directory for the cache entry + */ + load: function (docId, cacheDir) { + const me = this; + me.keyv = new Keyv(); + + me.__visited = {}; + me.__persisted = {}; + + me._pathToFile = cacheDir ? path.resolve(cacheDir, docId) : path.resolve(__dirname, '../.cache/', docId); + + if (fs.existsSync(me._pathToFile)) { + me._persisted = tryParse(me._pathToFile, {}); + } + }, + + get _persisted() { + return this.__persisted; + }, + + set _persisted(value) { + this.__persisted = value; + }, + + get _visited() { + return this.__visited; + }, + + set _visited(value) { + this.__visited = value; + }, + + /** + * Load the cache from the provided file + * @method loadFile + * @param {String} pathToFile the path to the file containing the info for the cache + */ + loadFile: function (pathToFile) { + const me = this; + const dir = path.dirname(pathToFile); + const fName = path.basename(pathToFile); + + me.load(fName, dir); + }, + + /** + * Returns the entire persisted object + * @method all + * @returns {*} + */ + all: function () { + return this._persisted; + }, + + keys: function () { + return Object.keys(this._persisted); + }, + /** + * sets a key to a given value + * @method setKey + * @param key {string} the key to set + * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify + */ + setKey: function (key, value) { + this._visited[key] = true; + this._persisted[key] = value; + }, + /** + * remove a given key from the cache + * @method removeKey + * @param key {String} the key to remove from the object + */ + removeKey: function (key) { + delete this._visited[key]; // esfmt-ignore-line + delete this._persisted[key]; // esfmt-ignore-line + }, + /** + * Return the value of the provided key + * @method getKey + * @param key {String} the name of the key to retrieve + * @returns {*} the value from the key + */ + getKey: function (key) { + this._visited[key] = true; + return this._persisted[key]; + }, + + /** + * Remove keys that were not accessed/set since the + * last time the `prune` method was called. + * @method _prune + * @private + */ + _prune: function () { + const me = this; + const obj = {}; + + const keys = Object.keys(me._visited); + + // no keys visited for either get or set value + if (keys.length === 0) { + return; + } + + keys.forEach(function (key) { + obj[key] = me._persisted[key]; + }); + + me._visited = {}; + me._persisted = obj; + }, + + /** + * Save the state of the cache identified by the docId to disk + * as a JSON structure + * @param [noPrune=false] {Boolean} whether to remove from cache the non visited files + * @method save + */ + save: function (noPrune) { + const me = this; + !noPrune && me._prune(); + writeJSON(me._pathToFile, me._persisted); + }, + + /** + * remove the file where the cache is persisted + * @method removeCacheFile + * @return {Boolean} true or false if the file was successfully deleted + */ + removeCacheFile: function () { + return del(this._pathToFile); + }, + /** + * Destroy the file cache and cache content. + * @method destroy + */ + destroy: function () { + const me = this; + me._visited = {}; + me._persisted = {}; + + me.removeCacheFile(); + }, +}; + +module.exports = { + /** + * Alias for create. Should be considered depreacted. Will be removed in next releases + * + * @method load + * @param docId {String} the id of the cache, would also be used as the name of the file cache + * @param [cacheDir] {String} directory for the cache entry + * @returns {cache} cache instance + */ + load: function (docId, cacheDir) { + return this.create(docId, cacheDir); + }, + + /** + * Load a cache identified by the given Id. If the element does not exists, then initialize an empty + * cache storage. + * + * @method create + * @param docId {String} the id of the cache, would also be used as the name of the file cache + * @param [cacheDir] {String} directory for the cache entry + * @returns {cache} cache instance + */ + create: function (docId, cacheDir) { + const obj = Object.create(cache); + obj.load(docId, cacheDir); + return obj; + }, + + createFromFile: function (filePath) { + const obj = Object.create(cache); + obj.loadFile(filePath); + return obj; + }, + /** + * Clear the cache identified by the given id. Caches stored in a different cache directory can be deleted directly + * + * @method clearCache + * @param docId {String} the id of the cache, would also be used as the name of the file cache + * @param cacheDir {String} the directory where the cache file was written + * @returns {Boolean} true if the cache folder was deleted. False otherwise + */ + clearCacheById: function (docId, cacheDir) { + const filePath = cacheDir ? path.resolve(cacheDir, docId) : path.resolve(__dirname, '../.cache/', docId); + return del(filePath); + }, + /** + * Remove all cache stored in the cache directory + * @method clearAll + * @returns {Boolean} true if the cache folder was deleted. False otherwise + */ + clearAll: function (cacheDir) { + const filePath = cacheDir ? path.resolve(cacheDir) : path.resolve(__dirname, '../.cache/'); + return del(filePath); + }, +}; diff --git a/node_modules/flat-cache/src/del.js b/node_modules/flat-cache/src/del.js new file mode 100644 index 0000000000000000000000000000000000000000..9cd55c369a0a4bd1bf0d177ca972cfc6faacfb49 --- /dev/null +++ b/node_modules/flat-cache/src/del.js @@ -0,0 +1,30 @@ +const fs = require('fs'); +const path = require('path'); + +function del(targetPath) { + if (!fs.existsSync(targetPath)) { + return false; + } + + try { + if (fs.statSync(targetPath).isDirectory()) { + // If it's a directory, delete its contents first + fs.readdirSync(targetPath).forEach(file => { + const curPath = path.join(targetPath, file); + + if (fs.statSync(curPath).isFile()) { + fs.unlinkSync(curPath); // Delete file + } + }); + fs.rmdirSync(targetPath); // Delete the now-empty directory + } else { + fs.unlinkSync(targetPath); // If it's a file, delete it directly + } + + return true; + } catch (error) { + console.error(`Error while deleting ${targetPath}: ${error.message}`); + } +} + +module.exports = { del }; diff --git a/node_modules/flat-cache/src/utils.js b/node_modules/flat-cache/src/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..c4f75fbc8bcf1704bc5bb608fd7e4782bf12550f --- /dev/null +++ b/node_modules/flat-cache/src/utils.js @@ -0,0 +1,42 @@ +const fs = require('fs'); +const path = require('path'); +const flatted = require('flatted'); + +function tryParse(filePath, defaultValue) { + let result; + try { + result = readJSON(filePath); + } catch (ex) { + result = defaultValue; + } + return result; +} + +/** + * Read json file synchronously using flatted + * + * @param {String} filePath Json filepath + * @returns {*} parse result + */ +function readJSON(filePath) { + return flatted.parse( + fs.readFileSync(filePath, { + encoding: 'utf8', + }) + ); +} + +/** + * Write json file synchronously using circular-json + * + * @param {String} filePath Json filepath + * @param {*} data Object to serialize + */ +function writeJSON(filePath, data) { + fs.mkdirSync(path.dirname(filePath), { + recursive: true, + }); + fs.writeFileSync(filePath, flatted.stringify(data)); +} + +module.exports = { tryParse, readJSON, writeJSON }; diff --git a/node_modules/flatted/LICENSE b/node_modules/flatted/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..506dc479c6b3482ff184ed1f32f284bfbcc47db8 --- /dev/null +++ b/node_modules/flatted/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2018-2020, Andrea Giammarchi, @WebReflection + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/flatted/README.md b/node_modules/flatted/README.md new file mode 100644 index 0000000000000000000000000000000000000000..429c15244b05f949a6214ce229c74a7df9ab6f4d --- /dev/null +++ b/node_modules/flatted/README.md @@ -0,0 +1,111 @@ +# flatted + +[![Downloads](https://img.shields.io/npm/dm/flatted.svg)](https://www.npmjs.com/package/flatted) [![Coverage Status](https://coveralls.io/repos/github/WebReflection/flatted/badge.svg?branch=main)](https://coveralls.io/github/WebReflection/flatted?branch=main) [![License: ISC](https://img.shields.io/badge/License-ISC-yellow.svg)](https://opensource.org/licenses/ISC) ![WebReflection status](https://offline.report/status/webreflection.svg) + +![snow flake](./flatted.jpg) + +**Social Media Photo by [Matt Seymour](https://unsplash.com/@mattseymour) on [Unsplash](https://unsplash.com/)** + +A super light (0.5K) and fast circular JSON parser, directly from the creator of [CircularJSON](https://github.com/WebReflection/circular-json/#circularjson). + +Available also for **[PHP](./php/flatted.php)**. + +Available also for **[Python](./python/flatted.py)**. + +Available also for **[Go](./golang/README.md)**. + +- - - + +## ℹ️ JSON only values + +If you need anything more complex than values JSON understands, there is a standard approach to recursion and more data-types than what JSON allows, and it's part of the [Structured Clone polyfill](https://github.com/ungap/structured-clone/#readme). + +- - - + +```js +npm i flatted +``` + +Usable via [CDN](https://unpkg.com/flatted) or as regular module. + +```js +// ESM +import {parse, stringify, toJSON, fromJSON} from 'flatted'; + +// CJS +const {parse, stringify, toJSON, fromJSON} = require('flatted'); + +const a = [{}]; +a[0].a = a; +a.push(a); + +stringify(a); // [["1","0"],{"a":"0"}] +``` + +## toJSON and fromJSON + +If you'd like to implicitly survive JSON serialization, these two helpers helps: + +```js +import {toJSON, fromJSON} from 'flatted'; + +class RecursiveMap extends Map { + static fromJSON(any) { + return new this(fromJSON(any)); + } + toJSON() { + return toJSON([...this.entries()]); + } +} + +const recursive = new RecursiveMap; +const same = {}; +same.same = same; +recursive.set('same', same); + +const asString = JSON.stringify(recursive); +const asMap = RecursiveMap.fromJSON(JSON.parse(asString)); +asMap.get('same') === asMap.get('same').same; +// true +``` + + +## Flatted VS JSON + +As it is for every other specialized format capable of serializing and deserializing circular data, you should never `JSON.parse(Flatted.stringify(data))`, and you should never `Flatted.parse(JSON.stringify(data))`. + +The only way this could work is to `Flatted.parse(Flatted.stringify(data))`, as it is also for _CircularJSON_ or any other, otherwise there's no granted data integrity. + +Also please note this project serializes and deserializes only data compatible with JSON, so that sockets, or anything else with internal classes different from those allowed by JSON standard, won't be serialized and unserialized as expected. + + +### New in V1: Exact same JSON API + + * Added a [reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Syntax) parameter to `.parse(string, reviver)` and revive your own objects. + * Added a [replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax) and a `space` parameter to `.stringify(object, replacer, space)` for feature parity with JSON signature. + + +### Compatibility +All ECMAScript engines compatible with `Map`, `Set`, `Object.keys`, and `Array.prototype.reduce` will work, even if polyfilled. + + +### How does it work ? +While stringifying, all Objects, including Arrays, and strings, are flattened out and replaced as unique index. `*` + +Once parsed, all indexes will be replaced through the flattened collection. + +`*` represented as string to avoid conflicts with numbers + +```js +// logic example +var a = [{one: 1}, {two: '2'}]; +a[0].a = a; +// a is the main object, will be at index '0' +// {one: 1} is the second object, index '1' +// {two: '2'} the third, in '2', and it has a string +// which will be found at index '3' + +Flatted.stringify(a); +// [["1","2"],{"one":1,"a":"0"},{"two":"3"},"2"] +// a[one,two] {one: 1, a} {two: '2'} '2' +``` diff --git a/node_modules/flatted/cjs/index.js b/node_modules/flatted/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a4833a5b44a6e826abbb0e83db7c17f28d7e0711 --- /dev/null +++ b/node_modules/flatted/cjs/index.js @@ -0,0 +1,132 @@ +'use strict'; +/// + +// (c) 2020-present Andrea Giammarchi + +const {parse: $parse, stringify: $stringify} = JSON; +const {keys} = Object; + +const Primitive = String; // it could be Number +const primitive = 'string'; // it could be 'number' + +const ignore = {}; +const object = 'object'; + +const noop = (_, value) => value; + +const primitives = value => ( + value instanceof Primitive ? Primitive(value) : value +); + +const Primitives = (_, value) => ( + typeof value === primitive ? new Primitive(value) : value +); + +const resolver = (input, lazy, parsed, $) => output => { + for (let ke = keys(output), {length} = ke, y = 0; y < length; y++) { + const k = ke[y]; + const value = output[k]; + if (value instanceof Primitive) { + const tmp = input[+value]; + if (typeof tmp === object && !parsed.has(tmp)) { + parsed.add(tmp); + output[k] = ignore; + lazy.push({ o: output, k, r: tmp }); + } + else + output[k] = $.call(output, k, tmp); + } + else if (output[k] !== ignore) + output[k] = $.call(output, k, value); + } + return output; +}; + +const set = (known, input, value) => { + const index = Primitive(input.push(value) - 1); + known.set(value, index); + return index; +}; + +/** + * Converts a specialized flatted string into a JS value. + * @param {string} text + * @param {(this: any, key: string, value: any) => any} [reviver] + * @returns {any} + */ +const parse = (text, reviver) => { + const input = $parse(text, Primitives).map(primitives); + const $ = reviver || noop; + + let value = input[0]; + + if (typeof value === object && value) { + const lazy = []; + const revive = resolver(input, lazy, new Set, $); + value = revive(value); + + let i = 0; + while (i < lazy.length) { + // it could be a lazy.shift() but that's costly + const {o, k, r} = lazy[i++]; + o[k] = $.call(o, k, revive(r)); + } + } + + return $.call({'': value}, '', value); +}; +exports.parse = parse; + +/** + * Converts a JS value into a specialized flatted string. + * @param {any} value + * @param {((this: any, key: string, value: any) => any) | (string | number)[] | null | undefined} [replacer] + * @param {string | number | undefined} [space] + * @returns {string} + */ +const stringify = (value, replacer, space) => { + const $ = replacer && typeof replacer === object ? + (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) : + (replacer || noop); + const known = new Map; + const input = []; + const output = []; + let i = +set(known, input, $.call({'': value}, '', value)); + let firstRun = !i; + while (i < input.length) { + firstRun = true; + output[i] = $stringify(input[i++], replace, space); + } + return '[' + output.join(',') + ']'; + function replace(key, value) { + if (firstRun) { + firstRun = !firstRun; + return value; + } + const after = $.call(this, key, value); + switch (typeof after) { + case object: + if (after === null) return after; + case primitive: + return known.get(after) || set(known, input, after); + } + return after; + } +}; +exports.stringify = stringify; + +/** + * Converts a generic value into a JSON serializable object without losing recursion. + * @param {any} value + * @returns {any} + */ +const toJSON = value => $parse(stringify(value)); +exports.toJSON = toJSON; + +/** + * Converts a previously serialized object with recursion into a recursive one. + * @param {any} value + * @returns {any} + */ +const fromJSON = value => parse($stringify(value)); +exports.fromJSON = fromJSON; diff --git a/node_modules/flatted/cjs/package.json b/node_modules/flatted/cjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0292b9956f2e40d6eb3d0f3998e710d973113aaa --- /dev/null +++ b/node_modules/flatted/cjs/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} \ No newline at end of file diff --git a/node_modules/flatted/es.js b/node_modules/flatted/es.js new file mode 100644 index 0000000000000000000000000000000000000000..3e4d1877aad1edf8d805f77e9c425556fae55318 --- /dev/null +++ b/node_modules/flatted/es.js @@ -0,0 +1 @@ +self.Flatted=function(t){"use strict";const{parse:e,stringify:n}=JSON,{keys:r}=Object,o=String,s="string",c={},l="object",f=(t,e)=>e,i=t=>t instanceof o?o(t):t,a=(t,e)=>typeof e===s?new o(e):e,u=(t,e,n)=>{const r=o(e.push(n)-1);return t.set(n,r),r},p=(t,n)=>{const s=e(t,a).map(i),u=n||f;let p=s[0];if(typeof p===l&&p){const t=[],e=((t,e,n,s)=>f=>{for(let i=r(f),{length:a}=i,u=0;u{const o=e&&typeof e===l?(t,n)=>""===t||-1p(n(t)),t.parse=p,t.stringify=g,t.toJSON=t=>e(g(t)),t}({}); diff --git a/node_modules/flatted/esm.js b/node_modules/flatted/esm.js new file mode 100644 index 0000000000000000000000000000000000000000..2563a4125c7ff76aff89c4ab92195d336066973f --- /dev/null +++ b/node_modules/flatted/esm.js @@ -0,0 +1 @@ +const{parse:t,stringify:e}=JSON,{keys:n}=Object,o=String,r="string",s={},c="object",l=(t,e)=>e,f=t=>t instanceof o?o(t):t,i=(t,e)=>typeof e===r?new o(e):e,a=(t,e,n)=>{const r=o(e.push(n)-1);return t.set(n,r),r},u=(e,r)=>{const a=t(e,i).map(f),u=r||l;let p=a[0];if(typeof p===c&&p){const t=[],e=((t,e,r,l)=>f=>{for(let i=n(f),{length:a}=i,u=0;u{const s=n&&typeof n===c?(t,e)=>""===t||-1t(p(e)),g=t=>u(e(t));export{g as fromJSON,u as parse,p as stringify,h as toJSON}; diff --git a/node_modules/flatted/esm/index.js b/node_modules/flatted/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..eb2da2d3faa14c5efa8ee865d939f2c2b02f795d --- /dev/null +++ b/node_modules/flatted/esm/index.js @@ -0,0 +1,127 @@ +/// + +// (c) 2020-present Andrea Giammarchi + +const {parse: $parse, stringify: $stringify} = JSON; +const {keys} = Object; + +const Primitive = String; // it could be Number +const primitive = 'string'; // it could be 'number' + +const ignore = {}; +const object = 'object'; + +const noop = (_, value) => value; + +const primitives = value => ( + value instanceof Primitive ? Primitive(value) : value +); + +const Primitives = (_, value) => ( + typeof value === primitive ? new Primitive(value) : value +); + +const resolver = (input, lazy, parsed, $) => output => { + for (let ke = keys(output), {length} = ke, y = 0; y < length; y++) { + const k = ke[y]; + const value = output[k]; + if (value instanceof Primitive) { + const tmp = input[+value]; + if (typeof tmp === object && !parsed.has(tmp)) { + parsed.add(tmp); + output[k] = ignore; + lazy.push({ o: output, k, r: tmp }); + } + else + output[k] = $.call(output, k, tmp); + } + else if (output[k] !== ignore) + output[k] = $.call(output, k, value); + } + return output; +}; + +const set = (known, input, value) => { + const index = Primitive(input.push(value) - 1); + known.set(value, index); + return index; +}; + +/** + * Converts a specialized flatted string into a JS value. + * @param {string} text + * @param {(this: any, key: string, value: any) => any} [reviver] + * @returns {any} + */ +export const parse = (text, reviver) => { + const input = $parse(text, Primitives).map(primitives); + const $ = reviver || noop; + + let value = input[0]; + + if (typeof value === object && value) { + const lazy = []; + const revive = resolver(input, lazy, new Set, $); + value = revive(value); + + let i = 0; + while (i < lazy.length) { + // it could be a lazy.shift() but that's costly + const {o, k, r} = lazy[i++]; + o[k] = $.call(o, k, revive(r)); + } + } + + return $.call({'': value}, '', value); +}; + +/** + * Converts a JS value into a specialized flatted string. + * @param {any} value + * @param {((this: any, key: string, value: any) => any) | (string | number)[] | null | undefined} [replacer] + * @param {string | number | undefined} [space] + * @returns {string} + */ +export const stringify = (value, replacer, space) => { + const $ = replacer && typeof replacer === object ? + (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) : + (replacer || noop); + const known = new Map; + const input = []; + const output = []; + let i = +set(known, input, $.call({'': value}, '', value)); + let firstRun = !i; + while (i < input.length) { + firstRun = true; + output[i] = $stringify(input[i++], replace, space); + } + return '[' + output.join(',') + ']'; + function replace(key, value) { + if (firstRun) { + firstRun = !firstRun; + return value; + } + const after = $.call(this, key, value); + switch (typeof after) { + case object: + if (after === null) return after; + case primitive: + return known.get(after) || set(known, input, after); + } + return after; + } +}; + +/** + * Converts a generic value into a JSON serializable object without losing recursion. + * @param {any} value + * @returns {any} + */ +export const toJSON = value => $parse(stringify(value)); + +/** + * Converts a previously serialized object with recursion into a recursive one. + * @param {any} value + * @returns {any} + */ +export const fromJSON = value => parse($stringify(value)); diff --git a/node_modules/flatted/golang/README.md b/node_modules/flatted/golang/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1db041bf789a8b13c2d9fd484d92df1ae7036973 --- /dev/null +++ b/node_modules/flatted/golang/README.md @@ -0,0 +1,60 @@ +# flatted (Go) + +A super light and fast circular JSON parser. + +## Usage + +```go +package main + +import ( + "fmt" + "github.com/WebReflection/flatted/golang/pkg/flatted" +) + +type Group struct { + Name string `json:"name"` +} + +type User struct { + Name string `json:"name"` + Friend *User `json:"friend"` + Group *Group `json:"group"` +} + +func main() { + group := &Group{Name: "Developers"} + alice := &User{Name: "Alice", Group: group} + bob := &User{Name: "Bob", Group: group} + + alice.Friend = bob + bob.Friend = alice // Circular reference + + // Stringify Alice + s, _ := flatted.Stringify(alice) + fmt.Println(s) + // Output: [{"name":"Alice","friend":"1","group":"2"},{"name":"Bob","friend":"0","group":"2"},{"name":"Developers"}] + + // Flattening in action: + // Index "0" is Alice, Index "1" is Bob, Index "2" is the shared Group. + + // Parse back into a generic map structure + res, _ := flatted.Parse(s) + aliceMap := res.(map[string]any) + fmt.Println(aliceMap["name"]) // Alice +} +``` + +## CLI + +Build the binary using the provided Makefile: + +```bash +make build +``` + +Then use it to parse flatted JSON from stdin: + +```bash +echo '[{"a":"1"},"b"]' | ./flatted +``` diff --git a/node_modules/flatted/golang/pkg/flatted/flatted.go b/node_modules/flatted/golang/pkg/flatted/flatted.go new file mode 100644 index 0000000000000000000000000000000000000000..8e3922c0926a84ee0fcdbe55ff6518ed500daa11 --- /dev/null +++ b/node_modules/flatted/golang/pkg/flatted/flatted.go @@ -0,0 +1,277 @@ +package flatted + +import ( + "encoding/json" + "reflect" + "sort" + "strconv" + "strings" +) + +// flattedIndex is a internal type used to distinguish between +// actual strings and flatted indices during the reconstruction phase. +type flattedIndex string + +// Stringify converts a Go value into a specialized flatted JSON string. +func Stringify(value any, replacer any, space any) (string, error) { + knownKeys := []any{} + knownValues := []string{} + input := []any{} + + index := func(v any) string { + input = append(input, v) + idx := strconv.Itoa(len(input) - 1) + knownKeys = append(knownKeys, v) + knownValues = append(knownValues, idx) + return idx + } + + relate := func(v any) any { + if v == nil { + return nil + } + rv := reflect.ValueOf(v) + kind := rv.Kind() + if kind == reflect.String || kind == reflect.Slice || kind == reflect.Map || kind == reflect.Ptr { + for i, k := range knownKeys { + if kind == reflect.String { + if k == v { + return knownValues[i] + } + } else { + rk := reflect.ValueOf(k) + if rk.Kind() == kind && rk.Pointer() == rv.Pointer() { + return knownValues[i] + } + } + } + return index(v) + } + return v + } + + transform := func(v any) any { + rv := reflect.ValueOf(v) + if !rv.IsValid() { + return nil + } + if _, ok := v.(json.Marshaler); ok { + return v + } + // Dereference pointers to process the underlying Slice, Map, or Array + for rv.Kind() == reflect.Ptr && !rv.IsNil() { + rv = rv.Elem() + } + switch rv.Kind() { + case reflect.Slice, reflect.Array: + res := make([]any, rv.Len()) + for i := 0; i < rv.Len(); i++ { + res[i] = relate(rv.Index(i).Interface()) + } + return res + case reflect.Map: + res := make(map[string]any) + keys := rv.MapKeys() + sort.Slice(keys, func(i, j int) bool { + return keys[i].String() < keys[j].String() + }) + + whitelist, isWhitelist := replacer.([]string) + for _, key := range keys { + kStr := key.String() + if isWhitelist { + found := false + for _, w := range whitelist { + if w == kStr { + found = true + break + } + } + if !found { + continue + } + } + res[kStr] = relate(rv.MapIndex(key).Interface()) + } + return res + case reflect.Struct: + res := make(map[string]any) + t := rv.Type() + for i := 0; i < rv.NumField(); i++ { + field := t.Field(i) + if field.PkgPath != "" { + continue + } + name := field.Name + if tag := field.Tag.Get("json"); tag != "" { + name = strings.Split(tag, ",")[0] + } + res[name] = relate(rv.Field(i).Interface()) + } + return res + default: + return v + } + } + + index(value) + output := []any{} + for i := 0; i < len(input); i++ { + output = append(output, transform(input[i])) + } + + var b []byte + var err error + indent := "" + if s, ok := space.(string); ok { + indent = s + } else if i, ok := space.(int); ok { + indent = strings.Repeat(" ", i) + } + + if indent != "" { + b, err = json.MarshalIndent(output, "", indent) + } else { + b, err = json.Marshal(output) + } + + if err != nil { + return "", err + } + return string(b), nil +} + +// Parse converts a specialized flatted string into a Go value. +func Parse(text string, reviver func(key string, value any) any) (any, error) { + var jsonInput []any + if err := json.Unmarshal([]byte(text), &jsonInput); err != nil { + return nil, err + } + + var wrap func(any) any + wrap = func(v any) any { + if s, ok := v.(string); ok { + return flattedIndex(s) + } + if arr, ok := v.([]any); ok { + for i, item := range arr { + arr[i] = wrap(item) + } + return arr + } + if m, ok := v.(map[string]any); ok { + for k, item := range m { + m[k] = wrap(item) + } + return m + } + return v + } + + wrapped := make([]any, len(jsonInput)) + for i, v := range jsonInput { + wrapped[i] = wrap(v) + } + + input := make([]any, len(wrapped)) + for i, v := range wrapped { + if fi, ok := v.(flattedIndex); ok { + input[i] = string(fi) + } else { + input[i] = v + } + } + + if len(input) == 0 { + return nil, nil + } + + value := input[0] + rv := reflect.ValueOf(value) + if rv.IsValid() && (rv.Kind() == reflect.Slice || rv.Kind() == reflect.Map) { + set := make(map[uintptr]bool) + set[rv.Pointer()] = true + res := loop(value, input, set) + if reviver != nil { + return revive("", res, reviver), nil + } + return res, nil + } + + if reviver != nil { + return reviver("", value), nil + } + return value, nil +} + +func revive(key string, value any, reviver func(k string, v any) any) any { + if arr, ok := value.([]any); ok { + for i, v := range arr { + arr[i] = revive(strconv.Itoa(i), v, reviver) + } + } else if m, ok := value.(map[string]any); ok { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + m[k] = revive(k, m[k], reviver) + } + } + return reviver(key, value) +} + +func loop(value any, input []any, set map[uintptr]bool) any { + if arr, ok := value.([]any); ok { + for i, v := range arr { + if fi, ok := v.(flattedIndex); ok { + idx, _ := strconv.Atoi(string(fi)) + arr[i] = ref(input[idx], input, set) + } + } + return arr + } + if m, ok := value.(map[string]any); ok { + for k, v := range m { + if fi, ok := v.(flattedIndex); ok { + idx, _ := strconv.Atoi(string(fi)) + m[k] = ref(input[idx], input, set) + } + } + return m + } + return value +} + +func ref(value any, input []any, set map[uintptr]bool) any { + rv := reflect.ValueOf(value) + if rv.IsValid() && (rv.Kind() == reflect.Slice || rv.Kind() == reflect.Map) { + ptr := rv.Pointer() + if !set[ptr] { + set[ptr] = true + return loop(value, input, set) + } + } + return value +} + +// ToJSON converts a generic value into a JSON serializable object without losing recursion. +func ToJSON(value any) (any, error) { + s, err := Stringify(value, nil, nil) + if err != nil { + return nil, err + } + var res any + err = json.Unmarshal([]byte(s), &res) + return res, err +} + +// FromJSON converts a previously serialized object with recursion into a recursive one. +func FromJSON(value any) (any, error) { + b, err := json.Marshal(value) + if err != nil { + return nil, err + } + return Parse(string(b), nil) +} diff --git a/node_modules/flatted/index.js b/node_modules/flatted/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9386548bf62da3c50b146e3781f4c9ca4519a3de --- /dev/null +++ b/node_modules/flatted/index.js @@ -0,0 +1,155 @@ +self.Flatted = (function (exports) { + 'use strict'; + + function _typeof(o) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, _typeof(o); + } + + /// + + // (c) 2020-present Andrea Giammarchi + + var $parse = JSON.parse, + $stringify = JSON.stringify; + var keys = Object.keys; + var Primitive = String; // it could be Number + var primitive = 'string'; // it could be 'number' + + var ignore = {}; + var object = 'object'; + var noop = function noop(_, value) { + return value; + }; + var primitives = function primitives(value) { + return value instanceof Primitive ? Primitive(value) : value; + }; + var Primitives = function Primitives(_, value) { + return _typeof(value) === primitive ? new Primitive(value) : value; + }; + var resolver = function resolver(input, lazy, parsed, $) { + return function (output) { + for (var ke = keys(output), length = ke.length, y = 0; y < length; y++) { + var k = ke[y]; + var value = output[k]; + if (value instanceof Primitive) { + var tmp = input[+value]; + if (_typeof(tmp) === object && !parsed.has(tmp)) { + parsed.add(tmp); + output[k] = ignore; + lazy.push({ + o: output, + k: k, + r: tmp + }); + } else output[k] = $.call(output, k, tmp); + } else if (output[k] !== ignore) output[k] = $.call(output, k, value); + } + return output; + }; + }; + var set = function set(known, input, value) { + var index = Primitive(input.push(value) - 1); + known.set(value, index); + return index; + }; + + /** + * Converts a specialized flatted string into a JS value. + * @param {string} text + * @param {(this: any, key: string, value: any) => any} [reviver] + * @returns {any} + */ + var parse = function parse(text, reviver) { + var input = $parse(text, Primitives).map(primitives); + var $ = reviver || noop; + var value = input[0]; + if (_typeof(value) === object && value) { + var lazy = []; + var revive = resolver(input, lazy, new Set(), $); + value = revive(value); + var i = 0; + while (i < lazy.length) { + // it could be a lazy.shift() but that's costly + var _lazy$i = lazy[i++], + o = _lazy$i.o, + k = _lazy$i.k, + r = _lazy$i.r; + o[k] = $.call(o, k, revive(r)); + } + } + return $.call({ + '': value + }, '', value); + }; + + /** + * Converts a JS value into a specialized flatted string. + * @param {any} value + * @param {((this: any, key: string, value: any) => any) | (string | number)[] | null | undefined} [replacer] + * @param {string | number | undefined} [space] + * @returns {string} + */ + var stringify = function stringify(value, replacer, space) { + var $ = replacer && _typeof(replacer) === object ? function (k, v) { + return k === '' || -1 < replacer.indexOf(k) ? v : void 0; + } : replacer || noop; + var known = new Map(); + var input = []; + var output = []; + var i = +set(known, input, $.call({ + '': value + }, '', value)); + var firstRun = !i; + while (i < input.length) { + firstRun = true; + output[i] = $stringify(input[i++], replace, space); + } + return '[' + output.join(',') + ']'; + function replace(key, value) { + if (firstRun) { + firstRun = !firstRun; + return value; + } + var after = $.call(this, key, value); + switch (_typeof(after)) { + case object: + if (after === null) return after; + case primitive: + return known.get(after) || set(known, input, after); + } + return after; + } + }; + + /** + * Converts a generic value into a JSON serializable object without losing recursion. + * @param {any} value + * @returns {any} + */ + var toJSON = function toJSON(value) { + return $parse(stringify(value)); + }; + + /** + * Converts a previously serialized object with recursion into a recursive one. + * @param {any} value + * @returns {any} + */ + var fromJSON = function fromJSON(value) { + return parse($stringify(value)); + }; + + exports.fromJSON = fromJSON; + exports.parse = parse; + exports.stringify = stringify; + exports.toJSON = toJSON; + + return exports; + +})({}); diff --git a/node_modules/flatted/min.js b/node_modules/flatted/min.js new file mode 100644 index 0000000000000000000000000000000000000000..d3a97cbf4de3ea8a688afaf8bd47ff90966ee096 --- /dev/null +++ b/node_modules/flatted/min.js @@ -0,0 +1 @@ +self.Flatted=function(n){"use strict";function t(n){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(n){return typeof n}:function(n){return n&&"function"==typeof Symbol&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},t(n)}var r=JSON.parse,e=JSON.stringify,o=Object.keys,u=String,f="string",i={},c="object",a=function(n,t){return t},l=function(n){return n instanceof u?u(n):n},s=function(n,r){return t(r)===f?new u(r):r},y=function(n,t,r){var e=u(t.push(r)-1);return n.set(r,e),e},p=function(n,e){var f=r(n,s).map(l),y=e||a,p=f[0];if(t(p)===c&&p){var v=[],S=function(n,r,e,f){return function(a){for(var l=o(a),s=l.length,y=0;y ./coverage/lcov.info" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/WebReflection/flatted.git" + }, + "files": [ + "LICENSE", + "README.md", + "cjs/", + "es.js", + "esm.js", + "esm/", + "index.js", + "min.js", + "php/flatted.php", + "python/flatted.py", + "golang/pkg/flatted/flatted.go", + "types/" + ], + "keywords": [ + "circular", + "JSON", + "fast", + "parser", + "minimal" + ], + "author": "Andrea Giammarchi", + "license": "ISC", + "bugs": { + "url": "https://github.com/WebReflection/flatted/issues" + }, + "homepage": "https://github.com/WebReflection/flatted#readme", + "devDependencies": { + "@babel/core": "^7.29.0", + "@babel/preset-env": "^7.29.0", + "@rollup/plugin-babel": "^7.0.0", + "@rollup/plugin-terser": "^1.0.0", + "@ungap/structured-clone": "^1.3.0", + "ascjs": "^6.0.3", + "c8": "^11.0.0", + "circular-json": "^0.5.9", + "circular-json-es6": "^2.0.2", + "flatted-view": "^0.1.1", + "jsan": "^3.1.14", + "rollup": "^4.59.0", + "terser": "^5.46.0", + "typescript": "^5.9.3" + }, + "module": "./esm/index.js", + "type": "module", + "exports": { + ".": { + "types": "./types/index.d.ts", + "import": "./esm/index.js", + "default": "./cjs/index.js" + }, + "./esm": "./esm.js", + "./package.json": "./package.json" + }, + "types": "./types/index.d.ts" +} diff --git a/node_modules/flatted/php/flatted.php b/node_modules/flatted/php/flatted.php new file mode 100644 index 0000000000000000000000000000000000000000..22659f6a01746c10b477cd8948505fc94f997772 --- /dev/null +++ b/node_modules/flatted/php/flatted.php @@ -0,0 +1,156 @@ +value = $value; + } +} + +class Flatted { + + // public utilities + public static function parse($json, $assoc = false, $depth = 512, $options = 0) { + $input = array_map( + 'Flatted::asString', + array_map( + 'Flatted::wrap', + json_decode($json, $assoc, $depth, $options) + ) + ); + $value = &$input[0]; + $set = array(); + $set[] = &$value; + if (is_array($value)) + return Flatted::loop(false, array_keys($value), $input, $set, $value); + if (is_object($value)) + return Flatted::loop(true, Flatted::keys($value), $input, $set, $value); + return $value; + } + + public static function stringify($value, $options = 0, $depth = 512) { + $known = new stdClass; + $known->key = array(); + $known->value = array(); + $input = array(); + $output = array(); + $i = intval(Flatted::index($known, $input, $value)); + while ($i < count($input)) { + $output[$i] = Flatted::transform($known, $input, $input[$i]); + $i++; + } + return json_encode($output, $options, $depth); + } + + // private helpers + private static function asString($value) { + return $value instanceof FlattedString ? $value->value : $value; + } + + private static function index(&$known, &$input, &$value) { + $input[] = &$value; + $index = strval(count($input) - 1); + $known->key[] = &$value; + $known->value[] = &$index; + return $index; + } + + private static function keys(&$value) { + $obj = new ReflectionObject($value); + $props = $obj->getProperties(); + $keys = array(); + foreach ($props as $prop) + $keys[] = $prop->getName(); + return $keys; + } + + private static function loop($obj, $keys, &$input, &$set, &$output) { + foreach ($keys as $key) { + $value = $obj ? $output->$key : $output[$key]; + if ($value instanceof FlattedString) + Flatted::ref($obj, $key, $input[$value->value], $input, $set, $output); + } + return $output; + } + + private static function relate(&$known, &$input, &$value) { + if (is_string($value) || is_array($value) || is_object($value)) { + $key = array_search($value, $known->key, true); + if ($key !== false) + return $known->value[$key]; + return Flatted::index($known, $input, $value); + } + return $value; + } + + private static function ref($obj, &$key, &$value, &$input, &$set, &$output) { + if (is_array($value) && !in_array($value, $set, true)) { + $set[] = $value; + $value = Flatted::loop(false, array_keys($value), $input, $set, $value); + } + elseif (is_object($value) && !in_array($value, $set, true)) { + $set[] = $value; + $value = Flatted::loop(true, Flatted::keys($value), $input, $set, $value); + } + if ($obj) { + $output->$key = &$value; + } + else { + $output[$key] = &$value; + } + } + + private static function transform(&$known, &$input, &$value) { + if (is_array($value)) { + return array_map( + function ($value) use(&$known, &$input) { + return Flatted::relate($known, $input, $value); + }, + $value + ); + } + if (is_object($value)) { + $object = new stdClass; + $keys = Flatted::keys($value); + foreach ($keys as $key) + $object->$key = Flatted::relate($known, $input, $value->$key); + return $object; + } + return $value; + } + + private static function wrap($value) { + if (is_string($value)) { + return new FlattedString($value); + } + if (is_array($value)) { + return array_map('Flatted::wrap', $value); + } + if (is_object($value)) { + $keys = Flatted::keys($value); + foreach ($keys as $key) { + $value->$key = self::wrap($value->$key); + } + } + return $value; + } +} +?> \ No newline at end of file diff --git a/node_modules/flatted/python/flatted.py b/node_modules/flatted/python/flatted.py new file mode 100644 index 0000000000000000000000000000000000000000..261fd4ae3917b6ffd1dce0caa6f585577cbc5673 --- /dev/null +++ b/node_modules/flatted/python/flatted.py @@ -0,0 +1,144 @@ +# ISC License +# +# Copyright (c) 2018-2025, Andrea Giammarchi, @WebReflection +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +# PERFORMANCE OF THIS SOFTWARE. + +import json as _json + +class _Known: + def __init__(self): + self.key = [] + self.value = [] + +class _String: + def __init__(self, value): + self.value = value + +def _array_keys(value): + for i in range(len(value)): + yield i + +def _object_keys(value): + for key in value: + yield key + +def _is_array(value): + return isinstance(value, (list, tuple)) + +def _is_object(value): + return isinstance(value, dict) + +def _is_string(value): + return isinstance(value, str) + +def _index(known, input, value): + input.append(value) + index = str(len(input) - 1) + known.key.append(value) + known.value.append(index) + return index + +def _relate(known, input, value): + if _is_string(value) or _is_array(value) or _is_object(value): + try: + return known.value[known.key.index(value)] + except: + return _index(known, input, value) + + return value + +def _resolver(input, lazy, parsed): + def resolver(output): + keys = _array_keys(output) if _is_array(output) else _object_keys(output) if _is_object(output) else [] + for key in keys: + value = output[key] + if isinstance(value, _String): + tmp = input[int(value.value)] + output[key] = tmp + if (_is_array(tmp) or _is_object(tmp)) and tmp not in parsed: + parsed.append(tmp) + lazy.append([output, key]) + + return output + + return resolver + +def _transform(known, input, value): + if _is_array(value): + output = [] + for val in value: + output.append(_relate(known, input, val)) + return output + + if _is_object(value): + obj = {} + for key in value: + obj[key] = _relate(known, input, value[key]) + return obj + + return value + +def _wrap(value): + if _is_string(value): + return _String(value) + + if _is_array(value): + i = 0 + for val in value: + value[i] = _wrap(val) + i += 1 + + elif _is_object(value): + for key in value: + value[key] = _wrap(value[key]) + + return value + +def parse(value, *args, **kwargs): + json = _json.loads(value, *args, **kwargs) + wrapped = [] + for value in json: + wrapped.append(_wrap(value)) + + input = [] + for value in wrapped: + if isinstance(value, _String): + input.append(value.value) + else: + input.append(value) + + value = input[0] + lazy = [] + revive = _resolver(input, lazy, [value]) + + value = revive(value) + + i = 0 + while i < len(lazy): + o, k = lazy[i] + i += 1 + o[k] = revive(o[k]) + + return value + + +def stringify(value, *args, **kwargs): + known = _Known() + input = [] + output = [] + i = int(_index(known, input, value)) + while i < len(input): + output.append(_transform(known, input, input[i])) + i += 1 + return _json.dumps(output, *args, **kwargs) diff --git a/node_modules/flatted/types/index.d.ts b/node_modules/flatted/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..75dac3385ee0c9eaee83d251c7d0caf919645af0 --- /dev/null +++ b/node_modules/flatted/types/index.d.ts @@ -0,0 +1,4 @@ +export function parse(text: string, reviver?: (this: any, key: string, value: any) => any): any; +export function stringify(value: any, replacer?: (string | number)[] | ((this: any, key: string, value: any) => any), space?: string | number | undefined): string; +export function toJSON(value: any): any; +export function fromJSON(value: any): any; diff --git a/node_modules/follow-redirects/LICENSE b/node_modules/follow-redirects/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..742cbada545ef218c598a58dabd7014e1701cb60 --- /dev/null +++ b/node_modules/follow-redirects/LICENSE @@ -0,0 +1,18 @@ +Copyright 2014–present Olivier Lalonde , James Talmage , Ruben Verborgh + +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. diff --git a/node_modules/follow-redirects/README.md b/node_modules/follow-redirects/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fd35b9e16295f386ab3c8a84713fc79eea6d15a1 --- /dev/null +++ b/node_modules/follow-redirects/README.md @@ -0,0 +1,157 @@ +## Follow Redirects + +Drop-in replacement for Node's `http` and `https` modules that automatically follows redirects. + +[![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) +[![Build Status](https://github.com/follow-redirects/follow-redirects/workflows/CI/badge.svg)](https://github.com/follow-redirects/follow-redirects/actions) +[![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master) +[![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) +[![Sponsor on GitHub](https://img.shields.io/static/v1?label=Sponsor&message=%F0%9F%92%96&logo=GitHub)](https://github.com/sponsors/RubenVerborgh) + +`follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback) + methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback) + modules, with the exception that they will seamlessly follow redirects. + +```javascript +const { http, https } = require('follow-redirects'); + +http.get('http://en.wikipedia.org/', response => { + response.on('data', chunk => { + console.log(chunk); + }); +}).on('error', err => { + console.error(err); +}); +``` + +You can inspect the final redirected URL through the `responseUrl` property on the `response`. +If no redirection happened, `responseUrl` is the original request URL. + +```javascript +const request = https.request({ + host: 'en.wikipedia.org', + path: '/', +}, response => { + console.log(response.responseUrl); + // 'http://duckduckgo.com/robots.txt' +}); +request.end(); +``` + +## Options +### Global options +Global options are set directly on the `follow-redirects` module: + +```javascript +const followRedirects = require('follow-redirects'); +followRedirects.maxRedirects = 10; +followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB +``` + +The following global options are supported: + +- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. + +- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. + +### Per-request options +Per-request options are set by passing an `options` object: + +```javascript +const url = require('url'); +const { http, https } = require('follow-redirects'); + +const options = url.parse('http://en.wikipedia.org/'); +options.maxRedirects = 10; +options.beforeRedirect = (options, response, request) => { + // Use this to adjust the request options upon redirecting, + // to inspect the latest response headers, + // or to cancel the request by throwing an error + + // response.headers = the redirect response headers + // response.statusCode = the redirect response code (eg. 301, 307, etc.) + + // request.url = the requested URL that resulted in a redirect + // request.headers = the headers in the request that resulted in a redirect + // request.method = the method of the request that resulted in a redirect + if (options.hostname === "example.org") { + options.auth = "user:password"; + } +}; +http.request(options); +``` + +In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback), +the following per-request options are supported: +- `followRedirects` (default: `true`) – whether redirects should be followed. + +- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. + +- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. + +- `beforeRedirect` (default: `undefined`) – optionally change the request `options` on redirects, or abort the request by throwing an error. + +- `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }` + +- `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object. + +- `sensitiveHeaders` (default: `[]`) – names of headers to omit when making redirected requests (such as `X-API-Key`, `X-Auth-Token`…) + + +### Advanced usage +By default, `follow-redirects` will use the Node.js default implementations +of [`http`](https://nodejs.org/api/http.html) +and [`https`](https://nodejs.org/api/https.html). +To enable features such as caching and/or intermediate request tracking, +you might instead want to wrap `follow-redirects` around custom protocol implementations: + +```javascript +const { http, https } = require('follow-redirects').wrap({ + http: require('your-custom-http'), + https: require('your-custom-https'), +}); +``` + +Such custom protocols only need an implementation of the `request` method. + +## Browser Usage + +Due to the way the browser works, +the `http` and `https` browser equivalents perform redirects by default. + +By requiring `follow-redirects` this way: +```javascript +const http = require('follow-redirects/http'); +const https = require('follow-redirects/https'); +``` +you can easily tell webpack and friends to replace +`follow-redirect` by the built-in versions: + +```json +{ + "follow-redirects/http" : "http", + "follow-redirects/https" : "https" +} +``` + +## Contributing + +Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues) + detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied + by tests. You can run the test suite locally with a simple `npm test` command. + +## Debug Logging + +`follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging + set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test + suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well. + +## Authors + +- [Ruben Verborgh](https://ruben.verborgh.org/) +- [Olivier Lalonde](mailto:olalonde@gmail.com) +- [James Talmage](mailto:james@talmage.io) + +## License + +[MIT License](https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE) diff --git a/node_modules/follow-redirects/debug.js b/node_modules/follow-redirects/debug.js new file mode 100644 index 0000000000000000000000000000000000000000..decb77dedde56627ef2d50280daa14326a6091e1 --- /dev/null +++ b/node_modules/follow-redirects/debug.js @@ -0,0 +1,15 @@ +var debug; + +module.exports = function () { + if (!debug) { + try { + /* eslint global-require: off */ + debug = require("debug")("follow-redirects"); + } + catch (error) { /* */ } + if (typeof debug !== "function") { + debug = function () { /* */ }; + } + } + debug.apply(null, arguments); +}; diff --git a/node_modules/follow-redirects/http.js b/node_modules/follow-redirects/http.js new file mode 100644 index 0000000000000000000000000000000000000000..695e356174a86759d476ae3c4098206580076fbd --- /dev/null +++ b/node_modules/follow-redirects/http.js @@ -0,0 +1 @@ +module.exports = require("./").http; diff --git a/node_modules/follow-redirects/https.js b/node_modules/follow-redirects/https.js new file mode 100644 index 0000000000000000000000000000000000000000..d21c921d99a7371e8cdeaeee43579f6bc3da77f6 --- /dev/null +++ b/node_modules/follow-redirects/https.js @@ -0,0 +1 @@ +module.exports = require("./").https; diff --git a/node_modules/follow-redirects/index.js b/node_modules/follow-redirects/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3d32523ec32f38db18e05a67551f1948af67c144 --- /dev/null +++ b/node_modules/follow-redirects/index.js @@ -0,0 +1,709 @@ +var url = require("url"); +var URL = url.URL; +var http = require("http"); +var https = require("https"); +var Writable = require("stream").Writable; +var assert = require("assert"); +var debug = require("./debug"); + +// Preventive platform detection +// istanbul ignore next +(function detectUnsupportedEnvironment() { + var looksLikeNode = typeof process !== "undefined"; + var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; + var looksLikeV8 = isFunction(Error.captureStackTrace); + if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { + console.warn("The follow-redirects package should be excluded from browser builds."); + } +}()); + +// Whether to use the native URL object or the legacy url module +var useNativeURL = false; +try { + assert(new URL("")); +} +catch (error) { + useNativeURL = error.code === "ERR_INVALID_URL"; +} + +// HTTP headers to drop across HTTP/HTTPS and domain boundaries +var sensitiveHeaders = [ + "Authorization", + "Proxy-Authorization", + "Cookie", +]; + +// URL fields to preserve in copy operations +var preservedUrlFields = [ + "auth", + "host", + "hostname", + "href", + "path", + "pathname", + "port", + "protocol", + "query", + "search", + "hash", +]; + +// Create handlers that pass events from native requests +var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; +var eventHandlers = Object.create(null); +events.forEach(function (event) { + eventHandlers[event] = function (arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; +}); + +// Error types with codes +var InvalidUrlError = createErrorType( + "ERR_INVALID_URL", + "Invalid URL", + TypeError +); +var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "Redirected request failed" +); +var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded", + RedirectionError +); +var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" +); +var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" +); + +// istanbul ignore next +var destroy = Writable.prototype.destroy || noop; + +// An HTTP(S) request that can be redirected +function RedirectableRequest(options, responseCallback) { + // Initialize the request + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; + + // Attach a callback if passed + if (responseCallback) { + this.on("response", responseCallback); + } + + // React to responses of native requests + var self = this; + this._onNativeResponse = function (response) { + try { + self._processResponse(response); + } + catch (cause) { + self.emit("error", cause instanceof RedirectionError ? + cause : new RedirectionError({ cause: cause })); + } + }; + + // Create filter for sensitive HTTP headers + this._headerFilter = new RegExp("^(?:" + + sensitiveHeaders.concat(options.sensitiveHeaders).map(escapeRegex).join("|") + + ")$", "i"); + + // Perform the first request + this._performRequest(); +} +RedirectableRequest.prototype = Object.create(Writable.prototype); + +RedirectableRequest.prototype.abort = function () { + destroyRequest(this._currentRequest); + this._currentRequest.abort(); + this.emit("abort"); +}; + +RedirectableRequest.prototype.destroy = function (error) { + destroyRequest(this._currentRequest, error); + destroy.call(this, error); + return this; +}; + +// Writes buffered data to the current native request +RedirectableRequest.prototype.write = function (data, encoding, callback) { + // Writing is not allowed if end has been called + if (this._ending) { + throw new WriteAfterEndError(); + } + + // Validate input and shift parameters if necessary + if (!isString(data) && !isBuffer(data)) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (isFunction(encoding)) { + callback = encoding; + encoding = null; + } + + // Ignore empty buffers, since writing them doesn't invoke the callback + // https://github.com/nodejs/node/issues/22066 + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + // Only write when we don't exceed the maximum body length + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data: data, encoding: encoding }); + this._currentRequest.write(data, encoding, callback); + } + // Error when we exceed the maximum body length + else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); + } +}; + +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (isFunction(data)) { + callback = data; + data = encoding = null; + } + else if (isFunction(encoding)) { + callback = encoding; + encoding = null; + } + + // Write data if needed and end + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } + else { + var self = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function () { + self._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; + } +}; + +// Sets a header value on the current native request +RedirectableRequest.prototype.setHeader = function (name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); +}; + +// Clears a header value on the current native request +RedirectableRequest.prototype.removeHeader = function (name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); +}; + +// Global timeout for all underlying requests +RedirectableRequest.prototype.setTimeout = function (msecs, callback) { + var self = this; + + // Destroys the socket on timeout + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } + + // Sets up a timer to trigger a timeout event + function startTimer(socket) { + if (self._timeout) { + clearTimeout(self._timeout); + } + self._timeout = setTimeout(function () { + self.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } + + // Stops a timeout from triggering + function clearTimer() { + // Clear the timeout + if (self._timeout) { + clearTimeout(self._timeout); + self._timeout = null; + } + + // Clean up all attached listeners + self.removeListener("abort", clearTimer); + self.removeListener("error", clearTimer); + self.removeListener("response", clearTimer); + self.removeListener("close", clearTimer); + if (callback) { + self.removeListener("timeout", callback); + } + if (!self.socket) { + self._currentRequest.removeListener("socket", startTimer); + } + } + + // Attach callback if passed + if (callback) { + this.on("timeout", callback); + } + + // Start the timer if or when the socket is opened + if (this.socket) { + startTimer(this.socket); + } + else { + this._currentRequest.once("socket", startTimer); + } + + // Clean up on events + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); + this.on("close", clearTimer); + + return this; +}; + +// Proxy all other public ClientRequest methods +[ + "flushHeaders", "getHeader", + "setNoDelay", "setSocketKeepAlive", +].forEach(function (method) { + RedirectableRequest.prototype[method] = function (a, b) { + return this._currentRequest[method](a, b); + }; +}); + +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); + +RedirectableRequest.prototype._sanitizeOptions = function (options) { + // Ensure headers are always present + if (!options.headers) { + options.headers = {}; + } + if (!isArray(options.sensitiveHeaders)) { + options.sensitiveHeaders = []; + } + + // Since http.request treats host as an alias of hostname, + // but the url module interprets host as hostname plus port, + // eliminate the host property to avoid confusion. + if (options.host) { + // Use hostname if set, because it has precedence + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } + + // Complete the URL object when necessary + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } + else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } +}; + + +// Executes the next native request (initial or redirect) +RedirectableRequest.prototype._performRequest = function () { + // Load the native protocol + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + throw new TypeError("Unsupported protocol " + protocol); + } + + // If specified, use the agent corresponding to the protocol + // (HTTP and HTTPS use different types of agents) + if (this._options.agents) { + var scheme = protocol.slice(0, -1); + this._options.agent = this._options.agents[scheme]; + } + + // Create the native request and set up its event handlers + var request = this._currentRequest = + nativeProtocol.request(this._options, this._onNativeResponse); + request._redirectable = this; + for (var event of events) { + request.on(event, eventHandlers[event]); + } + + // RFC7230§5.3.1: When making a request directly to an origin server, […] + // a client MUST send only the absolute path […] as the request-target. + this._currentUrl = /^\//.test(this._options.path) ? + url.format(this._options) : + // When making a request to a proxy, […] + // a client MUST send the target URI in absolute-form […]. + this._options.path; + + // End a redirected request + // (The first request must be ended explicitly with RedirectableRequest#end) + if (this._isRedirect) { + // Write the request entity and end + var i = 0; + var self = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + // Only write if this request has not been redirected yet + // istanbul ignore else + if (request === self._currentRequest) { + // Report any write errors + // istanbul ignore if + if (error) { + self.emit("error", error); + } + // Write the next buffer if there are still left + else if (i < buffers.length) { + var buffer = buffers[i++]; + // istanbul ignore else + if (!request.finished) { + request.write(buffer.data, buffer.encoding, writeNext); + } + } + // End the request if `end` has been called on us + else if (self._ended) { + request.end(); + } + } + }()); + } +}; + +// Processes a response from the current native request +RedirectableRequest.prototype._processResponse = function (response) { + // Store the redirected response + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode: statusCode, + }); + } + + // RFC7231§6.4: The 3xx (Redirection) class of status code indicates + // that further action needs to be taken by the user agent in order to + // fulfill the request. If a Location header field is provided, + // the user agent MAY automatically redirect its request to the URI + // referenced by the Location field value, + // even if the specific status code is not understood. + + // If the response is not a redirect; return it as-is + var location = response.headers.location; + if (!location || this._options.followRedirects === false || + statusCode < 300 || statusCode >= 400) { + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); + + // Clean up + this._requestBodyBuffers = []; + return; + } + + // The response is a redirect, so abort the current request + destroyRequest(this._currentRequest); + // Discard the remainder of the response to avoid waiting for data + response.destroy(); + + // RFC7231§6.4: A client SHOULD detect and intervene + // in cyclical redirections (i.e., "infinite" redirection loops). + if (++this._redirectCount > this._options.maxRedirects) { + throw new TooManyRedirectsError(); + } + + // Store the request headers if applicable + var requestHeaders; + var beforeRedirect = this._options.beforeRedirect; + if (beforeRedirect) { + requestHeaders = Object.assign({ + // The Host header was set by nativeProtocol.request + Host: response.req.getHeader("host"), + }, this._options.headers); + } + + // RFC7231§6.4: Automatic redirection needs to done with + // care for methods not known to be safe, […] + // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change + // the request method from POST to GET for the subsequent request. + var method = this._options.method; + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || + // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + // Drop a possible entity and headers related to it + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } + + // Drop the Host header, as the redirect might lead to a different host + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); + + // If the redirect is relative, carry over the host of the last request + var currentUrlParts = parseUrl(this._currentUrl); + var currentHost = currentHostHeader || currentUrlParts.host; + var currentUrl = /^\w+:/.test(location) ? this._currentUrl : + url.format(Object.assign(currentUrlParts, { host: currentHost })); + + // Create the redirected request + var redirectUrl = resolveUrl(location, currentUrl); + debug("redirecting to", redirectUrl.href); + this._isRedirect = true; + spreadUrlObject(redirectUrl, this._options); + + // Drop confidential headers when redirecting to a less secure protocol + // or to a different domain that is not a superdomain + if (redirectUrl.protocol !== currentUrlParts.protocol && + redirectUrl.protocol !== "https:" || + redirectUrl.host !== currentHost && + !isSubdomain(redirectUrl.host, currentHost)) { + removeMatchingHeaders(this._headerFilter, this._options.headers); + } + + // Evaluate the beforeRedirect callback + if (isFunction(beforeRedirect)) { + var responseDetails = { + headers: response.headers, + statusCode: statusCode, + }; + var requestDetails = { + url: currentUrl, + method: method, + headers: requestHeaders, + }; + beforeRedirect(this._options, responseDetails, requestDetails); + this._sanitizeOptions(this._options); + } + + // Perform the redirected request + this._performRequest(); +}; + +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; + + // Wrap each protocol + var nativeProtocols = {}; + Object.keys(protocols).forEach(function (scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); + + // Executes a request, following redirects + function request(input, options, callback) { + // Parse parameters, ensuring that input is an object + if (isURL(input)) { + input = spreadUrlObject(input); + } + else if (isString(input)) { + input = spreadUrlObject(parseUrl(input)); + } + else { + callback = options; + options = validateUrl(input); + input = { protocol: protocol }; + } + if (isFunction(options)) { + callback = options; + options = null; + } + + // Set defaults + options = Object.assign({ + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, input, options); + options.nativeProtocols = nativeProtocols; + if (!isString(options.host) && !isString(options.hostname)) { + options.hostname = "::1"; + } + + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + } + + // Executes a GET request, following redirects + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } + + // Expose the properties on the wrapped protocol + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true }, + }); + }); + return exports; +} + +function noop() { /* empty */ } + +function parseUrl(input) { + var parsed; + // istanbul ignore else + if (useNativeURL) { + parsed = new URL(input); + } + else { + // Ensure the URL is valid and absolute + parsed = validateUrl(url.parse(input)); + if (!isString(parsed.protocol)) { + throw new InvalidUrlError({ input }); + } + } + return parsed; +} + +function resolveUrl(relative, base) { + // istanbul ignore next + return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative)); +} + +function validateUrl(input) { + if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { + throw new InvalidUrlError({ input: input.href || input }); + } + if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { + throw new InvalidUrlError({ input: input.href || input }); + } + return input; +} + +function spreadUrlObject(urlObject, target) { + var spread = target || {}; + for (var key of preservedUrlFields) { + spread[key] = urlObject[key]; + } + + // Fix IPv6 hostname + if (spread.hostname.startsWith("[")) { + spread.hostname = spread.hostname.slice(1, -1); + } + // Ensure port is a number + if (spread.port !== "") { + spread.port = Number(spread.port); + } + // Concatenate path + spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; + + return spread; +} + +function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } + } + return (lastValue === null || typeof lastValue === "undefined") ? + undefined : String(lastValue).trim(); +} + +function createErrorType(code, message, baseClass) { + // Create constructor + function CustomError(properties) { + // istanbul ignore else + if (isFunction(Error.captureStackTrace)) { + Error.captureStackTrace(this, this.constructor); + } + Object.assign(this, properties || {}); + this.code = code; + this.message = this.cause ? message + ": " + this.cause.message : message; + } + + // Attach constructor and set default properties + CustomError.prototype = new (baseClass || Error)(); + Object.defineProperties(CustomError.prototype, { + constructor: { + value: CustomError, + enumerable: false, + }, + name: { + value: "Error [" + code + "]", + enumerable: false, + }, + }); + return CustomError; +} + +function destroyRequest(request, error) { + for (var event of events) { + request.removeListener(event, eventHandlers[event]); + } + request.on("error", noop); + request.destroy(error); +} + +function isSubdomain(subdomain, domain) { + assert(isString(subdomain) && isString(domain)); + var dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); +} + +function isArray(value) { + return value instanceof Array; +} + +function isString(value) { + return typeof value === "string" || value instanceof String; +} + +function isFunction(value) { + return typeof value === "function"; +} + +function isBuffer(value) { + return typeof value === "object" && ("length" in value); +} + +function isURL(value) { + return URL && value instanceof URL; +} + +function escapeRegex(regex) { + return regex.replace(/[\]\\/()*+?.$]/g, "\\$&"); +} + +// Exports +module.exports = wrap({ http: http, https: https }); +module.exports.wrap = wrap; diff --git a/node_modules/follow-redirects/package.json b/node_modules/follow-redirects/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1027c77095c649a0ab54f77fd61b5662e71195a5 --- /dev/null +++ b/node_modules/follow-redirects/package.json @@ -0,0 +1,58 @@ +{ + "name": "follow-redirects", + "version": "1.16.0", + "description": "HTTP and HTTPS modules that follow redirects.", + "license": "MIT", + "main": "index.js", + "files": [ + "*.js" + ], + "engines": { + "node": ">=4.0" + }, + "scripts": { + "lint": "eslint *.js test", + "test": "nyc mocha" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/follow-redirects/follow-redirects.git" + }, + "homepage": "https://github.com/follow-redirects/follow-redirects", + "bugs": { + "url": "https://github.com/follow-redirects/follow-redirects/issues" + }, + "keywords": [ + "http", + "https", + "url", + "redirect", + "client", + "location", + "utility" + ], + "author": "Ruben Verborgh (https://ruben.verborgh.org/)", + "contributors": [ + "Olivier Lalonde (http://www.syskall.com)", + "James Talmage " + ], + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "peerDependenciesMeta": { + "debug": { + "optional": true + } + }, + "devDependencies": { + "concat-stream": "^2.0.0", + "eslint": "^5.16.0", + "express": "^4.16.4", + "lolex": "^3.1.0", + "mocha": "^6.0.2", + "nyc": "^14.1.1" + } +} diff --git a/node_modules/fontkit/README.md b/node_modules/fontkit/README.md new file mode 100644 index 0000000000000000000000000000000000000000..027b61ce4e1f2e3aa97474c028dcec821475b769 --- /dev/null +++ b/node_modules/fontkit/README.md @@ -0,0 +1,266 @@ +# fontkit + +Fontkit is an advanced font engine for Node and the browser, used by [PDFKit](https://github.com/devongovett/pdfkit). It supports many font formats, advanced glyph substitution and layout features, glyph path extraction, color emoji glyphs, font subsetting, and more. + +## Features + +* Supports TrueType (.ttf), OpenType (.otf), WOFF, WOFF2, TrueType Collection (.ttc), and Datafork TrueType (.dfont) font files +* Supports mapping characters to glyphs, including support for ligatures and other advanced substitutions (see below) +* Supports reading glyph metrics and laying out glyphs, including support for kerning and other advanced layout features (see below) +* Advanced OpenType features including glyph substitution (GSUB) and positioning (GPOS) +* Apple Advanced Typography (AAT) glyph substitution features (morx table) +* Support for getting glyph vector paths and converting them to SVG paths, or rendering them to a graphics context +* Supports TrueType (glyf) and PostScript (CFF) outlines +* Support for color glyphs (e.g. emoji), including Apple’s SBIX table, and Microsoft’s COLR table +* Support for AAT variation glyphs, allowing for nearly infinite design control over weight, width, and other axes. +* Font subsetting support - create a new font including only the specified glyphs + +## Installation + + npm install fontkit + +## Example + +```javascript +var fontkit = require('fontkit'); + +// open a font synchronously +var font = fontkit.openSync('font.ttf'); + +// layout a string, using default shaping features. +// returns a GlyphRun, describing glyphs and positions. +var run = font.layout('hello world!'); + +// get an SVG path for a glyph +var svg = run.glyphs[0].path.toSVG(); + +// create a font subset +var subset = font.createSubset(); +run.glyphs.forEach(function(glyph) { + subset.includeGlyph(glyph); +}); + +let buffer = subset.encode(); +``` + +## API + +### `fontkit.open(filename, postscriptName = null)` + +Opens a font file asynchronously, and returns a `Promise` with a font object. For collection fonts (such as TrueType collection files), you can pass a `postscriptName` to get that font out of the collection instead of a collection object. + +### `fontkit.openSync(filename, postscriptName = null)` + +Opens a font file synchronously, and returns a font object. For collection fonts (such as TrueType collection files), you can pass a `postscriptName` to get that font out of the collection instead of a collection object. + +### `fontkit.create(buffer, postscriptName = null)` + +Returns a font object for the given buffer. For collection fonts (such as TrueType collection files), you can pass a `postscriptName` to get that font out of the collection instead of a collection object. + +## Font objects + +There are several different types of font objects that are returned by fontkit depending on the font format. They all inherit from the `TTFFont` class and have the same public API, described below. + +### Metadata properties + +The following properties are strings (or null if the font does not contain strings for them) describing the font, as specified by the font creator. + +* `postscriptName` +* `fullName` +* `familyName` +* `subfamilyName` +* `copyright` +* `version` + +### Metrics + +The following properties describe the general metrics of the font. See [here](http://www.freetype.org/freetype2/docs/glyphs/glyphs-3.html) for a good overview of how all of these properties relate to one another. + +* `unitsPerEm` - the size of the font’s internal coordinate grid +* `ascent` - the font’s [ascender](http://en.wikipedia.org/wiki/Ascender_(typography)) +* `descent` - the font’s [descender](http://en.wikipedia.org/wiki/Descender) +* `lineGap` - the amount of space that should be included between lines +* `underlinePosition` - the offset from the normal underline position that should be used +* `underlineThickness` - the weight of the underline that should be used +* `italicAngle` - if this is an italic font, the angle the cursor should be drawn at to match the font design +* `capHeight` - the height of capital letters above the baseline. See [here](http://en.wikipedia.org/wiki/Cap_height) for more details. +* `xHeight`- the height of lower case letters. See [here](http://en.wikipedia.org/wiki/X-height) for more details. +* `bbox` - the font’s bounding box, i.e. the box that encloses all glyphs in the font + +### Other properties + +* `numGlyphs` - the number of glyphs in the font +* `characterSet` - an array of all of the unicode code points supported by the font +* `availableFeatures` - an array of all [OpenType feature tags](https://www.microsoft.com/typography/otspec/featuretags.htm) (or mapped AAT tags) supported by the font (see below for a description of this) + +### Character to glyph mapping + +Fontkit includes several methods for character to glyph mapping, including support for advanced OpenType and AAT substitutions. + +#### `font.glyphForCodePoint(codePoint)` + +Maps a single unicode code point (number) to a Glyph object. Does not perform any advanced substitutions (there is no context to do so). + +#### `font.hasGlyphForCodePoint(codePoint)` + +Returns whether there is glyph in the font for the given unicode code point. + +#### `font.glyphsForString(string)` + +This method returns an array of Glyph objects for the given string. This is only a one-to-one mapping from characters +to glyphs. For most uses, you should use `font.layout` (described below), which provides a much more advanced mapping +supporting AAT and OpenType shaping. + +### Glyph metrics and layout + +Fontkit includes several methods for accessing glyph metrics and performing layout, including support for kerning and other advanced OpenType positioning adjustments. + +#### `font.widthOfGlyph(glyph_id)` + +Returns the advance width (described above) for a single glyph id. + +#### `font.layout(string, features = [] | {})` + +This method returns a `GlyphRun` object, which includes an array of `Glyph`s and `GlyphPosition`s for the given string. +`Glyph` objects are described below. `GlyphPosition` objects include 4 properties: `xAdvance`, `yAdvance`, `xOffset`, +and `yOffset`. + +The `features` parameter is either an array of [OpenType feature tags](https://www.microsoft.com/typography/otspec/featuretags.htm) to be applied +in addition to the default set, or an object mapping OpenType features to a boolean enabling or disabling each. If this is an AAT font, the OpenType feature tags are mapped to AAT features. + +### Variation fonts + +Fontkit has support for AAT variation fonts, where glyphs can adjust their shape according to user defined settings along +various axes including weight, width, and slant. Font designers specify the minimum, default, and maximum values for each +axis they support, and allow the user fine grained control over the rendered text. + +#### `font.variationAxes` + +Returns an object describing the available variation axes. Keys are 4 letter axis tags, and values include `name`, +`min`, `default`, and `max` properties for the axis. + +#### `font.namedVariations` + +The font designer may have picked out some variations that they think look particularly good, for example a light, regular, +and bold weight which would traditionally be separate fonts. This property returns an object describing these named variation +instances that the designer has specified. Keys are variation names, and values are objects with axis settings. + +#### `font.getVariation(variation)` + +Returns a new font object representing this variation, from which you can get glyphs and perform layout as normal. +The `variation` parameter can either be a variation settings object or a string variation name. Variation settings objects +have axis names as keys, and numbers as values (should be in the range specified by `font.variationAxes`). + +### Other methods + +#### `font.getGlyph(glyph_id, codePoints = [])` + +Returns a glyph object for the given glyph id. You can pass the array of code points this glyph represents for your use later, and it will be stored in the glyph object. + +#### `font.createSubset()` + +Returns a Subset object for this font, described below. + +## Font Collection objects + +For font collection files that contain multiple fonts in a single file, such as TrueType Collection (.ttc) and Datafork TrueType (.dfont) files, a font collection object can be returned by Fontkit. + +### `collection.getFont(postscriptName)` + +Gets a font from the collection by its postscript name. Returns a Font object, described above. + +### `collection.fonts` + +This property is a lazily-loaded array of all of the fonts in the collection. + +## Glyph objects + +Glyph objects represent a glyph in the font. They have various properties for accessing metrics and the actual vector path the glyph represents, and methods for rendering the glyph to a graphics context. + +You do not create glyph objects directly. They are created by various methods on the font object, described above. There are several subclasses of the base `Glyph` class internally that may be returned depending on the font format, but they all include the following API. + +### Properties + +* `id` - the glyph id in the font +* `name` - the glyph name in the font +* `codePoints` - an array of unicode code points that are represented by this glyph. There can be multiple code points in the case of ligatures and other glyphs that represent multiple visual characters. +* `path` - a vector Path object representing the glyph +* `bbox` - the glyph’s bounding box, i.e. the rectangle that encloses the glyph outline as tightly as possible. +* `cbox` - the glyph’s control box. This is often the same as the bounding box, but is faster to compute. Because of the way bezier curves are defined, some of the control points can be outside of the bounding box. Where `bbox` takes this into account, `cbox` does not. Thus, `cbox` is less accurate, but faster to compute. See [here](http://www.freetype.org/freetype2/docs/glyphs/glyphs-6.html#section-2) for a more detailed description. +* `advanceWidth` - the glyph’s advance width. + +### `glyph.render(ctx, size)` + +Renders the glyph to the given graphics context, at the specified font size. + +### Color glyphs (e.g. emoji) + +Fontkit has support for several different color emoji font formats. Currently, these include Apple’s SBIX table (as used by the “Apple Color Emoji” font), and Microsoft’s COLR table (supported by Windows 8.1). [Here](http://blog.symbolset.com/multicolor-fonts) is an overview of the various color font formats out there. + +#### `glyph.getImageForSize(size)` + +For SBIX glyphs, which are bitmap based, this returns an object containing some properties about the image, along with the image data itself (usually PNG). + +#### `glyph.layers` + +For COLR glyphs, which are vector based, this returns an array of objects representing the glyphs and colors for each layer in render order. + +## Path objects + +Path objects are returned by glyphs and represent the actual vector outlines for each glyph in the font. Paths can be converted to SVG path data strings, or to functions that can be applied to render the path to a graphics context. + +### `path.moveTo(x, y)` + +Moves the virtual pen to the given x, y coordinates. + +### `path.lineTo(x, y)` + +Adds a line to the path from the current point to the given x, y coordinates. + +### `path.quadraticCurveTo(cpx, cpy, x, y)` + +Adds a quadratic curve to the path from the current point to the given x, y coordinates using cpx, cpy as a control point. + +### `path.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)` + +Adds a bezier curve to the path from the current point to the given x, y coordinates using cp1x, cp1y and cp2x, cp2y as control points. + +### `path.closePath()` + +Closes the current sub-path by drawing a straight line back to the starting point. + +### `path.toFunction()` + +Compiles the path to a JavaScript function that can be applied with a graphics context in order to render the path. + +### `path.toSVG()` + +Converts the path to an SVG path data string. + +### `path.bbox` + +This property represents the path’s bounding box, i.e. the smallest rectangle that contains the entire path shape. This is the exact bounding box, taking into account control points that may be outside the visible shape. + +### `path.cbox` + +This property represents the path’s control box. It is like the bounding box, but it includes all points of the path, including control points of bezier segments. It is much faster to compute than the real bounding box, but less accurate if there are control points outside of the visible shape. + +## Subsets + +Fontkit can perform font subsetting, i.e. the process of creating a new font from an existing font where only the specified glyphs are included. This is useful to reduce the size of large fonts, such as in PDF generation or for web use. + +Currently, subsets produce minimal fonts designed for PDF embedding that may not work as standalone files. They have no cmap tables and other essential tables for standalone use. This limitation will be removed in the future. + +You create a Subset object by calling `font.createSubset()`, described above. The API on Subset objects is as follows. + +### `subset.includeGlyph(glyph)` + +Includes the given glyph object or glyph ID in the subset. + +### `subset.encode()` + +Returns a `Uint8Array` containing the encoded font file. + +## License + +MIT diff --git a/node_modules/fontkit/package.json b/node_modules/fontkit/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dff6f0f847f299c3be576644b4339d2220a31885 --- /dev/null +++ b/node_modules/fontkit/package.json @@ -0,0 +1,98 @@ +{ + "name": "fontkit", + "version": "2.0.4", + "description": "An advanced font engine for Node and the browser", + "keywords": [ + "opentype", + "font", + "typography", + "subset", + "emoji", + "glyph", + "layout" + ], + "scripts": { + "test": "run-s build mocha", + "mocha": "mocha", + "build": "parcel build", + "prepublish": "run-s clean trie:** build", + "trie:data": "node src/opentype/shapers/generate-data.js", + "trie:use": "node src/opentype/shapers/gen-use.js", + "trie:indic": "node src/opentype/shapers/gen-indic.js", + "clean": "shx rm -rf src/opentype/shapers/data.trie src/opentype/shapers/use.trie src/opentype/shapers/use.json src/opentype/shapers/indic.trie src/opentype/shapers/indic.json dist", + "coverage": "c8 mocha" + }, + "type": "module", + "main": "dist/main.cjs", + "node-module": "dist/module.mjs", + "browser": "dist/browser.cjs", + "module": "dist/browser-module.mjs", + "source": "src/index.js", + "exports": { + "node": { + "import": "./dist/module.mjs", + "require": "./dist/main.cjs" + }, + "import": "./dist/browser-module.mjs", + "require": "./dist/browser.cjs" + }, + "targets": { + "main": { + "source": "src/node.js", + "context": "browser", + "engines": { + "browsers": "chrome >= 70" + } + }, + "node-module": { + "source": "src/node.js", + "isLibrary": true, + "includeNodeModules": false, + "engines": { + "browsers": "chrome >= 70" + } + }, + "module": { + "source": "src/index.js", + "engines": { + "browsers": "chrome >= 70" + } + }, + "browser": { + "source": "src/index.js", + "engines": { + "browsers": "chrome >= 70" + } + } + }, + "files": [ + "src", + "dist" + ], + "author": "Devon Govett ", + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/foliojs/fontkit.git" + }, + "dependencies": { + "@swc/helpers": "^0.5.12", + "brotli": "^1.3.2", + "clone": "^2.1.2", + "dfa": "^1.2.0", + "fast-deep-equal": "^3.1.3", + "restructure": "^3.0.0", + "tiny-inflate": "^1.0.3", + "unicode-properties": "^1.4.0", + "unicode-trie": "^2.0.0" + }, + "devDependencies": { + "c8": "^7.11.3", + "codepoints": "^1.2.0", + "concat-stream": "^2.0.0", + "mocha": "^10.0.0", + "npm-run-all": "^4.1.5", + "parcel": "2.0.0-canary.1713", + "shx": "^0.3.4" + } +} diff --git a/node_modules/fontkit/src/CmapProcessor.js b/node_modules/fontkit/src/CmapProcessor.js new file mode 100644 index 0000000000000000000000000000000000000000..6acc50173b1452c47f9dfd131dead380c925a293 --- /dev/null +++ b/node_modules/fontkit/src/CmapProcessor.js @@ -0,0 +1,286 @@ +import { binarySearch } from './utils'; +import { encodingExists, getEncoding, getEncodingMapping } from './encodings'; +import { cache } from './decorators'; +import { range } from './utils'; + +export default class CmapProcessor { + constructor(cmapTable) { + // Attempt to find a Unicode cmap first + this.encoding = null; + this.cmap = this.findSubtable(cmapTable, [ + // 32-bit subtables + [3, 10], + [0, 6], + [0, 4], + + // 16-bit subtables + [3, 1], + [0, 3], + [0, 2], + [0, 1], + [0, 0] + ]); + + // If not unicode cmap was found, take the first table with a supported encoding. + if (!this.cmap) { + for (let cmap of cmapTable.tables) { + let encoding = getEncoding(cmap.platformID, cmap.encodingID, cmap.table.language - 1); + let mapping = getEncodingMapping(encoding); + if (mapping) { + this.cmap = cmap.table; + this.encoding = mapping; + } + } + } + + if (!this.cmap) { + throw new Error("Could not find a supported cmap table"); + } + + this.uvs = this.findSubtable(cmapTable, [[0, 5]]); + if (this.uvs && this.uvs.version !== 14) { + this.uvs = null; + } + } + + findSubtable(cmapTable, pairs) { + for (let [platformID, encodingID] of pairs) { + for (let cmap of cmapTable.tables) { + if (cmap.platformID === platformID && cmap.encodingID === encodingID) { + return cmap.table; + } + } + } + + return null; + } + + lookup(codepoint, variationSelector) { + // If there is no Unicode cmap in this font, we need to re-encode + // the codepoint in the encoding that the cmap supports. + if (this.encoding) { + codepoint = this.encoding.get(codepoint) || codepoint; + + // Otherwise, try to get a Unicode variation selector for this codepoint if one is provided. + } else if (variationSelector) { + let gid = this.getVariationSelector(codepoint, variationSelector); + if (gid) { + return gid; + } + } + + let cmap = this.cmap; + switch (cmap.version) { + case 0: + return cmap.codeMap.get(codepoint) || 0; + + case 4: { + let min = 0; + let max = cmap.segCount - 1; + while (min <= max) { + let mid = (min + max) >> 1; + + if (codepoint < cmap.startCode.get(mid)) { + max = mid - 1; + } else if (codepoint > cmap.endCode.get(mid)) { + min = mid + 1; + } else { + let rangeOffset = cmap.idRangeOffset.get(mid); + let gid; + + if (rangeOffset === 0) { + gid = codepoint + cmap.idDelta.get(mid); + } else { + let index = rangeOffset / 2 + (codepoint - cmap.startCode.get(mid)) - (cmap.segCount - mid); + gid = cmap.glyphIndexArray.get(index) || 0; + if (gid !== 0) { + gid += cmap.idDelta.get(mid); + } + } + + return gid & 0xffff; + } + } + + return 0; + } + + case 8: + throw new Error('TODO: cmap format 8'); + + case 6: + case 10: + return cmap.glyphIndices.get(codepoint - cmap.firstCode) || 0; + + case 12: + case 13: { + let min = 0; + let max = cmap.nGroups - 1; + while (min <= max) { + let mid = (min + max) >> 1; + let group = cmap.groups.get(mid); + + if (codepoint < group.startCharCode) { + max = mid - 1; + } else if (codepoint > group.endCharCode) { + min = mid + 1; + } else { + if (cmap.version === 12) { + return group.glyphID + (codepoint - group.startCharCode); + } else { + return group.glyphID; + } + } + } + + return 0; + } + + case 14: + throw new Error('TODO: cmap format 14'); + + default: + throw new Error(`Unknown cmap format ${cmap.version}`); + } + } + + getVariationSelector(codepoint, variationSelector) { + if (!this.uvs) { + return 0; + } + + let selectors = this.uvs.varSelectors.toArray(); + let i = binarySearch(selectors, x => variationSelector - x.varSelector); + let sel = selectors[i]; + + if (i !== -1 && sel.defaultUVS) { + i = binarySearch(sel.defaultUVS, x => + codepoint < x.startUnicodeValue ? -1 : codepoint > x.startUnicodeValue + x.additionalCount ? +1 : 0 + ); + } + + if (i !== -1 && sel.nonDefaultUVS) { + i = binarySearch(sel.nonDefaultUVS, x => codepoint - x.unicodeValue); + if (i !== -1) { + return sel.nonDefaultUVS[i].glyphID; + } + } + + return 0; + } + + @cache + getCharacterSet() { + let cmap = this.cmap; + switch (cmap.version) { + case 0: + return range(0, cmap.codeMap.length); + + case 4: { + let res = []; + let endCodes = cmap.endCode.toArray(); + for (let i = 0; i < endCodes.length; i++) { + let tail = endCodes[i] + 1; + let start = cmap.startCode.get(i); + res.push(...range(start, tail)); + } + + return res; + } + + case 8: + throw new Error('TODO: cmap format 8'); + + case 6: + case 10: + return range(cmap.firstCode, cmap.firstCode + cmap.glyphIndices.length); + + case 12: + case 13: { + let res = []; + for (let group of cmap.groups.toArray()) { + res.push(...range(group.startCharCode, group.endCharCode + 1)); + } + + return res; + } + + case 14: + throw new Error('TODO: cmap format 14'); + + default: + throw new Error(`Unknown cmap format ${cmap.version}`); + } + } + + @cache + codePointsForGlyph(gid) { + let cmap = this.cmap; + switch (cmap.version) { + case 0: { + let res = []; + for (let i = 0; i < 256; i++) { + if (cmap.codeMap.get(i) === gid) { + res.push(i); + } + } + + return res; + } + + case 4: { + let res = []; + for (let i = 0; i < cmap.segCount; i++) { + let end = cmap.endCode.get(i); + let start = cmap.startCode.get(i); + let rangeOffset = cmap.idRangeOffset.get(i); + let delta = cmap.idDelta.get(i); + + for (var c = start; c <= end; c++) { + let g = 0; + if (rangeOffset === 0) { + g = c + delta; + } else { + let index = rangeOffset / 2 + (c - start) - (cmap.segCount - i); + g = cmap.glyphIndexArray.get(index) || 0; + if (g !== 0) { + g += delta; + } + } + + if (g === gid) { + res.push(c); + } + } + } + + return res; + } + + case 12: { + let res = []; + for (let group of cmap.groups.toArray()) { + if (gid >= group.glyphID && gid <= group.glyphID + (group.endCharCode - group.startCharCode)) { + res.push(group.startCharCode + (gid - group.glyphID)); + } + } + + return res; + } + + case 13: { + let res = []; + for (let group of cmap.groups.toArray()) { + if (gid === group.glyphID) { + res.push(...range(group.startCharCode, group.endCharCode + 1)); + } + } + + return res; + } + + default: + throw new Error(`Unknown cmap format ${cmap.version}`); + } + } +} diff --git a/node_modules/fontkit/src/DFont.js b/node_modules/fontkit/src/DFont.js new file mode 100644 index 0000000000000000000000000000000000000000..5f606f6047ab9e0523cda97025a9144a7960bec8 --- /dev/null +++ b/node_modules/fontkit/src/DFont.js @@ -0,0 +1,117 @@ +import * as r from 'restructure'; +import TTFFont from './TTFFont'; + +let DFontName = new r.String(r.uint8); +let DFontData = new r.Struct({ + len: r.uint32, + buf: new r.Buffer('len') +}); + +let Ref = new r.Struct({ + id: r.uint16, + nameOffset: r.int16, + attr: r.uint8, + dataOffset: r.uint24, + handle: r.uint32 +}); + +let Type = new r.Struct({ + name: new r.String(4), + maxTypeIndex: r.uint16, + refList: new r.Pointer(r.uint16, new r.Array(Ref, t => t.maxTypeIndex + 1), { type: 'parent' }) +}); + +let TypeList = new r.Struct({ + length: r.uint16, + types: new r.Array(Type, t => t.length + 1) +}); + +let DFontMap = new r.Struct({ + reserved: new r.Reserved(r.uint8, 24), + typeList: new r.Pointer(r.uint16, TypeList), + nameListOffset: new r.Pointer(r.uint16, 'void') +}); + +let DFontHeader = new r.Struct({ + dataOffset: r.uint32, + map: new r.Pointer(r.uint32, DFontMap), + dataLength: r.uint32, + mapLength: r.uint32 +}); + +export default class DFont { + type = 'DFont'; + + static probe(buffer) { + let stream = new r.DecodeStream(buffer); + + try { + var header = DFontHeader.decode(stream); + } catch (e) { + return false; + } + + for (let type of header.map.typeList.types) { + if (type.name === 'sfnt') { + return true; + } + } + + return false; + } + + constructor(stream) { + this.stream = stream; + this.header = DFontHeader.decode(this.stream); + + for (let type of this.header.map.typeList.types) { + for (let ref of type.refList) { + if (ref.nameOffset >= 0) { + this.stream.pos = ref.nameOffset + this.header.map.nameListOffset; + ref.name = DFontName.decode(this.stream); + } else { + ref.name = null; + } + } + + if (type.name === 'sfnt') { + this.sfnt = type; + } + } + } + + getFont(name) { + if (!this.sfnt) { + return null; + } + + for (let ref of this.sfnt.refList) { + let pos = this.header.dataOffset + ref.dataOffset + 4; + let stream = new r.DecodeStream(this.stream.buffer.slice(pos)); + let font = new TTFFont(stream); + if ( + font.postscriptName === name || + ( + font.postscriptName instanceof Uint8Array && + name instanceof Uint8Array && + font.postscriptName.every((v, i) => name[i] === v) + ) + ) { + return font; + } + } + + return null; + } + + get fonts() { + let fonts = []; + for (let ref of this.sfnt.refList) { + let pos = this.header.dataOffset + ref.dataOffset + 4; + let stream = new r.DecodeStream(this.stream.buffer.slice(pos)); + fonts.push(new TTFFont(stream)); + } + + return fonts; + } +} diff --git a/node_modules/fontkit/src/TTFFont.js b/node_modules/fontkit/src/TTFFont.js new file mode 100644 index 0000000000000000000000000000000000000000..6aa0937a3b4717d2a23453ebd6ced9494adf6d5e --- /dev/null +++ b/node_modules/fontkit/src/TTFFont.js @@ -0,0 +1,554 @@ +import * as r from 'restructure'; +import { cache } from './decorators'; +import * as fontkit from './base'; +import Directory from './tables/directory'; +import tables from './tables'; +import CmapProcessor from './CmapProcessor'; +import LayoutEngine from './layout/LayoutEngine'; +import TTFGlyph from './glyph/TTFGlyph'; +import CFFGlyph from './glyph/CFFGlyph'; +import SBIXGlyph from './glyph/SBIXGlyph'; +import COLRGlyph from './glyph/COLRGlyph'; +import GlyphVariationProcessor from './glyph/GlyphVariationProcessor'; +import TTFSubset from './subset/TTFSubset'; +import CFFSubset from './subset/CFFSubset'; +import BBox from './glyph/BBox'; +import { asciiDecoder } from './utils'; + +/** + * This is the base class for all SFNT-based font formats in fontkit. + * It supports TrueType, and PostScript glyphs, and several color glyph formats. + */ +export default class TTFFont { + type = 'TTF'; + + static probe(buffer) { + let format = asciiDecoder.decode(buffer.slice(0, 4)); + return format === 'true' || format === 'OTTO' || format === String.fromCharCode(0, 1, 0, 0); + } + + constructor(stream, variationCoords = null) { + this.defaultLanguage = null; + this.stream = stream; + this.variationCoords = variationCoords; + + this._directoryPos = this.stream.pos; + this._tables = {}; + this._glyphs = {}; + this._decodeDirectory(); + + // define properties for each table to lazily parse + for (let tag in this.directory.tables) { + let table = this.directory.tables[tag]; + if (tables[tag] && table.length > 0) { + Object.defineProperty(this, tag, { + get: this._getTable.bind(this, table) + }); + } + } + } + + setDefaultLanguage(lang = null) { + this.defaultLanguage = lang; + } + + _getTable(table) { + if (!(table.tag in this._tables)) { + try { + this._tables[table.tag] = this._decodeTable(table); + } catch (e) { + if (fontkit.logErrors) { + console.error(`Error decoding table ${table.tag}`); + console.error(e.stack); + } + } + } + + return this._tables[table.tag]; + } + + _getTableStream(tag) { + let table = this.directory.tables[tag]; + if (table) { + this.stream.pos = table.offset; + return this.stream; + } + + return null; + } + + _decodeDirectory() { + return this.directory = Directory.decode(this.stream, {_startOffset: 0}); + } + + _decodeTable(table) { + let pos = this.stream.pos; + + let stream = this._getTableStream(table.tag); + let result = tables[table.tag].decode(stream, this, table.length); + + this.stream.pos = pos; + return result; + } + + /** + * Gets a string from the font's `name` table + * `lang` is a BCP-47 language code. + * @return {string} + */ + getName(key, lang = this.defaultLanguage || fontkit.defaultLanguage) { + let record = this.name && this.name.records[key]; + if (record) { + // Attempt to retrieve the entry, depending on which translation is available: + return ( + record[lang] + || record[this.defaultLanguage] + || record[fontkit.defaultLanguage] + || record['en'] + || record[Object.keys(record)[0]] // Seriously, ANY language would be fine + || null + ); + } + + return null; + } + + /** + * The unique PostScript name for this font, e.g. "Helvetica-Bold" + * @type {string} + */ + get postscriptName() { + return this.getName('postscriptName'); + } + + /** + * The font's full name, e.g. "Helvetica Bold" + * @type {string} + */ + get fullName() { + return this.getName('fullName'); + } + + /** + * The font's family name, e.g. "Helvetica" + * @type {string} + */ + get familyName() { + return this.getName('fontFamily'); + } + + /** + * The font's sub-family, e.g. "Bold". + * @type {string} + */ + get subfamilyName() { + return this.getName('fontSubfamily'); + } + + /** + * The font's copyright information + * @type {string} + */ + get copyright() { + return this.getName('copyright'); + } + + /** + * The font's version number + * @type {string} + */ + get version() { + return this.getName('version'); + } + + /** + * The font’s [ascender](https://en.wikipedia.org/wiki/Ascender_(typography)) + * @type {number} + */ + get ascent() { + return this.hhea.ascent; + } + + /** + * The font’s [descender](https://en.wikipedia.org/wiki/Descender) + * @type {number} + */ + get descent() { + return this.hhea.descent; + } + + /** + * The amount of space that should be included between lines + * @type {number} + */ + get lineGap() { + return this.hhea.lineGap; + } + + /** + * The offset from the normal underline position that should be used + * @type {number} + */ + get underlinePosition() { + return this.post.underlinePosition; + } + + /** + * The weight of the underline that should be used + * @type {number} + */ + get underlineThickness() { + return this.post.underlineThickness; + } + + /** + * If this is an italic font, the angle the cursor should be drawn at to match the font design + * @type {number} + */ + get italicAngle() { + return this.post.italicAngle; + } + + /** + * The height of capital letters above the baseline. + * See [here](https://en.wikipedia.org/wiki/Cap_height) for more details. + * @type {number} + */ + get capHeight() { + let os2 = this['OS/2']; + return os2 ? os2.capHeight : this.ascent; + } + + /** + * The height of lower case letters in the font. + * See [here](https://en.wikipedia.org/wiki/X-height) for more details. + * @type {number} + */ + get xHeight() { + let os2 = this['OS/2']; + return os2 ? os2.xHeight : 0; + } + + /** + * The number of glyphs in the font. + * @type {number} + */ + get numGlyphs() { + return this.maxp.numGlyphs; + } + + /** + * The size of the font’s internal coordinate grid + * @type {number} + */ + get unitsPerEm() { + return this.head.unitsPerEm; + } + + /** + * The font’s bounding box, i.e. the box that encloses all glyphs in the font. + * @type {BBox} + */ + @cache + get bbox() { + return Object.freeze(new BBox(this.head.xMin, this.head.yMin, this.head.xMax, this.head.yMax)); + } + + @cache + get _cmapProcessor() { + return new CmapProcessor(this.cmap); + } + + /** + * An array of all of the unicode code points supported by the font. + * @type {number[]} + */ + @cache + get characterSet() { + return this._cmapProcessor.getCharacterSet(); + } + + /** + * Returns whether there is glyph in the font for the given unicode code point. + * + * @param {number} codePoint + * @return {boolean} + */ + hasGlyphForCodePoint(codePoint) { + return !!this._cmapProcessor.lookup(codePoint); + } + + /** + * Maps a single unicode code point to a Glyph object. + * Does not perform any advanced substitutions (there is no context to do so). + * + * @param {number} codePoint + * @return {Glyph} + */ + glyphForCodePoint(codePoint) { + return this.getGlyph(this._cmapProcessor.lookup(codePoint), [codePoint]); + } + + /** + * Returns an array of Glyph objects for the given string. + * This is only a one-to-one mapping from characters to glyphs. + * For most uses, you should use font.layout (described below), which + * provides a much more advanced mapping supporting AAT and OpenType shaping. + * + * @param {string} string + * @return {Glyph[]} + */ + glyphsForString(string) { + let glyphs = []; + let len = string.length; + let idx = 0; + let last = -1; + let state = -1; + + while (idx <= len) { + let code = 0; + let nextState = 0; + + if (idx < len) { + // Decode the next codepoint from UTF 16 + code = string.charCodeAt(idx++); + if (0xd800 <= code && code <= 0xdbff && idx < len) { + let next = string.charCodeAt(idx); + if (0xdc00 <= next && next <= 0xdfff) { + idx++; + code = ((code & 0x3ff) << 10) + (next & 0x3ff) + 0x10000; + } + } + + // Compute the next state: 1 if the next codepoint is a variation selector, 0 otherwise. + nextState = ((0xfe00 <= code && code <= 0xfe0f) || (0xe0100 <= code && code <= 0xe01ef)) ? 1 : 0; + } else { + idx++; + } + + if (state === 0 && nextState === 1) { + // Variation selector following normal codepoint. + glyphs.push(this.getGlyph(this._cmapProcessor.lookup(last, code), [last, code])); + } else if (state === 0 && nextState === 0) { + // Normal codepoint following normal codepoint. + glyphs.push(this.glyphForCodePoint(last)); + } + + last = code; + state = nextState; + } + + return glyphs; + } + + @cache + get _layoutEngine() { + return new LayoutEngine(this); + } + + /** + * Returns a GlyphRun object, which includes an array of Glyphs and GlyphPositions for the given string. + * + * @param {string} string + * @param {string[]} [userFeatures] + * @param {string} [script] + * @param {string} [language] + * @param {string} [direction] + * @return {GlyphRun} + */ + layout(string, userFeatures, script, language, direction) { + return this._layoutEngine.layout(string, userFeatures, script, language, direction); + } + + /** + * Returns an array of strings that map to the given glyph id. + * @param {number} gid - glyph id + */ + stringsForGlyph(gid) { + return this._layoutEngine.stringsForGlyph(gid); + } + + /** + * An array of all [OpenType feature tags](https://www.microsoft.com/typography/otspec/featuretags.htm) + * (or mapped AAT tags) supported by the font. + * The features parameter is an array of OpenType feature tags to be applied in addition to the default set. + * If this is an AAT font, the OpenType feature tags are mapped to AAT features. + * + * @type {string[]} + */ + get availableFeatures() { + return this._layoutEngine.getAvailableFeatures(); + } + + getAvailableFeatures(script, language) { + return this._layoutEngine.getAvailableFeatures(script, language); + } + + _getBaseGlyph(glyph, characters = []) { + if (!this._glyphs[glyph]) { + if (this.directory.tables.glyf) { + this._glyphs[glyph] = new TTFGlyph(glyph, characters, this); + + } else if (this.directory.tables['CFF '] || this.directory.tables.CFF2) { + this._glyphs[glyph] = new CFFGlyph(glyph, characters, this); + } + } + + return this._glyphs[glyph] || null; + } + + /** + * Returns a glyph object for the given glyph id. + * You can pass the array of code points this glyph represents for + * your use later, and it will be stored in the glyph object. + * + * @param {number} glyph + * @param {number[]} characters + * @return {Glyph} + */ + getGlyph(glyph, characters = []) { + if (!this._glyphs[glyph]) { + if (this.directory.tables.sbix) { + this._glyphs[glyph] = new SBIXGlyph(glyph, characters, this); + + } else if ((this.directory.tables.COLR) && (this.directory.tables.CPAL)) { + this._glyphs[glyph] = new COLRGlyph(glyph, characters, this); + + } else { + this._getBaseGlyph(glyph, characters); + } + } + + return this._glyphs[glyph] || null; + } + + /** + * Returns a Subset for this font. + * @return {Subset} + */ + createSubset() { + if (this.directory.tables['CFF ']) { + return new CFFSubset(this); + } + + return new TTFSubset(this); + } + + /** + * Returns an object describing the available variation axes + * that this font supports. Keys are setting tags, and values + * contain the axis name, range, and default value. + * + * @type {object} + */ + @cache + get variationAxes() { + let res = {}; + if (!this.fvar) { + return res; + } + + for (let axis of this.fvar.axis) { + res[axis.axisTag.trim()] = { + name: axis.name.en, + min: axis.minValue, + default: axis.defaultValue, + max: axis.maxValue + }; + } + + return res; + } + + /** + * Returns an object describing the named variation instances + * that the font designer has specified. Keys are variation names + * and values are the variation settings for this instance. + * + * @type {object} + */ + @cache + get namedVariations() { + let res = {}; + if (!this.fvar) { + return res; + } + + for (let instance of this.fvar.instance) { + let settings = {}; + for (let i = 0; i < this.fvar.axis.length; i++) { + let axis = this.fvar.axis[i]; + settings[axis.axisTag.trim()] = instance.coord[i]; + } + + res[instance.name.en] = settings; + } + + return res; + } + + /** + * Returns a new font with the given variation settings applied. + * Settings can either be an instance name, or an object containing + * variation tags as specified by the `variationAxes` property. + * + * @param {object} settings + * @return {TTFFont} + */ + getVariation(settings) { + if (!(this.directory.tables.fvar && ((this.directory.tables.gvar && this.directory.tables.glyf) || this.directory.tables.CFF2))) { + throw new Error('Variations require a font with the fvar, gvar and glyf, or CFF2 tables.'); + } + + if (typeof settings === 'string') { + settings = this.namedVariations[settings]; + } + + if (typeof settings !== 'object') { + throw new Error('Variation settings must be either a variation name or settings object.'); + } + + // normalize the coordinates + let coords = this.fvar.axis.map((axis, i) => { + let axisTag = axis.axisTag.trim(); + if (axisTag in settings) { + return Math.max(axis.minValue, Math.min(axis.maxValue, settings[axisTag])); + } else { + return axis.defaultValue; + } + }); + + let stream = new r.DecodeStream(this.stream.buffer); + stream.pos = this._directoryPos; + + let font = new TTFFont(stream, coords); + font._tables = this._tables; + + return font; + } + + @cache + get _variationProcessor() { + if (!this.fvar) { + return null; + } + + let variationCoords = this.variationCoords; + + // Ignore if no variation coords and not CFF2 + if (!variationCoords && !this.CFF2) { + return null; + } + + if (!variationCoords) { + variationCoords = this.fvar.axis.map(axis => axis.defaultValue); + } + + return new GlyphVariationProcessor(this, variationCoords); + } + + // Standardized format plugin API + getFont(name) { + return this.getVariation(name); + } +} diff --git a/node_modules/fontkit/src/TrueTypeCollection.js b/node_modules/fontkit/src/TrueTypeCollection.js new file mode 100644 index 0000000000000000000000000000000000000000..2d273093b8e31227ffcefa47c3c75fea8dcdf487 --- /dev/null +++ b/node_modules/fontkit/src/TrueTypeCollection.js @@ -0,0 +1,67 @@ +import * as r from 'restructure'; +import TTFFont from './TTFFont'; +import Directory from './tables/directory'; +import tables from './tables'; +import { asciiDecoder } from './utils'; + +let TTCHeader = new r.VersionedStruct(r.uint32, { + 0x00010000: { + numFonts: r.uint32, + offsets: new r.Array(r.uint32, 'numFonts') + }, + 0x00020000: { + numFonts: r.uint32, + offsets: new r.Array(r.uint32, 'numFonts'), + dsigTag: r.uint32, + dsigLength: r.uint32, + dsigOffset: r.uint32 + } +}); + +export default class TrueTypeCollection { + type = 'TTC'; + + static probe(buffer) { + return asciiDecoder.decode(buffer.slice(0, 4)) === 'ttcf'; + } + + constructor(stream) { + this.stream = stream; + if (stream.readString(4) !== 'ttcf') { + throw new Error('Not a TrueType collection'); + } + + this.header = TTCHeader.decode(stream); + } + + getFont(name) { + for (let offset of this.header.offsets) { + let stream = new r.DecodeStream(this.stream.buffer); + stream.pos = offset; + let font = new TTFFont(stream); + if ( + font.postscriptName === name || + ( + font.postscriptName instanceof Uint8Array && + name instanceof Uint8Array && + font.postscriptName.every((v, i) => name[i] === v) + ) + ) { + return font; + } + } + + return null; + } + + get fonts() { + let fonts = []; + for (let offset of this.header.offsets) { + let stream = new r.DecodeStream(this.stream.buffer); + stream.pos = offset; + fonts.push(new TTFFont(stream)); + } + + return fonts; + } +} diff --git a/node_modules/fontkit/src/WOFF2Font.js b/node_modules/fontkit/src/WOFF2Font.js new file mode 100644 index 0000000000000000000000000000000000000000..2cb327d82c880e5b93d75029cf9fe9b4cb6187fa --- /dev/null +++ b/node_modules/fontkit/src/WOFF2Font.js @@ -0,0 +1,216 @@ +import * as r from 'restructure'; +import brotli from 'brotli/decompress.js'; +import TTFFont from './TTFFont'; +import TTFGlyph, { Point } from './glyph/TTFGlyph'; +import WOFF2Glyph from './glyph/WOFF2Glyph'; +import WOFF2Directory from './tables/WOFF2Directory'; +import { asciiDecoder } from './utils'; + +/** + * Subclass of TTFFont that represents a TTF/OTF font compressed by WOFF2 + * See spec here: http://www.w3.org/TR/WOFF2/ + */ +export default class WOFF2Font extends TTFFont { + type = 'WOFF2'; + + static probe(buffer) { + return asciiDecoder.decode(buffer.slice(0, 4)) === 'wOF2'; + } + + _decodeDirectory() { + this.directory = WOFF2Directory.decode(this.stream); + this._dataPos = this.stream.pos; + } + + _decompress() { + // decompress data and setup table offsets if we haven't already + if (!this._decompressed) { + this.stream.pos = this._dataPos; + let buffer = this.stream.readBuffer(this.directory.totalCompressedSize); + + let decompressedSize = 0; + for (let tag in this.directory.tables) { + let entry = this.directory.tables[tag]; + entry.offset = decompressedSize; + decompressedSize += (entry.transformLength != null) ? entry.transformLength : entry.length; + } + + let decompressed = brotli(buffer, decompressedSize); + if (!decompressed) { + throw new Error('Error decoding compressed data in WOFF2'); + } + + this.stream = new r.DecodeStream(decompressed); + this._decompressed = true; + } + } + + _decodeTable(table) { + this._decompress(); + return super._decodeTable(table); + } + + // Override this method to get a glyph and return our + // custom subclass if there is a glyf table. + _getBaseGlyph(glyph, characters = []) { + if (!this._glyphs[glyph]) { + if (this.directory.tables.glyf && this.directory.tables.glyf.transformed) { + if (!this._transformedGlyphs) { this._transformGlyfTable(); } + return this._glyphs[glyph] = new WOFF2Glyph(glyph, characters, this); + + } else { + return super._getBaseGlyph(glyph, characters); + } + } + } + + _transformGlyfTable() { + this._decompress(); + this.stream.pos = this.directory.tables.glyf.offset; + let table = GlyfTable.decode(this.stream); + let glyphs = []; + + for (let index = 0; index < table.numGlyphs; index++) { + let glyph = {}; + let nContours = table.nContours.readInt16BE(); + glyph.numberOfContours = nContours; + + if (nContours > 0) { // simple glyph + let nPoints = []; + let totalPoints = 0; + + for (let i = 0; i < nContours; i++) { + let r = read255UInt16(table.nPoints); + totalPoints += r; + nPoints.push(totalPoints); + } + + glyph.points = decodeTriplet(table.flags, table.glyphs, totalPoints); + for (let i = 0; i < nContours; i++) { + glyph.points[nPoints[i] - 1].endContour = true; + } + + var instructionSize = read255UInt16(table.glyphs); + + } else if (nContours < 0) { // composite glyph + let haveInstructions = TTFGlyph.prototype._decodeComposite.call({ _font: this }, glyph, table.composites); + if (haveInstructions) { + var instructionSize = read255UInt16(table.glyphs); + } + } + + glyphs.push(glyph); + } + + this._transformedGlyphs = glyphs; + } +} + +// Special class that accepts a length and returns a sub-stream for that data +class Substream { + constructor(length) { + this.length = length; + this._buf = new r.Buffer(length); + } + + decode(stream, parent) { + return new r.DecodeStream(this._buf.decode(stream, parent)); + } +} + +// This struct represents the entire glyf table +let GlyfTable = new r.Struct({ + version: r.uint32, + numGlyphs: r.uint16, + indexFormat: r.uint16, + nContourStreamSize: r.uint32, + nPointsStreamSize: r.uint32, + flagStreamSize: r.uint32, + glyphStreamSize: r.uint32, + compositeStreamSize: r.uint32, + bboxStreamSize: r.uint32, + instructionStreamSize: r.uint32, + nContours: new Substream('nContourStreamSize'), + nPoints: new Substream('nPointsStreamSize'), + flags: new Substream('flagStreamSize'), + glyphs: new Substream('glyphStreamSize'), + composites: new Substream('compositeStreamSize'), + bboxes: new Substream('bboxStreamSize'), + instructions: new Substream('instructionStreamSize') +}); + +const WORD_CODE = 253; +const ONE_MORE_BYTE_CODE2 = 254; +const ONE_MORE_BYTE_CODE1 = 255; +const LOWEST_U_CODE = 253; + +function read255UInt16(stream) { + let code = stream.readUInt8(); + + if (code === WORD_CODE) { + return stream.readUInt16BE(); + } + + if (code === ONE_MORE_BYTE_CODE1) { + return stream.readUInt8() + LOWEST_U_CODE; + } + + if (code === ONE_MORE_BYTE_CODE2) { + return stream.readUInt8() + LOWEST_U_CODE * 2; + } + + return code; +} + +function withSign(flag, baseval) { + return flag & 1 ? baseval : -baseval; +} + +function decodeTriplet(flags, glyphs, nPoints) { + let y; + let x = y = 0; + let res = []; + + for (let i = 0; i < nPoints; i++) { + let dx = 0, dy = 0; + let flag = flags.readUInt8(); + let onCurve = !(flag >> 7); + flag &= 0x7f; + + if (flag < 10) { + dx = 0; + dy = withSign(flag, ((flag & 14) << 7) + glyphs.readUInt8()); + + } else if (flag < 20) { + dx = withSign(flag, (((flag - 10) & 14) << 7) + glyphs.readUInt8()); + dy = 0; + + } else if (flag < 84) { + var b0 = flag - 20; + var b1 = glyphs.readUInt8(); + dx = withSign(flag, 1 + (b0 & 0x30) + (b1 >> 4)); + dy = withSign(flag >> 1, 1 + ((b0 & 0x0c) << 2) + (b1 & 0x0f)); + + } else if (flag < 120) { + var b0 = flag - 84; + dx = withSign(flag, 1 + ((b0 / 12) << 8) + glyphs.readUInt8()); + dy = withSign(flag >> 1, 1 + (((b0 % 12) >> 2) << 8) + glyphs.readUInt8()); + + } else if (flag < 124) { + var b1 = glyphs.readUInt8(); + let b2 = glyphs.readUInt8(); + dx = withSign(flag, (b1 << 4) + (b2 >> 4)); + dy = withSign(flag >> 1, ((b2 & 0x0f) << 8) + glyphs.readUInt8()); + + } else { + dx = withSign(flag, glyphs.readUInt16BE()); + dy = withSign(flag >> 1, glyphs.readUInt16BE()); + } + + x += dx; + y += dy; + res.push(new Point(onCurve, false, x, y)); + } + + return res; +} diff --git a/node_modules/fontkit/src/WOFFFont.js b/node_modules/fontkit/src/WOFFFont.js new file mode 100644 index 0000000000000000000000000000000000000000..6a2399a1a734a6376020032bb497886573a17ee2 --- /dev/null +++ b/node_modules/fontkit/src/WOFFFont.js @@ -0,0 +1,36 @@ +import TTFFont from './TTFFont'; +import WOFFDirectory from './tables/WOFFDirectory'; +import tables from './tables'; +import inflate from 'tiny-inflate'; +import * as r from 'restructure'; +import { asciiDecoder } from './utils'; + +export default class WOFFFont extends TTFFont { + type = 'WOFF'; + + static probe(buffer) { + return asciiDecoder.decode(buffer.slice(0, 4)) === 'wOFF'; + } + + _decodeDirectory() { + this.directory = WOFFDirectory.decode(this.stream, { _startOffset: 0 }); + } + + _getTableStream(tag) { + let table = this.directory.tables[tag]; + if (table) { + this.stream.pos = table.offset; + + if (table.compLength < table.length) { + this.stream.pos += 2; // skip deflate header + let outBuffer = new Uint8Array(table.length); + let buf = inflate(this.stream.readBuffer(table.compLength - 2), outBuffer); + return new r.DecodeStream(buf); + } else { + return this.stream; + } + } + + return null; + } +} diff --git a/node_modules/fontkit/src/aat/AATFeatureMap.js b/node_modules/fontkit/src/aat/AATFeatureMap.js new file mode 100644 index 0000000000000000000000000000000000000000..2aacffec2ddacf43e0ab6e5998ddba42ed5b0246 --- /dev/null +++ b/node_modules/fontkit/src/aat/AATFeatureMap.js @@ -0,0 +1,543 @@ +// see https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html +// and /System/Library/Frameworks/CoreText.framework/Versions/A/Headers/SFNTLayoutTypes.h on a Mac +const features = { + allTypographicFeatures: { + code: 0, + exclusive: false, + allTypeFeatures: 0 + }, + ligatures: { + code: 1, + exclusive: false, + requiredLigatures: 0, + commonLigatures: 2, + rareLigatures: 4, + // logos: 6 + rebusPictures: 8, + diphthongLigatures: 10, + squaredLigatures: 12, + abbrevSquaredLigatures: 14, + symbolLigatures: 16, + contextualLigatures: 18, + historicalLigatures: 20 + }, + cursiveConnection: { + code: 2, + exclusive: true, + unconnected: 0, + partiallyConnected: 1, + cursive: 2 + }, + letterCase: { + code: 3, + exclusive: true + }, + // upperAndLowerCase: 0 # deprecated + // allCaps: 1 # deprecated + // allLowerCase: 2 # deprecated + // smallCaps: 3 # deprecated + // initialCaps: 4 # deprecated + // initialCapsAndSmallCaps: 5 # deprecated + verticalSubstitution: { + code: 4, + exclusive: false, + substituteVerticalForms: 0 + }, + linguisticRearrangement: { + code: 5, + exclusive: false, + linguisticRearrangement: 0 + }, + numberSpacing: { + code: 6, + exclusive: true, + monospacedNumbers: 0, + proportionalNumbers: 1, + thirdWidthNumbers: 2, + quarterWidthNumbers: 3 + }, + smartSwash: { + code: 8, + exclusive: false, + wordInitialSwashes: 0, + wordFinalSwashes: 2, + // lineInitialSwashes: 4 + // lineFinalSwashes: 6 + nonFinalSwashes: 8 + }, + diacritics: { + code: 9, + exclusive: true, + showDiacritics: 0, + hideDiacritics: 1, + decomposeDiacritics: 2 + }, + verticalPosition: { + code: 10, + exclusive: true, + normalPosition: 0, + superiors: 1, + inferiors: 2, + ordinals: 3, + scientificInferiors: 4 + }, + fractions: { + code: 11, + exclusive: true, + noFractions: 0, + verticalFractions: 1, + diagonalFractions: 2 + }, + overlappingCharacters: { + code: 13, + exclusive: false, + preventOverlap: 0 + }, + typographicExtras: { + code: 14, + exclusive: false, + // hyphensToEmDash: 0 + // hyphenToEnDash: 2 + slashedZero: 4 + }, + // formInterrobang: 6 + // smartQuotes: 8 + // periodsToEllipsis: 10 + mathematicalExtras: { + code: 15, + exclusive: false, + // hyphenToMinus: 0 + // asteristoMultiply: 2 + // slashToDivide: 4 + // inequalityLigatures: 6 + // exponents: 8 + mathematicalGreek: 10 + }, + ornamentSets: { + code: 16, + exclusive: true, + noOrnaments: 0, + dingbats: 1, + piCharacters: 2, + fleurons: 3, + decorativeBorders: 4, + internationalSymbols: 5, + mathSymbols: 6 + }, + characterAlternatives: { + code: 17, + exclusive: true, + noAlternates: 0 + }, + // user defined options + designComplexity: { + code: 18, + exclusive: true, + designLevel1: 0, + designLevel2: 1, + designLevel3: 2, + designLevel4: 3, + designLevel5: 4 + }, + styleOptions: { + code: 19, + exclusive: true, + noStyleOptions: 0, + displayText: 1, + engravedText: 2, + illuminatedCaps: 3, + titlingCaps: 4, + tallCaps: 5 + }, + characterShape: { + code: 20, + exclusive: true, + traditionalCharacters: 0, + simplifiedCharacters: 1, + JIS1978Characters: 2, + JIS1983Characters: 3, + JIS1990Characters: 4, + traditionalAltOne: 5, + traditionalAltTwo: 6, + traditionalAltThree: 7, + traditionalAltFour: 8, + traditionalAltFive: 9, + expertCharacters: 10, + JIS2004Characters: 11, + hojoCharacters: 12, + NLCCharacters: 13, + traditionalNamesCharacters: 14 + }, + numberCase: { + code: 21, + exclusive: true, + lowerCaseNumbers: 0, + upperCaseNumbers: 1 + }, + textSpacing: { + code: 22, + exclusive: true, + proportionalText: 0, + monospacedText: 1, + halfWidthText: 2, + thirdWidthText: 3, + quarterWidthText: 4, + altProportionalText: 5, + altHalfWidthText: 6 + }, + transliteration: { + code: 23, + exclusive: true, + noTransliteration: 0 + }, + // hanjaToHangul: 1 + // hiraganaToKatakana: 2 + // katakanaToHiragana: 3 + // kanaToRomanization: 4 + // romanizationToHiragana: 5 + // romanizationToKatakana: 6 + // hanjaToHangulAltOne: 7 + // hanjaToHangulAltTwo: 8 + // hanjaToHangulAltThree: 9 + annotation: { + code: 24, + exclusive: true, + noAnnotation: 0, + boxAnnotation: 1, + roundedBoxAnnotation: 2, + circleAnnotation: 3, + invertedCircleAnnotation: 4, + parenthesisAnnotation: 5, + periodAnnotation: 6, + romanNumeralAnnotation: 7, + diamondAnnotation: 8, + invertedBoxAnnotation: 9, + invertedRoundedBoxAnnotation: 10 + }, + kanaSpacing: { + code: 25, + exclusive: true, + fullWidthKana: 0, + proportionalKana: 1 + }, + ideographicSpacing: { + code: 26, + exclusive: true, + fullWidthIdeographs: 0, + proportionalIdeographs: 1, + halfWidthIdeographs: 2 + }, + unicodeDecomposition: { + code: 27, + exclusive: false, + canonicalComposition: 0, + compatibilityComposition: 2, + transcodingComposition: 4 + }, + rubyKana: { + code: 28, + exclusive: false, + // noRubyKana: 0 # deprecated - use rubyKanaOff instead + // rubyKana: 1 # deprecated - use rubyKanaOn instead + rubyKana: 2 + }, + CJKSymbolAlternatives: { + code: 29, + exclusive: true, + noCJKSymbolAlternatives: 0, + CJKSymbolAltOne: 1, + CJKSymbolAltTwo: 2, + CJKSymbolAltThree: 3, + CJKSymbolAltFour: 4, + CJKSymbolAltFive: 5 + }, + ideographicAlternatives: { + code: 30, + exclusive: true, + noIdeographicAlternatives: 0, + ideographicAltOne: 1, + ideographicAltTwo: 2, + ideographicAltThree: 3, + ideographicAltFour: 4, + ideographicAltFive: 5 + }, + CJKVerticalRomanPlacement: { + code: 31, + exclusive: true, + CJKVerticalRomanCentered: 0, + CJKVerticalRomanHBaseline: 1 + }, + italicCJKRoman: { + code: 32, + exclusive: false, + // noCJKItalicRoman: 0 # deprecated - use CJKItalicRomanOff instead + // CJKItalicRoman: 1 # deprecated - use CJKItalicRomanOn instead + CJKItalicRoman: 2 + }, + caseSensitiveLayout: { + code: 33, + exclusive: false, + caseSensitiveLayout: 0, + caseSensitiveSpacing: 2 + }, + alternateKana: { + code: 34, + exclusive: false, + alternateHorizKana: 0, + alternateVertKana: 2 + }, + stylisticAlternatives: { + code: 35, + exclusive: false, + noStylisticAlternates: 0, + stylisticAltOne: 2, + stylisticAltTwo: 4, + stylisticAltThree: 6, + stylisticAltFour: 8, + stylisticAltFive: 10, + stylisticAltSix: 12, + stylisticAltSeven: 14, + stylisticAltEight: 16, + stylisticAltNine: 18, + stylisticAltTen: 20, + stylisticAltEleven: 22, + stylisticAltTwelve: 24, + stylisticAltThirteen: 26, + stylisticAltFourteen: 28, + stylisticAltFifteen: 30, + stylisticAltSixteen: 32, + stylisticAltSeventeen: 34, + stylisticAltEighteen: 36, + stylisticAltNineteen: 38, + stylisticAltTwenty: 40 + }, + contextualAlternates: { + code: 36, + exclusive: false, + contextualAlternates: 0, + swashAlternates: 2, + contextualSwashAlternates: 4 + }, + lowerCase: { + code: 37, + exclusive: true, + defaultLowerCase: 0, + lowerCaseSmallCaps: 1, + lowerCasePetiteCaps: 2 + }, + upperCase: { + code: 38, + exclusive: true, + defaultUpperCase: 0, + upperCaseSmallCaps: 1, + upperCasePetiteCaps: 2 + }, + languageTag: { // indices into ltag table + code: 39, + exclusive: true + }, + CJKRomanSpacing: { + code: 103, + exclusive: true, + halfWidthCJKRoman: 0, + proportionalCJKRoman: 1, + defaultCJKRoman: 2, + fullWidthCJKRoman: 3 + } +}; + +const feature = (name, selector) => [features[name].code, features[name][selector]]; + +const OTMapping = { + rlig: feature('ligatures', 'requiredLigatures'), + clig: feature('ligatures', 'contextualLigatures'), + dlig: feature('ligatures', 'rareLigatures'), + hlig: feature('ligatures', 'historicalLigatures'), + liga: feature('ligatures', 'commonLigatures'), + hist: feature('ligatures', 'historicalLigatures'), // ?? + + smcp: feature('lowerCase', 'lowerCaseSmallCaps'), + pcap: feature('lowerCase', 'lowerCasePetiteCaps'), + + frac: feature('fractions', 'diagonalFractions'), + dnom: feature('fractions', 'diagonalFractions'), // ?? + numr: feature('fractions', 'diagonalFractions'), // ?? + afrc: feature('fractions', 'verticalFractions'), + // aalt + // abvf, abvm, abvs, akhn, blwf, blwm, blws, cfar, cjct, cpsp, falt, isol, jalt, ljmo, mset? + // ltra, ltrm, nukt, pref, pres, pstf, psts, rand, rkrf, rphf, rtla, rtlm, size, tjmo, tnum? + // unic, vatu, vhal, vjmo, vpal, vrt2 + // dist -> trak table? + // kern, vkrn -> kern table + // lfbd + opbd + rtbd -> opbd table? + // mark, mkmk -> acnt table? + // locl -> languageTag + ltag table + + case: feature('caseSensitiveLayout', 'caseSensitiveLayout'), // also caseSensitiveSpacing + ccmp: feature('unicodeDecomposition', 'canonicalComposition'), // compatibilityComposition? + cpct: feature('CJKVerticalRomanPlacement', 'CJKVerticalRomanCentered'), // guess..., probably not given below + valt: feature('CJKVerticalRomanPlacement', 'CJKVerticalRomanCentered'), + swsh: feature('contextualAlternates', 'swashAlternates'), + cswh: feature('contextualAlternates', 'contextualSwashAlternates'), + curs: feature('cursiveConnection', 'cursive'), // ?? + c2pc: feature('upperCase', 'upperCasePetiteCaps'), + c2sc: feature('upperCase', 'upperCaseSmallCaps'), + + init: feature('smartSwash', 'wordInitialSwashes'), // ?? + fin2: feature('smartSwash', 'wordFinalSwashes'), // ?? + medi: feature('smartSwash', 'nonFinalSwashes'), // ?? + med2: feature('smartSwash', 'nonFinalSwashes'), // ?? + fin3: feature('smartSwash', 'wordFinalSwashes'), // ?? + fina: feature('smartSwash', 'wordFinalSwashes'), // ?? + + pkna: feature('kanaSpacing', 'proportionalKana'), + half: feature('textSpacing', 'halfWidthText'), // also HalfWidthCJKRoman, HalfWidthIdeographs? + halt: feature('textSpacing', 'altHalfWidthText'), + + hkna: feature('alternateKana', 'alternateHorizKana'), + vkna: feature('alternateKana', 'alternateVertKana'), + // hngl: feature 'transliteration', 'hanjaToHangulSelector' # deprecated + + ital: feature('italicCJKRoman', 'CJKItalicRoman'), + lnum: feature('numberCase', 'upperCaseNumbers'), + onum: feature('numberCase', 'lowerCaseNumbers'), + mgrk: feature('mathematicalExtras', 'mathematicalGreek'), + + // nalt: not enough info. what type of annotation? + // ornm: ditto, which ornament style? + + calt: feature('contextualAlternates', 'contextualAlternates'), // or more? + vrt2: feature('verticalSubstitution', 'substituteVerticalForms'), // oh... below? + vert: feature('verticalSubstitution', 'substituteVerticalForms'), + tnum: feature('numberSpacing', 'monospacedNumbers'), + pnum: feature('numberSpacing', 'proportionalNumbers'), + sups: feature('verticalPosition', 'superiors'), + subs: feature('verticalPosition', 'inferiors'), + ordn: feature('verticalPosition', 'ordinals'), + pwid: feature('textSpacing', 'proportionalText'), + hwid: feature('textSpacing', 'halfWidthText'), + qwid: feature('textSpacing', 'quarterWidthText'), // also QuarterWidthNumbers? + twid: feature('textSpacing', 'thirdWidthText'), // also ThirdWidthNumbers? + fwid: feature('textSpacing', 'proportionalText'), //?? + palt: feature('textSpacing', 'altProportionalText'), + trad: feature('characterShape', 'traditionalCharacters'), + smpl: feature('characterShape', 'simplifiedCharacters'), + jp78: feature('characterShape', 'JIS1978Characters'), + jp83: feature('characterShape', 'JIS1983Characters'), + jp90: feature('characterShape', 'JIS1990Characters'), + jp04: feature('characterShape', 'JIS2004Characters'), + expt: feature('characterShape', 'expertCharacters'), + hojo: feature('characterShape', 'hojoCharacters'), + nlck: feature('characterShape', 'NLCCharacters'), + tnam: feature('characterShape', 'traditionalNamesCharacters'), + ruby: feature('rubyKana', 'rubyKana'), + titl: feature('styleOptions', 'titlingCaps'), + zero: feature('typographicExtras', 'slashedZero'), + + ss01: feature('stylisticAlternatives', 'stylisticAltOne'), + ss02: feature('stylisticAlternatives', 'stylisticAltTwo'), + ss03: feature('stylisticAlternatives', 'stylisticAltThree'), + ss04: feature('stylisticAlternatives', 'stylisticAltFour'), + ss05: feature('stylisticAlternatives', 'stylisticAltFive'), + ss06: feature('stylisticAlternatives', 'stylisticAltSix'), + ss07: feature('stylisticAlternatives', 'stylisticAltSeven'), + ss08: feature('stylisticAlternatives', 'stylisticAltEight'), + ss09: feature('stylisticAlternatives', 'stylisticAltNine'), + ss10: feature('stylisticAlternatives', 'stylisticAltTen'), + ss11: feature('stylisticAlternatives', 'stylisticAltEleven'), + ss12: feature('stylisticAlternatives', 'stylisticAltTwelve'), + ss13: feature('stylisticAlternatives', 'stylisticAltThirteen'), + ss14: feature('stylisticAlternatives', 'stylisticAltFourteen'), + ss15: feature('stylisticAlternatives', 'stylisticAltFifteen'), + ss16: feature('stylisticAlternatives', 'stylisticAltSixteen'), + ss17: feature('stylisticAlternatives', 'stylisticAltSeventeen'), + ss18: feature('stylisticAlternatives', 'stylisticAltEighteen'), + ss19: feature('stylisticAlternatives', 'stylisticAltNineteen'), + ss20: feature('stylisticAlternatives', 'stylisticAltTwenty') +}; + + // salt: feature 'stylisticAlternatives', 'stylisticAltOne' # hmm, which one to choose + +// Add cv01-cv99 features +for (let i = 1; i <= 99; i++) { + OTMapping[`cv${`00${i}`.slice(-2)}`] = [features.characterAlternatives.code, i]; +} + +// create inverse mapping +let AATMapping = {}; +for (let ot in OTMapping) { + let aat = OTMapping[ot]; + if (AATMapping[aat[0]] == null) { + AATMapping[aat[0]] = {}; + } + + AATMapping[aat[0]][aat[1]] = ot; +} + +// Maps an array of OpenType features to AAT features +// in the form of {featureType:{featureSetting:true}} +export function mapOTToAAT(features) { + let res = {}; + for (let k in features) { + let r; + if (r = OTMapping[k]) { + if (res[r[0]] == null) { + res[r[0]] = {}; + } + + res[r[0]][r[1]] = features[k]; + } + } + + return res; +} + +// Maps strings in a [featureType, featureSetting] +// to their equivalent number codes +function mapFeatureStrings(f) { + let [type, setting] = f; + if (isNaN(type)) { + var typeCode = features[type] && features[type].code; + } else { + var typeCode = type; + } + + if (isNaN(setting)) { + var settingCode = features[type] && features[type][setting]; + } else { + var settingCode = setting; + } + + return [typeCode, settingCode]; +} + +// Maps AAT features to an array of OpenType features +// Supports both arrays in the form of [[featureType, featureSetting]] +// and objects in the form of {featureType:{featureSetting:true}} +// featureTypes and featureSettings can be either strings or number codes +export function mapAATToOT(features) { + let res = {}; + if (Array.isArray(features)) { + for (let k = 0; k < features.length; k++) { + let r; + let f = mapFeatureStrings(features[k]); + if (r = AATMapping[f[0]] && AATMapping[f[0]][f[1]]) { + res[r] = true; + } + } + + } else if (typeof features === 'object') { + for (let type in features) { + let feature = features[type]; + for (let setting in feature) { + let r; + let f = mapFeatureStrings([type, setting]); + if (feature[setting] && (r = AATMapping[f[0]] && AATMapping[f[0]][f[1]])) { + res[r] = true; + } + } + } + } + + return Object.keys(res); +} diff --git a/node_modules/fontkit/src/aat/AATLayoutEngine.js b/node_modules/fontkit/src/aat/AATLayoutEngine.js new file mode 100644 index 0000000000000000000000000000000000000000..1097e4a1b0abfa0b0daf909bf235037c7b58dc44 --- /dev/null +++ b/node_modules/fontkit/src/aat/AATLayoutEngine.js @@ -0,0 +1,49 @@ +import * as AATFeatureMap from './AATFeatureMap'; +import * as Script from '../layout/Script'; +import AATMorxProcessor from './AATMorxProcessor'; + +export default class AATLayoutEngine { + constructor(font) { + this.font = font; + this.morxProcessor = new AATMorxProcessor(font); + this.fallbackPosition = false; + } + + substitute(glyphRun) { + // AAT expects the glyphs to be in visual order prior to morx processing, + // so reverse the glyphs if the script is right-to-left. + if (glyphRun.direction === 'rtl') { + glyphRun.glyphs.reverse(); + } + + this.morxProcessor.process(glyphRun.glyphs, AATFeatureMap.mapOTToAAT(glyphRun.features)); + } + + getAvailableFeatures(script, language) { + return AATFeatureMap.mapAATToOT(this.morxProcessor.getSupportedFeatures()); + } + + stringsForGlyph(gid) { + let glyphStrings = this.morxProcessor.generateInputs(gid); + let result = new Set; + + for (let glyphs of glyphStrings) { + this._addStrings(glyphs, 0, result, ''); + } + + return result; + } + + _addStrings(glyphs, index, strings, string) { + let codePoints = this.font._cmapProcessor.codePointsForGlyph(glyphs[index]); + + for (let codePoint of codePoints) { + let s = string + String.fromCodePoint(codePoint); + if (index < glyphs.length - 1) { + this._addStrings(glyphs, index + 1, strings, s); + } else { + strings.add(s); + } + } + } +} diff --git a/node_modules/fontkit/src/aat/AATLookupTable.js b/node_modules/fontkit/src/aat/AATLookupTable.js new file mode 100644 index 0000000000000000000000000000000000000000..74f764c7ea8358e11f6d51f53b678eb4bab84446 --- /dev/null +++ b/node_modules/fontkit/src/aat/AATLookupTable.js @@ -0,0 +1,125 @@ +import {cache} from '../decorators'; +import {range} from '../utils'; + +export default class AATLookupTable { + constructor(table) { + this.table = table; + } + + lookup(glyph) { + switch (this.table.version) { + case 0: // simple array format + return this.table.values.getItem(glyph); + + case 2: // segment format + case 4: { + let min = 0; + let max = this.table.binarySearchHeader.nUnits - 1; + + while (min <= max) { + var mid = (min + max) >> 1; + var seg = this.table.segments[mid]; + + // special end of search value + if (seg.firstGlyph === 0xffff) { + return null; + } + + if (glyph < seg.firstGlyph) { + max = mid - 1; + } else if (glyph > seg.lastGlyph) { + min = mid + 1; + } else { + if (this.table.version === 2) { + return seg.value; + } else { + return seg.values[glyph - seg.firstGlyph]; + } + } + } + + return null; + } + + case 6: { // lookup single + let min = 0; + let max = this.table.binarySearchHeader.nUnits - 1; + + while (min <= max) { + var mid = (min + max) >> 1; + var seg = this.table.segments[mid]; + + // special end of search value + if (seg.glyph === 0xffff) { + return null; + } + + if (glyph < seg.glyph) { + max = mid - 1; + } else if (glyph > seg.glyph) { + min = mid + 1; + } else { + return seg.value; + } + } + + return null; + } + + case 8: // lookup trimmed + return this.table.values[glyph - this.table.firstGlyph]; + + default: + throw new Error(`Unknown lookup table format: ${this.table.version}`); + } + } + + @cache + glyphsForValue(classValue) { + let res = []; + + switch (this.table.version) { + case 2: // segment format + case 4: { + for (let segment of this.table.segments) { + if ((this.table.version === 2 && segment.value === classValue)) { + res.push(...range(segment.firstGlyph, segment.lastGlyph + 1)); + } else { + for (let index = 0; index < segment.values.length; index++) { + if (segment.values[index] === classValue) { + res.push(segment.firstGlyph + index); + } + } + } + } + + break; + } + + case 6: { // lookup single + for (let segment of this.table.segments) { + if (segment.value === classValue) { + res.push(segment.glyph); + } + } + + break; + } + + case 8: { // lookup trimmed + for (let i = 0; i < this.table.values.length; i++) { + if (this.table.values[i] === classValue) { + res.push(this.table.firstGlyph + i); + } + } + + break; + } + + default: + throw new Error(`Unknown lookup table format: ${this.table.version}`); + } + + return res; + } +} diff --git a/node_modules/fontkit/src/aat/AATMorxProcessor.js b/node_modules/fontkit/src/aat/AATMorxProcessor.js new file mode 100644 index 0000000000000000000000000000000000000000..94744e1a9f8ddd24aab24136ea86a3c449ffbbd2 --- /dev/null +++ b/node_modules/fontkit/src/aat/AATMorxProcessor.js @@ -0,0 +1,430 @@ +import AATStateMachine from './AATStateMachine'; +import AATLookupTable from './AATLookupTable'; +import {cache} from '../decorators'; + +// indic replacement flags +const MARK_FIRST = 0x8000; +const MARK_LAST = 0x2000; +const VERB = 0x000F; + +// contextual substitution and glyph insertion flag +const SET_MARK = 0x8000; + +// ligature entry flags +const SET_COMPONENT = 0x8000; +const PERFORM_ACTION = 0x2000; + +// ligature action masks +const LAST_MASK = 0x80000000; +const STORE_MASK = 0x40000000; +const OFFSET_MASK = 0x3FFFFFFF; + +const VERTICAL_ONLY = 0x800000; +const REVERSE_DIRECTION = 0x400000; +const HORIZONTAL_AND_VERTICAL = 0x200000; + +// glyph insertion flags +const CURRENT_IS_KASHIDA_LIKE = 0x2000; +const MARKED_IS_KASHIDA_LIKE = 0x1000; +const CURRENT_INSERT_BEFORE = 0x0800; +const MARKED_INSERT_BEFORE = 0x0400; +const CURRENT_INSERT_COUNT = 0x03E0; +const MARKED_INSERT_COUNT = 0x001F; + +export default class AATMorxProcessor { + constructor(font) { + this.processIndicRearragement = this.processIndicRearragement.bind(this); + this.processContextualSubstitution = this.processContextualSubstitution.bind(this); + this.processLigature = this.processLigature.bind(this); + this.processNoncontextualSubstitutions = this.processNoncontextualSubstitutions.bind(this); + this.processGlyphInsertion = this.processGlyphInsertion.bind(this); + this.font = font; + this.morx = font.morx; + this.inputCache = null; + } + + // Processes an array of glyphs and applies the specified features + // Features should be in the form of {featureType:{featureSetting:boolean}} + process(glyphs, features = {}) { + for (let chain of this.morx.chains) { + let flags = chain.defaultFlags; + + // enable/disable the requested features + for (let feature of chain.features) { + let f; + if (f = features[feature.featureType]) { + if (f[feature.featureSetting]) { + flags &= feature.disableFlags; + flags |= feature.enableFlags; + } else if (f[feature.featureSetting] === false) { + flags |= ~feature.disableFlags; + flags &= ~feature.enableFlags; + } + } + } + + for (let subtable of chain.subtables) { + if (subtable.subFeatureFlags & flags) { + this.processSubtable(subtable, glyphs); + } + } + } + + // remove deleted glyphs + let index = glyphs.length - 1; + while (index >= 0) { + if (glyphs[index].id === 0xffff) { + glyphs.splice(index, 1); + } + + index--; + } + + return glyphs; + } + + processSubtable(subtable, glyphs) { + this.subtable = subtable; + this.glyphs = glyphs; + if (this.subtable.type === 4) { + this.processNoncontextualSubstitutions(this.subtable, this.glyphs); + return; + } + + this.ligatureStack = []; + this.markedGlyph = null; + this.firstGlyph = null; + this.lastGlyph = null; + this.markedIndex = null; + + let stateMachine = this.getStateMachine(subtable); + let process = this.getProcessor(); + + let reverse = !!(this.subtable.coverage & REVERSE_DIRECTION); + return stateMachine.process(this.glyphs, reverse, process); + } + + @cache + getStateMachine(subtable) { + return new AATStateMachine(subtable.table.stateTable); + } + + getProcessor() { + switch (this.subtable.type) { + case 0: + return this.processIndicRearragement; + case 1: + return this.processContextualSubstitution; + case 2: + return this.processLigature; + case 4: + return this.processNoncontextualSubstitutions; + case 5: + return this.processGlyphInsertion; + default: + throw new Error(`Invalid morx subtable type: ${this.subtable.type}`); + } + } + + processIndicRearragement(glyph, entry, index) { + if (entry.flags & MARK_FIRST) { + this.firstGlyph = index; + } + + if (entry.flags & MARK_LAST) { + this.lastGlyph = index; + } + + reorderGlyphs(this.glyphs, entry.flags & VERB, this.firstGlyph, this.lastGlyph); + } + + processContextualSubstitution(glyph, entry, index) { + let subsitutions = this.subtable.table.substitutionTable.items; + if (entry.markIndex !== 0xffff) { + let lookup = subsitutions.getItem(entry.markIndex); + let lookupTable = new AATLookupTable(lookup); + glyph = this.glyphs[this.markedGlyph]; + var gid = lookupTable.lookup(glyph.id); + if (gid) { + this.glyphs[this.markedGlyph] = this.font.getGlyph(gid, glyph.codePoints); + } + } + + if (entry.currentIndex !== 0xffff) { + let lookup = subsitutions.getItem(entry.currentIndex); + let lookupTable = new AATLookupTable(lookup); + glyph = this.glyphs[index]; + var gid = lookupTable.lookup(glyph.id); + if (gid) { + this.glyphs[index] = this.font.getGlyph(gid, glyph.codePoints); + } + } + + if (entry.flags & SET_MARK) { + this.markedGlyph = index; + } + } + + processLigature(glyph, entry, index) { + if (entry.flags & SET_COMPONENT) { + this.ligatureStack.push(index); + } + + if (entry.flags & PERFORM_ACTION) { + let actions = this.subtable.table.ligatureActions; + let components = this.subtable.table.components; + let ligatureList = this.subtable.table.ligatureList; + + let actionIndex = entry.action; + let last = false; + let ligatureIndex = 0; + let codePoints = []; + let ligatureGlyphs = []; + + while (!last) { + let componentGlyph = this.ligatureStack.pop(); + codePoints.unshift(...this.glyphs[componentGlyph].codePoints); + + let action = actions.getItem(actionIndex++); + last = !!(action & LAST_MASK); + let store = !!(action & STORE_MASK); + let offset = (action & OFFSET_MASK) << 2 >> 2; // sign extend 30 to 32 bits + offset += this.glyphs[componentGlyph].id; + + let component = components.getItem(offset); + ligatureIndex += component; + + if (last || store) { + let ligatureEntry = ligatureList.getItem(ligatureIndex); + this.glyphs[componentGlyph] = this.font.getGlyph(ligatureEntry, codePoints); + ligatureGlyphs.push(componentGlyph); + ligatureIndex = 0; + codePoints = []; + } else { + this.glyphs[componentGlyph] = this.font.getGlyph(0xffff); + } + } + + // Put ligature glyph indexes back on the stack + this.ligatureStack.push(...ligatureGlyphs); + } + } + + processNoncontextualSubstitutions(subtable, glyphs, index) { + let lookupTable = new AATLookupTable(subtable.table.lookupTable); + + for (index = 0; index < glyphs.length; index++) { + let glyph = glyphs[index]; + if (glyph.id !== 0xffff) { + let gid = lookupTable.lookup(glyph.id); + if (gid) { // 0 means do nothing + glyphs[index] = this.font.getGlyph(gid, glyph.codePoints); + } + } + } + } + + _insertGlyphs(glyphIndex, insertionActionIndex, count, isBefore) { + let insertions = []; + while (count--) { + let gid = this.subtable.table.insertionActions.getItem(insertionActionIndex++); + insertions.push(this.font.getGlyph(gid)); + } + + if (!isBefore) { + glyphIndex++; + } + + this.glyphs.splice(glyphIndex, 0, ...insertions); + } + + processGlyphInsertion(glyph, entry, index) { + if (entry.flags & SET_MARK) { + this.markedIndex = index; + } + + if (entry.markedInsertIndex !== 0xffff) { + let count = (entry.flags & MARKED_INSERT_COUNT) >>> 5; + let isBefore = !!(entry.flags & MARKED_INSERT_BEFORE); + this._insertGlyphs(this.markedIndex, entry.markedInsertIndex, count, isBefore); + } + + if (entry.currentInsertIndex !== 0xffff) { + let count = (entry.flags & CURRENT_INSERT_COUNT) >>> 5; + let isBefore = !!(entry.flags & CURRENT_INSERT_BEFORE); + this._insertGlyphs(index, entry.currentInsertIndex, count, isBefore); + } + } + + getSupportedFeatures() { + let features = []; + for (let chain of this.morx.chains) { + for (let feature of chain.features) { + features.push([feature.featureType, feature.featureSetting]); + } + } + + return features; + } + + generateInputs(gid) { + if (!this.inputCache) { + this.generateInputCache(); + } + + return this.inputCache[gid] || []; + } + + generateInputCache() { + this.inputCache = {}; + + for (let chain of this.morx.chains) { + let flags = chain.defaultFlags; + + for (let subtable of chain.subtables) { + if (subtable.subFeatureFlags & flags) { + this.generateInputsForSubtable(subtable); + } + } + } + } + + generateInputsForSubtable(subtable) { + // Currently, only supporting ligature subtables. + if (subtable.type !== 2) { + return; + } + + let reverse = !!(subtable.coverage & REVERSE_DIRECTION); + if (reverse) { + throw new Error('Reverse subtable, not supported.'); + } + + this.subtable = subtable; + this.ligatureStack = []; + + let stateMachine = this.getStateMachine(subtable); + let process = this.getProcessor(); + + let input = []; + let stack = []; + this.glyphs = []; + + stateMachine.traverse({ + enter: (glyph, entry) => { + let glyphs = this.glyphs; + stack.push({ + glyphs: glyphs.slice(), + ligatureStack: this.ligatureStack.slice() + }); + + // Add glyph to input and glyphs to process. + let g = this.font.getGlyph(glyph); + input.push(g); + glyphs.push(input[input.length - 1]); + + // Process ligature substitution + process(glyphs[glyphs.length - 1], entry, glyphs.length - 1); + + // Add input to result if only one matching (non-deleted) glyph remains. + let count = 0; + let found = 0; + for (let i = 0; i < glyphs.length && count <= 1; i++) { + if (glyphs[i].id !== 0xffff) { + count++; + found = glyphs[i].id; + } + } + + if (count === 1) { + let result = input.map(g => g.id); + let cache = this.inputCache[found]; + if (cache) { + cache.push(result); + } else { + this.inputCache[found] = [result]; + } + } + }, + + exit: () => { + ({glyphs: this.glyphs, ligatureStack: this.ligatureStack} = stack.pop()); + input.pop(); + } + }); + } +} + +// swaps the glyphs in rangeA with those in rangeB +// reverse the glyphs inside those ranges if specified +// ranges are in [offset, length] format +function swap(glyphs, rangeA, rangeB, reverseA = false, reverseB = false) { + let end = glyphs.splice(rangeB[0] - (rangeB[1] - 1), rangeB[1]); + if (reverseB) { + end.reverse(); + } + + let start = glyphs.splice(rangeA[0], rangeA[1], ...end); + if (reverseA) { + start.reverse(); + } + + glyphs.splice(rangeB[0] - (rangeA[1] - 1), 0, ...start); + return glyphs; +} + +function reorderGlyphs(glyphs, verb, firstGlyph, lastGlyph) { + let length = lastGlyph - firstGlyph + 1; + switch (verb) { + case 0: // no change + return glyphs; + + case 1: // Ax => xA + return swap(glyphs, [firstGlyph, 1], [lastGlyph, 0]); + + case 2: // xD => Dx + return swap(glyphs, [firstGlyph, 0], [lastGlyph, 1]); + + case 3: // AxD => DxA + return swap(glyphs, [firstGlyph, 1], [lastGlyph, 1]); + + case 4: // ABx => xAB + return swap(glyphs, [firstGlyph, 2], [lastGlyph, 0]); + + case 5: // ABx => xBA + return swap(glyphs, [firstGlyph, 2], [lastGlyph, 0], true, false); + + case 6: // xCD => CDx + return swap(glyphs, [firstGlyph, 0], [lastGlyph, 2]); + + case 7: // xCD => DCx + return swap(glyphs, [firstGlyph, 0], [lastGlyph, 2], false, true); + + case 8: // AxCD => CDxA + return swap(glyphs, [firstGlyph, 1], [lastGlyph, 2]); + + case 9: // AxCD => DCxA + return swap(glyphs, [firstGlyph, 1], [lastGlyph, 2], false, true); + + case 10: // ABxD => DxAB + return swap(glyphs, [firstGlyph, 2], [lastGlyph, 1]); + + case 11: // ABxD => DxBA + return swap(glyphs, [firstGlyph, 2], [lastGlyph, 1], true, false); + + case 12: // ABxCD => CDxAB + return swap(glyphs, [firstGlyph, 2], [lastGlyph, 2]); + + case 13: // ABxCD => CDxBA + return swap(glyphs, [firstGlyph, 2], [lastGlyph, 2], true, false); + + case 14: // ABxCD => DCxAB + return swap(glyphs, [firstGlyph, 2], [lastGlyph, 2], false, true); + + case 15: // ABxCD => DCxBA + return swap(glyphs, [firstGlyph, 2], [lastGlyph, 2], true, true); + + default: + throw new Error(`Unknown verb: ${verb}`); + } +} diff --git a/node_modules/fontkit/src/aat/AATStateMachine.js b/node_modules/fontkit/src/aat/AATStateMachine.js new file mode 100644 index 0000000000000000000000000000000000000000..77d31ef02f2dcd5c8ab7f70a825e92d8aef574bf --- /dev/null +++ b/node_modules/fontkit/src/aat/AATStateMachine.js @@ -0,0 +1,96 @@ +import AATLookupTable from './AATLookupTable'; + +const START_OF_TEXT_STATE = 0; +const START_OF_LINE_STATE = 1; + +const END_OF_TEXT_CLASS = 0; +const OUT_OF_BOUNDS_CLASS = 1; +const DELETED_GLYPH_CLASS = 2; +const END_OF_LINE_CLASS = 3; + +const DONT_ADVANCE = 0x4000; + +export default class AATStateMachine { + constructor(stateTable) { + this.stateTable = stateTable; + this.lookupTable = new AATLookupTable(stateTable.classTable); + } + + process(glyphs, reverse, processEntry) { + let currentState = START_OF_TEXT_STATE; // START_OF_LINE_STATE is used for kashida glyph insertions sometimes I think? + let index = reverse ? glyphs.length - 1 : 0; + let dir = reverse ? -1 : 1; + + while ((dir === 1 && index <= glyphs.length) || (dir === -1 && index >= -1)) { + let glyph = null; + let classCode = OUT_OF_BOUNDS_CLASS; + let shouldAdvance = true; + + if (index === glyphs.length || index === -1) { + classCode = END_OF_TEXT_CLASS; + } else { + glyph = glyphs[index]; + if (glyph.id === 0xffff) { // deleted glyph + classCode = DELETED_GLYPH_CLASS; + } else { + classCode = this.lookupTable.lookup(glyph.id); + if (classCode == null) { + classCode = OUT_OF_BOUNDS_CLASS; + } + } + } + + let row = this.stateTable.stateArray.getItem(currentState); + let entryIndex = row[classCode]; + let entry = this.stateTable.entryTable.getItem(entryIndex); + + if (classCode !== END_OF_TEXT_CLASS && classCode !== DELETED_GLYPH_CLASS) { + processEntry(glyph, entry, index); + shouldAdvance = !(entry.flags & DONT_ADVANCE); + } + + currentState = entry.newState; + if (shouldAdvance) { + index += dir; + } + } + + return glyphs; + } + + /** + * Performs a depth-first traversal of the glyph strings + * represented by the state machine. + */ + traverse(opts, state = 0, visited = new Set) { + if (visited.has(state)) { + return; + } + + visited.add(state); + + let {nClasses, stateArray, entryTable} = this.stateTable; + let row = stateArray.getItem(state); + + // Skip predefined classes + for (let classCode = 4; classCode < nClasses; classCode++) { + let entryIndex = row[classCode]; + let entry = entryTable.getItem(entryIndex); + + // Try all glyphs in the class + for (let glyph of this.lookupTable.glyphsForValue(classCode)) { + if (opts.enter) { + opts.enter(glyph, entry); + } + + if (entry.newState !== 0) { + this.traverse(opts, entry.newState, visited); + } + + if (opts.exit) { + opts.exit(glyph, entry); + } + } + } + } +} diff --git a/node_modules/fontkit/src/base.js b/node_modules/fontkit/src/base.js new file mode 100644 index 0000000000000000000000000000000000000000..1f9d40b8590763c53e5ce092e478fd65ff5cfe99 --- /dev/null +++ b/node_modules/fontkit/src/base.js @@ -0,0 +1,29 @@ +import {DecodeStream} from 'restructure'; + +export let logErrors = false; + +let formats = []; +export function registerFormat(format) { + formats.push(format); +}; + +export function create(buffer, postscriptName) { + for (let i = 0; i < formats.length; i++) { + let format = formats[i]; + if (format.probe(buffer)) { + let font = new format(new DecodeStream(buffer)); + if (postscriptName) { + return font.getFont(postscriptName); + } + + return font; + } + } + + throw new Error('Unknown font format'); +}; + +export let defaultLanguage = 'en'; +export function setDefaultLanguage(lang = 'en') { + defaultLanguage = lang; +}; diff --git a/node_modules/fontkit/src/cff/CFFCharsets.js b/node_modules/fontkit/src/cff/CFFCharsets.js new file mode 100644 index 0000000000000000000000000000000000000000..b7a987418eeaddd57cc4874b41e4c865ac48d639 --- /dev/null +++ b/node_modules/fontkit/src/cff/CFFCharsets.js @@ -0,0 +1,99 @@ +export let ISOAdobeCharset = [ + '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', + 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', + 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', + 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', + 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', + 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', + 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', + 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', + 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', + 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', + 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', + 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', + 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', + 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', + 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla', + 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', + 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash', + 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', + 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', + 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior', + 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', + 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', + 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute', + 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', + 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', + 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute', + 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', + 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', + 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis', + 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', + 'ugrave', 'yacute', 'ydieresis', 'zcaron' +]; + +export let ExpertCharset = [ + '.notdef', 'space', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', + 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', + 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', + 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', + 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', + 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', + 'colon', 'semicolon', 'commasuperior', 'threequartersemdash', + 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior', + 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', + 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', + 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', + 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', + 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', + 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', + 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', + 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', + 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle', + 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', + 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall', + 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', + 'Cedillasmall', 'onequarter', 'onehalf', 'threequarters', + 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', + 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior', + 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', + 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', + 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', + 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', + 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', + 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', + 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', + 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', + 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', + 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', + 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', + 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', + 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', + 'Ydieresissmall' +]; + +export let ExpertSubsetCharset = [ + '.notdef', 'space', 'dollaroldstyle', 'dollarsuperior', + 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', + 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', + 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', + 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', + 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior', + 'threequartersemdash', 'periodsuperior', 'asuperior', 'bsuperior', + 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', + 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', + 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', + 'parenrightinferior', 'hyphensuperior', 'colonmonetary', 'onefitted', + 'rupiah', 'centoldstyle', 'figuredash', 'hypheninferior', 'onequarter', + 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths', + 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior', + 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', + 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', + 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', + 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', + 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', + 'periodinferior', 'commainferior' +]; diff --git a/node_modules/fontkit/src/cff/CFFDict.js b/node_modules/fontkit/src/cff/CFFDict.js new file mode 100644 index 0000000000000000000000000000000000000000..569c106755295a58463a3bfb0f67f76d8e86c0e1 --- /dev/null +++ b/node_modules/fontkit/src/cff/CFFDict.js @@ -0,0 +1,167 @@ +import isEqual from 'fast-deep-equal'; +import * as r from 'restructure'; +import CFFOperand from './CFFOperand'; +import { PropertyDescriptor } from 'restructure'; + +export default class CFFDict { + constructor(ops = []) { + this.ops = ops; + this.fields = {}; + for (let field of ops) { + let key = Array.isArray(field[0]) ? field[0][0] << 8 | field[0][1] : field[0]; + this.fields[key] = field; + } + } + + decodeOperands(type, stream, ret, operands) { + if (Array.isArray(type)) { + return operands.map((op, i) => this.decodeOperands(type[i], stream, ret, [op])); + } else if (type.decode != null) { + return type.decode(stream, ret, operands); + } else { + switch (type) { + case 'number': + case 'offset': + case 'sid': + return operands[0]; + case 'boolean': + return !!operands[0]; + default: + return operands; + } + } + } + + encodeOperands(type, stream, ctx, operands) { + if (Array.isArray(type)) { + return operands.map((op, i) => this.encodeOperands(type[i], stream, ctx, op)[0]); + } else if (type.encode != null) { + return type.encode(stream, operands, ctx); + } else if (typeof operands === 'number') { + return [operands]; + } else if (typeof operands === 'boolean') { + return [+operands]; + } else if (Array.isArray(operands)) { + return operands; + } else { + return [operands]; + } + } + + decode(stream, parent) { + let end = stream.pos + parent.length; + let ret = {}; + let operands = []; + + // define hidden properties + Object.defineProperties(ret, { + parent: { value: parent }, + _startOffset: { value: stream.pos } + }); + + // fill in defaults + for (let key in this.fields) { + let field = this.fields[key]; + ret[field[1]] = field[3]; + } + + while (stream.pos < end) { + let b = stream.readUInt8(); + if (b < 28) { + if (b === 12) { + b = (b << 8) | stream.readUInt8(); + } + + let field = this.fields[b]; + if (!field) { + throw new Error(`Unknown operator ${b}`); + } + + let val = this.decodeOperands(field[2], stream, ret, operands); + if (val != null) { + if (val instanceof PropertyDescriptor) { + Object.defineProperty(ret, field[1], val); + } else { + ret[field[1]] = val; + } + } + + operands = []; + } else { + operands.push(CFFOperand.decode(stream, b)); + } + } + + return ret; + } + + size(dict, parent, includePointers = true) { + let ctx = { + parent, + val: dict, + pointerSize: 0, + startOffset: parent.startOffset || 0 + }; + + let len = 0; + + for (let k in this.fields) { + let field = this.fields[k]; + let val = dict[field[1]]; + if (val == null || isEqual(val, field[3])) { + continue; + } + + let operands = this.encodeOperands(field[2], null, ctx, val); + for (let op of operands) { + len += CFFOperand.size(op); + } + + let key = Array.isArray(field[0]) ? field[0] : [field[0]]; + len += key.length; + } + + if (includePointers) { + len += ctx.pointerSize; + } + + return len; + } + + encode(stream, dict, parent) { + let ctx = { + pointers: [], + startOffset: stream.pos, + parent, + val: dict, + pointerSize: 0 + }; + + ctx.pointerOffset = stream.pos + this.size(dict, ctx, false); + + for (let field of this.ops) { + let val = dict[field[1]]; + if (val == null || isEqual(val, field[3])) { + continue; + } + + let operands = this.encodeOperands(field[2], stream, ctx, val); + for (let op of operands) { + CFFOperand.encode(stream, op); + } + + let key = Array.isArray(field[0]) ? field[0] : [field[0]]; + for (let op of key) { + stream.writeUInt8(op); + } + } + + let i = 0; + while (i < ctx.pointers.length) { + let ptr = ctx.pointers[i++]; + ptr.type.encode(stream, ptr.val, ptr.parent); + } + + return; + } +} diff --git a/node_modules/fontkit/src/cff/CFFEncodings.js b/node_modules/fontkit/src/cff/CFFEncodings.js new file mode 100644 index 0000000000000000000000000000000000000000..5465bb4f93a00b972e17d4e419f71bdbd28b7209 --- /dev/null +++ b/node_modules/fontkit/src/cff/CFFEncodings.js @@ -0,0 +1,48 @@ +export let StandardEncoding = [ + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', + 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', + 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', + 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', + 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', + 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', + 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', + 'daggerdbl', 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', + 'guillemotright', 'ellipsis', 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', 'tilde', + 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla', '', 'hungarumlaut', 'ogonek', 'caron', + 'emdash', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '', '', + '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae', '', '', '', 'dotlessi', '', '', + 'lslash', 'oslash', 'oe', 'germandbls' +]; + +export let ExpertEncoding = [ + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior', + 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', + 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', + 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', + 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior', + 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior', + 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', + 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', + 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', + 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', + 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', + 'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior', + '', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters', + 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '', + '', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', + 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', + 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', + 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', + 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', + 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', + 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', + 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', + 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall' +]; diff --git a/node_modules/fontkit/src/cff/CFFFont.js b/node_modules/fontkit/src/cff/CFFFont.js new file mode 100644 index 0000000000000000000000000000000000000000..c6c6809b36002bb6d1725dc05efce5cd482630e2 --- /dev/null +++ b/node_modules/fontkit/src/cff/CFFFont.js @@ -0,0 +1,159 @@ +import * as r from 'restructure'; +import CFFIndex from './CFFIndex'; +import CFFTop from './CFFTop'; +import CFFPrivateDict from './CFFPrivateDict'; +import standardStrings from './CFFStandardStrings'; + +class CFFFont { + constructor(stream) { + this.stream = stream; + this.decode(); + } + + static decode(stream) { + return new CFFFont(stream); + } + + decode() { + let start = this.stream.pos; + let top = CFFTop.decode(this.stream); + for (let key in top) { + let val = top[key]; + this[key] = val; + } + + if (this.version < 2) { + if (this.topDictIndex.length !== 1) { + throw new Error("Only a single font is allowed in CFF"); + } + + this.topDict = this.topDictIndex[0]; + } + + this.isCIDFont = this.topDict.ROS != null; + return this; + } + + string(sid) { + if (this.version >= 2) { + return null; + } + + if (sid < standardStrings.length) { + return standardStrings[sid]; + } + + return this.stringIndex[sid - standardStrings.length]; + } + + get postscriptName() { + if (this.version < 2) { + return this.nameIndex[0]; + } + + return null; + } + + get fullName() { + return this.string(this.topDict.FullName); + } + + get familyName() { + return this.string(this.topDict.FamilyName); + } + + getCharString(glyph) { + this.stream.pos = this.topDict.CharStrings[glyph].offset; + return this.stream.readBuffer(this.topDict.CharStrings[glyph].length); + } + + getGlyphName(gid) { + // CFF2 glyph names are in the post table. + if (this.version >= 2) { + return null; + } + + // CID-keyed fonts don't have glyph names + if (this.isCIDFont) { + return null; + } + + let { charset } = this.topDict; + if (Array.isArray(charset)) { + return charset[gid]; + } + + if (gid === 0) { + return '.notdef'; + } + + gid -= 1; + + switch (charset.version) { + case 0: + return this.string(charset.glyphs[gid]); + + case 1: + case 2: + for (let i = 0; i < charset.ranges.length; i++) { + let range = charset.ranges[i]; + if (range.offset <= gid && gid <= range.offset + range.nLeft) { + return this.string(range.first + (gid - range.offset)); + } + } + break; + } + + return null; + } + + fdForGlyph(gid) { + if (!this.topDict.FDSelect) { + return null; + } + + switch (this.topDict.FDSelect.version) { + case 0: + return this.topDict.FDSelect.fds[gid]; + + case 3: + case 4: + let { ranges } = this.topDict.FDSelect; + let low = 0; + let high = ranges.length - 1; + + while (low <= high) { + let mid = (low + high) >> 1; + + if (gid < ranges[mid].first) { + high = mid - 1; + } else if (mid < high && gid >= ranges[mid + 1].first) { + low = mid + 1; + } else { + return ranges[mid].fd; + } + } + default: + throw new Error(`Unknown FDSelect version: ${this.topDict.FDSelect.version}`); + } + } + + privateDictForGlyph(gid) { + if (this.topDict.FDSelect) { + let fd = this.fdForGlyph(gid); + if (this.topDict.FDArray[fd]) { + return this.topDict.FDArray[fd].Private; + } + + return null; + } + + if (this.version < 2) { + return this.topDict.Private; + } + + return this.topDict.FDArray[0].Private; + } +} + +export default CFFFont; diff --git a/node_modules/fontkit/src/cff/CFFIndex.js b/node_modules/fontkit/src/cff/CFFIndex.js new file mode 100644 index 0000000000000000000000000000000000000000..fea5eaf3f966817343ec33fc99eb0bfa4a3c651a --- /dev/null +++ b/node_modules/fontkit/src/cff/CFFIndex.js @@ -0,0 +1,150 @@ +import * as r from 'restructure'; + +export default class CFFIndex { + constructor(type) { + this.type = type; + } + + getCFFVersion(ctx) { + while (ctx && !ctx.hdrSize) { + ctx = ctx.parent; + } + + return ctx ? ctx.version : -1; + } + + decode(stream, parent) { + let version = this.getCFFVersion(parent); + let count = version >= 2 + ? stream.readUInt32BE() + : stream.readUInt16BE(); + + if (count === 0) { + return []; + } + + let offSize = stream.readUInt8(); + let offsetType; + if (offSize === 1) { + offsetType = r.uint8; + } else if (offSize === 2) { + offsetType = r.uint16; + } else if (offSize === 3) { + offsetType = r.uint24; + } else if (offSize === 4) { + offsetType = r.uint32; + } else { + throw new Error(`Bad offset size in CFFIndex: ${offSize} ${stream.pos}`); + } + + let ret = []; + let startPos = stream.pos + ((count + 1) * offSize) - 1; + + let start = offsetType.decode(stream); + for (let i = 0; i < count; i++) { + let end = offsetType.decode(stream); + + if (this.type != null) { + let pos = stream.pos; + stream.pos = startPos + start; + + parent.length = end - start; + ret.push(this.type.decode(stream, parent)); + stream.pos = pos; + } else { + ret.push({ + offset: startPos + start, + length: end - start + }); + } + + start = end; + } + + stream.pos = startPos + start; + return ret; + } + + size(arr, parent) { + let size = 2; + if (arr.length === 0) { + return size; + } + + let type = this.type || new r.Buffer; + + // find maximum offset to detminine offset type + let offset = 1; + for (let i = 0; i < arr.length; i++) { + let item = arr[i]; + offset += type.size(item, parent); + } + + let offsetType; + if (offset <= 0xff) { + offsetType = r.uint8; + } else if (offset <= 0xffff) { + offsetType = r.uint16; + } else if (offset <= 0xffffff) { + offsetType = r.uint24; + } else if (offset <= 0xffffffff) { + offsetType = r.uint32; + } else { + throw new Error("Bad offset in CFFIndex"); + } + + size += 1 + offsetType.size() * (arr.length + 1); + size += offset - 1; + + return size; + } + + encode(stream, arr, parent) { + stream.writeUInt16BE(arr.length); + if (arr.length === 0) { + return; + } + + let type = this.type || new r.Buffer; + + // find maximum offset to detminine offset type + let sizes = []; + let offset = 1; + for (let item of arr) { + let s = type.size(item, parent); + sizes.push(s); + offset += s; + } + + let offsetType; + if (offset <= 0xff) { + offsetType = r.uint8; + } else if (offset <= 0xffff) { + offsetType = r.uint16; + } else if (offset <= 0xffffff) { + offsetType = r.uint24; + } else if (offset <= 0xffffffff) { + offsetType = r.uint32; + } else { + throw new Error("Bad offset in CFFIndex"); + } + + // write offset size + stream.writeUInt8(offsetType.size()); + + // write elements + offset = 1; + offsetType.encode(stream, offset); + + for (let size of sizes) { + offset += size; + offsetType.encode(stream, offset); + } + + for (let item of arr) { + type.encode(stream, item, parent); + } + + return; + } +} diff --git a/node_modules/fontkit/src/cff/CFFOperand.js b/node_modules/fontkit/src/cff/CFFOperand.js new file mode 100644 index 0000000000000000000000000000000000000000..28f858c1c325b05af2c1525aa4973350bfd15e75 --- /dev/null +++ b/node_modules/fontkit/src/cff/CFFOperand.js @@ -0,0 +1,134 @@ +const FLOAT_EOF = 0xf; +const FLOAT_LOOKUP = [ + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', '.', 'E', 'E-', null, '-' +]; + +const FLOAT_ENCODE_LOOKUP = { + '.': 10, + 'E': 11, + 'E-': 12, + '-': 14 +}; + +export default class CFFOperand { + static decode(stream, value) { + if (32 <= value && value <= 246) { + return value - 139; + } + + if (247 <= value && value <= 250) { + return (value - 247) * 256 + stream.readUInt8() + 108; + } + + if (251 <= value && value <= 254) { + return -(value - 251) * 256 - stream.readUInt8() - 108; + } + + if (value === 28) { + return stream.readInt16BE(); + } + + if (value === 29) { + return stream.readInt32BE(); + } + + if (value === 30) { + let str = ''; + while (true) { + let b = stream.readUInt8(); + + let n1 = b >> 4; + if (n1 === FLOAT_EOF) { break; } + str += FLOAT_LOOKUP[n1]; + + let n2 = b & 15; + if (n2 === FLOAT_EOF) { break; } + str += FLOAT_LOOKUP[n2]; + } + + return parseFloat(str); + } + + return null; + } + + static size(value) { + // if the value needs to be forced to the largest size (32 bit) + // e.g. for unknown pointers, set to 32768 + if (value.forceLarge) { + value = 32768; + } + + if ((value | 0) !== value) { // floating point + let str = '' + value; + return 1 + Math.ceil((str.length + 1) / 2); + + } else if (-107 <= value && value <= 107) { + return 1; + + } else if (108 <= value && value <= 1131 || -1131 <= value && value <= -108) { + return 2; + + } else if (-32768 <= value && value <= 32767) { + return 3; + + } else { + return 5; + } + } + + static encode(stream, value) { + // if the value needs to be forced to the largest size (32 bit) + // e.g. for unknown pointers, save the old value and set to 32768 + let val = Number(value); + + if (value.forceLarge) { + stream.writeUInt8(29); + return stream.writeInt32BE(val); + + } else if ((val | 0) !== val) { // floating point + stream.writeUInt8(30); + + let str = '' + val; + for (let i = 0; i < str.length; i += 2) { + let c1 = str[i]; + let n1 = FLOAT_ENCODE_LOOKUP[c1] || +c1; + + if (i === str.length - 1) { + var n2 = FLOAT_EOF; + } else { + let c2 = str[i + 1]; + var n2 = FLOAT_ENCODE_LOOKUP[c2] || +c2; + } + + stream.writeUInt8((n1 << 4) | (n2 & 15)); + } + + if (n2 !== FLOAT_EOF) { + return stream.writeUInt8((FLOAT_EOF << 4)); + } + + } else if (-107 <= val && val <= 107) { + return stream.writeUInt8(val + 139); + + } else if (108 <= val && val <= 1131) { + val -= 108; + stream.writeUInt8((val >> 8) + 247); + return stream.writeUInt8(val & 0xff); + + } else if (-1131 <= val && val <= -108) { + val = -val - 108; + stream.writeUInt8((val >> 8) + 251); + return stream.writeUInt8(val & 0xff); + + } else if (-32768 <= val && val <= 32767) { + stream.writeUInt8(28); + return stream.writeInt16BE(val); + + } else { + stream.writeUInt8(29); + return stream.writeInt32BE(val); + } + } +} diff --git a/node_modules/fontkit/src/cff/CFFPointer.js b/node_modules/fontkit/src/cff/CFFPointer.js new file mode 100644 index 0000000000000000000000000000000000000000..771e834bf6d3a26246aad280e5dbfb26a022f537 --- /dev/null +++ b/node_modules/fontkit/src/cff/CFFPointer.js @@ -0,0 +1,50 @@ +import * as r from 'restructure'; + +export default class CFFPointer extends r.Pointer { + constructor(type, options = {}) { + if (options.type == null) { + options.type = 'global'; + } + + super(null, type, options); + } + + decode(stream, parent, operands) { + this.offsetType = { + decode: () => operands[0] + }; + + return super.decode(stream, parent, operands); + } + + encode(stream, value, ctx) { + if (!stream) { + // compute the size (so ctx.pointerSize is correct) + this.offsetType = { + size: () => 0 + }; + + this.size(value, ctx); + return [new Ptr(0)]; + } + + let ptr = null; + this.offsetType = { + encode: (stream, val) => ptr = val + }; + + super.encode(stream, value, ctx); + return [new Ptr(ptr)]; + } +} + +class Ptr { + constructor(val) { + this.val = val; + this.forceLarge = true; + } + + valueOf() { + return this.val; + } +} diff --git a/node_modules/fontkit/src/cff/CFFPrivateDict.js b/node_modules/fontkit/src/cff/CFFPrivateDict.js new file mode 100644 index 0000000000000000000000000000000000000000..59fcab65037828d2f0e9111b6dd92742df214c0a --- /dev/null +++ b/node_modules/fontkit/src/cff/CFFPrivateDict.js @@ -0,0 +1,39 @@ +import CFFDict from './CFFDict'; +import CFFIndex from './CFFIndex'; +import CFFPointer from './CFFPointer'; + +class CFFBlendOp { + static decode(stream, parent, operands) { + let numBlends = operands.pop(); + + // TODO: actually blend. For now just consume the deltas + // since we don't use any of the values anyway. + while (operands.length > numBlends) { + operands.pop(); + } + } +} + +export default new CFFDict([ + // key name type default + [6, 'BlueValues', 'delta', null], + [7, 'OtherBlues', 'delta', null], + [8, 'FamilyBlues', 'delta', null], + [9, 'FamilyOtherBlues', 'delta', null], + [[12, 9], 'BlueScale', 'number', 0.039625], + [[12, 10], 'BlueShift', 'number', 7], + [[12, 11], 'BlueFuzz', 'number', 1], + [10, 'StdHW', 'number', null], + [11, 'StdVW', 'number', null], + [[12, 12], 'StemSnapH', 'delta', null], + [[12, 13], 'StemSnapV', 'delta', null], + [[12, 14], 'ForceBold', 'boolean', false], + [[12, 17], 'LanguageGroup', 'number', 0], + [[12, 18], 'ExpansionFactor', 'number', 0.06], + [[12, 19], 'initialRandomSeed', 'number', 0], + [20, 'defaultWidthX', 'number', 0], + [21, 'nominalWidthX', 'number', 0], + [22, 'vsindex', 'number', 0], + [23, 'blend', CFFBlendOp, null], + [19, 'Subrs', new CFFPointer(new CFFIndex, {type: 'local'}), null] +]); diff --git a/node_modules/fontkit/src/cff/CFFStandardStrings.js b/node_modules/fontkit/src/cff/CFFStandardStrings.js new file mode 100644 index 0000000000000000000000000000000000000000..b5d59560f65c934c25adac1d14c47ffbfe67fb89 --- /dev/null +++ b/node_modules/fontkit/src/cff/CFFStandardStrings.js @@ -0,0 +1,71 @@ +// Automatically generated from Appendix A of the CFF specification; do +// not edit. Length should be 391. +export default [ + ".notdef", "space", "exclam", "quotedbl", "numbersign", "dollar", + "percent", "ampersand", "quoteright", "parenleft", "parenright", + "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", + "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", + "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", + "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", + "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", + "bracketright", "asciicircum", "underscore", "quoteleft", "a", "b", "c", + "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", + "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", + "asciitilde", "exclamdown", "cent", "sterling", "fraction", "yen", + "florin", "section", "currency", "quotesingle", "quotedblleft", + "guillemotleft", "guilsinglleft", "guilsinglright", "fi", "fl", "endash", + "dagger", "daggerdbl", "periodcentered", "paragraph", "bullet", + "quotesinglbase", "quotedblbase", "quotedblright", "guillemotright", + "ellipsis", "perthousand", "questiondown", "grave", "acute", "circumflex", + "tilde", "macron", "breve", "dotaccent", "dieresis", "ring", "cedilla", + "hungarumlaut", "ogonek", "caron", "emdash", "AE", "ordfeminine", "Lslash", + "Oslash", "OE", "ordmasculine", "ae", "dotlessi", "lslash", "oslash", "oe", + "germandbls", "onesuperior", "logicalnot", "mu", "trademark", "Eth", + "onehalf", "plusminus", "Thorn", "onequarter", "divide", "brokenbar", + "degree", "thorn", "threequarters", "twosuperior", "registered", "minus", + "eth", "multiply", "threesuperior", "copyright", "Aacute", "Acircumflex", + "Adieresis", "Agrave", "Aring", "Atilde", "Ccedilla", "Eacute", + "Ecircumflex", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", + "Igrave", "Ntilde", "Oacute", "Ocircumflex", "Odieresis", "Ograve", + "Otilde", "Scaron", "Uacute", "Ucircumflex", "Udieresis", "Ugrave", + "Yacute", "Ydieresis", "Zcaron", "aacute", "acircumflex", "adieresis", + "agrave", "aring", "atilde", "ccedilla", "eacute", "ecircumflex", + "edieresis", "egrave", "iacute", "icircumflex", "idieresis", "igrave", + "ntilde", "oacute", "ocircumflex", "odieresis", "ograve", "otilde", + "scaron", "uacute", "ucircumflex", "udieresis", "ugrave", "yacute", + "ydieresis", "zcaron", "exclamsmall", "Hungarumlautsmall", + "dollaroldstyle", "dollarsuperior", "ampersandsmall", "Acutesmall", + "parenleftsuperior", "parenrightsuperior", "twodotenleader", + "onedotenleader", "zerooldstyle", "oneoldstyle", "twooldstyle", + "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", + "sevenoldstyle", "eightoldstyle", "nineoldstyle", "commasuperior", + "threequartersemdash", "periodsuperior", "questionsmall", "asuperior", + "bsuperior", "centsuperior", "dsuperior", "esuperior", "isuperior", + "lsuperior", "msuperior", "nsuperior", "osuperior", "rsuperior", + "ssuperior", "tsuperior", "ff", "ffi", "ffl", "parenleftinferior", + "parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall", + "Asmall", "Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall", "Gsmall", + "Hsmall", "Ismall", "Jsmall", "Ksmall", "Lsmall", "Msmall", "Nsmall", + "Osmall", "Psmall", "Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall", + "Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall", "colonmonetary", + "onefitted", "rupiah", "Tildesmall", "exclamdownsmall", "centoldstyle", + "Lslashsmall", "Scaronsmall", "Zcaronsmall", "Dieresissmall", "Brevesmall", + "Caronsmall", "Dotaccentsmall", "Macronsmall", "figuredash", + "hypheninferior", "Ogoneksmall", "Ringsmall", "Cedillasmall", + "questiondownsmall", "oneeighth", "threeeighths", "fiveeighths", + "seveneighths", "onethird", "twothirds", "zerosuperior", "foursuperior", + "fivesuperior", "sixsuperior", "sevensuperior", "eightsuperior", + "ninesuperior", "zeroinferior", "oneinferior", "twoinferior", + "threeinferior", "fourinferior", "fiveinferior", "sixinferior", + "seveninferior", "eightinferior", "nineinferior", "centinferior", + "dollarinferior", "periodinferior", "commainferior", "Agravesmall", + "Aacutesmall", "Acircumflexsmall", "Atildesmall", "Adieresissmall", + "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall", "Eacutesmall", + "Ecircumflexsmall", "Edieresissmall", "Igravesmall", "Iacutesmall", + "Icircumflexsmall", "Idieresissmall", "Ethsmall", "Ntildesmall", + "Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall", + "Odieresissmall", "OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall", + "Ucircumflexsmall", "Udieresissmall", "Yacutesmall", "Thornsmall", + "Ydieresissmall", "001.000", "001.001", "001.002", "001.003", "Black", + "Bold", "Book", "Light", "Medium", "Regular", "Roman", "Semibold" +]; diff --git a/node_modules/fontkit/src/cff/CFFTop.js b/node_modules/fontkit/src/cff/CFFTop.js new file mode 100644 index 0000000000000000000000000000000000000000..efdba720db9a5ad9812abfaa37eff2ae68f3cd6e --- /dev/null +++ b/node_modules/fontkit/src/cff/CFFTop.js @@ -0,0 +1,237 @@ +import * as r from 'restructure'; +import { resolveLength } from 'restructure'; +import CFFDict from './CFFDict'; +import CFFIndex from './CFFIndex'; +import CFFPointer from './CFFPointer'; +import CFFPrivateDict from './CFFPrivateDict'; +import StandardStrings from './CFFStandardStrings'; +import { StandardEncoding, ExpertEncoding } from './CFFEncodings'; +import { ISOAdobeCharset, ExpertCharset, ExpertSubsetCharset } from './CFFCharsets'; +import { ItemVariationStore } from '../tables/variations'; + +// Checks if an operand is an index of a predefined value, +// otherwise delegates to the provided type. +class PredefinedOp { + constructor(predefinedOps, type) { + this.predefinedOps = predefinedOps; + this.type = type; + } + + decode(stream, parent, operands) { + if (this.predefinedOps[operands[0]]) { + return this.predefinedOps[operands[0]]; + } + + return this.type.decode(stream, parent, operands); + } + + size(value, ctx) { + return this.type.size(value, ctx); + } + + encode(stream, value, ctx) { + let index = this.predefinedOps.indexOf(value); + if (index !== -1) { + return index; + } + + return this.type.encode(stream, value, ctx); + } +} + +class CFFEncodingVersion extends r.Number { + constructor() { + super('UInt8'); + } + + decode(stream) { + return r.uint8.decode(stream) & 0x7f; + } +} + +let Range1 = new r.Struct({ + first: r.uint16, + nLeft: r.uint8 +}); + +let Range2 = new r.Struct({ + first: r.uint16, + nLeft: r.uint16 +}); + +let CFFCustomEncoding = new r.VersionedStruct(new CFFEncodingVersion(), { + 0: { + nCodes: r.uint8, + codes: new r.Array(r.uint8, 'nCodes') + }, + + 1: { + nRanges: r.uint8, + ranges: new r.Array(Range1, 'nRanges') + } + + // TODO: supplement? +}); + +let CFFEncoding = new PredefinedOp([ StandardEncoding, ExpertEncoding ], new CFFPointer(CFFCustomEncoding, { lazy: true })); + +// Decodes an array of ranges until the total +// length is equal to the provided length. +class RangeArray extends r.Array { + decode(stream, parent) { + let length = resolveLength(this.length, stream, parent); + let count = 0; + let res = []; + while (count < length) { + let range = this.type.decode(stream, parent); + range.offset = count; + count += range.nLeft + 1; + res.push(range); + } + + return res; + } +} + +let CFFCustomCharset = new r.VersionedStruct(r.uint8, { + 0: { + glyphs: new r.Array(r.uint16, t => t.parent.CharStrings.length - 1) + }, + + 1: { + ranges: new RangeArray(Range1, t => t.parent.CharStrings.length - 1) + }, + + 2: { + ranges: new RangeArray(Range2, t => t.parent.CharStrings.length - 1) + } +}); + +let CFFCharset = new PredefinedOp([ ISOAdobeCharset, ExpertCharset, ExpertSubsetCharset ], new CFFPointer(CFFCustomCharset, {lazy: true})); + +let FDRange3 = new r.Struct({ + first: r.uint16, + fd: r.uint8 +}); + +let FDRange4 = new r.Struct({ + first: r.uint32, + fd: r.uint16 +}); + +let FDSelect = new r.VersionedStruct(r.uint8, { + 0: { + fds: new r.Array(r.uint8, t => t.parent.CharStrings.length) + }, + + 3: { + nRanges: r.uint16, + ranges: new r.Array(FDRange3, 'nRanges'), + sentinel: r.uint16 + }, + + 4: { + nRanges: r.uint32, + ranges: new r.Array(FDRange4, 'nRanges'), + sentinel: r.uint32 + } +}); + +let ptr = new CFFPointer(CFFPrivateDict); +class CFFPrivateOp { + decode(stream, parent, operands) { + parent.length = operands[0]; + return ptr.decode(stream, parent, [operands[1]]); + } + + size(dict, ctx) { + return [CFFPrivateDict.size(dict, ctx, false), ptr.size(dict, ctx)[0]]; + } + + encode(stream, dict, ctx) { + return [CFFPrivateDict.size(dict, ctx, false), ptr.encode(stream, dict, ctx)[0]]; + } +} + +let FontDict = new CFFDict([ + // key name type(s) default + [18, 'Private', new CFFPrivateOp, null], + [[12, 38], 'FontName', 'sid', null], + [[12, 7], 'FontMatrix', 'array', [0.001, 0, 0, 0.001, 0, 0]], + [[12, 5], 'PaintType', 'number', 0], +]); + +let CFFTopDict = new CFFDict([ + // key name type(s) default + [[12, 30], 'ROS', ['sid', 'sid', 'number'], null], + + [0, 'version', 'sid', null], + [1, 'Notice', 'sid', null], + [[12, 0], 'Copyright', 'sid', null], + [2, 'FullName', 'sid', null], + [3, 'FamilyName', 'sid', null], + [4, 'Weight', 'sid', null], + [[12, 1], 'isFixedPitch', 'boolean', false], + [[12, 2], 'ItalicAngle', 'number', 0], + [[12, 3], 'UnderlinePosition', 'number', -100], + [[12, 4], 'UnderlineThickness', 'number', 50], + [[12, 5], 'PaintType', 'number', 0], + [[12, 6], 'CharstringType', 'number', 2], + [[12, 7], 'FontMatrix', 'array', [0.001, 0, 0, 0.001, 0, 0]], + [13, 'UniqueID', 'number', null], + [5, 'FontBBox', 'array', [0, 0, 0, 0]], + [[12, 8], 'StrokeWidth', 'number', 0], + [14, 'XUID', 'array', null], + [15, 'charset', CFFCharset, ISOAdobeCharset], + [16, 'Encoding', CFFEncoding, StandardEncoding], + [17, 'CharStrings', new CFFPointer(new CFFIndex), null], + [18, 'Private', new CFFPrivateOp, null], + [[12, 20], 'SyntheticBase', 'number', null], + [[12, 21], 'PostScript', 'sid', null], + [[12, 22], 'BaseFontName', 'sid', null], + [[12, 23], 'BaseFontBlend', 'delta', null], + + // CID font specific + [[12, 31], 'CIDFontVersion', 'number', 0], + [[12, 32], 'CIDFontRevision', 'number', 0], + [[12, 33], 'CIDFontType', 'number', 0], + [[12, 34], 'CIDCount', 'number', 8720], + [[12, 35], 'UIDBase', 'number', null], + [[12, 37], 'FDSelect', new CFFPointer(FDSelect), null], + [[12, 36], 'FDArray', new CFFPointer(new CFFIndex(FontDict)), null], + [[12, 38], 'FontName', 'sid', null] +]); + +let VariationStore = new r.Struct({ + length: r.uint16, + itemVariationStore: ItemVariationStore +}) + +let CFF2TopDict = new CFFDict([ + [[12, 7], 'FontMatrix', 'array', [0.001, 0, 0, 0.001, 0, 0]], + [17, 'CharStrings', new CFFPointer(new CFFIndex), null], + [[12, 37], 'FDSelect', new CFFPointer(FDSelect), null], + [[12, 36], 'FDArray', new CFFPointer(new CFFIndex(FontDict)), null], + [24, 'vstore', new CFFPointer(VariationStore), null], + [25, 'maxstack', 'number', 193] +]); + +let CFFTop = new r.VersionedStruct(r.fixed16, { + 1: { + hdrSize: r.uint8, + offSize: r.uint8, + nameIndex: new CFFIndex(new r.String('length')), + topDictIndex: new CFFIndex(CFFTopDict), + stringIndex: new CFFIndex(new r.String('length')), + globalSubrIndex: new CFFIndex + }, + + 2: { + hdrSize: r.uint8, + length: r.uint16, + topDict: CFF2TopDict, + globalSubrIndex: new CFFIndex + } +}); + +export default CFFTop; diff --git a/node_modules/fontkit/src/decorators.js b/node_modules/fontkit/src/decorators.js new file mode 100644 index 0000000000000000000000000000000000000000..ce0d90b88b9c05557f505a3318c0ec1ad150d5ff --- /dev/null +++ b/node_modules/fontkit/src/decorators.js @@ -0,0 +1,36 @@ +/** + * This decorator caches the results of a getter or method such that + * the results are lazily computed once, and then cached. + * @private + */ +export function cache(target, key, descriptor) { + if (descriptor.get) { + let get = descriptor.get; + descriptor.get = function() { + let value = get.call(this); + Object.defineProperty(this, key, { value }); + return value; + }; + } else if (typeof descriptor.value === 'function') { + let fn = descriptor.value; + + return { + get() { + let cache = new Map; + function memoized(...args) { + let key = args.length > 0 ? args[0] : 'value'; + if (cache.has(key)) { + return cache.get(key); + } + + let result = fn.apply(this, args); + cache.set(key, result); + return result; + }; + + Object.defineProperty(this, key, {value: memoized}); + return memoized; + } + }; + } +} diff --git a/node_modules/fontkit/src/encodings.js b/node_modules/fontkit/src/encodings.js new file mode 100644 index 0000000000000000000000000000000000000000..83b785e09351777da37ec47f38ad579f1c1ade70 --- /dev/null +++ b/node_modules/fontkit/src/encodings.js @@ -0,0 +1,219 @@ +/** + * Gets an encoding name from platform, encoding, and language ids. + * Returned encoding names can be used in iconv-lite to decode text. + */ +export function getEncoding(platformID, encodingID, languageID = 0) { + if (platformID === 1 && MAC_LANGUAGE_ENCODINGS[languageID]) { + return MAC_LANGUAGE_ENCODINGS[languageID]; + } + + return ENCODINGS[platformID][encodingID]; +} + +const SINGLE_BYTE_ENCODINGS = new Set(['x-mac-roman', 'x-mac-cyrillic', 'iso-8859-6', 'iso-8859-8']); +const MAC_ENCODINGS = { + 'x-mac-croatian': 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ', + 'x-mac-gaelic': 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ', + 'x-mac-greek': 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ\u00AD', + 'x-mac-icelandic': 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', + 'x-mac-inuit': 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł', + 'x-mac-ce': 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ', + 'x-mac-romanian': 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', + 'x-mac-turkish': 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ' +}; + +const encodingCache = new Map(); + +export function getEncodingMapping(encoding) { + let cached = encodingCache.get(encoding); + if (cached) { + return cached; + } + + // These encodings aren't supported by TextDecoder. + let mapping = MAC_ENCODINGS[encoding]; + if (mapping) { + let res = new Map(); + for (let i = 0; i < mapping.length; i++) { + res.set(mapping.charCodeAt(i), 0x80 + i); + } + + encodingCache.set(encoding, res); + return res; + } + + // Only single byte encodings can be mapped 1:1. + if (SINGLE_BYTE_ENCODINGS.has(encoding)) { + // TextEncoder only supports utf8, whereas TextDecoder supports legacy encodings. + // Use this to create a mapping of code points. + let decoder = new TextDecoder(encoding); + let mapping = new Uint8Array(0x80); + for (let i = 0; i < 0x80; i++) { + mapping[i] = 0x80 + i; + } + + let res = new Map(); + let s = decoder.decode(mapping); + for (let i = 0; i < 0x80; i++) { + res.set(s.charCodeAt(i), 0x80 + i); + } + + encodingCache.set(encoding, res); + return res; + } +} + +// Map of platform ids to encoding ids. +export const ENCODINGS = [ + // unicode + ['utf-16be', 'utf-16be', 'utf-16be', 'utf-16be', 'utf-16be', 'utf-16be', 'utf-16be'], + + // macintosh + // Mappings available at http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/ + // 0 Roman 17 Malayalam + // 1 Japanese 18 Sinhalese + // 2 Traditional Chinese 19 Burmese + // 3 Korean 20 Khmer + // 4 Arabic 21 Thai + // 5 Hebrew 22 Laotian + // 6 Greek 23 Georgian + // 7 Russian 24 Armenian + // 8 RSymbol 25 Simplified Chinese + // 9 Devanagari 26 Tibetan + // 10 Gurmukhi 27 Mongolian + // 11 Gujarati 28 Geez + // 12 Oriya 29 Slavic + // 13 Bengali 30 Vietnamese + // 14 Tamil 31 Sindhi + // 15 Telugu 32 (Uninterpreted) + // 16 Kannada + ['x-mac-roman', 'shift-jis', 'big5', 'euc-kr', 'iso-8859-6', 'iso-8859-8', + 'x-mac-greek', 'x-mac-cyrillic', 'x-mac-symbol', 'x-mac-devanagari', 'x-mac-gurmukhi', 'x-mac-gujarati', + 'Oriya', 'Bengali', 'Tamil', 'Telugu', 'Kannada', 'Malayalam', 'Sinhalese', + 'Burmese', 'Khmer', 'iso-8859-11', 'Laotian', 'Georgian', 'Armenian', 'gbk', + 'Tibetan', 'Mongolian', 'Geez', 'x-mac-ce', 'Vietnamese', 'Sindhi'], + + // ISO (deprecated) + ['ascii', null, 'iso-8859-1'], + + // windows + // Docs here: http://msdn.microsoft.com/en-us/library/system.text.encoding(v=vs.110).aspx + ['symbol', 'utf-16be', 'shift-jis', 'gb18030', 'big5', 'euc-kr', 'johab', null, null, null, 'utf-16be'] +]; + +// Overrides for Mac scripts by language id. +// See http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt +export const MAC_LANGUAGE_ENCODINGS = { + 15: 'x-mac-icelandic', + 17: 'x-mac-turkish', + 18: 'x-mac-croatian', + 24: 'x-mac-ce', + 25: 'x-mac-ce', + 26: 'x-mac-ce', + 27: 'x-mac-ce', + 28: 'x-mac-ce', + 30: 'x-mac-icelandic', + 37: 'x-mac-romanian', + 38: 'x-mac-ce', + 39: 'x-mac-ce', + 40: 'x-mac-ce', + 143: 'x-mac-inuit', + 146: 'x-mac-gaelic' +}; + +// Map of platform ids to BCP-47 language codes. +export const LANGUAGES = [ + // unicode + [], + + { // macintosh + 0: 'en', 30: 'fo', 60: 'ks', 90: 'rw', + 1: 'fr', 31: 'fa', 61: 'ku', 91: 'rn', + 2: 'de', 32: 'ru', 62: 'sd', 92: 'ny', + 3: 'it', 33: 'zh', 63: 'bo', 93: 'mg', + 4: 'nl', 34: 'nl-BE', 64: 'ne', 94: 'eo', + 5: 'sv', 35: 'ga', 65: 'sa', 128: 'cy', + 6: 'es', 36: 'sq', 66: 'mr', 129: 'eu', + 7: 'da', 37: 'ro', 67: 'bn', 130: 'ca', + 8: 'pt', 38: 'cz', 68: 'as', 131: 'la', + 9: 'no', 39: 'sk', 69: 'gu', 132: 'qu', + 10: 'he', 40: 'si', 70: 'pa', 133: 'gn', + 11: 'ja', 41: 'yi', 71: 'or', 134: 'ay', + 12: 'ar', 42: 'sr', 72: 'ml', 135: 'tt', + 13: 'fi', 43: 'mk', 73: 'kn', 136: 'ug', + 14: 'el', 44: 'bg', 74: 'ta', 137: 'dz', + 15: 'is', 45: 'uk', 75: 'te', 138: 'jv', + 16: 'mt', 46: 'be', 76: 'si', 139: 'su', + 17: 'tr', 47: 'uz', 77: 'my', 140: 'gl', + 18: 'hr', 48: 'kk', 78: 'km', 141: 'af', + 19: 'zh-Hant', 49: 'az-Cyrl', 79: 'lo', 142: 'br', + 20: 'ur', 50: 'az-Arab', 80: 'vi', 143: 'iu', + 21: 'hi', 51: 'hy', 81: 'id', 144: 'gd', + 22: 'th', 52: 'ka', 82: 'tl', 145: 'gv', + 23: 'ko', 53: 'mo', 83: 'ms', 146: 'ga', + 24: 'lt', 54: 'ky', 84: 'ms-Arab', 147: 'to', + 25: 'pl', 55: 'tg', 85: 'am', 148: 'el-polyton', + 26: 'hu', 56: 'tk', 86: 'ti', 149: 'kl', + 27: 'es', 57: 'mn-CN', 87: 'om', 150: 'az', + 28: 'lv', 58: 'mn', 88: 'so', 151: 'nn', + 29: 'se', 59: 'ps', 89: 'sw', + }, + + // ISO (deprecated) + [], + + { // windows + 0x0436: 'af', 0x4009: 'en-IN', 0x0487: 'rw', 0x0432: 'tn', + 0x041C: 'sq', 0x1809: 'en-IE', 0x0441: 'sw', 0x045B: 'si', + 0x0484: 'gsw', 0x2009: 'en-JM', 0x0457: 'kok', 0x041B: 'sk', + 0x045E: 'am', 0x4409: 'en-MY', 0x0412: 'ko', 0x0424: 'sl', + 0x1401: 'ar-DZ', 0x1409: 'en-NZ', 0x0440: 'ky', 0x2C0A: 'es-AR', + 0x3C01: 'ar-BH', 0x3409: 'en-PH', 0x0454: 'lo', 0x400A: 'es-BO', + 0x0C01: 'ar', 0x4809: 'en-SG', 0x0426: 'lv', 0x340A: 'es-CL', + 0x0801: 'ar-IQ', 0x1C09: 'en-ZA', 0x0427: 'lt', 0x240A: 'es-CO', + 0x2C01: 'ar-JO', 0x2C09: 'en-TT', 0x082E: 'dsb', 0x140A: 'es-CR', + 0x3401: 'ar-KW', 0x0809: 'en-GB', 0x046E: 'lb', 0x1C0A: 'es-DO', + 0x3001: 'ar-LB', 0x0409: 'en', 0x042F: 'mk', 0x300A: 'es-EC', + 0x1001: 'ar-LY', 0x3009: 'en-ZW', 0x083E: 'ms-BN', 0x440A: 'es-SV', + 0x1801: 'ary', 0x0425: 'et', 0x043E: 'ms', 0x100A: 'es-GT', + 0x2001: 'ar-OM', 0x0438: 'fo', 0x044C: 'ml', 0x480A: 'es-HN', + 0x4001: 'ar-QA', 0x0464: 'fil', 0x043A: 'mt', 0x080A: 'es-MX', + 0x0401: 'ar-SA', 0x040B: 'fi', 0x0481: 'mi', 0x4C0A: 'es-NI', + 0x2801: 'ar-SY', 0x080C: 'fr-BE', 0x047A: 'arn', 0x180A: 'es-PA', + 0x1C01: 'aeb', 0x0C0C: 'fr-CA', 0x044E: 'mr', 0x3C0A: 'es-PY', + 0x3801: 'ar-AE', 0x040C: 'fr', 0x047C: 'moh', 0x280A: 'es-PE', + 0x2401: 'ar-YE', 0x140C: 'fr-LU', 0x0450: 'mn', 0x500A: 'es-PR', + 0x042B: 'hy', 0x180C: 'fr-MC', 0x0850: 'mn-CN', 0x0C0A: 'es', + 0x044D: 'as', 0x100C: 'fr-CH', 0x0461: 'ne', 0x040A: 'es', + 0x082C: 'az-Cyrl', 0x0462: 'fy', 0x0414: 'nb', 0x540A: 'es-US', + 0x042C: 'az', 0x0456: 'gl', 0x0814: 'nn', 0x380A: 'es-UY', + 0x046D: 'ba', 0x0437: 'ka', 0x0482: 'oc', 0x200A: 'es-VE', + 0x042D: 'eu', 0x0C07: 'de-AT', 0x0448: 'or', 0x081D: 'sv-FI', + 0x0423: 'be', 0x0407: 'de', 0x0463: 'ps', 0x041D: 'sv', + 0x0845: 'bn', 0x1407: 'de-LI', 0x0415: 'pl', 0x045A: 'syr', + 0x0445: 'bn-IN', 0x1007: 'de-LU', 0x0416: 'pt', 0x0428: 'tg', + 0x201A: 'bs-Cyrl', 0x0807: 'de-CH', 0x0816: 'pt-PT', 0x085F: 'tzm', + 0x141A: 'bs', 0x0408: 'el', 0x0446: 'pa', 0x0449: 'ta', + 0x047E: 'br', 0x046F: 'kl', 0x046B: 'qu-BO', 0x0444: 'tt', + 0x0402: 'bg', 0x0447: 'gu', 0x086B: 'qu-EC', 0x044A: 'te', + 0x0403: 'ca', 0x0468: 'ha', 0x0C6B: 'qu', 0x041E: 'th', + 0x0C04: 'zh-HK', 0x040D: 'he', 0x0418: 'ro', 0x0451: 'bo', + 0x1404: 'zh-MO', 0x0439: 'hi', 0x0417: 'rm', 0x041F: 'tr', + 0x0804: 'zh', 0x040E: 'hu', 0x0419: 'ru', 0x0442: 'tk', + 0x1004: 'zh-SG', 0x040F: 'is', 0x243B: 'smn', 0x0480: 'ug', + 0x0404: 'zh-TW', 0x0470: 'ig', 0x103B: 'smj-NO', 0x0422: 'uk', + 0x0483: 'co', 0x0421: 'id', 0x143B: 'smj', 0x042E: 'hsb', + 0x041A: 'hr', 0x045D: 'iu', 0x0C3B: 'se-FI', 0x0420: 'ur', + 0x101A: 'hr-BA', 0x085D: 'iu-Latn', 0x043B: 'se', 0x0843: 'uz-Cyrl', + 0x0405: 'cs', 0x083C: 'ga', 0x083B: 'se-SE', 0x0443: 'uz', + 0x0406: 'da', 0x0434: 'xh', 0x203B: 'sms', 0x042A: 'vi', + 0x048C: 'prs', 0x0435: 'zu', 0x183B: 'sma-NO', 0x0452: 'cy', + 0x0465: 'dv', 0x0410: 'it', 0x1C3B: 'sms', 0x0488: 'wo', + 0x0813: 'nl-BE', 0x0810: 'it-CH', 0x044F: 'sa', 0x0485: 'sah', + 0x0413: 'nl', 0x0411: 'ja', 0x1C1A: 'sr-Cyrl-BA', 0x0478: 'ii', + 0x0C09: 'en-AU', 0x044B: 'kn', 0x0C1A: 'sr', 0x046A: 'yo', + 0x2809: 'en-BZ', 0x043F: 'kk', 0x181A: 'sr-Latn-BA', + 0x1009: 'en-CA', 0x0453: 'km', 0x081A: 'sr-Latn', + 0x2409: 'en-029', 0x0486: 'quc', 0x046C: 'nso', + } +]; diff --git a/node_modules/fontkit/src/fs.js b/node_modules/fontkit/src/fs.js new file mode 100644 index 0000000000000000000000000000000000000000..5dab9958726ece7ab15c2a4c4ea583cf167fda2c --- /dev/null +++ b/node_modules/fontkit/src/fs.js @@ -0,0 +1,17 @@ +import { create } from './base'; +import fs from 'fs'; + +export function openSync(filename, postscriptName) { + let buffer = fs.readFileSync(filename); + return create(buffer, postscriptName); +} + +export async function open(filename, postscriptName, callback) { + if (typeof postscriptName === 'function') { + callback = postscriptName; + postscriptName = null; + } + + let buffer = await fs.promises.readFile(filename); + return create(buffer, postscriptName); +} diff --git a/node_modules/fontkit/src/glyph/BBox.js b/node_modules/fontkit/src/glyph/BBox.js new file mode 100644 index 0000000000000000000000000000000000000000..bba7237043d96b55c5a6618422d4fdeda523059c --- /dev/null +++ b/node_modules/fontkit/src/glyph/BBox.js @@ -0,0 +1,72 @@ +/** + * Represents a glyph bounding box + */ +export default class BBox { + constructor(minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity) { + /** + * The minimum X position in the bounding box + * @type {number} + */ + this.minX = minX; + + /** + * The minimum Y position in the bounding box + * @type {number} + */ + this.minY = minY; + + /** + * The maxmimum X position in the bounding box + * @type {number} + */ + this.maxX = maxX; + + /** + * The maxmimum Y position in the bounding box + * @type {number} + */ + this.maxY = maxY; + } + + /** + * The width of the bounding box + * @type {number} + */ + get width() { + return this.maxX - this.minX; + } + + /** + * The height of the bounding box + * @type {number} + */ + get height() { + return this.maxY - this.minY; + } + + addPoint(x, y) { + if (Math.abs(x) !== Infinity) { + if (x < this.minX) { + this.minX = x; + } + + if (x > this.maxX) { + this.maxX = x; + } + } + + if (Math.abs(y) !== Infinity) { + if (y < this.minY) { + this.minY = y; + } + + if (y > this.maxY) { + this.maxY = y; + } + } + } + + copy() { + return new BBox(this.minX, this.minY, this.maxX, this.maxY); + } +} diff --git a/node_modules/fontkit/src/glyph/CFFGlyph.js b/node_modules/fontkit/src/glyph/CFFGlyph.js new file mode 100644 index 0000000000000000000000000000000000000000..1ac182f157ec8b61e0d0184bfd81a36490b02fff --- /dev/null +++ b/node_modules/fontkit/src/glyph/CFFGlyph.js @@ -0,0 +1,604 @@ +import Glyph from './Glyph'; +import Path from './Path'; + +/** + * Represents an OpenType PostScript glyph, in the Compact Font Format. + */ +export default class CFFGlyph extends Glyph { + type = 'CFF'; + + _getName() { + if (this._font.CFF2) { + return super._getName(); + } + + return this._font['CFF '].getGlyphName(this.id); + } + + bias(s) { + if (s.length < 1240) { + return 107; + } else if (s.length < 33900) { + return 1131; + } else { + return 32768; + } + } + + _getPath() { + let cff = this._font.CFF2 || this._font['CFF ']; + let { stream } = cff; + let str = cff.topDict.CharStrings[this.id]; + let end = str.offset + str.length; + stream.pos = str.offset; + + let path = new Path; + let stack = []; + let trans = []; + + let width = null; + let nStems = 0; + let x = 0, y = 0; + let usedGsubrs; + let usedSubrs; + let open = false; + + this._usedGsubrs = usedGsubrs = {}; + this._usedSubrs = usedSubrs = {}; + + let gsubrs = cff.globalSubrIndex || []; + let gsubrsBias = this.bias(gsubrs); + + let privateDict = cff.privateDictForGlyph(this.id) || {}; + let subrs = privateDict.Subrs || []; + let subrsBias = this.bias(subrs); + + let vstore = cff.topDict.vstore && cff.topDict.vstore.itemVariationStore; + let vsindex = privateDict.vsindex; + let variationProcessor = this._font._variationProcessor; + + function checkWidth() { + if (width == null) { + width = stack.shift() + privateDict.nominalWidthX; + } + } + + function parseStems() { + if (stack.length % 2 !== 0) { + checkWidth(); + } + + nStems += stack.length >> 1; + return stack.length = 0; + } + + function moveTo(x, y) { + if (open) { + path.closePath(); + } + + path.moveTo(x, y); + open = true; + } + + let parse = function () { + while (stream.pos < end) { + let op = stream.readUInt8(); + if (op < 32) { + let index, subr, phase; + let c1x, c1y, c2x, c2y, c3x, c3y; + let c4x, c4y, c5x, c5y, c6x, c6y; + let pts; + + switch (op) { + case 1: // hstem + case 3: // vstem + case 18: // hstemhm + case 23: // vstemhm + parseStems(); + break; + + case 4: // vmoveto + if (stack.length > 1) { + checkWidth(); + } + + y += stack.shift(); + moveTo(x, y); + break; + + case 5: // rlineto + while (stack.length >= 2) { + x += stack.shift(); + y += stack.shift(); + path.lineTo(x, y); + } + break; + + case 6: // hlineto + case 7: // vlineto + phase = op === 6; + while (stack.length >= 1) { + if (phase) { + x += stack.shift(); + } else { + y += stack.shift(); + } + + path.lineTo(x, y); + phase = !phase; + } + break; + + case 8: // rrcurveto + while (stack.length > 0) { + c1x = x + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + stack.shift(); + path.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); + } + break; + + case 10: // callsubr + index = stack.pop() + subrsBias; + subr = subrs[index]; + if (subr) { + usedSubrs[index] = true; + let p = stream.pos; + let e = end; + stream.pos = subr.offset; + end = subr.offset + subr.length; + parse(); + stream.pos = p; + end = e; + } + break; + + case 11: // return + if (cff.version >= 2) { + break; + } + return; + + case 14: // endchar + if (cff.version >= 2) { + break; + } + + if (stack.length > 0) { + checkWidth(); + } + + if (open) { + path.closePath(); + open = false; + } + break; + + case 15: { // vsindex + if (cff.version < 2) { + throw new Error('vsindex operator not supported in CFF v1'); + } + + vsindex = stack.pop(); + break; + } + + case 16: { // blend + if (cff.version < 2) { + throw new Error('blend operator not supported in CFF v1'); + } + + if (!variationProcessor) { + throw new Error('blend operator in non-variation font'); + } + + let blendVector = variationProcessor.getBlendVector(vstore, vsindex); + let numBlends = stack.pop(); + let numOperands = numBlends * blendVector.length; + let delta = stack.length - numOperands; + let base = delta - numBlends; + + for (let i = 0; i < numBlends; i++) { + let sum = stack[base + i]; + for (let j = 0; j < blendVector.length; j++) { + sum += blendVector[j] * stack[delta++]; + } + + stack[base + i] = sum; + } + + while (numOperands--) { + stack.pop(); + } + + break; + } + + case 19: // hintmask + case 20: // cntrmask + parseStems(); + stream.pos += (nStems + 7) >> 3; + break; + + case 21: // rmoveto + if (stack.length > 2) { + checkWidth(); + } + + x += stack.shift(); + y += stack.shift(); + moveTo(x, y); + break; + + case 22: // hmoveto + if (stack.length > 1) { + checkWidth(); + } + + x += stack.shift(); + moveTo(x, y); + break; + + case 24: // rcurveline + while (stack.length >= 8) { + c1x = x + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + stack.shift(); + path.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); + } + + x += stack.shift(); + y += stack.shift(); + path.lineTo(x, y); + break; + + case 25: // rlinecurve + while (stack.length >= 8) { + x += stack.shift(); + y += stack.shift(); + path.lineTo(x, y); + } + + c1x = x + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + stack.shift(); + path.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); + break; + + case 26: // vvcurveto + if (stack.length % 2) { + x += stack.shift(); + } + + while (stack.length >= 4) { + c1x = x; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x; + y = c2y + stack.shift(); + path.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); + } + break; + + case 27: // hhcurveto + if (stack.length % 2) { + y += stack.shift(); + } + + while (stack.length >= 4) { + c1x = x + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y; + path.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); + } + break; + + case 28: // shortint + stack.push(stream.readInt16BE()); + break; + + case 29: // callgsubr + index = stack.pop() + gsubrsBias; + subr = gsubrs[index]; + if (subr) { + usedGsubrs[index] = true; + let p = stream.pos; + let e = end; + stream.pos = subr.offset; + end = subr.offset + subr.length; + parse(); + stream.pos = p; + end = e; + } + break; + + case 30: // vhcurveto + case 31: // hvcurveto + phase = op === 31; + while (stack.length >= 4) { + if (phase) { + c1x = x + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + y = c2y + stack.shift(); + x = c2x + (stack.length === 1 ? stack.shift() : 0); + } else { + c1x = x; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + (stack.length === 1 ? stack.shift() : 0); + } + + path.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); + phase = !phase; + } + break; + + case 12: + op = stream.readUInt8(); + switch (op) { + case 3: // and + let a = stack.pop(); + let b = stack.pop(); + stack.push(a && b ? 1 : 0); + break; + + case 4: // or + a = stack.pop(); + b = stack.pop(); + stack.push(a || b ? 1 : 0); + break; + + case 5: // not + a = stack.pop(); + stack.push(a ? 0 : 1); + break; + + case 9: // abs + a = stack.pop(); + stack.push(Math.abs(a)); + break; + + case 10: // add + a = stack.pop(); + b = stack.pop(); + stack.push(a + b); + break; + + case 11: // sub + a = stack.pop(); + b = stack.pop(); + stack.push(a - b); + break; + + case 12: // div + a = stack.pop(); + b = stack.pop(); + stack.push(a / b); + break; + + case 14: // neg + a = stack.pop(); + stack.push(-a); + break; + + case 15: // eq + a = stack.pop(); + b = stack.pop(); + stack.push(a === b ? 1 : 0); + break; + + case 18: // drop + stack.pop(); + break; + + case 20: // put + let val = stack.pop(); + let idx = stack.pop(); + trans[idx] = val; + break; + + case 21: // get + idx = stack.pop(); + stack.push(trans[idx] || 0); + break; + + case 22: // ifelse + let s1 = stack.pop(); + let s2 = stack.pop(); + let v1 = stack.pop(); + let v2 = stack.pop(); + stack.push(v1 <= v2 ? s1 : s2); + break; + + case 23: // random + stack.push(Math.random()); + break; + + case 24: // mul + a = stack.pop(); + b = stack.pop(); + stack.push(a * b); + break; + + case 26: // sqrt + a = stack.pop(); + stack.push(Math.sqrt(a)); + break; + + case 27: // dup + a = stack.pop(); + stack.push(a, a); + break; + + case 28: // exch + a = stack.pop(); + b = stack.pop(); + stack.push(b, a); + break; + + case 29: // index + idx = stack.pop(); + if (idx < 0) { + idx = 0; + } else if (idx > stack.length - 1) { + idx = stack.length - 1; + } + + stack.push(stack[idx]); + break; + + case 30: // roll + let n = stack.pop(); + let j = stack.pop(); + + if (j >= 0) { + while (j > 0) { + var t = stack[n - 1]; + for (let i = n - 2; i >= 0; i--) { + stack[i + 1] = stack[i]; + } + + stack[0] = t; + j--; + } + } else { + while (j < 0) { + var t = stack[0]; + for (let i = 0; i <= n; i++) { + stack[i] = stack[i + 1]; + } + + stack[n - 1] = t; + j++; + } + } + break; + + case 34: // hflex + c1x = x + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + c3x = c2x + stack.shift(); + c3y = c2y; + c4x = c3x + stack.shift(); + c4y = c3y; + c5x = c4x + stack.shift(); + c5y = c4y; + c6x = c5x + stack.shift(); + c6y = c5y; + x = c6x; + y = c6y; + + path.bezierCurveTo(c1x, c1y, c2x, c2y, c3x, c3y); + path.bezierCurveTo(c4x, c4y, c5x, c5y, c6x, c6y); + break; + + case 35: // flex + pts = []; + + for (let i = 0; i <= 5; i++) { + x += stack.shift(); + y += stack.shift(); + pts.push(x, y); + } + + path.bezierCurveTo(...pts.slice(0, 6)); + path.bezierCurveTo(...pts.slice(6)); + stack.shift(); // fd + break; + + case 36: // hflex1 + c1x = x + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + c3x = c2x + stack.shift(); + c3y = c2y; + c4x = c3x + stack.shift(); + c4y = c3y; + c5x = c4x + stack.shift(); + c5y = c4y + stack.shift(); + c6x = c5x + stack.shift(); + c6y = c5y; + x = c6x; + y = c6y; + + path.bezierCurveTo(c1x, c1y, c2x, c2y, c3x, c3y); + path.bezierCurveTo(c4x, c4y, c5x, c5y, c6x, c6y); + break; + + case 37: // flex1 + let startx = x; + let starty = y; + + pts = []; + for (let i = 0; i <= 4; i++) { + x += stack.shift(); + y += stack.shift(); + pts.push(x, y); + } + + if (Math.abs(x - startx) > Math.abs(y - starty)) { // horizontal + x += stack.shift(); + y = starty; + } else { + x = startx; + y += stack.shift(); + } + + pts.push(x, y); + path.bezierCurveTo(...pts.slice(0, 6)); + path.bezierCurveTo(...pts.slice(6)); + break; + + default: + throw new Error(`Unknown op: 12 ${op}`); + } + break; + + default: + throw new Error(`Unknown op: ${op}`); + } + + } else if (op < 247) { + stack.push(op - 139); + } else if (op < 251) { + var b1 = stream.readUInt8(); + stack.push((op - 247) * 256 + b1 + 108); + } else if (op < 255) { + var b1 = stream.readUInt8(); + stack.push(-(op - 251) * 256 - b1 - 108); + } else { + stack.push(stream.readInt32BE() / 65536); + } + } + }; + + parse(); + + if (open) { + path.closePath(); + } + + return path; + } +} diff --git a/node_modules/fontkit/src/glyph/COLRGlyph.js b/node_modules/fontkit/src/glyph/COLRGlyph.js new file mode 100644 index 0000000000000000000000000000000000000000..85d594b695023881c20499cddc710d8891bdf26c --- /dev/null +++ b/node_modules/fontkit/src/glyph/COLRGlyph.js @@ -0,0 +1,90 @@ +import Glyph from './Glyph'; +import BBox from './BBox'; + +class COLRLayer { + constructor(glyph, color) { + this.glyph = glyph; + this.color = color; + } +} + +/** + * Represents a color (e.g. emoji) glyph in Microsoft's COLR format. + * Each glyph in this format contain a list of colored layers, each + * of which is another vector glyph. + */ +export default class COLRGlyph extends Glyph { + type = 'COLR'; + + _getBBox() { + let bbox = new BBox; + for (let i = 0; i < this.layers.length; i++) { + let layer = this.layers[i]; + let b = layer.glyph.bbox; + bbox.addPoint(b.minX, b.minY); + bbox.addPoint(b.maxX, b.maxY); + } + + return bbox; + } + + /** + * Returns an array of objects containing the glyph and color for + * each layer in the composite color glyph. + * @type {object[]} + */ + get layers() { + let cpal = this._font.CPAL; + let colr = this._font.COLR; + let low = 0; + let high = colr.baseGlyphRecord.length - 1; + + while (low <= high) { + let mid = (low + high) >> 1; + var rec = colr.baseGlyphRecord[mid]; + + if (this.id < rec.gid) { + high = mid - 1; + } else if (this.id > rec.gid) { + low = mid + 1; + } else { + var baseLayer = rec; + break; + } + } + + // if base glyph not found in COLR table, + // default to normal glyph from glyf or CFF + if (baseLayer == null) { + var g = this._font._getBaseGlyph(this.id); + var color = { + red: 0, + green: 0, + blue: 0, + alpha: 255 + }; + + return [new COLRLayer(g, color)]; + } + + // otherwise, return an array of all the layers + let layers = []; + for (let i = baseLayer.firstLayerIndex; i < baseLayer.firstLayerIndex + baseLayer.numLayers; i++) { + var rec = colr.layerRecords[i]; + var color = cpal.colorRecords[rec.paletteIndex]; + var g = this._font._getBaseGlyph(rec.gid); + layers.push(new COLRLayer(g, color)); + } + + return layers; + } + + render(ctx, size) { + for (let {glyph, color} of this.layers) { + ctx.fillColor([color.red, color.green, color.blue], color.alpha / 255 * 100); + glyph.render(ctx, size); + } + + return; + } +} diff --git a/node_modules/fontkit/src/glyph/Glyph.js b/node_modules/fontkit/src/glyph/Glyph.js new file mode 100644 index 0000000000000000000000000000000000000000..3592150fc5d02b617b55936bc43c628c9b6b3ea8 --- /dev/null +++ b/node_modules/fontkit/src/glyph/Glyph.js @@ -0,0 +1,212 @@ +import { cache } from '../decorators'; +import Path from './Path'; +import {isMark} from 'unicode-properties'; +import StandardNames from './StandardNames'; + +/** + * Glyph objects represent a glyph in the font. They have various properties for accessing metrics and + * the actual vector path the glyph represents, and methods for rendering the glyph to a graphics context. + * + * You do not create glyph objects directly. They are created by various methods on the font object. + * There are several subclasses of the base Glyph class internally that may be returned depending + * on the font format, but they all inherit from this class. + */ +export default class Glyph { + constructor(id, codePoints, font) { + /** + * The glyph id in the font + * @type {number} + */ + this.id = id; + + /** + * An array of unicode code points that are represented by this glyph. + * There can be multiple code points in the case of ligatures and other glyphs + * that represent multiple visual characters. + * @type {number[]} + */ + this.codePoints = codePoints; + this._font = font; + + // TODO: get this info from GDEF if available + this.isMark = this.codePoints.length > 0 && this.codePoints.every(isMark); + this.isLigature = this.codePoints.length > 1; + } + + _getPath() { + return new Path(); + } + + _getCBox() { + return this.path.cbox; + } + + _getBBox() { + return this.path.bbox; + } + + _getTableMetrics(table) { + if (this.id < table.metrics.length) { + return table.metrics.get(this.id); + } + + let metric = table.metrics.get(table.metrics.length - 1); + let res = { + advance: metric ? metric.advance : 0, + bearing: table.bearings.get(this.id - table.metrics.length) || 0 + }; + + return res; + } + + _getMetrics(cbox) { + if (this._metrics) { return this._metrics; } + + let {advance:advanceWidth, bearing:leftBearing} = this._getTableMetrics(this._font.hmtx); + + // For vertical metrics, use vmtx if available, or fall back to global data from OS/2 or hhea + if (this._font.vmtx) { + var {advance:advanceHeight, bearing:topBearing} = this._getTableMetrics(this._font.vmtx); + + } else { + let os2; + if (typeof cbox === 'undefined' || cbox === null) { ({ cbox } = this); } + + if ((os2 = this._font['OS/2']) && os2.version > 0) { + var advanceHeight = Math.abs(os2.typoAscender - os2.typoDescender); + var topBearing = os2.typoAscender - cbox.maxY; + + } else { + let { hhea } = this._font; + var advanceHeight = Math.abs(hhea.ascent - hhea.descent); + var topBearing = hhea.ascent - cbox.maxY; + } + } + + if (this._font._variationProcessor && this._font.HVAR) { + advanceWidth += this._font._variationProcessor.getAdvanceAdjustment(this.id, this._font.HVAR); + } + + return this._metrics = { advanceWidth, advanceHeight, leftBearing, topBearing }; + } + + /** + * The glyph’s control box. + * This is often the same as the bounding box, but is faster to compute. + * Because of the way bezier curves are defined, some of the control points + * can be outside of the bounding box. Where `bbox` takes this into account, + * `cbox` does not. Thus, cbox is less accurate, but faster to compute. + * See [here](http://www.freetype.org/freetype2/docs/glyphs/glyphs-6.html#section-2) + * for a more detailed description. + * + * @type {BBox} + */ + @cache + get cbox() { + return this._getCBox(); + } + + /** + * The glyph’s bounding box, i.e. the rectangle that encloses the + * glyph outline as tightly as possible. + * @type {BBox} + */ + @cache + get bbox() { + return this._getBBox(); + } + + /** + * A vector Path object representing the glyph outline. + * @type {Path} + */ + @cache + get path() { + // Cache the path so we only decode it once + // Decoding is actually performed by subclasses + return this._getPath(); + } + + /** + * Returns a path scaled to the given font size. + * @param {number} size + * @return {Path} + */ + getScaledPath(size) { + let scale = 1 / this._font.unitsPerEm * size; + return this.path.scale(scale); + } + + /** + * The glyph's advance width. + * @type {number} + */ + @cache + get advanceWidth() { + return this._getMetrics().advanceWidth; + } + + /** + * The glyph's advance height. + * @type {number} + */ + @cache + get advanceHeight() { + return this._getMetrics().advanceHeight; + } + + get ligatureCaretPositions() {} + + _getName() { + let { post } = this._font; + if (!post) { + return null; + } + + switch (post.version) { + case 1: + return StandardNames[this.id]; + + case 2: + let id = post.glyphNameIndex[this.id]; + if (id < StandardNames.length) { + return StandardNames[id]; + } + + return post.names[id - StandardNames.length]; + + case 2.5: + return StandardNames[this.id + post.offsets[this.id]]; + + case 4: + return String.fromCharCode(post.map[this.id]); + } + } + + /** + * The glyph's name + * @type {string} + */ + @cache + get name() { + return this._getName(); + } + + /** + * Renders the glyph to the given graphics context, at the specified font size. + * @param {CanvasRenderingContext2d} ctx + * @param {number} size + */ + render(ctx, size) { + ctx.save(); + + let scale = 1 / this._font.head.unitsPerEm * size; + ctx.scale(scale, scale); + + let fn = this.path.toFunction(); + fn(ctx); + ctx.fill(); + + ctx.restore(); + } +} diff --git a/node_modules/fontkit/src/glyph/GlyphVariationProcessor.js b/node_modules/fontkit/src/glyph/GlyphVariationProcessor.js new file mode 100644 index 0000000000000000000000000000000000000000..78662795ea259e8f84d416a29f033d4af13f0044 --- /dev/null +++ b/node_modules/fontkit/src/glyph/GlyphVariationProcessor.js @@ -0,0 +1,486 @@ +const TUPLES_SHARE_POINT_NUMBERS = 0x8000; +const TUPLE_COUNT_MASK = 0x0fff; +const EMBEDDED_TUPLE_COORD = 0x8000; +const INTERMEDIATE_TUPLE = 0x4000; +const PRIVATE_POINT_NUMBERS = 0x2000; +const TUPLE_INDEX_MASK = 0x0fff; +const POINTS_ARE_WORDS = 0x80; +const POINT_RUN_COUNT_MASK = 0x7f; +const DELTAS_ARE_ZERO = 0x80; +const DELTAS_ARE_WORDS = 0x40; +const DELTA_RUN_COUNT_MASK = 0x3f; + +/** + * This class is transforms TrueType glyphs according to the data from + * the Apple Advanced Typography variation tables (fvar, gvar, and avar). + * These tables allow infinite adjustments to glyph weight, width, slant, + * and optical size without the designer needing to specify every exact style. + * + * Apple's documentation for these tables is not great, so thanks to the + * Freetype project for figuring much of this out. + * + * @private + */ +export default class GlyphVariationProcessor { + constructor(font, coords) { + this.font = font; + this.normalizedCoords = this.normalizeCoords(coords); + this.blendVectors = new Map; + } + + normalizeCoords(coords) { + // the default mapping is linear along each axis, in two segments: + // from the minValue to defaultValue, and from defaultValue to maxValue. + let normalized = []; + for (var i = 0; i < this.font.fvar.axis.length; i++) { + let axis = this.font.fvar.axis[i]; + if (coords[i] < axis.defaultValue) { + normalized.push((coords[i] - axis.defaultValue + Number.EPSILON) / (axis.defaultValue - axis.minValue + Number.EPSILON)); + } else { + normalized.push((coords[i] - axis.defaultValue + Number.EPSILON) / (axis.maxValue - axis.defaultValue + Number.EPSILON)); + } + } + + // if there is an avar table, the normalized value is calculated + // by interpolating between the two nearest mapped values. + if (this.font.avar) { + for (var i = 0; i < this.font.avar.segment.length; i++) { + let segment = this.font.avar.segment[i]; + for (let j = 0; j < segment.correspondence.length; j++) { + let pair = segment.correspondence[j]; + if (j >= 1 && normalized[i] < pair.fromCoord) { + let prev = segment.correspondence[j - 1]; + normalized[i] = ((normalized[i] - prev.fromCoord) * (pair.toCoord - prev.toCoord) + Number.EPSILON) / + (pair.fromCoord - prev.fromCoord + Number.EPSILON) + + prev.toCoord; + + break; + } + } + } + } + + return normalized; + } + + transformPoints(gid, glyphPoints) { + if (!this.font.fvar || !this.font.gvar) { return; } + + let { gvar } = this.font; + if (gid >= gvar.glyphCount) { return; } + + let offset = gvar.offsets[gid]; + if (offset === gvar.offsets[gid + 1]) { return; } + + // Read the gvar data for this glyph + let { stream } = this.font; + stream.pos = offset; + if (stream.pos >= stream.length) { + return; + } + + let tupleCount = stream.readUInt16BE(); + let offsetToData = offset + stream.readUInt16BE(); + + if (tupleCount & TUPLES_SHARE_POINT_NUMBERS) { + var here = stream.pos; + stream.pos = offsetToData; + var sharedPoints = this.decodePoints(); + offsetToData = stream.pos; + stream.pos = here; + } + + let origPoints = glyphPoints.map(pt => pt.copy()); + + tupleCount &= TUPLE_COUNT_MASK; + for (let i = 0; i < tupleCount; i++) { + let tupleDataSize = stream.readUInt16BE(); + let tupleIndex = stream.readUInt16BE(); + + if (tupleIndex & EMBEDDED_TUPLE_COORD) { + var tupleCoords = []; + for (let a = 0; a < gvar.axisCount; a++) { + tupleCoords.push(stream.readInt16BE() / 16384); + } + + } else { + if ((tupleIndex & TUPLE_INDEX_MASK) >= gvar.globalCoordCount) { + throw new Error('Invalid gvar table'); + } + + var tupleCoords = gvar.globalCoords[tupleIndex & TUPLE_INDEX_MASK]; + } + + if (tupleIndex & INTERMEDIATE_TUPLE) { + var startCoords = []; + for (let a = 0; a < gvar.axisCount; a++) { + startCoords.push(stream.readInt16BE() / 16384); + } + + var endCoords = []; + for (let a = 0; a < gvar.axisCount; a++) { + endCoords.push(stream.readInt16BE() / 16384); + } + } + + // Get the factor at which to apply this tuple + let factor = this.tupleFactor(tupleIndex, tupleCoords, startCoords, endCoords); + if (factor === 0) { + offsetToData += tupleDataSize; + continue; + } + + var here = stream.pos; + stream.pos = offsetToData; + + if (tupleIndex & PRIVATE_POINT_NUMBERS) { + var points = this.decodePoints(); + } else { + var points = sharedPoints; + } + + // points.length = 0 means there are deltas for all points + let nPoints = points.length === 0 ? glyphPoints.length : points.length; + let xDeltas = this.decodeDeltas(nPoints); + let yDeltas = this.decodeDeltas(nPoints); + + if (points.length === 0) { // all points + for (let i = 0; i < glyphPoints.length; i++) { + var point = glyphPoints[i]; + point.x += Math.round(xDeltas[i] * factor); + point.y += Math.round(yDeltas[i] * factor); + } + } else { + let outPoints = origPoints.map(pt => pt.copy()); + let hasDelta = glyphPoints.map(() => false); + + for (let i = 0; i < points.length; i++) { + let idx = points[i]; + if (idx < glyphPoints.length) { + let point = outPoints[idx]; + hasDelta[idx] = true; + + point.x += xDeltas[i] * factor; + point.y += yDeltas[i] * factor; + } + } + + this.interpolateMissingDeltas(outPoints, origPoints, hasDelta); + + for (let i = 0; i < glyphPoints.length; i++) { + let deltaX = outPoints[i].x - origPoints[i].x; + let deltaY = outPoints[i].y - origPoints[i].y; + + glyphPoints[i].x = Math.round(glyphPoints[i].x + deltaX); + glyphPoints[i].y = Math.round(glyphPoints[i].y + deltaY); + } + } + + offsetToData += tupleDataSize; + stream.pos = here; + } + } + + decodePoints() { + let stream = this.font.stream; + let count = stream.readUInt8(); + + if (count & POINTS_ARE_WORDS) { + count = (count & POINT_RUN_COUNT_MASK) << 8 | stream.readUInt8(); + } + + let points = new Uint16Array(count); + let i = 0; + let point = 0; + while (i < count) { + let run = stream.readUInt8(); + let runCount = (run & POINT_RUN_COUNT_MASK) + 1; + let fn = run & POINTS_ARE_WORDS ? stream.readUInt16 : stream.readUInt8; + + for (let j = 0; j < runCount && i < count; j++) { + point += fn.call(stream); + points[i++] = point; + } + } + + return points; + } + + decodeDeltas(count) { + let stream = this.font.stream; + let i = 0; + let deltas = new Int16Array(count); + + while (i < count) { + let run = stream.readUInt8(); + let runCount = (run & DELTA_RUN_COUNT_MASK) + 1; + + if (run & DELTAS_ARE_ZERO) { + i += runCount; + + } else { + let fn = run & DELTAS_ARE_WORDS ? stream.readInt16BE : stream.readInt8; + for (let j = 0; j < runCount && i < count; j++) { + deltas[i++] = fn.call(stream); + } + } + } + + return deltas; + } + + tupleFactor(tupleIndex, tupleCoords, startCoords, endCoords) { + let normalized = this.normalizedCoords; + let { gvar } = this.font; + let factor = 1; + + for (let i = 0; i < gvar.axisCount; i++) { + if (tupleCoords[i] === 0) { + continue; + } + + if (normalized[i] === 0) { + return 0; + } + + if ((tupleIndex & INTERMEDIATE_TUPLE) === 0) { + if ((normalized[i] < Math.min(0, tupleCoords[i])) || + (normalized[i] > Math.max(0, tupleCoords[i]))) { + return 0; + } + + factor = (factor * normalized[i] + Number.EPSILON) / (tupleCoords[i] + Number.EPSILON); + } else { + if ((normalized[i] < startCoords[i]) || + (normalized[i] > endCoords[i])) { + return 0; + + } else if (normalized[i] < tupleCoords[i]) { + factor = factor * (normalized[i] - startCoords[i] + Number.EPSILON) / (tupleCoords[i] - startCoords[i] + Number.EPSILON); + + } else { + factor = factor * (endCoords[i] - normalized[i] + Number.EPSILON) / (endCoords[i] - tupleCoords[i] + Number.EPSILON); + } + } + } + + return factor; + } + + // Interpolates points without delta values. + // Needed for the Ø and Q glyphs in Skia. + // Algorithm from Freetype. + interpolateMissingDeltas(points, inPoints, hasDelta) { + if (points.length === 0) { + return; + } + + let point = 0; + while (point < points.length) { + let firstPoint = point; + + // find the end point of the contour + let endPoint = point; + let pt = points[endPoint]; + while (!pt.endContour) { + pt = points[++endPoint]; + } + + // find the first point that has a delta + while (point <= endPoint && !hasDelta[point]) { + point++; + } + + if (point > endPoint) { + continue; + } + + let firstDelta = point; + let curDelta = point; + point++; + + while (point <= endPoint) { + // find the next point with a delta, and interpolate intermediate points + if (hasDelta[point]) { + this.deltaInterpolate(curDelta + 1, point - 1, curDelta, point, inPoints, points); + curDelta = point; + } + + point++; + } + + // shift contour if we only have a single delta + if (curDelta === firstDelta) { + this.deltaShift(firstPoint, endPoint, curDelta, inPoints, points); + } else { + // otherwise, handle the remaining points at the end and beginning of the contour + this.deltaInterpolate(curDelta + 1, endPoint, curDelta, firstDelta, inPoints, points); + + if (firstDelta > 0) { + this.deltaInterpolate(firstPoint, firstDelta - 1, curDelta, firstDelta, inPoints, points); + } + } + + point = endPoint + 1; + } + } + + deltaInterpolate(p1, p2, ref1, ref2, inPoints, outPoints) { + if (p1 > p2) { + return; + } + + let iterable = ['x', 'y']; + for (let i = 0; i < iterable.length; i++) { + let k = iterable[i]; + if (inPoints[ref1][k] > inPoints[ref2][k]) { + var p = ref1; + ref1 = ref2; + ref2 = p; + } + + let in1 = inPoints[ref1][k]; + let in2 = inPoints[ref2][k]; + let out1 = outPoints[ref1][k]; + let out2 = outPoints[ref2][k]; + + // If the reference points have the same coordinate but different + // delta, inferred delta is zero. Otherwise interpolate. + if (in1 !== in2 || out1 === out2) { + let scale = in1 === in2 ? 0 : (out2 - out1) / (in2 - in1); + + for (let p = p1; p <= p2; p++) { + let out = inPoints[p][k]; + + if (out <= in1) { + out += out1 - in1; + } else if (out >= in2) { + out += out2 - in2; + } else { + out = out1 + (out - in1) * scale; + } + + outPoints[p][k] = out; + } + } + } + } + + deltaShift(p1, p2, ref, inPoints, outPoints) { + let deltaX = outPoints[ref].x - inPoints[ref].x; + let deltaY = outPoints[ref].y - inPoints[ref].y; + + if (deltaX === 0 && deltaY === 0) { + return; + } + + for (let p = p1; p <= p2; p++) { + if (p !== ref) { + outPoints[p].x += deltaX; + outPoints[p].y += deltaY; + } + } + } + + getAdvanceAdjustment(gid, table) { + let outerIndex, innerIndex; + + if (table.advanceWidthMapping) { + let idx = gid; + if (idx >= table.advanceWidthMapping.mapCount) { + idx = table.advanceWidthMapping.mapCount - 1; + } + + let entryFormat = table.advanceWidthMapping.entryFormat; + ({outerIndex, innerIndex} = table.advanceWidthMapping.mapData[idx]); + } else { + outerIndex = 0; + innerIndex = gid; + } + + return this.getDelta(table.itemVariationStore, outerIndex, innerIndex); + } + + // See pseudo code from `Font Variations Overview' + // in the OpenType specification. + getDelta(itemStore, outerIndex, innerIndex) { + if (outerIndex >= itemStore.itemVariationData.length) { + return 0; + } + + let varData = itemStore.itemVariationData[outerIndex]; + if (innerIndex >= varData.deltaSets.length) { + return 0; + } + + let deltaSet = varData.deltaSets[innerIndex]; + let blendVector = this.getBlendVector(itemStore, outerIndex); + let netAdjustment = 0; + + for (let master = 0; master < varData.regionIndexCount; master++) { + netAdjustment += deltaSet.deltas[master] * blendVector[master]; + } + + return netAdjustment; + } + + getBlendVector(itemStore, outerIndex) { + let varData = itemStore.itemVariationData[outerIndex]; + if (this.blendVectors.has(varData)) { + return this.blendVectors.get(varData); + } + + let normalizedCoords = this.normalizedCoords; + let blendVector = []; + + // outer loop steps through master designs to be blended + for (let master = 0; master < varData.regionIndexCount; master++) { + let scalar = 1; + let regionIndex = varData.regionIndexes[master]; + let axes = itemStore.variationRegionList.variationRegions[regionIndex]; + + // inner loop steps through axes in this region + for (let j = 0; j < axes.length; j++) { + let axis = axes[j]; + let axisScalar; + + // compute the scalar contribution of this axis + // ignore invalid ranges + if (axis.startCoord > axis.peakCoord || axis.peakCoord > axis.endCoord) { + axisScalar = 1; + + } else if (axis.startCoord < 0 && axis.endCoord > 0 && axis.peakCoord !== 0) { + axisScalar = 1; + + // peak of 0 means ignore this axis + } else if (axis.peakCoord === 0) { + axisScalar = 1; + + // ignore this region if coords are out of range + } else if (normalizedCoords[j] < axis.startCoord || normalizedCoords[j] > axis.endCoord) { + axisScalar = 0; + + // calculate a proportional factor + } else { + if (normalizedCoords[j] === axis.peakCoord) { + axisScalar = 1; + } else if (normalizedCoords[j] < axis.peakCoord) { + axisScalar = (normalizedCoords[j] - axis.startCoord + Number.EPSILON) / + (axis.peakCoord - axis.startCoord + Number.EPSILON); + } else { + axisScalar = (axis.endCoord - normalizedCoords[j] + Number.EPSILON) / + (axis.endCoord - axis.peakCoord + Number.EPSILON); + } + } + + // take product of all the axis scalars + scalar *= axisScalar; + } + + blendVector[master] = scalar; + } + + this.blendVectors.set(varData, blendVector); + return blendVector; + } +} diff --git a/node_modules/fontkit/src/glyph/Path.js b/node_modules/fontkit/src/glyph/Path.js new file mode 100644 index 0000000000000000000000000000000000000000..a119fb28ed54db1150d209bd7d4a027424b732f9 --- /dev/null +++ b/node_modules/fontkit/src/glyph/Path.js @@ -0,0 +1,244 @@ +import BBox from './BBox'; + +const SVG_COMMANDS = { + moveTo: 'M', + lineTo: 'L', + quadraticCurveTo: 'Q', + bezierCurveTo: 'C', + closePath: 'Z' +}; + +/** + * Path objects are returned by glyphs and represent the actual + * vector outlines for each glyph in the font. Paths can be converted + * to SVG path data strings, or to functions that can be applied to + * render the path to a graphics context. + */ +export default class Path { + constructor() { + this.commands = []; + this._bbox = null; + this._cbox = null; + } + + /** + * Compiles the path to a JavaScript function that can be applied with + * a graphics context in order to render the path. + * @return {string} + */ + toFunction() { + return ctx => { + this.commands.forEach(c => { + return ctx[c.command].apply(ctx, c.args) + }) + }; + } + + /** + * Converts the path to an SVG path data string + * @return {string} + */ + toSVG() { + let cmds = this.commands.map(c => { + let args = c.args.map(arg => Math.round(arg * 100) / 100); + return `${SVG_COMMANDS[c.command]}${args.join(' ')}`; + }); + + return cmds.join(''); + } + + /** + * Gets the "control box" of a path. + * This is like the bounding box, but it includes all points including + * control points of bezier segments and is much faster to compute than + * the real bounding box. + * @type {BBox} + */ + get cbox() { + if (!this._cbox) { + let cbox = new BBox; + for (let command of this.commands) { + for (let i = 0; i < command.args.length; i += 2) { + cbox.addPoint(command.args[i], command.args[i + 1]); + } + } + + this._cbox = Object.freeze(cbox); + } + + return this._cbox; + } + + /** + * Gets the exact bounding box of the path by evaluating curve segments. + * Slower to compute than the control box, but more accurate. + * @type {BBox} + */ + get bbox() { + if (this._bbox) { + return this._bbox; + } + + let bbox = new BBox; + let cx = 0, cy = 0; + + let f = t => ( + Math.pow(1 - t, 3) * p0[i] + + 3 * Math.pow(1 - t, 2) * t * p1[i] + + 3 * (1 - t) * Math.pow(t, 2) * p2[i] + + Math.pow(t, 3) * p3[i] + ); + + for (let c of this.commands) { + switch (c.command) { + case 'moveTo': + case 'lineTo': + let [x, y] = c.args; + bbox.addPoint(x, y); + cx = x; + cy = y; + break; + + case 'quadraticCurveTo': + case 'bezierCurveTo': + if (c.command === 'quadraticCurveTo') { + // http://fontforge.org/bezier.html + var [qp1x, qp1y, p3x, p3y] = c.args; + var cp1x = cx + 2 / 3 * (qp1x - cx); // CP1 = QP0 + 2/3 * (QP1-QP0) + var cp1y = cy + 2 / 3 * (qp1y - cy); + var cp2x = p3x + 2 / 3 * (qp1x - p3x); // CP2 = QP2 + 2/3 * (QP1-QP2) + var cp2y = p3y + 2 / 3 * (qp1y - p3y); + } else { + var [cp1x, cp1y, cp2x, cp2y, p3x, p3y] = c.args; + } + + // http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html + bbox.addPoint(p3x, p3y); + + var p0 = [cx, cy]; + var p1 = [cp1x, cp1y]; + var p2 = [cp2x, cp2y]; + var p3 = [p3x, p3y]; + + for (var i = 0; i <= 1; i++) { + let b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; + let a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; + c = 3 * p1[i] - 3 * p0[i]; + + if (a === 0) { + if (b === 0) { + continue; + } + + let t = -c / b; + if (0 < t && t < 1) { + if (i === 0) { + bbox.addPoint(f(t), bbox.maxY); + } else if (i === 1) { + bbox.addPoint(bbox.maxX, f(t)); + } + } + + continue; + } + + let b2ac = Math.pow(b, 2) - 4 * c * a; + if (b2ac < 0) { + continue; + } + + let t1 = (-b + Math.sqrt(b2ac)) / (2 * a); + if (0 < t1 && t1 < 1) { + if (i === 0) { + bbox.addPoint(f(t1), bbox.maxY); + } else if (i === 1) { + bbox.addPoint(bbox.maxX, f(t1)); + } + } + + let t2 = (-b - Math.sqrt(b2ac)) / (2 * a); + if (0 < t2 && t2 < 1) { + if (i === 0) { + bbox.addPoint(f(t2), bbox.maxY); + } else if (i === 1) { + bbox.addPoint(bbox.maxX, f(t2)); + } + } + } + + cx = p3x; + cy = p3y; + break; + } + } + + return this._bbox = Object.freeze(bbox); + } + + /** + * Applies a mapping function to each point in the path. + * @param {function} fn + * @return {Path} + */ + mapPoints(fn) { + let path = new Path; + + for (let c of this.commands) { + let args = []; + for (let i = 0; i < c.args.length; i += 2) { + let [x, y] = fn(c.args[i], c.args[i + 1]); + args.push(x, y); + } + + path[c.command](...args); + } + + return path; + } + + /** + * Transforms the path by the given matrix. + */ + transform(m0, m1, m2, m3, m4, m5) { + return this.mapPoints((x, y) => { + const tx = m0 * x + m2 * y + m4; + const ty = m1 * x + m3 * y + m5; + return [tx, ty]; + }); + } + + /** + * Translates the path by the given offset. + */ + translate(x, y) { + return this.transform(1, 0, 0, 1, x, y); + } + + /** + * Rotates the path by the given angle (in radians). + */ + rotate(angle) { + let cos = Math.cos(angle); + let sin = Math.sin(angle); + return this.transform(cos, sin, -sin, cos, 0, 0); + } + + /** + * Scales the path. + */ + scale(scaleX, scaleY = scaleX) { + return this.transform(scaleX, 0, 0, scaleY, 0, 0); + } +} + +for (let command of ['moveTo', 'lineTo', 'quadraticCurveTo', 'bezierCurveTo', 'closePath']) { + Path.prototype[command] = function(...args) { + this._bbox = this._cbox = null; + this.commands.push({ + command, + args + }); + + return this; + }; +} diff --git a/node_modules/fontkit/src/glyph/SBIXGlyph.js b/node_modules/fontkit/src/glyph/SBIXGlyph.js new file mode 100644 index 0000000000000000000000000000000000000000..fda3b8909f7e9d011cb424e6ca29d2aa213903bc --- /dev/null +++ b/node_modules/fontkit/src/glyph/SBIXGlyph.js @@ -0,0 +1,54 @@ +import TTFGlyph from './TTFGlyph'; +import * as r from 'restructure'; + +let SBIXImage = new r.Struct({ + originX: r.uint16, + originY: r.uint16, + type: new r.String(4), + data: new r.Buffer(t => t.parent.buflen - t._currentOffset) +}); + +/** + * Represents a color (e.g. emoji) glyph in Apple's SBIX format. + */ +export default class SBIXGlyph extends TTFGlyph { + type = 'SBIX'; + + /** + * Returns an object representing a glyph image at the given point size. + * The object has a data property with a Buffer containing the actual image data, + * along with the image type, and origin. + * + * @param {number} size + * @return {object} + */ + getImageForSize(size) { + for (let i = 0; i < this._font.sbix.imageTables.length; i++) { + var table = this._font.sbix.imageTables[i]; + if (table.ppem >= size) { break; } + } + + let offsets = table.imageOffsets; + let start = offsets[this.id]; + let end = offsets[this.id + 1]; + + if (start === end) { + return null; + } + + this._font.stream.pos = start; + return SBIXImage.decode(this._font.stream, {buflen: end - start}); + } + + render(ctx, size) { + let img = this.getImageForSize(size); + if (img != null) { + let scale = size / this._font.unitsPerEm; + ctx.image(img.data, {height: size, x: img.originX, y: (this.bbox.minY - img.originY) * scale}); + } + + if (this._font.sbix.flags.renderOutlines) { + super.render(ctx, size); + } + } +} diff --git a/node_modules/fontkit/src/glyph/StandardNames.js b/node_modules/fontkit/src/glyph/StandardNames.js new file mode 100644 index 0000000000000000000000000000000000000000..7c024a1f19be5f627dcdf20953447e1551c8655d --- /dev/null +++ b/node_modules/fontkit/src/glyph/StandardNames.js @@ -0,0 +1,27 @@ +export default [ + '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', + 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', + 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', + 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', + 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', + 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', + 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', + 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', + 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', + 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', + 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal', + 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', + 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown', + 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', + 'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', + 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', + 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', + 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', + 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex', + 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', + 'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth', + 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior', + 'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla', + 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat' +]; diff --git a/node_modules/fontkit/src/glyph/TTFGlyph.js b/node_modules/fontkit/src/glyph/TTFGlyph.js new file mode 100644 index 0000000000000000000000000000000000000000..8dc1c75be607def47789b1804df7ac3f1788002c --- /dev/null +++ b/node_modules/fontkit/src/glyph/TTFGlyph.js @@ -0,0 +1,393 @@ +import Glyph from './Glyph'; +import Path from './Path'; +import BBox from './BBox'; +import * as r from 'restructure'; + +// The header for both simple and composite glyphs +let GlyfHeader = new r.Struct({ + numberOfContours: r.int16, // if negative, this is a composite glyph + xMin: r.int16, + yMin: r.int16, + xMax: r.int16, + yMax: r.int16 +}); + +// Flags for simple glyphs +const ON_CURVE = 1 << 0; +const X_SHORT_VECTOR = 1 << 1; +const Y_SHORT_VECTOR = 1 << 2; +const REPEAT = 1 << 3; +const SAME_X = 1 << 4; +const SAME_Y = 1 << 5; + +// Flags for composite glyphs +const ARG_1_AND_2_ARE_WORDS = 1 << 0; +const ARGS_ARE_XY_VALUES = 1 << 1; +const ROUND_XY_TO_GRID = 1 << 2; +const WE_HAVE_A_SCALE = 1 << 3; +const MORE_COMPONENTS = 1 << 5; +const WE_HAVE_AN_X_AND_Y_SCALE = 1 << 6; +const WE_HAVE_A_TWO_BY_TWO = 1 << 7; +const WE_HAVE_INSTRUCTIONS = 1 << 8; +const USE_MY_METRICS = 1 << 9; +const OVERLAP_COMPOUND = 1 << 10; +const SCALED_COMPONENT_OFFSET = 1 << 11; +const UNSCALED_COMPONENT_OFFSET = 1 << 12; + +// Represents a point in a simple glyph +export class Point { + constructor(onCurve, endContour, x = 0, y = 0) { + this.onCurve = onCurve; + this.endContour = endContour; + this.x = x; + this.y = y; + } + + copy() { + return new Point(this.onCurve, this.endContour, this.x, this.y); + } +} + +// Represents a component in a composite glyph +class Component { + constructor(glyphID, dx, dy) { + this.glyphID = glyphID; + this.dx = dx; + this.dy = dy; + this.pos = 0; + this.scaleX = this.scaleY = 1; + this.scale01 = this.scale10 = 0; + } +} + +/** + * Represents a TrueType glyph. + */ +export default class TTFGlyph extends Glyph { + type = 'TTF'; + + // Parses just the glyph header and returns the bounding box + _getCBox(internal) { + // We need to decode the glyph if variation processing is requested, + // so it's easier just to recompute the path's cbox after decoding. + if (this._font._variationProcessor && !internal) { + return this.path.cbox; + } + + let stream = this._font._getTableStream('glyf'); + stream.pos += this._font.loca.offsets[this.id]; + let glyph = GlyfHeader.decode(stream); + + let cbox = new BBox(glyph.xMin, glyph.yMin, glyph.xMax, glyph.yMax); + return Object.freeze(cbox); + } + + // Parses a single glyph coordinate + _parseGlyphCoord(stream, prev, short, same) { + if (short) { + var val = stream.readUInt8(); + if (!same) { + val = -val; + } + + val += prev; + } else { + if (same) { + var val = prev; + } else { + var val = prev + stream.readInt16BE(); + } + } + + return val; + } + + // Decodes the glyph data into points for simple glyphs, + // or components for composite glyphs + _decode() { + let glyfPos = this._font.loca.offsets[this.id]; + let nextPos = this._font.loca.offsets[this.id + 1]; + + // Nothing to do if there is no data for this glyph + if (glyfPos === nextPos) { return null; } + + let stream = this._font._getTableStream('glyf'); + stream.pos += glyfPos; + let startPos = stream.pos; + + let glyph = GlyfHeader.decode(stream); + + if (glyph.numberOfContours > 0) { + this._decodeSimple(glyph, stream); + + } else if (glyph.numberOfContours < 0) { + this._decodeComposite(glyph, stream, startPos); + } + + return glyph; + } + + _decodeSimple(glyph, stream) { + // this is a simple glyph + glyph.points = []; + + let endPtsOfContours = new r.Array(r.uint16, glyph.numberOfContours).decode(stream); + glyph.instructions = new r.Array(r.uint8, r.uint16).decode(stream); + + let flags = []; + let numCoords = endPtsOfContours[endPtsOfContours.length - 1] + 1; + + while (flags.length < numCoords) { + var flag = stream.readUInt8(); + flags.push(flag); + + // check for repeat flag + if (flag & REPEAT) { + let count = stream.readUInt8(); + for (let j = 0; j < count; j++) { + flags.push(flag); + } + } + } + + for (var i = 0; i < flags.length; i++) { + var flag = flags[i]; + let point = new Point(!!(flag & ON_CURVE), endPtsOfContours.indexOf(i) >= 0, 0, 0); + glyph.points.push(point); + } + + let px = 0; + for (var i = 0; i < flags.length; i++) { + var flag = flags[i]; + glyph.points[i].x = px = this._parseGlyphCoord(stream, px, flag & X_SHORT_VECTOR, flag & SAME_X); + } + + let py = 0; + for (var i = 0; i < flags.length; i++) { + var flag = flags[i]; + glyph.points[i].y = py = this._parseGlyphCoord(stream, py, flag & Y_SHORT_VECTOR, flag & SAME_Y); + } + + if (this._font._variationProcessor) { + let points = glyph.points.slice(); + points.push(...this._getPhantomPoints(glyph)); + + this._font._variationProcessor.transformPoints(this.id, points); + glyph.phantomPoints = points.slice(-4); + } + + return; + } + + _decodeComposite(glyph, stream, offset = 0) { + // this is a composite glyph + glyph.components = []; + let haveInstructions = false; + let flags = MORE_COMPONENTS; + + while (flags & MORE_COMPONENTS) { + flags = stream.readUInt16BE(); + let gPos = stream.pos - offset; + let glyphID = stream.readUInt16BE(); + if (!haveInstructions) { + haveInstructions = (flags & WE_HAVE_INSTRUCTIONS) !== 0; + } + + if (flags & ARG_1_AND_2_ARE_WORDS) { + var dx = stream.readInt16BE(); + var dy = stream.readInt16BE(); + } else { + var dx = stream.readInt8(); + var dy = stream.readInt8(); + } + + var component = new Component(glyphID, dx, dy); + component.pos = gPos; + + if (flags & WE_HAVE_A_SCALE) { + // fixed number with 14 bits of fraction + component.scaleX = + component.scaleY = ((stream.readUInt8() << 24) | (stream.readUInt8() << 16)) / 1073741824; + + } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) { + component.scaleX = ((stream.readUInt8() << 24) | (stream.readUInt8() << 16)) / 1073741824; + component.scaleY = ((stream.readUInt8() << 24) | (stream.readUInt8() << 16)) / 1073741824; + + } else if (flags & WE_HAVE_A_TWO_BY_TWO) { + component.scaleX = ((stream.readUInt8() << 24) | (stream.readUInt8() << 16)) / 1073741824; + component.scale01 = ((stream.readUInt8() << 24) | (stream.readUInt8() << 16)) / 1073741824; + component.scale10 = ((stream.readUInt8() << 24) | (stream.readUInt8() << 16)) / 1073741824; + component.scaleY = ((stream.readUInt8() << 24) | (stream.readUInt8() << 16)) / 1073741824; + } + + glyph.components.push(component); + } + + if (this._font._variationProcessor) { + let points = []; + for (let j = 0; j < glyph.components.length; j++) { + var component = glyph.components[j]; + points.push(new Point(true, true, component.dx, component.dy)); + } + + points.push(...this._getPhantomPoints(glyph)); + + this._font._variationProcessor.transformPoints(this.id, points); + glyph.phantomPoints = points.splice(-4, 4); + + for (let i = 0; i < points.length; i++) { + let point = points[i]; + glyph.components[i].dx = point.x; + glyph.components[i].dy = point.y; + } + } + + return haveInstructions; + } + + _getPhantomPoints(glyph) { + let cbox = this._getCBox(true); + if (this._metrics == null) { + this._metrics = Glyph.prototype._getMetrics.call(this, cbox); + } + + let { advanceWidth, advanceHeight, leftBearing, topBearing } = this._metrics; + + return [ + new Point(false, true, glyph.xMin - leftBearing, 0), + new Point(false, true, glyph.xMin - leftBearing + advanceWidth, 0), + new Point(false, true, 0, glyph.yMax + topBearing), + new Point(false, true, 0, glyph.yMax + topBearing + advanceHeight) + ]; + } + + // Decodes font data, resolves composite glyphs, and returns an array of contours + _getContours() { + let glyph = this._decode(); + if (!glyph) { + return []; + } + + let points = []; + + if (glyph.numberOfContours < 0) { + // resolve composite glyphs + for (let component of glyph.components) { + let contours = this._font.getGlyph(component.glyphID)._getContours(); + for (let i = 0; i < contours.length; i++) { + let contour = contours[i]; + for (let j = 0; j < contour.length; j++) { + let point = contour[j]; + let x = point.x * component.scaleX + point.y * component.scale01 + component.dx; + let y = point.y * component.scaleY + point.x * component.scale10 + component.dy; + points.push(new Point(point.onCurve, point.endContour, x, y)); + } + } + } + } else { + points = glyph.points || []; + } + + // Recompute and cache metrics if we performed variation processing, and don't have an HVAR table + if (glyph.phantomPoints && !this._font.directory.tables.HVAR) { + this._metrics.advanceWidth = glyph.phantomPoints[1].x - glyph.phantomPoints[0].x; + this._metrics.advanceHeight = glyph.phantomPoints[3].y - glyph.phantomPoints[2].y; + this._metrics.leftBearing = glyph.xMin - glyph.phantomPoints[0].x; + this._metrics.topBearing = glyph.phantomPoints[2].y - glyph.yMax; + } + + let contours = []; + let cur = []; + for (let k = 0; k < points.length; k++) { + var point = points[k]; + cur.push(point); + if (point.endContour) { + contours.push(cur); + cur = []; + } + } + + return contours; + } + + _getMetrics() { + if (this._metrics) { + return this._metrics; + } + + let cbox = this._getCBox(true); + super._getMetrics(cbox); + + if (this._font._variationProcessor && !this._font.HVAR) { + // No HVAR table, decode the glyph. This triggers recomputation of metrics. + this.path; + } + + return this._metrics; + } + + // Converts contours to a Path object that can be rendered + _getPath() { + let contours = this._getContours(); + let path = new Path; + + for (let i = 0; i < contours.length; i++) { + let contour = contours[i]; + let firstPt = contour[0]; + let lastPt = contour[contour.length - 1]; + let start = 0; + + if (firstPt.onCurve) { + // The first point will be consumed by the moveTo command, so skip in the loop + var curvePt = null; + start = 1; + } else { + if (lastPt.onCurve) { + // Start at the last point if the first point is off curve and the last point is on curve + firstPt = lastPt; + } else { + // Start at the middle if both the first and last points are off curve + firstPt = new Point(false, false, (firstPt.x + lastPt.x) / 2, (firstPt.y + lastPt.y) / 2); + } + + var curvePt = firstPt; + } + + path.moveTo(firstPt.x, firstPt.y); + + for (let j = start; j < contour.length; j++) { + let pt = contour[j]; + let prevPt = j === 0 ? firstPt : contour[j - 1]; + + if (prevPt.onCurve && pt.onCurve) { + path.lineTo(pt.x, pt.y); + + } else if (prevPt.onCurve && !pt.onCurve) { + var curvePt = pt; + + } else if (!prevPt.onCurve && !pt.onCurve) { + let midX = (prevPt.x + pt.x) / 2; + let midY = (prevPt.y + pt.y) / 2; + path.quadraticCurveTo(prevPt.x, prevPt.y, midX, midY); + var curvePt = pt; + + } else if (!prevPt.onCurve && pt.onCurve) { + path.quadraticCurveTo(curvePt.x, curvePt.y, pt.x, pt.y); + var curvePt = null; + + } else { + throw new Error("Unknown TTF path state"); + } + } + + // Connect the first and last points + if (curvePt) { + path.quadraticCurveTo(curvePt.x, curvePt.y, firstPt.x, firstPt.y); + } + + path.closePath(); + } + + return path; + } +} diff --git a/node_modules/fontkit/src/glyph/TTFGlyphEncoder.js b/node_modules/fontkit/src/glyph/TTFGlyphEncoder.js new file mode 100644 index 0000000000000000000000000000000000000000..6ab8b73c6532146442ea1564aa56dca417b369b9 --- /dev/null +++ b/node_modules/fontkit/src/glyph/TTFGlyphEncoder.js @@ -0,0 +1,158 @@ +import * as r from 'restructure'; + +// Flags for simple glyphs +const ON_CURVE = 1 << 0; +const X_SHORT_VECTOR = 1 << 1; +const Y_SHORT_VECTOR = 1 << 2; +const REPEAT = 1 << 3; +const SAME_X = 1 << 4; +const SAME_Y = 1 << 5; + +class Point { + static size(val) { + return val >= 0 && val <= 255 ? 1 : 2; + } + + static encode(stream, value) { + if (value >= 0 && value <= 255) { + stream.writeUInt8(value); + } else { + stream.writeInt16BE(value); + } + } +} + +let Glyf = new r.Struct({ + numberOfContours: r.int16, // if negative, this is a composite glyph + xMin: r.int16, + yMin: r.int16, + xMax: r.int16, + yMax: r.int16, + endPtsOfContours: new r.Array(r.uint16, 'numberOfContours'), + instructions: new r.Array(r.uint8, r.uint16), + flags: new r.Array(r.uint8, 0), + xPoints: new r.Array(Point, 0), + yPoints: new r.Array(Point, 0) +}); + +/** + * Encodes TrueType glyph outlines + */ +export default class TTFGlyphEncoder { + encodeSimple(path, instructions = []) { + let endPtsOfContours = []; + let xPoints = []; + let yPoints = []; + let flags = []; + let same = 0; + let lastX = 0, lastY = 0, lastFlag = 0; + let pointCount = 0; + + for (let i = 0; i < path.commands.length; i++) { + let c = path.commands[i]; + + for (let j = 0; j < c.args.length; j += 2) { + let x = c.args[j]; + let y = c.args[j + 1]; + let flag = 0; + + // If the ending point of a quadratic curve is the midpoint + // between the control point and the control point of the next + // quadratic curve, we can omit the ending point. + if (c.command === 'quadraticCurveTo' && j === 2) { + let next = path.commands[i + 1]; + if (next && next.command === 'quadraticCurveTo') { + let midX = (lastX + next.args[0]) / 2; + let midY = (lastY + next.args[1]) / 2; + + if (x === midX && y === midY) { + continue; + } + } + } + + // All points except control points are on curve. + if (!(c.command === 'quadraticCurveTo' && j === 0)) { + flag |= ON_CURVE; + } + + flag = this._encodePoint(x, lastX, xPoints, flag, X_SHORT_VECTOR, SAME_X); + flag = this._encodePoint(y, lastY, yPoints, flag, Y_SHORT_VECTOR, SAME_Y); + + if (flag === lastFlag && same < 255) { + flags[flags.length - 1] |= REPEAT; + same++; + } else { + if (same > 0) { + flags.push(same); + same = 0; + } + + flags.push(flag); + lastFlag = flag; + } + + lastX = x; + lastY = y; + pointCount++; + } + + if (c.command === 'closePath') { + endPtsOfContours.push(pointCount - 1); + } + } + + // Close the path if the last command didn't already + if (path.commands.length > 1 && path.commands[path.commands.length - 1].command !== 'closePath') { + endPtsOfContours.push(pointCount - 1); + } + + let bbox = path.bbox; + let glyf = { + numberOfContours: endPtsOfContours.length, + xMin: bbox.minX, + yMin: bbox.minY, + xMax: bbox.maxX, + yMax: bbox.maxY, + endPtsOfContours: endPtsOfContours, + instructions: instructions, + flags: flags, + xPoints: xPoints, + yPoints: yPoints + }; + + let size = Glyf.size(glyf); + let tail = 4 - (size % 4); + + let stream = new r.EncodeStream(size + tail); + Glyf.encode(stream, glyf); + + // Align to 4-byte length + if (tail !== 0) { + stream.fill(0, tail); + } + + return stream.buffer; + } + + _encodePoint(value, last, points, flag, shortFlag, sameFlag) { + let diff = value - last; + + if (value === last) { + flag |= sameFlag; + } else { + if (-255 <= diff && diff <= 255) { + flag |= shortFlag; + if (diff < 0) { + diff = -diff; + } else { + flag |= sameFlag; + } + } + + points.push(diff); + } + + return flag; + } +} diff --git a/node_modules/fontkit/src/glyph/WOFF2Glyph.js b/node_modules/fontkit/src/glyph/WOFF2Glyph.js new file mode 100644 index 0000000000000000000000000000000000000000..9b451c1bfabedcccdc268606e9abf4339c4d95e1 --- /dev/null +++ b/node_modules/fontkit/src/glyph/WOFF2Glyph.js @@ -0,0 +1,17 @@ +import TTFGlyph from './TTFGlyph'; + +/** + * Represents a TrueType glyph in the WOFF2 format, which compresses glyphs differently. + */ +export default class WOFF2Glyph extends TTFGlyph { + type = 'WOFF2'; + + _decode() { + // We have to decode in advance (in WOFF2Font), so just return the pre-decoded data. + return this._font._transformedGlyphs[this.id]; + } + + _getCBox() { + return this.path.bbox; + } +} diff --git a/node_modules/fontkit/src/index.js b/node_modules/fontkit/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e27a7b25e51d55d244ac8d06b46888be23ae7c63 --- /dev/null +++ b/node_modules/fontkit/src/index.js @@ -0,0 +1,15 @@ +import { registerFormat, create, defaultLanguage, setDefaultLanguage } from './base'; +import TTFFont from './TTFFont'; +import WOFFFont from './WOFFFont'; +import WOFF2Font from './WOFF2Font'; +import TrueTypeCollection from './TrueTypeCollection'; +import DFont from './DFont'; + +// Register font formats +registerFormat(TTFFont); +registerFormat(WOFFFont); +registerFormat(WOFF2Font); +registerFormat(TrueTypeCollection); +registerFormat(DFont); + +export * from './base'; diff --git a/node_modules/fontkit/src/layout/GlyphPosition.js b/node_modules/fontkit/src/layout/GlyphPosition.js new file mode 100644 index 0000000000000000000000000000000000000000..79a4422a5ee1eff3b7d81771b8aaa99f69c222f1 --- /dev/null +++ b/node_modules/fontkit/src/layout/GlyphPosition.js @@ -0,0 +1,30 @@ +/** + * Represents positioning information for a glyph in a GlyphRun. + */ +export default class GlyphPosition { + constructor(xAdvance = 0, yAdvance = 0, xOffset = 0, yOffset = 0) { + /** + * The amount to move the virtual pen in the X direction after rendering this glyph. + * @type {number} + */ + this.xAdvance = xAdvance; + + /** + * The amount to move the virtual pen in the Y direction after rendering this glyph. + * @type {number} + */ + this.yAdvance = yAdvance; + + /** + * The offset from the pen position in the X direction at which to render this glyph. + * @type {number} + */ + this.xOffset = xOffset; + + /** + * The offset from the pen position in the Y direction at which to render this glyph. + * @type {number} + */ + this.yOffset = yOffset; + } +} diff --git a/node_modules/fontkit/src/layout/GlyphRun.js b/node_modules/fontkit/src/layout/GlyphRun.js new file mode 100644 index 0000000000000000000000000000000000000000..18e2f236d909245788e8f42c8f2c152800477b8e --- /dev/null +++ b/node_modules/fontkit/src/layout/GlyphRun.js @@ -0,0 +1,108 @@ +import BBox from '../glyph/BBox'; +import * as Script from '../layout/Script'; + +/** + * Represents a run of Glyph and GlyphPosition objects. + * Returned by the font layout method. + */ +export default class GlyphRun { + constructor(glyphs, features, script, language, direction) { + /** + * An array of Glyph objects in the run + * @type {Glyph[]} + */ + this.glyphs = glyphs; + + /** + * An array of GlyphPosition objects for each glyph in the run + * @type {GlyphPosition[]} + */ + this.positions = null; + + /** + * The script that was requested for shaping. This was either passed in or detected automatically. + * @type {string} + */ + this.script = script; + + /** + * The language requested for shaping, as passed in. If `null`, the default language for the + * script was used. + * @type {string} + */ + this.language = language || null; + + /** + * The direction requested for shaping, as passed in (either ltr or rtl). + * If `null`, the default direction of the script is used. + * @type {string} + */ + this.direction = direction || Script.direction(script); + + /** + * The features requested during shaping. This is a combination of user + * specified features and features chosen by the shaper. + * @type {object} + */ + this.features = {}; + + // Convert features to an object + if (Array.isArray(features)) { + for (let tag of features) { + this.features[tag] = true; + } + } else if (typeof features === 'object') { + this.features = features; + } + } + + /** + * The total advance width of the run. + * @type {number} + */ + get advanceWidth() { + let width = 0; + for (let position of this.positions) { + width += position.xAdvance; + } + + return width; + } + + /** + * The total advance height of the run. + * @type {number} + */ + get advanceHeight() { + let height = 0; + for (let position of this.positions) { + height += position.yAdvance; + } + + return height; + } + + /** + * The bounding box containing all glyphs in the run. + * @type {BBox} + */ + get bbox() { + let bbox = new BBox; + + let x = 0; + let y = 0; + for (let index = 0; index < this.glyphs.length; index++) { + let glyph = this.glyphs[index]; + let p = this.positions[index]; + let b = glyph.bbox; + + bbox.addPoint(b.minX + x + p.xOffset, b.minY + y + p.yOffset); + bbox.addPoint(b.maxX + x + p.xOffset, b.maxY + y + p.yOffset); + + x += p.xAdvance; + y += p.yAdvance; + } + + return bbox; + } +} diff --git a/node_modules/fontkit/src/layout/KernProcessor.js b/node_modules/fontkit/src/layout/KernProcessor.js new file mode 100644 index 0000000000000000000000000000000000000000..4d4f6db5cd82e946622cd6f1f65644c289c4f28c --- /dev/null +++ b/node_modules/fontkit/src/layout/KernProcessor.js @@ -0,0 +1,94 @@ +import {binarySearch} from '../utils'; + +export default class KernProcessor { + constructor(font) { + this.kern = font.kern; + } + + process(glyphs, positions) { + for (let glyphIndex = 0; glyphIndex < glyphs.length - 1; glyphIndex++) { + let left = glyphs[glyphIndex].id; + let right = glyphs[glyphIndex + 1].id; + positions[glyphIndex].xAdvance += this.getKerning(left, right); + } + } + + getKerning(left, right) { + let res = 0; + + for (let table of this.kern.tables) { + if (table.coverage.crossStream) { + continue; + } + + switch (table.version) { + case 0: + if (!table.coverage.horizontal) { + continue; + } + + break; + case 1: + if (table.coverage.vertical || table.coverage.variation) { + continue; + } + + break; + default: + throw new Error(`Unsupported kerning table version ${table.version}`); + } + + let val = 0; + let s = table.subtable; + switch (table.format) { + case 0: + let pairIdx = binarySearch(s.pairs, function (pair) { + return (left - pair.left) || (right - pair.right); + }); + + if (pairIdx >= 0) { + val = s.pairs[pairIdx].value; + } + + break; + + case 2: + let leftOffset = 0, rightOffset = 0; + if (left >= s.leftTable.firstGlyph && left < s.leftTable.firstGlyph + s.leftTable.nGlyphs) { + leftOffset = s.leftTable.offsets[left - s.leftTable.firstGlyph]; + } else { + leftOffset = s.array.off; + } + + if (right >= s.rightTable.firstGlyph && right < s.rightTable.firstGlyph + s.rightTable.nGlyphs) { + rightOffset = s.rightTable.offsets[right - s.rightTable.firstGlyph]; + } + + let index = (leftOffset + rightOffset - s.array.off) / 2; + val = s.array.values.get(index); + break; + + case 3: + if (left >= s.glyphCount || right >= s.glyphCount) { + return 0; + } + + val = s.kernValue[s.kernIndex[s.leftClass[left] * s.rightClassCount + s.rightClass[right]]]; + break; + + default: + throw new Error(`Unsupported kerning sub-table format ${table.format}`); + } + + // Microsoft supports the override flag, which resets the result + // Otherwise, the sum of the results from all subtables is returned + if (table.coverage.override) { + res = val; + } else { + res += val; + } + } + + return res; + } +} diff --git a/node_modules/fontkit/src/layout/LayoutEngine.js b/node_modules/fontkit/src/layout/LayoutEngine.js new file mode 100644 index 0000000000000000000000000000000000000000..1b035a723190e1e3622af4bd60247307e65c6128 --- /dev/null +++ b/node_modules/fontkit/src/layout/LayoutEngine.js @@ -0,0 +1,189 @@ +import KernProcessor from './KernProcessor'; +import UnicodeLayoutEngine from './UnicodeLayoutEngine'; +import GlyphRun from './GlyphRun'; +import GlyphPosition from './GlyphPosition'; +import * as Script from './Script'; +import AATLayoutEngine from '../aat/AATLayoutEngine'; +import OTLayoutEngine from '../opentype/OTLayoutEngine'; + +export default class LayoutEngine { + constructor(font) { + this.font = font; + this.unicodeLayoutEngine = null; + this.kernProcessor = null; + + // Choose an advanced layout engine. We try the AAT morx table first since more + // scripts are currently supported because the shaping logic is built into the font. + if (this.font.morx) { + this.engine = new AATLayoutEngine(this.font); + + } else if (this.font.GSUB || this.font.GPOS) { + this.engine = new OTLayoutEngine(this.font); + } + } + + layout(string, features, script, language, direction) { + // Make the features parameter optional + if (typeof features === 'string') { + direction = language; + language = script; + script = features; + features = []; + } + + // Map string to glyphs if needed + if (typeof string === 'string') { + // Attempt to detect the script from the string if not provided. + if (script == null) { + script = Script.forString(string); + } + + var glyphs = this.font.glyphsForString(string); + } else { + // Attempt to detect the script from the glyph code points if not provided. + if (script == null) { + let codePoints = []; + for (let glyph of string) { + codePoints.push(...glyph.codePoints); + } + + script = Script.forCodePoints(codePoints); + } + + var glyphs = string; + } + + let glyphRun = new GlyphRun(glyphs, features, script, language, direction); + + // Return early if there are no glyphs + if (glyphs.length === 0) { + glyphRun.positions = []; + return glyphRun; + } + + // Setup the advanced layout engine + if (this.engine && this.engine.setup) { + this.engine.setup(glyphRun); + } + + // Substitute and position the glyphs + this.substitute(glyphRun); + this.position(glyphRun); + + this.hideDefaultIgnorables(glyphRun.glyphs, glyphRun.positions); + + // Let the layout engine clean up any state it might have + if (this.engine && this.engine.cleanup) { + this.engine.cleanup(); + } + + return glyphRun; + } + + substitute(glyphRun) { + // Call the advanced layout engine to make substitutions + if (this.engine && this.engine.substitute) { + this.engine.substitute(glyphRun); + } + } + + position(glyphRun) { + // Get initial glyph positions + glyphRun.positions = glyphRun.glyphs.map(glyph => new GlyphPosition(glyph.advanceWidth)); + let positioned = null; + + // Call the advanced layout engine. Returns the features applied. + if (this.engine && this.engine.position) { + positioned = this.engine.position(glyphRun); + } + + // if there is no GPOS table, use unicode properties to position marks. + if (!positioned && (!this.engine || this.engine.fallbackPosition)) { + if (!this.unicodeLayoutEngine) { + this.unicodeLayoutEngine = new UnicodeLayoutEngine(this.font); + } + + this.unicodeLayoutEngine.positionGlyphs(glyphRun.glyphs, glyphRun.positions); + } + + // if kerning is not supported by GPOS, do kerning with the TrueType/AAT kern table + if ((!positioned || !positioned.kern) && glyphRun.features.kern !== false && this.font.kern) { + if (!this.kernProcessor) { + this.kernProcessor = new KernProcessor(this.font); + } + + this.kernProcessor.process(glyphRun.glyphs, glyphRun.positions); + glyphRun.features.kern = true; + } + } + + hideDefaultIgnorables(glyphs, positions) { + let space = this.font.glyphForCodePoint(0x20); + for (let i = 0; i < glyphs.length; i++) { + if (this.isDefaultIgnorable(glyphs[i].codePoints[0])) { + glyphs[i] = space; + positions[i].xAdvance = 0; + positions[i].yAdvance = 0; + } + } + } + + isDefaultIgnorable(ch) { + // From DerivedCoreProperties.txt in the Unicode database, + // minus U+115F, U+1160, U+3164 and U+FFA0, which is what + // Harfbuzz and Uniscribe do. + let plane = ch >> 16; + if (plane === 0) { + // BMP + switch (ch >> 8) { + case 0x00: return ch === 0x00AD; + case 0x03: return ch === 0x034F; + case 0x06: return ch === 0x061C; + case 0x17: return 0x17B4 <= ch && ch <= 0x17B5; + case 0x18: return 0x180B <= ch && ch <= 0x180E; + case 0x20: return (0x200B <= ch && ch <= 0x200F) || (0x202A <= ch && ch <= 0x202E) || (0x2060 <= ch && ch <= 0x206F); + case 0xFE: return (0xFE00 <= ch && ch <= 0xFE0F) || ch === 0xFEFF; + case 0xFF: return 0xFFF0 <= ch && ch <= 0xFFF8; + default: return false; + } + } else { + // Other planes + switch (plane) { + case 0x01: return (0x1BCA0 <= ch && ch <= 0x1BCA3) || (0x1D173 <= ch && ch <= 0x1D17A); + case 0x0E: return 0xE0000 <= ch && ch <= 0xE0FFF; + default: return false; + } + } + } + + getAvailableFeatures(script, language) { + let features = []; + + if (this.engine) { + features.push(...this.engine.getAvailableFeatures(script, language)); + } + + if (this.font.kern && features.indexOf('kern') === -1) { + features.push('kern'); + } + + return features; + } + + stringsForGlyph(gid) { + let result = new Set; + + let codePoints = this.font._cmapProcessor.codePointsForGlyph(gid); + for (let codePoint of codePoints) { + result.add(String.fromCodePoint(codePoint)); + } + + if (this.engine && this.engine.stringsForGlyph) { + for (let string of this.engine.stringsForGlyph(gid)) { + result.add(string); + } + } + + return Array.from(result); + } +}